text:
Q: Using require when electron app is packaged in an asar In my main.js, I have:
var mainFrm = require('./MainFrm');

This works fine except when the application is packaged as an asar file.  I get a 'Cannot find module' error.
The documentation states to use the following:
require('/path/to/example.asar/dir/module.js');

I tried that but got the same error.  Where does the path begin when using the above?  Does path start with electron.exe is?  Also, if I use require('/resources/app.asar/MainFrm.js') what path do I use for OS X apps since the Resources folder is in a different location?  What path should I use during development/debugging (i.e. not inside of an asar)

A: I think you may have 2 issues. First, you may need to be explicit about the file extension, thus looking for MainFrm.js, not just MainFrm. Second, try using resolve to determine the name relative to the current directory.
One way to resolve this is to resolve the path at runtime, like this:
    var mainFrm = require("path").resolve(__dirname, "./MainFrm.js");

Try some combinations of that and see if it doesn't help.


text:
Q: Multiple values for a column MySQL/CodeIgniter There are three tables in my application: products, sizes and product_sizes.
The structure is something like this:
products' table:
id INT(11)
name VARCHAR(48)

sizes' table:
id INT(11)
name VARCHAR(48)

product_sizes' table:
id INT(11)
product_id INT(11)
size_id INT(11)

As you can see, there are some products that has three sizes for instance. What I need to show up to the user those three sizes with their names.
What I have in PHP now:
index.php (view)
<?php

[...]

foreach ($products as $product) {
    echo $product->name; // for each item, show its name
}

And I want to iterate with the sizes just like that:
<?php

[...]

foreach ($products as $product) {
    [...]

    echo $product->name;

    foreach($product->sizes as $size) {
        echo $size; // for each item, shows its available sizes (s, M, L, for example)
    }
}

How can I make sizes work together to the products in a consistent way like showed above?
My query, for now is:
SELECT products.id, products.name, sizes.name FROM products
JOIN product_sizes ON product_sizes.product_id = products.id
JOIN sizes ON product_sizes.size_id = sizes.id

I marked as CodeIgniter because if there have a way to solve this problem through its ACtiveRecord, no problem because my application runs on the top of CI. You can share your solution normally.

A: You can use GROUP_CONCAT() in your SQL Query to concat multiple sizes in a one column and later process that cell value.
SELECT products.id, products.name,  GROUP_CONCAT( sizes.name ) available_sizes
FROM products
     JOIN product_sizes ON product_sizes.product_id = products.id
     JOIN sizes ON product_sizes.size_id = sizes.id
group by products.id

in PHP you can use it as following.
foreach ($products as $product) {
    [...]

    echo $product->name;

    $available_sizes=explode(",",$product->available_sizes);
    foreach($available_sizes as $size) {
        echo $size; // for each item, shows its available sizes (s, M, L, for example)
    }
}

Hope, this helps :)

A: What you want to do you may achieve it with a bit of SQL, check this, it's an example of getting grouped values (what you want to do) into a single field:
http://sqlfiddle.com/#!2/400994/20
In your case, you'd do something like:
SELECT
  p.id
, p.name
, CONCAT( "[", GROUP_CONCAT( s.name SEPARATOR ", "), "]" ) sizes
FROM products p
INNER JOIN product_sizes ps
ON ps.product_id = p.id
INNER JOIN sizes s
ON ps.size_id = s.id
GROUP BY p.id

In your PHP, with a json_decode, you'd get the values you wanted.
foreach ($products as $product) {
    [...]

    echo $product->name;
    $product_sizes = json_decode($product->sizes);

    foreach($product_sizes as $size) {
        echo $size; // for each item, shows its available sizes (s, M, L, for example)
    }
}

The advantage of a JSON string, is that when you format it you may get complicated structure data with it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ServiceLoader using ClassLoader pointing to different path Have been trying this since few days and can't get it working!
I am trying to build a pluggable java application where I can run it from command line and provide plugins (jars) in a separated folder. It seems the ServiceLoader would fit my requirement but I think I need a special case where the jars are not part of the classpath whereas they are stored in a different location, and for this reason I would need to use a ClassLoder pointing its url to this file system path.
One of the plugin i want to provide to the main application is a log jar with some custom features.
Here below the code I am using , but can't get to go into the for/loop .. it means that the ServiceLoader is not able to identify/match any class implementation :
final URL u = new File("C:\\data\\myLogJar-1.0-SNAPSHOT.jar").toURI().toURL();
ClassLoader ucl = new URLClassLoader(new URL[] {u});

ServiceLoader<Log> loader = ServiceLoader.load(Log.class, ucl);
for (Iterator<Log> iterator = loader.iterator(); iterator.hasNext(); ) {
    System.out.println(iterator.next());
}
loader = ServiceLoader.load(Log.class,ucl);
for (final Log log : loader) {
    log.info("Test log");
}

I wish you could help!
Thanks a lot
====
adding project files :
Main pluggable application :

    package com.company.dep.automation;

import com.company.dep.automation.pluggable.Log;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

import java.util.*;

public class Main {

    private static ServiceLoader<Log> serviceLoader;

    public static void main(String[] args) {

        final URL u;
        ClassLoader ucl = null;

        try {
            u = new File("C:\\data\\myLogJar-1.0-SNAPSHOT.jar").toURI().toURL();
             ucl = new URLClassLoader(new URL[]{u});
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        }

        ServiceLoader<Log> loader = ServiceLoader.load(Log.class, ucl);
        for (Iterator<Log> iterator = loader.iterator(); iterator.hasNext(); ) {
            System.out.println(iterator.next());
        }

        loader = ServiceLoader.load(Log.class, ucl);
        for (final Log log : loader) {
            log.info("Test log");
        }

    }

}

the "Log" plugin
The interface Log
package com.company.automation.service;

public interface Log {

    void trace(String message);
    void debug(String message);
    void info(String message);
    void warn(String message);
    void severe(String message);
    void error(String message);
    void fatal(String message);

}

Its implementation
package com.company.automation.service.impl;

import com.company.automation.service.Log;

public class LogImpl implements Log {

    @Override
    public void trace(String message) {
        log("TRACE --> " + message);
    }

    @Override
    public void debug(String message) {
        log("DEBUG --> " + message);
    }

    @Override
    public void info(String message) {
        log("INFO --> " + message);
    }

    @Override
    public void warn(String message) {
        log("WARN --> " + message);
    }

    @Override
    public void severe(String message) {
        log("SEVERE --> " + message);
    }

    @Override
    public void error(String message) {
        log("ERROR --> " + message);
    }

    @Override
    public void fatal(String message) {
        log("FATAL --> " + message);
    }

    private void log(String message) {
        System.out.println(message);
    }

}

*

*Structure

=================
Adjusted the project structure as following but still doesnt work :
Main App :

Extension app :

A: It doesn't work because it is not the same class Log, your main method try to find implementations of com.company.dep.automation.pluggable.Log while your jar defines an implementation of com.company.automation.service.Log such that ServiceLoader.load simply cannot find anything.
You should move the interface com.company.automation.service.Log from the extension jar to the project with your Main class and import com.company.automation.service.Log instead of com.company.dep.automation.pluggable.Log in your Main class then everything should work.

A: Regarding the "pluggable" part of your application and the loading of jars in a folder, instead of re-inventing the wheel, maybe you could have a look at OSGI. By using an OSGI implementation (Apache Felix for example), you could load jars plugins into your application. This is how Eclipse plugins are working for example. (Atlassian is also using this OSGI mechanism for their Jira/Confluence/etc plugins).
OSGI will handle a lot of issue that you will encounter one day if you want a pluggable plugin system.
For example, this is how I'm doing it:
public ChannelListener init() {
    private ChannelListener listener = new ChannelListener();
    logger.info("Initializing Felix...");
    felix = new Felix(getConfig());

    try {
        felix.start();
    } catch (BundleException e) {
        logger.error("Error while initializing Felix", e);
        throw new RuntimeException(e);
    }

    try {
        // On the next line, you are registering a listener that will listen for all
        //Log implementations service registration.
        felix.getBundleContext().addServiceListener(listener, "(objectClass=com.company.automation.service.Log)");
    } catch (InvalidSyntaxException e) {
        logger.error("Error while registering service listener", e);
    }
    listener.start(felix.getBundleContext());

    startAllBundlesInDirectory(BUNDLE_DIRECTORY, felix.getBundleContext());
    return listener;
}

private void startAllBundlesInDirectory(String directory, BundleContext context) {
    File bundleFolder = new File(directory);
    File[] bundleFilesList = bundleFolder.listFiles((dir, name) -> name.endsWith(".jar"));

    List<Bundle> installedBundles = new ArrayList<>();
    logger.info("Installing {} bundles in {}.", bundleFilesList.length, directory);
    for(File bundleFile : bundleFilesList) {
        logger.info("Installing {}", bundleFile.getName());
        try {
            installedBundles.add(context.installBundle("file:" + directory + bundleFile.getName()));
        } catch (BundleException e) {
            logger.error("Error while installing bundle {}{}", directory, bundleFile.getName(), e);
        }
    }

    for(Bundle bundle : installedBundles) {
        try {
            bundle.start();
        } catch (BundleException e) {
            logger.error("Error while starting bundle {}{}", directory, bundle.getSymbolicName(), e);
        }
    }
}


text:
Q: Relative width of rotated element I have an anchor (a) that has height: 40% and width: 20px. Its child element is a span to which I have applied transform: rotate(90deg) and transform-origin: left bottom.
I want the dimensions of the span to be the same as the parent, so I specify width: 100%. However, when rotated the span loses those dimensions. I can specify the text width with a hardcoded pixel value, but I want this span to be flexible, relative to the available screen size.
Fiddle demonstrating this issue
I know I can set the width of the span with JavaScript, but I want to avoid having to do so if at all possible. Does anyone know of a CSS-only solution to this?

A: Now define white-space: nowrap;
.pulltab > a > span {white-space: nowrap;}

Demo


text:
Q: German sharp S or eszett How can I write the German sharp S or 'eszett' (ß) in a question here?
In LaTeX it is written like {\ss} but that doesn't seem to work.

A: I have my keyboard set for US-International, rather than the default EN-US layout. On a US-INT keyboard, AltGr-s produces the ß. Note that the US-INT keyboard does not support the recently-defined uppercase ß (ẞ); for that, I had to hack together an AutoHotKey script.
(AltGr is the right Alt key.)

A: Stack Exchange has full Unicode support. This means you just need to type the character into the post body, or copy it from somewhere.
In Windows, you can use Alt + Num2 + Num2 + Num5, or using the character map.
In macOS, you can long press S to get it.

A: You can use the HTML entity: ß produces ß. Or just copy it over from other posts, since it's part of Unicode.


text:
Q: How to list files containing the range of numbers with GLOBBING? So for example with the range of numbers 10-20 its easy. I would use:
ls *[12][0-9]*

But what if the range was for example 00-32 ?

A: ls *{00..32}

But be aware, that this will result in 33 separate executions of ls, not 1 single execution. When you have for example only one file ending with 31, this file will be listed, but you will get 32 times the error ls: cannot access your_file00: No such file or directory.


text:
Q: How do I customize TAIGA's backlog graph? I am new to Taiga and have started using it on a project with a small team.  The backlog page has a header that says 'CUSTOMIZE YOUR BACKLOG GRAPH' and provides a link to Admin. However, I can not find anything under admin menu that would allow me to define or customize the graph. How do I update this section?

A: Very simple. Go to
Admin > Project > Modules > Backlog
Now you may configure the number of "Expected number of sprints" and  "Expected total of story points". If you dont know how many story point you will may put 0. You may change these values any time you want. After writing the numbers, just click on the save disk, on the right side.
Now reload, and go to backlog tab.


text:
Q: Slow performance when deleting on a self-joined table I've got a MySQL server that receives data from a game via an AJAX handler, and occasionally despite best efforts rows will somehow end up duplicating on-the-fly during the INSERT. I've got a solution that removes them immediately after the INSERTs are done and it was working fine when I only had a few thousand rows in the DB. Now I've got a million rows and during peak time this query takes about 40 seconds to run, and they'll get stacked up as it gets run after every game (peak times right now I get about 3 or 4 new games a minute), and the server doesn't answer any other queries while the delete is running.
$removedupes = query("DELETE g1 FROM games g1, games g2 WHERE g1.name=g2.name AND g1.gameno=g2.gameno AND g1.score=g2.score AND g1.id > g2.id AND g1.gameno=".$lastgame);

When I EXPLAIN the query it appears that no keys or indices are being used and it's having to check all million+ rows when it only needs to be looking at about 30 at the most.
EXPLAIN DELETE g1 FROM games g1, games g2 WHERE g1.name=g2.name AND g1.gameno=g2.gameno AND g1.score=g2.score AND g1.id > g2.id AND g1.gameno=101010
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE g1 ALL PRIMARY,name,name_2,cleanup NULL NULL NULL 1045764 Using where
1 SIMPLE g2 ref PRIMARY,name,name_2,cleanup cleanup 53 dbname.g1.name,const,dbname.g1.score 1 Using where; Using index

I've tried doing a select first, but even with forcing new indices to be used the performance is very bad during load. Off-peak times it takes 2-8 seconds to run. I've tried my hand at building a query to put that game into a temp table but I haven't found the right syntax yet. Any help would be appreciated.


text:
Q: My site load is very high. JS files are slowing it down I have a site that was very slow with load time approx. >15s. I read a lot of articles and optimized it and brought it down to 5-6 sec. But, My JS files loading are a real pain. They are getting blocked and increasing site load time.
Image of the waterfall from GTMetrix.


text:
Q: Can't include something from folder in root I'm unable to include files in a folder from the root. Here's something similar to what I'm trying to do.
Root:
 -folder1
   --folder2 (I need to include stuff in this folder)

 -otherfolder1
   --otherfolder2
     --otherfolder3 (This is my website folder)

This is what I have for my path so far which doesn't work.
define("FOLDER2_ROOT", "/folder1/folder2/");

A:
../ is used to go up one folder.

So according to your situation, you need the following code:
include("../../../folder1/folder2/abc.php");


text:
Q: jquery stop sliding delay if button is pressed more than once I know there is a way to stop the code from looping everytime you call an animation in jquery but for the life of me i can not find it!
How can i turn this code below in order for it not to keep looping if i push the button more than one?
$('#message-box').slideDown('slow').delay(10000).slideUp('slow');

If i hit the button that calls that more than once then it slides down, displays for 10 secs, slides back up then back down again.
What i would like it to do is if its already down and i hit the button then NOT to display it again. Or if nothing else, slide up the current message and slide down the new one right then and there without the delay between.
Any help would be great!
David

A: This will check to see if the message element is already being animated before running the function.
$('#btn').click(function () {
    if (!$('#message-box').is(':animated')) {
        $('#message-box').slideDown('slow').delay(10000).slideUp('slow')
    }
});

A: Simplest method if you only want event to occur once is one()
http://api.jquery.com/one/
$('#myButton').one('click', function(){
    $('#message-box').slideDown('slow').delay(10000).slideUp('slow');
})

A: check out " .one "
http://api.jquery.com/one/

A: You could try this:
$('#message-box').stop(true,true).slideDown('slow').delay(10000).slideUp('slow');

If there is a down-delay-up animation already in progress for the element then .stop(true) will stop that, clear the element's animation queue, and only then requeue the down-delay-up thing.
Demo: http://jsfiddle.net/bSeE7/

A: $('#message-box').slideDown('slow', function(){
$('#message-box').delay(10000).slideUp('slow');
})

A: You need a conditional to prevent it from being activated when it's running. The callback function will reset the boolean to allow you to then click on it again when the animation is finished.
var animationRunning = false;

if(!animationRunning) {
    $('#message-box').slideDown('slow')
                     .delay(10000)
                     .slideUp('slow', function() { animationRunning = false; });

    animationRunning = true;
}

A: Using .stop() is the obvious answer but when used with .slideUp() a small fraction of height is still displayed whenever .stop() is invoked. You could use .stop(true,true) but that will cause the slide animation to 'jumptoend' causing jerky animation. Not ideal.
Consider using .animate() instead of .slideUp()
Fiddle
$('button').click(function() {
    $('#message-box').stop(true).animate({height: 100}).delay(1000).animate({height: 0});
});


text:
Q: Why is ListView not scrolling consistently? I am currently working on a ListView that contains around 80 to 100 items (TextViews). I don't think it is too much content, but when i scroll (with fingers) the ListView is bobbing or laging. However, when I use the "fast-scroll-button" - that thing on the right of the ListView - the scrolling appears very consistent and smooth.
Did anyone have the same problem? I tested the ListView on my HTC Sensation.
Here is my ListView code:
<ListView
     android:id="@+id/list_view"
     android:layout_height="match_parent"
     android:layout_width="match_parent"
     android:scrollingCache="true">

</ListView>

And the Java code:
adptr = new ArrayAdapter<String>(iF, R.layout.list_item, showing) {

        @Override
        public View getView(int position, View convertView, ViewGroup grp) {

            LinearLayout lin = new LinearLayout(this.getContext());
            lin.setOrientation(LinearLayout.HORIZONTAL);

            // Icon
            ImageView v = new ImageView(this.getContext());
            // v.setBackgroundDrawable(iF.getResources().getDrawable(R.drawable.cube_icon));

            // Text
            TextView txt = new TextView(this.getContext());
            txt.setTextSize(Float.valueOf(prefs.getString("pref_txtSize", "12")));
            txt.setPadding(10, 10, 10, 10);
            txt.setText(this.getItem(position));
            txt.setTextColor(getLineColor(position));

            // Shortcut
            LinearLayout shortLin = new LinearLayout(this.getContext());
            shortLin.setGravity(Gravity.RIGHT);

            LayoutParams par = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
            shortLin.setLayoutParams(par);

            TextView s = new TextView(this.getContext());
            s.setTextSize(Float.valueOf(prefs.getString("pref_txtSize", "12")));
            s.setWidth(iF.getResources().getDimensionPixelSize(R.dimen.shortcutWidth));
            s.setPadding(10, 10, 10, 10);

            s.setText(getShortcut(position));

            shortLin.addView(s);

            // Return
            txt.invalidate();
            v.invalidate();
            s.invalidate();

            lin.addView(v);
            lin.addView(txt);
            lin.addView(shortLin);

            return lin;
        }
    };

As you can see, I made a customized ListView. The ArrayAdapter will be added in a different method (not shown here).
Thanks in advance
Adrian

A: Do you remember about cache?
    public View getView(int position, View convertView, ViewGroup parent) {

    View view = convertView;
    ViewHolder holder;

    if (view == null) {

        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater
                .inflate(R.layout.list_view_home_item, parent, false);

        holder = new ViewHolder();
        holder.title = (TextView) view
                .findViewById(R.id.textView);

        holder.title.setText("blah");
        view.setTag(holder);
    } else {
        holder = (ViewHolder) view.getTag();
    }

    return view;

and
    static class ViewHolder {
    TextView title;
}

?

A: You're creating every View element for your list dynamically every time you pull a view. That's possibly the most inefficient mechanism ever :).
As a first step, see if you can layout your view in XML. Makes things easier to manage.
Even if you don't do that, use the convertView parameter. Its sole reason for existence is to keep you from having to reallocate views if possible. If convertView is non-null, it has all the views you created in a previous invocation of getView(). All you have to do is fill in the appropriate information in each view (essentially, in your case, the setText() calls). If convertView is null, create your views.
Also, don't invalidate(). At a minimum, without the XML layout, here's a rewritten version that should be a bit faster.
@Override
public View getView(int position, View convertView, ViewGroup grp) {
    if(convertView == null) {
        LinearLayout lin = new LinearLayout(this.getContext());
        lin.setOrientation(LinearLayout.HORIZONTAL);

        // Icon
        ImageView v = new ImageView(this.getContext());
        // v.setBackgroundDrawable(iF.getResources().getDrawable(R.drawable.cube_icon));

        // Text
        TextView txt = new TextView(this.getContext());
        txt.setId(1);
        txt.setTextSize(Float.valueOf(prefs.getString("pref_txtSize", "12")));
        txt.setPadding(10, 10, 10, 10);
        txt.setTextColor(getLineColor(position));

        // Shortcut
        LinearLayout shortLin = new LinearLayout(this.getContext());
        shortLin.setGravity(Gravity.RIGHT);

        LayoutParams par = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        shortLin.setLayoutParams(par);

        TextView s = new TextView(this.getContext());
        s.setId(2);
        s.setTextSize(Float.valueOf(prefs.getString("pref_txtSize", "12")));
        s.setWidth(iF.getResources().getDimensionPixelSize(R.dimen.shortcutWidth));
        s.setPadding(10, 10, 10, 10);

        shortLin.addView(s);
        lin.addView(v);
        lin.addView(txt);
        lin.addView(shortLin);
    }

    TextView txt = (TextView)convertView.findViewById(1);
    txt.setText(this.getItem(position));
    TextView txt = (TextView)convertView.findViewById(2);
    txt.setText(getShortcut(position));

    return lin;
}

Again, not the best way or a best practice, but this should work.

A: Finally, I came up with this solution:
@Override
        public View getView(int position, View convertView, ViewGroup parent) {

            View view = convertView;
            ViewHolder holder;

            if (view == null) {

                LayoutInflater inflater = (LayoutInflater) iF.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = inflater.inflate(R.layout.list_item, parent, false);

                holder = new ViewHolder();
                holder.title = (TextView) view.findViewById(R.id.item_text);
                holder.shortcut = (TextView) view.findViewById(R.id.item_short);

                holder.title.setId(1);
                holder.shortcut.setId(2);

                holder.title.setText(getItem((position)));
                holder.shortcut.setText(getShortcut(position));

                holder.title.setTextSize(Float.valueOf(prefs.getString("pref_txtSize", "12")));
                holder.shortcut.setTextSize(Float.valueOf(prefs.getString("prefs_txtSize", "12")));

                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();

                TextView title = (TextView) convertView.findViewById(1);
                title.setText(getItem(position));

                TextView shortcut = (TextView) convertView.findViewById(2);
                shortcut.setText(getShortcut(position));
            }

            return view;
        }

I am really happy right now that it worked. It is 00:33, so I think I go to bed now. Enough work for today (yesterday :)
Thanks for all the support


text:
Q: A function in the $L^2$ closure of the set of smooth, harmonic functions on the closed unit disk is smooth and has a harmonic representative. This is is a homework problem I'm having trouble understanding. I am given the set $$Y=\{u\in \mathbb{C}^{\infty}(\bar{D_1})| \triangle u=0\}$$ and its closure with respect to the $L^2$ norm, $\bar{Y}$. I am asked to show that each $v\in \bar{Y}$ has a representative that is smooth on the interior of $D_1$ and that $\triangle v=0$ on the interior of $D_1$. Further, I am asked to describe the radial functions (functions of $r=\sqrt{x^2+y^2}$) orthogonal to $\bar{Y}$.
I have been advised to use the Poison kernel on the disk, although it's been a couple years since I've worked with that formula. $\bar{Y}$ is $Y$ together with its limit points in the $L^2$ norm, so it seems as if I should just consider $v$ that are limit points of sequences $\{u_n\}$ in $Y$. Also, from what I remember of measure theory, representatives of $v$ differ from it on a set of measure zero. At any rate, since this is a homework problem, could someone point me in the right direction?


text:
Q: TreeSets and removing specific unnamed Objects So I'm writing a program for an assignment where I store Patients into a TreeSet. The problemn I'm having is I have to implement a method to discharge a specefic patient from the TreeSet.
for(int i = 0; i < 10 ; i++){
        Random ag = new Random();
        int age = ag.nextInt(99) + 1;
        Names randomname = Names.getRandom();
        String name = randomname.name();
        String sex;
        if(Math.random() > 0.5)sex = "female";
        else sex = "male";
        Random sn = new Random();
        int serial = sn.nextInt(10000) + 1;
        Address randomAddress = Address.getRandom();
        String address = randomAddress.name();
        Hospital.admitPatient(new Patient(age, name, sex, serial, Birthday.produceBirthday(), address));
    }

So Thats how I am looping to get the Patients info and stats for the Patient Object. The admit patient method adds them to the TreeSet.
public static void admitPatient(Patient obj){
    if(numofPatients < maxPatients){
        patientList1.add(obj);
    }
}

The Problem I'm having is withbthe Discharge patient method. Where I don't know what to put in the method
public static void dischargePatient(What do i put here in the driver when i call this method?){
    patientList1.remove(w/e i put up there);

}
Since I didn't name the Objects of patients when creating them but just inserted them straight into the TreeSet I'm not sure exactly how to call them when i call the discharge patient method.

A: As you usually want to work with selected objects (patients) and not the whole list, you need a way to identify them somehow (for example by name or ID).
Since add and remove are similar, your dischargePatient method will be similar as well. Try
public static void dischargePatient(Patient patient) {
     patientList1.remove(patient);
}

To retrieve a patient with a certain ID, you may iterate through your set and return it:
public Patient getPatientByID(String id) {
    for (Patient patient : patientList1) {
        if (patient.getID().equals(id)) {
            return patient;
        }
    }
}

To remove a patient with ID "1234abc", you could do the following:
dischargePatient(getPatientByID("1234abc"));

Using this pattern, you rebuild the functionality of the map datastructure. Thus it might be better to use a Map (e.g. HashMap<>). Code will be reduced to operations like:
Map<String, Patient> patients = new HashMap<>();
patients.put("1234abc", patient1);
patients.remove("1234abc");

Full code for your example:
public static void admitPatient(Patient patient) {
    if(numofPatients < maxPatients){
        patients.put(patient.getID(), patient);
    }
}

public static void dischargePatient(String id) {
    patients.remove(id);
}


text:
Q: Control order of execution of parallel.foreach tasks I have a list of table names (student, exam, school).
I use a Parallel.ForEach loop to iterate over the table names and do processing for each table, with MaxDegreeOfParallelism = 8.
My problem is that my Parallel.ForEach doesn't always engage in work stealing. For example, when two tables are left to process, they may be processed one after another instead of in parallel. I'm trying to improve performance and increase throughput.
I tried to do this by creating a custom TaskScheduler, however, for my implementation I need a sorted list of tasks with the easiest tasks ordered first, so that they aren't held-up by longer-running tables.  I can't seem to do this by sorting the list passed to Parallel.ForEach (List< string >) because the tasks are Enqueued by the TaskScheduler out-of-order. Therefore, I need a way to sort a list of tasks inside my CustomTaskScheduler, which is based on https://psycodedeveloper.wordpress.com/2013/06/28/a-custom-taskscheduler-in-c/
How can I control the order in which tasks are passed by the Parallel.ForEach to the TaskScheduler to be enqueued?

A: The Parallel.ForEach method employs two different partitioning strategies depending on the type of the source. If the source is an array or a List, it is partitioned statically (upfront). If the source is an honest-to-goodness¹ IEnumerable, it is partitioned dynamically (on the go). The dynamic partitioning has the desirable behavior of work-stealing, but has more overhead. In your case the overhead is not important, because the granularity of your workload is very low.
To ensure that the partitioning is dynamic, the easiest way is to wrap your source with the Partitioner.Create method:
string[] tableNames;
Parallel.ForEach(Partitioner.Create(tableNames), tableName =>
{
    // Process table
});

¹ (The expression is borrowed from a comment in the source code)

A: I would recommend looking up partitioners. Managing threads on a Parallel loop has some overhead, so there is some built-in logic to try to keep this overhead small while still balancing the work across all cores propperly. This is done by dividing the list into chunks and adjusting the chunk-size to hit some sweet-spot.
I would guess that ordering the tasks as as smallest first will work against the paritioners balancing. I would try ordering the work largest first if balancing is the goal. Another thing I would try is to partition the work items with some constant chunk-size and see if that helps. Or perhaps even write your own partitioner.
I'm not sure it is a great idea to try to enforce some execution order. Since you do not control the OS scheduler there cannot be any guaranteed ordering. And even if you can make it more ordered, it would probably be at the cost of throughput.
Also, if you are spending lots of time optimizing the parallelization, are you sure the rest of the code is optimized?


text:
Q: How to specify default Application Pool in ASP.NET MVC Project? In my ASP.NET MVC project I have added a parameters.xml file that looks like:
<?xml version="1.0" encoding="utf-8" ?>
<parameters>
  <parameter name="Application Pool" description="Application Pool Name" defaultValue="PreferredPool">
    <parameterEntry kind="DeploymentObjectAttribute"
                    scope="appHostConfig"
                    match="application/@applicationPool"/>
  </parameter>
</parameters>

Then I go ahead and build the deployment package:
MSBuild.exe myproject.csproj /t:Package /p:PackageLocation="C:\packages\myproject.zip"

And then I invoke the batch script generated (myproject.deploy.cmd) and deploy the app to a local IIS 7 server. The problem is, it is always the Default Application Pool that is assigned to the app instead of the PreferredPool as specified in parameters.xml.
What did I do wrong?

A: Change your parameterEntry's scope to "application":
<parameterEntry kind="DeploymentObjectAttribute"
                scope="application"
                 match="application/@applicationPool"/>


text:
Q: PHP - strpos if it contains anything inside [ ] I have the following which works great, but now what I want to do is if a user types [MAP] then I want to get the word MAP
I also want allow users to send things like [MAP = array("LOCATION"=>"Melbourne Australia")]
and for the PHP to make map a array so I can then send it to a function later on
I currently do the following
$map = strpos($stringtocheck, "[MAP]");

But the issue here, is if we have a number of [] with different insides like [BOLD], [INSERT] etc then it wont find it and put it in its own $
and also it means we need to know what the array is field with or anything like that

A: A simple regex will pull info out of square brackets:
$s = 'Yo be [diggin] [my leet] scriptzors!';
$matches = null;
preg_match_all('/\[(.*?)\]/', $s, $matches);
var_dump($matches[1]);

Result:
array(2) {
  [0]=>
  string(6) "diggin"
  [1]=>
  string(7) "my leet"
}

Example: http://codepad.viper-7.com/erBpuB


text:
Q: Separable metric spaces? Two questions: Is the property of being separable topological, and is the continuous image of a separable metric space separable? I have intuition that the answer to the first question is true and the answer to the second question is false, but am confused as to how to begin the proofs. Any guidance or hints would be appreciated. Thanks!

A: Both are true. If $X$ is separable, with countable dense subset $D$, and $f:X\to Y$ is a continuous surjection, then $f[D]$ is a countable dense subset of $Y$. Let $U$ be any non-empty open set in $Y$; then $f^{-1}[U]$ is a non-empty open set in $X$, so there is an $x\in f^{-1}[U]\cap D$, and clearly $f(x)\in U\cap f[D]$.


text:
Q: SqlException Timeout expired into Dot net core 2.2 My website build with 4.1 nopcommerce platform. now I have update all the dll of this website to the latest. now it working fine in normal days but in some of time I get an error log regarding "SqlException: Timeout expired". now how to resolve this issue. I have reviewed many posts and many think changes i have made to resolve this issue but I can't find any solution.
Log detail as below
System.Exception: Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. --->
System.Data.SqlClient.SqlException: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
The statement has been terminated. ---> System.ComponentModel.Win32Exception: The wait operation timed out
   --- End of inner exception stack trace ---
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
   at System.Data.SqlClient.SqlDataReader.get_MetaData()
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite, String method)
   at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
   at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues)
   at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
   --- End of inner exception stack trace ---
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(DbContext _, ValueTuple`2 parameters)
   at Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.ExecuteImplementation[TState,TResult](Func`3 operation, Func`3 verifySucceeded, TState state)
   at Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable`1 commandBatches, IRelationalConnection connection)
   at Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IReadOnlyList`1 entries)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList`1 entriesToSave)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
   at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
   at Microsoft.EntityFrameworkCore.DbContext.SaveChanges()
   at Nop.Data.EfRepository`1.Insert(TEntity entity) in C:\\Libraries\Nop.Data\EfRepository.cs:line 100 ---> Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
The statement has been terminated. ---> System.ComponentModel.Win32Exception: The wait operation timed out
   --- End of inner exception stack trace ---
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
   at System.Data.SqlClient.SqlDataReader.get_MetaData()
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite, String method)
   at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
   at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues)
   at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
   --- End of inner exception stack trace ---
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(DbContext _, ValueTuple`2 parameters)
   at Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.ExecuteImplementation[TState,TResult](Func`3 operation, Func`3 verifySucceeded, TState state)
   at Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable`1 commandBatches, IRelationalConnection connection)
   at Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IReadOnlyList`1 entries)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList`1 entriesToSave)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
   at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
   at Microsoft.EntityFrameworkCore.DbContext.SaveChanges()
   at Nop.Data.EfRepository`1.Insert(TEntity entity) in C:\\Libraries\Nop.Data\EfRepository.cs:line 100
   --- End of inner exception stack trace ---
   at Nop.Data.EfRepository`1.Insert(TEntity entity) in C:\\Libraries\Nop.Data\EfRepository.cs:line 105
   at Nop.Services.Customers.CustomerService.InsertGuestCustomer(Int32 storeId) in C:\\Libraries\Nop.Services\Customers\CustomerService.cs:line 446
   at Nop.Web.Framework.WebWorkContext.get_CurrentCustomer() in C:\\Presentation\Nop.Web.Framework\WebWorkContext.cs:line 250
   at Nop.Web.Framework.WebWorkContext.get_WorkingLanguage() in C:\\Presentation\Nop.Web.Framework\WebWorkContext.cs:line 360
   at Nop.Web.Framework.Globalization.CultureMiddleware.SetWorkingCulture(IWebHelper webHelper, IWorkContext workContext) in C:\\Presentation\Nop.Web.Framework\Globalization\CultureMiddleware.cs:line 62
   at Nop.Web.Framework.Globalization.CultureMiddleware.Invoke(HttpContext context, IWebHelper webHelper, IWorkContext workContext) in C:\\Presentation\Nop.Web.Framework\Globalization\CultureMiddleware.cs:line 82
   at lambda_method(Closure , Object , HttpContext , IServiceProvider )
   at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.<>c__DisplayClass4_1.<UseMiddleware>b__2(HttpContext context)
   at Nop.Services.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) in C:\\Libraries\Nop.Services\Authentication\AuthenticationMiddleware.cs:line 79
   at Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
   at Nop.Core.Http.InstallUrlMiddleware.Invoke(HttpContext context, IWebHelper webHelper) in C:\\Libraries\Nop.Core\Http\InstallUrlMiddleware.cs:line 51
   at Nop.Core.Http.KeepAliveMiddleware.Invoke(HttpContext context, IWebHelper webHelper) in C:\\Libraries\Nop.Core\Http\KeepAliveMiddleware.cs:line 50
   at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.ResponseCompression.ResponseCompressionMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.Invoke(HttpContext context)

A:
SqlException: Timeout expired

This error is very common in SQL Server, and when I take a look on your trace, seems you want to read data. If you want to fix this error, my answer is it can't be FIXED PERMANENTLY. Because? This exception depends on many factors such as Network (in case you deploy application and database in different servers), Workload when error occurs, how large data you read, etc.
In case you thought an old version is working better, so that a new version get a problem in handling Database Connection. I read that you use nopcommerce platform, that means it needs to be fixed somewhere in nopcommerce.
Then a good solution is tuning 1. Your query 2. Your database server, or if you aren't good in Database side, I suggest you apply Retry Pattern or breaking smaller data which you want to read.

A: This is a very common error.

*

*Any deadlock issues on executed queries ?

*Have you reached the number of opened connections which is usually limited to 300 - 600 ?
The database may return this error if the limit has been exceeded.


text:
Q: CFDataRef to NSData I am having trouble converting a CFDataRef into NSData whilst using ARC. I am using the __bridge_transfer OR __bridge cast but it is not working. Could anyone suggest me some other way of casting this two types.
I get the following error
Automatic Reference Counting Issue: Incompatible types casting 'CFDataRef *' (aka 'const struct __CFData **') to 'NSData *' with a __bridge cast

A: NSData *my_nsdata = (__bridge_transfer NSData*)my_cfdata; // -1 on the my_cfdata

or
NSData *my_nsdata = (__bridge NSData*)my_cfdata; // no adjustment of retain counts.

From my blog post here:
http://amattn.com/2011/12/07/arc_best_practices.html


text:
Q: Python requests.post certificate verify fails I have a python app that connects to a web page (wikis.xxx.yyy) via HTTPS to retrieve and parse data from it. I can browse to the web page given that the certificate chain required to do so is in the browser (my system uses Ubuntu 14.04 LTS).
$ python --version
Python 2.7.6

The call to connect:
data = requests.post(URL, data=payload)

is failing with the following error:
requests.exceptions.SSLError: [Errno bad handshake] [('SSL routines', 'SSL3_GET_SERVER_CERTIFICATE', 'certificate verify failed')]

I can't use verify=False given that if I do I get this error:
/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/connectionpool.py:768: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.org/en/latest/security.html InsecureRequestWarning)

I tried passing the certificate in the verify as a client side side certificate (http://docs.python-requests.org/en/latest/user/advanced/): data = requests.post(radio_status_URL, data=payload, verify="/home/user/.cert/foo.pem")
but it does not connect and actually does not return any errors.
Thinking that I needed to install the certificate chain into the trusted Ubuntu CA store I followed the instructions from: https://askubuntu.com/questions/73287/how-do-i-install-a-root-certificate
The foo.cert certificate that I added has the following format:
-----BEGIN CERTIFICATE-----
<....>
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
<....>
-----END CERTIFICATE-----

Using openssl I can see that the certificate chain is OK and that I can connect to wikis.xxx.yyy :-)
$ openssl s_client -CApath ~/.cert/ -connect wikis.xxx.yyy:443
CONNECTED(00000003)
depth=2 DC = local, DC = windows, CN = RIM Root CA MCA01YKF
verify return:1
depth=1 DC = net, DC = rim, CN = RIM Subordinate CA MCA03YKF
verify return:1
depth=0 C = CA, ST = Ontario, L = Waterloo, O = BlackBerry, OU = BTS Operations, CN = wikis.xxx.yyy, emailAddress = no-reply@xxx.yyy

verify return:1
---
Certificate chain
 0 s:/C=CA/ST=Ontario/L=Waterloo/O=BlackBerry/OU=BTS Operations/CN=wikis.xxx.yyy/emailAddress=no-reply@xxx.yyy
   i:/DC=net/DC=rim/CN=RIM Subordinate CA MCA03YKF
---
Server certificate
-----BEGIN CERTIFICATE-----
<...>
-----END CERTIFICATE-----
subject=/C=CA/ST=Ontario/L=Waterloo/O=BlackBerry/OU=BTS Operations/CN=wikis.xxx.yyy/emailAddress=no-reply@xxx.yyy
issuer=/DC=net/DC=rim/CN=RIM Subordinate CA MCA03YKF
---
No client certificate CA names sent
---
SSL handshake has read 1810 bytes and written 609 bytes
---
New, TLSv1/SSLv3, Cipher is RC4-SHA
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : RC4-SHA
    Session-ID: FFD3D3EAC3807427D2D5E5BB2D70F064E2BB14218A368676A3225FBC5E5F1078
    Session-ID-ctx:
    Master-Key: 930FBFB110BFC861E06C6A27DEBB15C2524A86F7EFC56693F4E52BA33F0AD236E5182169039909EC1BB3DE89C4C96B2B
    Key-Arg   : None
    PSK identity: None
    PSK identity hint: None
    SRP username: None
    Start Time: 1442413894
    Timeout   : 300 (sec)
    Verify return code: 0 (ok)

So it works and gives a ret code of 0. Unfortunately python fails to do the same and I have no clue how to connect :-(
How do I fix this?

A: From your last testing case it shows that wikis.xxx.yyy use TLSv1.2, however Requests module needs a little revise to use it.
Please refer to this post:
https://lukasa.co.uk/2013/01/Choosing_SSL_Version_In_Requests/
And there is a good plug-in to do that:
https://toolbelt.readthedocs.org/en/latest/user.html#ssladapter
BTW, if you have installed urllib3, the Requests will use it, but urllib3 doesn't support TLS v1.2 until now.


text:
Q: Performance with Julia. Looping through boolean data N = 100000
a = randbool(N)
b = randbool(N)

Here is my current code (the slow part of my code)
onefalse = a $ b
twofalses = !a & !b
sum(onefalse)
sum(twofalses)

Is there any way to improve this code? I am feeling like I am looping twice through a and through b. I tried with a for loop and if statements but it was way slower.
for i = 1:N
        if a[i]
            if b[i]

            else
                onefalse+=1
            end
        else
            if b[i]
                onefalse+=1
            else
                twofalses+=1
            end
        end
       end

A: First of all, a valid question is why is the for loop version slow. Its partly because randbool gives a BitArray, not a normal array. I decided to compare with Array{Bool} out of curiosity. I was able to speed it up a bit - I think you are probably at the limits of what is possible though. In particular, indexing into an Array{Bool} seems to be faster than BitArray, but operations on BitArrays like those done here are hard to beat.
function countfalse1(N, a, b)
    return sum(a $ b), sum(!a & !b)
end

function countfalse2(N, a, b)
    return N-sum(a), N-sum(a|b)
end

function countfalse3(N, a, b)
    onef, twof = 0, 0
    @inbounds for i = 1:N
        if a[i]
            if !b[i]
                onef += 1
            end
        else
            if b[i]
                onef += 1
            else
                twof += 1
            end
        end
   end
   return onef, twof
end

srand(1000)
N = 10000000
a = randbool(N)
b = randbool(N)
c = Bool[a[i] for i in 1:N]
d = Bool[b[i] for i in 1:N]

println("BitArray")
@show countfalse1(N, a, b)
@time countfalse1(N, a, b)
@time countfalse1(N, a, b)
@time countfalse1(N, a, b)

@show countfalse2(N, a, b)
@time countfalse2(N, a, b)
@time countfalse2(N, a, b)
@time countfalse2(N, a, b)

@show countfalse3(N, a, b)
@time countfalse3(N, a, b)
@time countfalse3(N, a, b)
@time countfalse3(N, a, b)

println("\nArray{Bool}")
@show countfalse1(N, c, d)
@time countfalse1(N, c, d)
@time countfalse1(N, c, d)
@time countfalse1(N, c, d)

@show countfalse2(N, c, d)
@time countfalse2(N, c, d)
@time countfalse2(N, c, d)
@time countfalse2(N, c, d)

@show countfalse3(N, c, d)
@time countfalse3(N, c, d)
@time countfalse3(N, c, d)
@time countfalse3(N, c, d)

gives
BitArray
countfalse1(N,a,b) => (5001756,2500026)
elapsed time: 0.004565573 seconds (5014328 bytes allocated)
elapsed time: 0.003607561 seconds (5000528 bytes allocated)
elapsed time: 0.013880181 seconds (5000528 bytes allocated, 83.83% gc time)
countfalse2(N,a,b) => (5003620,2500026)
elapsed time: 0.000784883 seconds (1250240 bytes allocated)
elapsed time: 0.000752576 seconds (1250240 bytes allocated)
elapsed time: 0.000758695 seconds (1250240 bytes allocated)
countfalse3(N,a,b) => (5001812,2500026)
elapsed time: 0.120491323 seconds (144 bytes allocated)
elapsed time: 0.118401949 seconds (144 bytes allocated)
elapsed time: 0.11807728 seconds (144 bytes allocated)

Array{Bool}
countfalse1(N,c,d) => (5001756,2500026)
elapsed time: 0.098838752 seconds (40000640 bytes allocated)
elapsed time: 0.112468122 seconds (40000640 bytes allocated, 10.64% gc time)
elapsed time: 0.11305269 seconds (40000640 bytes allocated, 10.22% gc time)
countfalse2(N,c,d) => (5003620,2500026)
elapsed time: 0.066169587 seconds (10000328 bytes allocated)
elapsed time: 0.084794646 seconds (10000328 bytes allocated, 17.78% gc time)
elapsed time: 0.067458965 seconds (10000328 bytes allocated)
countfalse3(N,c,d) => (5001812,2500026)
elapsed time: 0.066095076 seconds (144 bytes allocated)
elapsed time: 0.067585543 seconds (144 bytes allocated)
elapsed time: 0.06718118 seconds (144 bytes allocated)


text:
Q: Libre office configuration file bootstrap.ini corrupt I am using the libreoffice-convert package to convert a Word file into PDF. But when I try to convert I get this error. How do I fix this? I have installed LibreOffice 7.0.5

Console log is showing this error:
'C:\\Program Files\\LibreOffice\\program\\soffice.exe -env:UserInstallation=file://C:\\Users\\thesa\\AppData\\Local\\Temp\\soffice-10416-bQefydwUfs2F --headless --convert-to .pdf --outdir C:\\Users\\thesa\\AppData\\Local\\Temp\\libreofficeConvert_-10416-v46bO7ljGHRe C:\\Users\\thesa\\AppData\\Local\\Temp\\libreofficeConvert_-10416-v46bO7ljGHRe\\source'

A: Try this, you will probably need administrator rights.

*

*Locate and copy your orignal file, for example to "bootstrap.ini.org", in the same directory1.

*Open the file and replace its contents with this, which is a copy of my file:
[Bootstrap]
InstallMode=<installmode>
ProductKey=LibreOffice 7.0
UserInstallation=$SYSUSERCONFIG/LibreOffice/4

Another option is to re-install or repair the installation.
Note 1: This copy is just in case you need to revert.

A: //let data = await fs.promises.readFile(path_to_excel_file);
            let data = fs.readFileSync(path_to_excel_file)
            let pdfFile = await libreConvert(data, '.pdf', undefined);
            await fs.promises.writeFile(`${__dirname}/${docName}.pdf`, pdfFile);
            res.download(`${__dirname}/${docName}.pdf`)

It will works File.
Even If don't work then follow
below step:
Add this line 14 after instalDir
const installDir = tmp.dirSync({prefix: 'soffice', unsafeCleanup: true, ...tmpOptions});
const posixInstallDir = installDir.name.split(path.sep).join(path.posix.sep);

then Replace commant
let command = `${results.soffice}  --headless --convert-to ${format}`;

That's it..

A: -env:UserInstallation needs to be in URI form.
Note: also that you using file:// this should be file:/// see File URI scheme
-env:UserInstallation=file:///C:/Users/thesa/AppData/Local/Temp/soffice-10416-bQefydwUfs2F

>>> from pathlib import Path

>>> def get_posix(mypath) -> str:
>>>     p = Path(mypath)
>>>     return p.as_posix()

>>> tmp = "C:\\Users\\thesa\\AppData\\Local\\Temp\\soffice-10416-bQefydwUfs2F"

>>> get_posix(tmp)
'C:/Users/thesa/AppData/Local/Temp/soffice-10416-bQefydwUfs2F'

or
>>> from pathlib import Path

>>> tmp = Path("C:\\Users\\thesa\\AppData\\Local\\Temp\\soffice-10416-bQefydwUfs2F")
>>> tmp.as_uri()
'file:///C:/Users/thesa/AppData/Local/Temp/soffice-10416-bQefydwUfs2F'


text:
Q: how to serialize two model in django rest framework to get nested json data Hi everyone i have two model one is Name and 2nd is Role, i have join two or more model multiple time, but this time response is different, here i have share my model and expected response,please help me out.
models.py
class Name(BaseModel):
    first_name=models.CharField(max_length=255,null=True, blank=True)
    middle_name=models.CharField(max_length=255,null=True, blank=True)
    last_name=models.CharField(max_length=255,null=True, blank=True)

class Role(BaseModel):
    role=models.CharField(max_length=255,null=True, blank=True)
    name=models.ForeignKey(Name, models.CASCADE, null=True, blank=True)

serializer.py
class RoleSerializer(serializers.ModelSerializer):
    name=NameSerializer()
    class Meta:
        model = Role
        fields = "__all__"

Current Response
{
      "id": 1,
      "name": {
        "id": 1,
        "first_name": "thor",
        "middle_name": "",
        "last_name": ""

      }
    }

Expected Response
{
    "id": 1,
    "first_name": "thor",
    "middle_name": "",
    "last_name": ""
    "role": {
                    "id": 1,
                    "name": 1
                 }
 }

A: you did the work upside down. you should use name serializer as parent and use that.
class RoleSerializer(serializer.ModelSerializer):
    class Meta:
        model = Role
        fields= "__all__"

class NameSerializer(serializers.ModelSerializer):
    role=RoleSerializer()
    class Meta:
        model = Name
        fields = ['id','first_name','last_name','middle_name','role']


text:
Q: NEventStore CommonDomain: Why does EventStoreRepository.GetById open a new stream when an aggregate doesn't exist? Please explain the reasoning behind making EventStoreRepository.GetById create a new stream when an aggregate doesn't exist. This behavior appears to give GetById a dual responsibility which in my case could result in undesirable results. For example, my aggregates always implement a factory method for their creation so that their first event results in the setting of the aggregate's Id. If a command was handled prior to the existance of the aggregate it may succeed even though the aggregate doesn't have it's Id set or other state initialized (crash-n-burn with null reference exception is equally as likely).
I would much rather have GetById throw an exception if an aggregate doesn't exist to prevent premature creation and command handling.

A: That was a dumb design decision on my part.  I went back and forth on this one.  To be honest, I'm still back and forth on it.
The issue is that exceptions should really be used to indicate exceptional or unexpected scenarios.  The problem is that a stream not being found can be a common operation and even an expected operation in some regards.  I tinkered with the idea of throwing an exception, returning null, or returning an empty stream.
The way to determine if the aggregate is empty is to check the Revision property to see if it's zero.


text:
Q: Creating dynamic content in nancy self hosting I have a standard .NET framework application and I'm trying to make a web front end for it. I'm trying to have nancy render custom content, where i can pass in a model and then i can reference that in the page code, here is the code i am trying to use to do this:
public class Server : NancyModule
{
    readonly string main = "WebServer/Pages/main.html";

    public Server()
    {
        dynamic Model = new ExpandoObject();
        Model.username = "blah";
        Get("/", p => View[main, Model]);
    }
}

and then in the main.html file:
<h1>@username</h1>

I was expecting this to show me "blah" as a header, but it is just showing me @username instead.
How can i pass in variables and show them in the content?

A: Solved, needed to specify @Model.username instead of just @username


text:
Q: type mismatch in QT 5.3.0 compile on OSX10.10 I am using qt-everywhere-opensource-src-5.3.0, and trying to build it on OSX10.10.
After configure, when I run "make -j", I get the following error:

qcocoamenuloader.mm:177:22: error: cannot initialize a parameter of type
'NSInteger' (aka 'long') with an rvalue of type 'nullptr_t'
[item setTag:nil];

/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/usr/include/MacTypes.h:92:19: note:
expanded from macro 'nil'

#define nil nullptr

/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/System/Library/Frameworks/AppKit.framework/Headers/NSMenuItem.h:115:21: note:
passing argument to parameter 'tag' here
@property NSInteger tag;
1 error generated.
make[5]: *** [.obj/qcocoamenuloader.o] Error 1
make[4]: *** [sub-cocoa-make_first] Error 2
make[3]: *** [sub-platforms-make_first] Error 2
make[2]: *** [sub-plugins-make_first] Error 2
make[1]: *** [sub-src-make_first] Error 2
make: *** [module-qtbase-make_first] Error 2

To me it looks like the Mac SDK is defining nil to be nullptr and this caused a problem. Is there a way to work around this?
My configure call looks like this:

./configure -release -opensource -confirm-license -qt-harfbuzz -qt-zlib -qt-libpng -qt-libjpeg -no-pch -nomake examples -nomake tools -verbose -arch x86_64


text:
Q: Error by sending Konva. Collection by JQuery $.getJSON to Flask backend I want to send coordinates of all rectangles on layer to my backend, so I'm using var nodes = layer.find(".Rect"), and this works fine for printing it (console.log(nodes)), but when I send it by jquery $.getJSON it breakes with error of KONVA Uncaught TypeError: t is undefined konva konva.min.js:12/7 0.4

var nodes;
nodes = layer.find('.Rect')
$(function () {
    $('#save-template').bind('click', function () {
        $.getJSON('/_background_process', {
            squares: nodes,
        });
        return false;
    });
});
<button id="save-template">Save</button>

def background_process():
    try:
        squares = request.args.get('squares')
        return jsonify(result="0")
    except Exception as e:
        return str(e)

A: You may need to save your array into plain objects first:
const nodes = layer.find('.Rect');
const data = nodes.map(node => node.toObject());


text:
Q: Evaluate chaiscript file within a chaiscript file I'm starting to learn chaiscript and couldn't find this in the documentation.
I know there is API to evaluate a chaiscript file from C++ by calling ChaiScript::eval_file
But is it possible to do the same from a chaiscript file?

A: From within ChaiScript the use function is available, but the eval_file is not. use only loads a file if it has not already been loaded. eval_file loads the file regardless.
use("use.inc")

assert_equal("hello", greet())

// Include it a second time and see if there are any errors
use("use.inc")

assert_equal("hello", greet())

From here: https://github.com/ChaiScript/ChaiScript/blob/master/unittests/use.chai
Documentation of the C++ implementation of this function is here: http://chaiscript.com/docs/5/classchaiscript_1_1_chai_script.html#a9fc2eaf37274d09d1ee90ffd411e665c
I don't see any documentation specifying that it's also exposed to the ChaiScript runtime, but you can see many of the functions that are exposed here: https://github.com/ChaiScript/ChaiScript/blob/master/include/chaiscript/language/chaiscript_engine.hpp#L318


text:
Q: log message to text box from other class i have a multi line text box that i would like to log messages to from other classes
however i am getting a infinite loop in class creation.
What is the correct way of update form controls from outside the form class?
namespace Program
{

    public partial class MainForm : Form
    {
        engine connEngine = new engine();

        public MainForm()
        {
            InitializeComponent();

        }

        private void Start_Click(object sender, EventArgs e)
        {
            msgLog("Connection Start Clicked");

            if (connEngine.StartConnection(txtIPAddress.Text, 8002) == false)
            {
                msgLog("Connection Start Failed");
            }
            else
            {
                msgLog("Connection Start Success");
            }

        }

        public void msgLog(string message)
        {
            txtMessageLog.AppendText(message + Environment.NewLine);
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            msgLog("Form Load Success");
        }

    }

    class engine
    {
        MainForm _mainForm = new MainForm();

        public bool StartConnection(string txtIPAddress, int p)
        {
            _mainForm.msgLog("StartConnection started");
            //do something
            return true;
        }
    }
}

A: Your problem is that you're creating an instance of the engine in the main form and an instance of the MainForm in the engine - this creates the loop. Instead of creating new instance of the MainForm in the engine, please consider passing it as a parameter to the engine's constructor. Something like this (not tested):
class engine
{
private MainForm _mainForm = null;

engine(MainForm formInstance)
{
   _mainForm = formInstance;
}

public bool StartConnection(string txtIPAddress, int p)
{
    _mainForm.msgLog("StartConnection started");
    //do something
    return true;
}
}

And you could use it like this:
    public partial class MainForm : Form
    {
       private engine connEngine = null;

       public MainForm()
       {
          InitializeComponent();

          connEngine = new engine(this);
       }

...

Excuse my formatting...

A: Piotr solution is good. However, I prefer to have an Action delegate instead in the class that wants to log. So the engine class remains independant of anything else coming from the MainForm, and everything stays loosely coupled.
public partial class MainForm : Form
{
    engine connEngine = new engine();

    public MainForm()
    {
        InitializeComponent();

        connEngine.log = s => { msgLog(s); };
    }

    private void Start_Click(object sender, EventArgs e)
    {
        msgLog("Connection Start Clicked");

        if (connEngine.StartConnection(txtIPAddress.Text, 8002) == false)
        {
            msgLog("Connection Start Failed");
        }
        else
        {
            msgLog("Connection Start Success");
        }

    }

    void msgLog(string message)
    {
        txtMessageLog.AppendText(message + Environment.NewLine);
    }

    private void MainForm_Load(object sender, EventArgs e)
    {
        msgLog("Form Load Success");
    }

}

class engine
{
    internal Action<string> log;

    public bool StartConnection(string txtIPAddress, int p)
    {
        log("StartConnection started");
        //do something
        return true;
    }
}

A: you have a bit of recursion here.  MainForm instanciates an engine
public partial class MainForm : Form
{
    engine connEngine = new engine();

and engine instanciates a MainForm
class engine
{
    MainForm _mainForm = new MainForm();

What you end up with is an infinite cycle of instantiation.


text:
Q: I need help with this induction proof I need help prooving this with induction for n greater or equal to 2.
I know what induction is and how it works but I'm having a hard time with this one.

I know $
\prod_{k=1}^{n+1} =
(\prod_{k=1}^{n}\frac {2k-1}{2k})*\frac {2(n+1)-1}{2(n+1)}$
Then i can replace $\prod_{k=1}^{n}\frac {2k-1}{2k} $ with $\frac {1}{n+1}$ since i know it's smaller thanks to assuming the induction property is true.
Wich gives me $\frac {2(n+1)-1}{2(n+1)^2}$ and i need to show this is bigger than $\frac {1}{n+2}$.
This is when I get stuck since I don't know how to do this.
Thank you for your help ! Also i'm not sure if I took the right path.

A: Let $$P(n) = \prod_{k=1}^n \frac{2k-1}{2k}. \tag{1}$$  Then $$P(n+1) = \frac{2(n+1)-1}{2(n+1)} P(n) = \frac{2n+1}{2n+2} P(n). \tag{2}$$
So if the induction hypothesis holds, then
$$P(n+1) > \frac{2n+1}{2n+2} \frac{1}{n+1}, \tag{3}$$
and we wish to establish that $$\frac{2n+1}{(2n+2)(n+1)} > \frac{1}{n+2}. \tag{4}$$  Is inequality $(4)$ true?  Well, if we suppose for the time being that it is true, then it would imply $$(2n+1)(n+2) > (2n+2)(n+1)$$ or $$2n^2 + 5n + 2 > 2n^2 + 4n + 2,$$ which is satisfied when $n > 0$.  So it does seem to hold.  What we can then do is use this logic in reverse to formally establish $(4)$:  We write
$$\frac{2n+1}{(2n+2)(n+1)} = \frac{2n+1}{2n^2 + 4n + 2} > \frac{2n+1}{2n^2 + 5n + 2} = \frac{2n+1}{(2n+1)(n+2)} = \frac{1}{n+2}, \tag{5}$$ and this combined with $(3)$ completes the inductive step; i.e., if $P(n) > 1/(n+1)$, then $P(n+1) > 1/(n+2)$.


text:
Q: How to append json array using jq+shell in a loop? I can create a json object with an array using jq like this
 echo '{"input":{"names":[]}}' |  jq --arg val "alice" '.input.names[0] += $val'| jq --arg val "bob" '.input.names[1] += $val'
which gives
{
  "input": {
    "names": [
      "alice",
      "bob"
    ]
  }
}

Now I want to recreate this in a shell script where "names" come from a shell array
#!/bin/sh

names=( alice bob )

ITER=0
for i in "${names[@]}"
do
    echo '{"input":{"names":[]}}' |  jq --arg val "$i" '.input.names[$ITER] += $val'
    echo ${I} ${ITER}
    ITER=$(expr $ITER + 1)
done

but I run into
jq: error: $ITER is not defined at <top-level>, line 1:
.input.names[$ITER] += $val
jq: 1 compile error
0
jq: error: $ITER is not defined at <top-level>, line 1:
.input.names[$ITER] += $val
jq: 1 compile error
1

A: You could get rid of the shell loop and use one jq call:
names=( alice bob )
jq -n --arg names "${names[*]}" '{"input": {"names": ($names / " ") } }'

or
names=( alice bob )
printf '%s\0' "${names[@]}" |
jq -sR '(. / "\u0000") as $names | { "input": { "names": $names } }'

A: You don't capture the output of an iteration step, so you lose the output from the jq call and start all over again in the next iteration step.
Here's a bash solution which captures the output using $(...) and provides it for the next using <<<. (Note that there are better ways to solve this problem, e.g. without looping but by proving jq all elements to be added at once.)
json='{"input":{"names":[]}}'

for i in alice bob
do json="$(jq --arg val "$i" '.input.names += [$val]' <<< "$json")"
done

echo "$json"

{
  "input": {
    "names": [
      "alice",
      "bob"
    ]
  }
}


text:
Q: How can I call functions from module patterns from an event function I am experimenting with the Javascript module pattern and the html5 canvas by making a simple html5 based game and have run into my first obstacle. I am listening for a mousemove event over a canvas.
init: function () {
    var gameCanvas = document.getElementById("gameCanvas");
    gameCanvas.addEventListener("mousemove", this.redrawAvatar);
}

What I'm doing is letting my avatar follow the movement of the mousepointer over the canvas.
The problem then is that I have several functions in my module which I wish to call from inside the redrawAvatar function, like so:
redrawAvatar: function (mouseEvent) {
    var gameCanvas = document.getElementById("gameCanvas"),
    avatarCoord = {x: mouseEvent.offsetX, y: mouseEvent.offsetY},
    enemyCoord = {x: 100, y: 100};

    this.clear(gameCanvas);
    this.drawAvatar(avatarCoord);
    this.drawEnemy(enemyCoord);

    if (that.isCollision({coord: avatarCoord, size: 30}, {coord: enemyCoord, size: 30})) {
       alert("Avatar died, collided with enemy");
    }
}

While inside redrawAvatar the this object is not my module anymore but is instead the source of the event (the canvas in this case).
Here is the essence of my module:
var MyGame = (function () {

    var Game = {

        draw: function (image, coord) {},

        drawAvatar: function (coord) {},

        clear: function (canvas) { canvas.width = canvas.width + 1 - 1;},

        drawEnemy: function (xPos, yPos) {},

        isCollision: function (a, b) {},

        redrawAvatar: function (mouseEvent) {
            var gameCanvas = document.getElementById("gameCanvas"),
                avatarCoord = {x: mouseEvent.offsetX, y: mouseEvent.offsetY},
                enemyCoord = {x: 100, y: 100};

            this.clear(gameCanvas);
            this.drawAvatar(avatarCoord);
            this.drawEnemy(enemyCoord);
            if (that.isCollision({coord: avatarCoord, size: 30}, {coord: enemyCoord, size: 30})) {
                alert("Avatar died, collided with enemy");
            }
        },

        init: function () {
            var gameCanvas = document.getElementById("gameCanvas");
            gameCanvas.addEventListener("mousemove", this.redrawAvatar);
        }
    };

    (function () {
        var that = Game;
        that.init();
    }());

}());

How do I get to the functions in my module which I would like to call?

A: You can use bind to use the current context (in your case the game module) in the function as opposed to the event's context.
gameCanvas.addEventListener("mousemove", this.redrawAvatar.bind(this));

Here is a basic demo reproducing the binding effect. It uses a click event.

var MyGame = (function () {
        var Game = {
            scoped: 5,
            redrawAvatar: function (mouseEvent) {
             alert(this.scoped);
            },

            init: function () {
                var gameCanvas = document.getElementById("d");
                gameCanvas.addEventListener("click", this.redrawAvatar.bind(this));
            }
        };
        (function () {
            var that = Game;
            that.init();
        }());
    }());

Basic element for click handler (click for demo)

Run code snippet or jsFiddle Demo


text:
Q: WordPress "Featured Image" Functionality Broken IIS7 Install We have WordPress 3.4.2 installed on a Windows Server 2003 and IIS 7 box. Moving to a x-NIX environment is not a possibility.
We have had an outside contractor come in and get MOST everything working, but there is one last problem that he has completely given up on.
Anything that tries to use the "Featured Image" functionality is broken. This includes Themes that use the "Featured Image" functionality to upload a header image, and the image thumbnails for post excerpts.
Images upload fine, but you cannot select USE AS FEATURED IMAGE when editing a post, page, or anywhere else for that matter.
We have tested with several current Themes and it doesn't seem to be Theme specific in any way.
If this were on a linux box, I would expect it to be a folder permissions issue, but I don't know where to begin troubleshooting in this IIS environment.
Any help would be greatly appreciated. If I can provide any further info, please let me know.
AK

A: I ran into the same issue. After an unbelievably annoying round of troubleshooting, I found that I did not have the graphics library extension enabled on my server. I had to uncomment the following line in my php.ini file:
extension=php_gd2.dll
Once I made that change, I restarted IIS and all featured images began displaying properly. Hope this helps!


text:
Q: Generating random passwords with shell on server deployment I'm trying to generate random and secure passwords to my various configuration files and settings on the fly when I run my automated deployment script. I want them to be generated, shown to the user, used as part of the deployment and then discarded.
This is what I was going with:
# FUNCTION TO GENERATE A RANDOM STRING
function randpass() {
  [ "$2" == "0" ] && CHAR="[:alnum:]" || CHAR="[:graph:]"
    cat /dev/urandom | tr -cd "$CHAR" | head -c ${1:-32}
    echo
}

$NOW = $(date +"%m-%d-%Y") || echo ="Time = $now"
$APPKEY = randpass(20) || echo "Secret key = $APPKEY"
read -p "Copied down?" -n1 -s

*

*Is this a bad approach?

*Is this secure?

*Will the passwords be stored as variables after deployment has finished?

I'm new to shell and linux administration so any help is appreciated.
James

A: 1) Yes, use something like pwgen that allows for customization of passwords (such as which character sets to include, length, total number of generated passwords etc).
2) YMMV
3) since you are not exporting them, no.

A: I'm using this approach:
PASSWORD=$(strings /dev/urandom | grep -o '[[:alnum:]]' | head -n 12 | tr -d '\n'; echo)

From my point of view generated passwords are reasonably secure, but I'm not a crypto-expert.
Variables are only stored in the context of the script, as long as you do not use "source" to execute it . If you do, you can use "unset PASSWORD" to delete the content of the variable.
*pwgen is of course fine, but you might face a situation where you simply cannot install/use it, I did this quite often.


text:
Q: Cascade Dropdownlist by JQuery I am creating an asp.net core cascade dropdownlist with JQuery. The first dropdownlist- Areas binds to Viewbag.areas. The second dropdownlist-Degrees is populating based on the first dropdownlist selected value. The JsonResult GetDegree() method returns a list of data. For some reasons, my second dropdownlist options displays as a list of undefined data when using JQuery. Do I need to bind asp-items to the second dropdownlist and how to do it?  Thanks in advance!
controller:
    [BindProperty]
    public int AreaId { get; set; }
    [BindProperty]
    public int? DegreeId { get; set; }
    public IActionResult Index()
    {
                ViewBag.Areas = GetAreas();
                var qry = (from a in _context.Degrees
                           where a.AreaId == AreaId  && a.Active == true
                           select a).ToList();
                return View(qry);
    }
    public JsonResult GetDegree()
        {
            List<SelectListItem> list = new List<SelectListItem>();

            var degrees = (from a in _context.Degrees
                           where a.AreaId==AreaId
                           select new SelectListItem
                           {
                               Value = a.DegreeId.ToString(),
                               Text = a.DegreeName,
                               Selected = (a.DegreeId== 0)
                           });

            if (degrees != null)
            {
                //assign 0 to the first option
                list.Add(new SelectListItem { Text = "Select a Degree", Value = "0" });
                foreach (var item in degrees)
                {
                    list.Add(new SelectListItem { Text = item.Text, Value = item.Value });
                }
                return Json(new SelectList(list, "Value", "Text"));
            }
            else
            {
                return Json(new SelectList(list, "0", "Select a Degree"));
            }

        }

View:

    <form asp-action="Index" asp-controller="Home">
    Areas
    <select id="AreaId" name="AreaId" asp-items="@(new SelectList(ViewBag.Areas,"Value","Text"))">
        <option value="">--Select --</option>
    </select>

    Degrees
    <select id="DegreeId" name="DegreeId" value=""/>
    <input type="submit" value="Search" />

</form>
@section scripts{

A: Find the solution from this post stackoverflow.com/questions/59600959/… . change the code $("#DegreeId").append($("").val(degree.value).html(degree.text));


text:
Q: Why doesn't division produce a result in shell programming? I have a shell programe, a little part of it can be seen as following:
count=1000
total=100000
percent=`expr $count/$total`

it cannot produce the division result, in the result file, only 1000/100000 was shown.
Any help? Many thanks.~

A: You need to add spaces before and after '/' sign:
percent=`expr $count / $total`

But it's an integer division. So you either need to multiply $count by 100 first or use something like 'bc'.

A: You should have spaces between values to be divided and / operator like here:
count=1000
total=100000
percent=`expr $count / $total`
#                   ^ ^ - those are important

A: better use bc:
percent=$(echo "scale=2; $count/$total" | bc)

A: use gawk
count=1000
total=100000
result=$(gawk -v c=$count -v t=$total 'BEGIN{print c/t }')
echo "result is $result"


text:
Q: Multiple Facebook Like Buttons Same Page URL I want to have multiple Facebook Like Buttons on a single page, all pointing to the same URL. My understanding of the Like Button is that you are liking the URL of the page. But, say for example I have a page with several product attributes, maybe a t-shirt in different colors (Red, Blue, Green, etc.). Each of these colors does not have it's own URL.
Is it possible to like the same URL multiple times? Person likes Red Shirt, Person Likes Blue Shirt, etc.
I attempted to do this with hashtags, yet this did not work. Initial thoughts were to dynamically change the Open Graph Meta tags via Javascript, but A) that doesn't combat the issue of the same URL, and B) that would only work assuming the Facebook API pulls the information from the Meta tags immediately after the click, and not on initial page load or with a separate remote call.
Any ideas?
NOTE: I can not append a query string to the url (i.e. mysite.com/t-shirt?color=red )

A: You should really consider creating a single page for every product.
This will bring you additional benefits:
- images and product links in the news feed;
- much better seo for the single product;
- much better seo for your website.
Are you using a cms?
EDIT:
There are a few examples if you google it. But all of them require you to at least create a very basic html page. It's easy and fast.
You can try being more specific about your situation if you need better help.

A: The only way to do this is dynamic. It uses php. So the address for every button will be the redirecting to the php... something like this:
For the tShirt red:
http://www.yourDomain.com/tshirt.php?color=red
For the tShirt blue:
http://www.yourDomain.com/tshirt.php?color=blue
Put every address in the like button href-param
This work for me every time that i used for multiples Facebook's like buttons.


text:
Q: How would I approach creating a window skin (GDI+, C#) I'm currently creating a GameEngine in C# using GDI+ and am implementing a "MenuComponent" for a 2D style game, but I've come to a point where now I want to my make my menus look nicer, with images behind each button, instead of just text.
However, the issue is that each menu can have different sized text, which in turn means different sized images need to be created for each menu. To me, this sounds tedious and annoying to do this in a 3rd party program (like photoshop, or paint.net) and I'd much rather create a class which will make sure the images will have the right dimensions, but still maintain the same quality no matter the size of the 'control'.
Clearly, there's a better way to approach my issue, but I just don't know how. Like how does RPG Maker allow their windows and buttons to be any size, whilst maintaining the quality of the images, are they making their images on-the-fly?
Any help would be appreciated!
Thanks
If it helps, by menu I mean something like this title screen:


text:
Q: Waiting for a method/process to yield - Spring WebFlux I have created a spring Webflux application. In this application, we are trying to retrieve a record from the DB and then use that record to complete further processing.
I have wrapped my repository.get() method within a Mono like below:
find()
@NotNull
  private Mono<RuntimeCallbackDetails> find(DealsFulfilmentCallback callback, DealsFulfilmentCallbackStatus status) {
    String entityId = callback.getEntityId();
    String itemId = callback.getItemId();
    String type = getCallbackType(callback.getEntityId());
    Long fulfilmentId = Optional.ofNullable(callback.getFId()).orElse(-1L);

    return fulfilmentAcknowledgementService.findFulfilmentAcknowledgement(entityId, itemId, fulfilmentId, type)
        .map(acknowledgement -> {
          validationService.validate(acknowledgement, CALLBACK);
          return RuntimeCallbackDetails.from(callback, acknowledgement, status);
        })
        .doOnError(throwable -> log.error("Error while retrieving fulfilment acknowledgement for callback: ", throwable))
        .switchIfEmpty(Mono.defer(() -> Mono.just(RuntimeCallbackDetails.from(callback, status))));
  }

FulfilmentAcknowledgementService.findFulfilmentAcknowledgement()
@org.jetbrains.annotations.NotNull
  public Mono<FulfilmentAcknowledgement> findFulfilmentAcknowledgement(String entityId, String itemId, Long fulfilmentId, String type) {
    return Mono.justOrEmpty(fulfilmentAcknowledgementRepository.findFulfilmentAcknowledgement(entityId, itemId, fulfilmentId, type));
  }

Now the challenge here is that the flow does not even wait for the find method to execute and return the record. It moves on and since nothing is retrieved, an empty response is propagated downstream. How do I make this find method execute the query and return the Mono based on this retrieved element?


text:
Q: Error Fatal error: Call to a member function insert() on a non-object I'm using a callback after inserting in the database, to pass values to this other table, i think the method i used its fine. But it gives me this error when its inserting to the other table in the database, probably in my model, or something in the controller im kind of clueless in this error, can someone please help me.
Before someone say its to put $this->load->database(); its already in my autoload in config file :)
Fatal error: Call to a member function insert() on a non-object

A PHP Error was encountered
Severity: Notice
Message: Undefined property: Finances::$inventory_model
Filename: controllers/finances.php
Line Number: 125

CONTROLLER:
public function inventory_management($post_array,$primary_key)
    {
        $this->load->model('inventory_model');

        if($post_array['id_expense']!=null){
            $type = 'add';
            $id_exp_detail = $primary_key;

            $result = $this->inventory_model->insert([
                'id_exp_detail' => $id_exp_detail,
                'name' => $post_array['brand'],
                'quantity' => $post_array['item_quantity'],
                'lote' => $post_array['package_code'];
                'type' => $type,
                'date' => date(),
                'id_user' => $this->session->userdata('id_user'),
                'id_entity' => $this->session->userdata('id_entity')
            ]);
        }else if ($post_array['name']!=null){
            $type = 'sub';
            $id_treatment = $primary_key;

            $result = $this->inventory_model->insert([
                'id_treatment' => $id_treatment,
                'name' => $post_array['name'],
                'quantity' => $post_data['recomended_dose'],
                'lote' => $post_array['id_package'],
                'type' => $type,
                'date' => date(),
                'id_user' => $this->session->userdata('id_user'),
                'id_entity' => $this->session->userdata('id_entity')
            ]);
        }else{
            $type = 'sub';
            $id_fertilization = $primary_key;

            $result = $this->inventory_model->insert([
                'id_fertilization' => $id_fertilization,
                'name' => $post_data['name'],
                'quantity' => $post_data['quantity'],
                'lote' => $post_data['id_package'],
                'type' => $type,
                'date' => date(),
                'id_user' => $this->session->userdata('id_user'),
                'id_entity' => $this->session->userdata('id_entity')
            ]);
        }

        if($result){
            echo "validation Complete";
        }

    }

MODEL
class CRUD_model extends CI_Model
{

    protected $_table = null;
    protected $_primary_key = null;

    // ------------------------------------------------------------------------

    public function __construct()
    {
        parent::__construct();
    }

    public function insert($data)
    {

        $this->db->insert($this->_table, $data);
        // return $this->db->insert_id();
    }

MODEL:
class inventory_model extends CRUD_model
{
    protected $_table = 'inventory_management';
    protected $_primary_key = 'id';

    // ------------------------------------------------------------------------

    public function __construct()
    {
        parent::__construct();
    }

    // ------------------------------------------------------------------------

}

A: here is the wrong you call wrong model file
$this->load->model('inventory_model');

it should be
$this->load->model('crud_model');

and you use wrong way to pass array in function
$param = array('id_exp_detail' => $id_exp_detail, 'name' => $post_array['brand'], 'quantity' => $post_array['item_quantity'], 'lote' => $post_array['package_code'], 'type' => $type, 'date' => date(), 'id_user' => $this->session->userdata('id_user'), 'id_entity' => $this->session->userdata('id_entity'));

$result = $this->inventory_model->insert($param);


text:
Q: cakePHP calling methods syntax i'm new to cakePHP and OO programation, this question will seem VERY obvious to all of you, but i'll ask it anyway :
I have a Model, called 'Dossier', that gets it's data from an SQL table containing various fields, of of which is a int(1) (boolean) type called 'bin_valide'.
I wanted to write a simple function that just checks the value of this field and display true or false in the View part (index.ctp)

*

*where do i declare such function (that will look like something like this, i put this code in the model Dossier.php page, but maybe it should go in DossierController.php ... (not sure here)
public function estClos() {
    if ($this->Dossier->field('bin_valide')==0) { return $this->true ; }
    else return $this->false;
}

*how can i call this function ? (i tried something like this in the index.ctp View page:
echo $dossier['Dossier']['commentaire'];

echo $dossier->estClos();

I know this seems very easy, but i just can't figure out where i should decalre such method, and how i am supposed to access it. Thank you very much.

A: Instead of trying to glue pieces together I recommend you to start by getting a basic understanding of MVC and CakePHP.
It is required that you understand the MVC design pattern. Check this link about design patterns in general and this link about MVC. And this github repo has examples of different patterns in php.
Also start by doing the CakePHP blog tutorial instead of trying and unstructured trial and error approach by doing something without having read about the basic.
Your controller is named wrong. Controllers should be named plural, so it should be DossiersController. Models are always singular. You should follow the CakePHP coding standards. If you don't follow them some of the automagic won't work.
All data manipulation and fetching should go into the model
public function getStatus() {
    return $this->Dossier->field('bin_valide');
}

Your controller acts like a manager getting the data from the model and returning it to the view. It basically handles just your request. Models are also easier to test than controllers and the basic rule is that you want fat models and skinny controllers. The controller will just set the data to the view:
public function status() {
    $this->set('status', $this->Dossier->getStatus());
}

In your view simply do something with it:
if ($status === 1) { echo 'Yes'; } else { echo 'No'; }

Do yourself a favor and do the blog tutorial first, it will give you a basic insight into CakePHP and prevent frustration from unstructured trial and error attempts. :)

A: pass a variable to your view, and you can reference it from there on.
public function view_action() {
   $value = false;
   if ($this->Dossier->field('bin_valide')==0) {  $value = true; }
    $this->set('myValue', $value);
}

you can then reference myValue variable in your view.

A: You shouldn't call any functions in your View, the Controller is the place to prepare all data you want to use in your view. In this case, I'd just cast the integer that should be in your dataset as boolean in your view.
First of all, fetch all the entries from the dossiers table (or add conditions to it if needed):
// app/Controller/DossiersController.php
public function index() {
    // Find all the dossiers
    $dossiers = $this->Dossier->find('all');
    // Pass the found dossiers to your view
    $this->set(compact('dossiers'));
}

Then you will get an array that looks something like:
0 => array( // First dossier
    'Dossier' => array(
        'id' => 1,
        'name' => 'Some dossier',
        'bin_valide' => 0
    )
),
1 => array( // Second dossier
    'Dossier' => array(
        'id' => 2,
        'name' => 'Another dossier',
        'bin_valide' => 1
    )
)

In your View you can then simply loop over the dossiers:
// app/View/Dossiers/index.ctp
foreach ($dossiers as $dossier):
    echo '
The name of the dossier is: ' . $dossier['Dossier']['name'] . '
';
    echo '
Valid: ' . (bool)$dossier['Dossier']['bin_valide'] . '
';
endforeach;

This will print:

The name of the dossier is: Some dossier
Valid: false
The name of the dossier is: Another dossier
Valid: true


text:
Q: How to build a GraphQL API on top of a Django/Elasticsearch/MySQL backend? I'm looking into develop a GraphQL API. I have a django/elasticsearch/mysql backend and I'm figuring out how GraphQL fits into this picture.
I reading about the graphene-django project but it seems tightly coupled with the Django ORM, so I'm wondering if elasticsearch can fits in this recipe.
I'm just starting this research so there is a chance that even this question is making no sense.
Any clue about how to do this?

A: graphene is a generic GraphQL server implementation from python.
Using graphene you can build a representation of your graph data and query it from anywhere (MySQL, ElasticSearch, Mongo, whatever) - each field's value is basically resolved by a resolver function which can read data from wherever needed.
graphene-django is just an extension of graphene that automatically wraps django ORM and lets you easily expose django ORM objects as part of your schema without going through the hassle of defining re-defining all the objects and fields already defined in the ORM model.
It does not, however, limit you to only use the django ORM.
You can have many objects in relationships in your GraphQL schema, some objects can work against the django ORM while others can read from ElasticSearch or wherever else you store data.
I would suggest you watch this short video as an intro on how to get started writing your GraphQL server - https://www.youtube.com/watch?v=UBGzsb2UkeY
Then head on to http://graphene-python.org and check out the docs.

A: Some attempts are started at https://pypi.org/project/graphene-elastic/
Yet, still alpha.


text:
Q: Yoast makes comment_reply_link function output plain link to comment instead of reply link EDITED - I discovered that my problem only arises when the Yoast plugin is active. But I want to keep Yoast active, so my updated question is: Any idea what to do for comment replies working while Yoast is activated?
Here's my original question:
In a custom theme created by myself, or rather its child theme on a multisite, I am having trouble with the comment_reply_link function. I am using it as follows:
<?php comment_reply_link(array_merge( $args, array('depth' => $depth, 'max_depth' => $args['max_depth']))) ?>

Now on the website, the link doesn't result in the expected /?replytocom=6#respond appended to the URL of the post, but simply in a local #comment-6 href attribute for the link. So when a user clicks on "Reply", nothing happens. When he/she writes a reply then, it is posted as a first-level reply, not as a reply to the intended previous comment.

A: Version 7 of WordPress SEO by Yoast removes the replytocom variables by default.

We've removed the option to turn off the replytocom variable. The replytocom feature in WordPress lets you reply to comments without activating JavaScript in your browser. However, every comment gets is own link and these could all end up in the search engines. So we now remove these variables by default.

To get the replytcom variables back we can add the following filter in our theme's functions.php
add_filter( 'wpseo_remove_reply_to_com', '__return_false' );