text:
Q: Dual Boot: Does data get deleted because the drive is partitioned? I'm pretty bad at the whole computer literacy thing, but for the most part I can Google things pretty well. From what I've read, partitioning deallocates everything on the partition that is getting modified. However, I've also read on the Installer package that if it's installed alongside my current OS, I won't lose my stuff (I've got Windows 8, and UEFI kinda sucks, but I can get the try Ubuntu to work. It's just not a cursor based GUI, and it's a lot less pretty). Does Ubuntu Desktop identify and reallocate everything as it was? Because I gotta say, if it does, that's pretty rad. If not, while I've got backups, I don't want to reinstall software. I can just wait until I get a new laptop and use have the clean slate with a dual boot.
Thanks,
If this is on another thread, please point me in the right way. I've spent 40 minutes trekking through these forums.

A: You should allocate a separate partition for Ubuntu if you are planning to dual-boot with windows. If you choose so, make sure that you have moved all data from these partition(s) to some other partition because installing Ubuntu will format this partition and you will lose data if you put anything here. In addition, installing Ubuntu alongside windows like described above will not harm your data that is still in windows. There are a lot of information on Ubuntu-Windows dual boot. To start with look at the official documentation.

A: It's possible to resize partitions in such a way that data are not lost, although the amount of free space on the resized partition(s) will change. New partitions for Ubuntu can then be created in the space "vacated" by the resized partition(s). The Ubuntu installer can do this automatically or semi-automatically in some cases.
BEWARE, THOUGH! There are numerous posts here from people who've mistakenly wiped out their Windows installations by accidentally selecting an option that allocates the entire disk to Ubuntu when they'd intended to have Ubuntu coexist alongside their existing Windows installation. I haven't thoroughly investigated these cases, so I don't know what specific mistake they're making or what specific bug might exist in the Ubuntu installer that creates this problem. It's best to make a backup of all your important data before installing Ubuntu, just in case you run into this problem. When you do your installation, be sure to follow a procedure that explicitly states your Windows installation will remain intact. Pay particular attention to any partitioning instructions and the option on the "Installation Type" screen. If you don't see the option your procedure specifies on this screen, do not shrug your shoulders and select something else at random, since that could be the mistake that costs you your Windows installation. Research what each of the options you see does before picking one. (The available options vary depending on your current configuration and boot mode.)


text:
Q: I cannot identify what is causing this unexpected upload error on my app I am relatively new to android development and I have been squeezing my brain juice for hours on probably a very simple error. Look, the app's been working fine yesterday and after I made some changes on some XML files and ran the app on my emulator, I experience this error:
2019-09-10 14:13:19.533 6388-
6516/ E/Volley: [301]
BasicNetwork.performRequest: Unexpected response code 406 for
http://applybpojobs.com/widevalueappfiles/server/api/addvehicle.php
2019-09-10 14:13:21.573 1633-1656/system_process E/memtrack: Couldn't load
memtrack module

I have already tried numerous solutions on the web and it seems not to fix my problem. This is my code:
    StringRequest stringRequest = new StringRequest(Request.Method.POST,
    URL_ADD_VEHICLE,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.i(TAG, response.toString());
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String Success = jsonObject.getString("success");
                        if (Success.equals("1")){
                            hideLoader();
                            Toast.makeText(Addvehicle.this,"Vehicle Added
     Successfully",Toast.LENGTH_SHORT).show();

                        }else if (Success.equals("0")){
                            hideLoader();
                            Toast.makeText(Addvehicle.this,"Vehicle
     Already Exist",Toast.LENGTH_SHORT).show();

                        }

                    }catch (JSONException e){
                        e.printStackTrace();
                        hideLoader();
                        Toast.makeText(Addvehicle.this,"Vehicle Added
     Error"+e.toString(),Toast.LENGTH_SHORT).show();
                    }
                }
            },
            new Response.ErrorListener(){

                @Override
                public void onErrorResponse(VolleyError error){
                    Toast.makeText(Addvehicle.this,"Vehicle Added
     Error"+error.toString(),Toast.LENGTH_SHORT).show();
                    hideLoader();
                }

            })

I am receiving a blank response from this URL and I need guidance on how to fix this:
http://*********.php
For whatever reasons, this page on my app stopped working because of this error. Any help would be appreciated. Again, I'm basically new in android development so please understand that a simple error like this bleeds my nose.
Here are my server php codes:
<?php

require '../core/connect.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $plate_number=$_POST['plate_number'];
    $vin=$_POST['vin'];
    $car_make=$_POST['car_make'];
    $car_model=$_POST['car_model'];
    $car_year=$_POST['car_year'];
    $displacement=$_POST['displacement'];
    $fuel_type=$_POST['fuel_type'];
    $transmission=$_POST['transmission'];
    $mileage=$_POST['mileage'];
    $owner_name=$_POST['owner_name'];
    $address=$_POST['address'];
    $phone_number=$_POST['phone_number'];
    $email_adress=$_POST['email_adress'];
    $facebook=$_POST['facebook'];
    $adddate = date("d/m/Y");

    $photo = $_POST['photo'];

    $id=uniqid();

    $path = "vehicle_upload/$id.jpeg";
    $finalpath = "*********.$path;

    $sql1=mysqli_query($connect,"SELECT * FROM _addvehicle WHERE
 PlateNumber='$plate_number'");
    if (mysqli_num_rows($sql1) > 0) {
            $result['success'] = "0";
            $result['message'] = "error";
            echo json_encode($result);
    }else{

        $sql = mysqli_query($connect, "INSERT IGNORE INTO
_addvehicle(PlateNumber, Vin, Make, Model, Year, Displacement, FuelType,
Transmission, Mileage, OwnerorCompany, HomeorCompanyAddress, ContactNumber,
EmailAddress, FacebookID, AddDate, vehicleImage)VALUES('$plate_number','$vin','$car_make','$car_model','$car_year','$displacement','$fuel_type','$transmission','$mileage','$owner_name','$address','$phone_number','$email_adress','$facebook','$adddate','$finalpath')");

        if ($sql) {

                if (file_put_contents($path, base64_decode($photo))) {
                    $result['success'] = "1";
                    $result['message'] = "success";
                    echo json_encode($result);
                    //mysqli_close($connect);
                }

            }
    }

}

?>

A: In POST request you need to send parameters like an empty Hashmap i.e
{"":""} or you need to try https instead of http.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python Socket GetAddrInfo (GAI) Error I'm running Python (2.7.2) on an embedded linux system has roughly this startup sequence:
0) Reboot
1) Wait 2 minutes
2) Acquire network config via DHCP
A daemon process uses ntplib to acquire the current time and update its clock accordingly.
import ntplib  # http://pypi.python.org/pypi/ntplib/
...

    self.ntpClient = ntplib.NTPClient()
...

def getDate(self):

    try:
        logging.info('Sending NTP request to %s' % ('pool.ntp.org'))
        response = self.ntpClient.request('pool.ntp.org')
        secs = time.localtime(response.tx_time)
        logging.info('Response returned')
        return secs

    except Exception, e:
        logging.exception(e)
        return RESULT_FAILURE

A problem arises if the daemon process begins trying to resolve address info before the dhcp has run (step 2). This continues to be an error even after the DHCP client has run.
Here is the exception:
ERROR:[Errno 2] temporary failure in name resolution.
Traceback (most recent call last):
  File "/home/root/ntp_manager/ntp_manager.py", line 34, in getDate
    response = self.ntpClient.request('pool.ntp.org')
  File "/usr/lib/python2.7/ntplib.py", line 265, in request
    addrinfo = socket.getaddrinfo(host, port)[0]
gaierror: [Errno 2] temporary failure in name resolution.

However if the ntpClient makes its first attempt after the dhcp, then everything works fine.
It's as if the error is a product of some sort of caching (?!)
I've run out of ideas, some help would be much appreciated.
Thanks

A: I've worked out a solution that doesn't need any other libraries or scripts.
Scripts in the directory, /etc/network/if-up.d/ will be execute when a network interface is brought up. Here is a reference.
Therefore this ensures that my NTP script gets executed once the system has configured DHCP client and thereby to the internet. This the correct behaviour that avoids the name resolution problems that I ran into.
I've put together this simple script (and chmod +x it!) It checks that the network method is dhcp, and subsquently initializes my NTP daemon process.
#! /bin/sh
# ntp time-sync manager python daemon starter script

set -e

# ... Some Stuff Omitted Here ...

if [ "$METHOD" = dhcp ]; then
  echo -n "Starting $DESC..."
  start-stop-daemon --start --verbose --pidfile $PIDFILE --exec $DAEMON -- $DAEMON_ARGS
  echo "METHOD: $METHOD"
  echo "IFACE: $IFACE"
fi

echo "Exiting if-up.d/ntp_manager"
exit 0

Here is a dump of what happens on the system. Please note the line: run-parts /etc/network/if-up.d being executed right after an IP has been resolved.
Reconfiguring network interfaces eth0 with DHCP... cat: can't open '/var/run/udh
cpc.eth0.pid': No such file or directory
run-parts /etc/network/if-pre-up.d
ifconfig eth0 up
udhcpc -R -b -p /var/run/udhcpc.eth0.pid -i eth0
udhcpc (v1.13.2) started
Sending discover...
Sending discover...
Sending select for 192.168.1.145...
Lease of 192.168.1.145 obtained, lease time 86400
adding dns 192.168.1.1
run-parts /etc/network/if-up.d
Starting NTP Time Manager...Daemon PID 1059
Redirecting serivice startup output to /home/root/Connect/log/ntp_manager_daemon.log
METHOD: dhcp
IFACE: eth0
Exiting if-up.d/ntp_manager

Anyway, I thought that this is a adequately simple and robust solution to the problem. Hopefully it will help someone else in the future.


text:
Q: Troubles with stimulated emission of single photons and the no cloning theorem I think I don't understand something basic about stimulated emission: it seems to violate the no cloning theorem, and applying its arguments give me 2 different results when trying to understand a basic experiment.
Before I present my question, I will use the following notations:
$$|0\rangle = \operatorname{one photon with horizontal polarization}$$
$$|1\rangle = \operatorname{one photon with vertical polarization}$$
and the two states of a photon in a diagonal polarization:
$$|+\rangle = \frac{|0\rangle +|1\rangle}{\sqrt2}  , |-\rangle = \frac{|0\rangle -|1\rangle}{\sqrt2}$$
Now for the question: I know that if you enter a state $|0\rangle$ to a stimulated emission medium you get $|00\rangle$ and if you enter $|1\rangle$ you get $|11\rangle$. But what happens if you enter a state $|+\rangle$?
Well, according to the no cloning theorem you can't get $|++\rangle$, but instead you will get $$\frac{|00\rangle +|11\rangle}{\sqrt{2}}$$
But in the diagonal basis this is just:
$$\frac{(|+\rangle + |-\rangle)\otimes (|+\rangle + |-\rangle) + (|+\rangle - |-\rangle)\otimes (|+\rangle - |-\rangle)}{2} = \frac{|++\rangle +|--\rangle}{\sqrt{2}}$$
Which means that although I entered a single photon with a $|+\rangle$ polarization, I could measure 2 photons with $|-\rangle$ polarization.
What am I missing?
Thank you
Note: I saw that there is a similar question regarding the issue about the no cloning theorem and stimulated emission but the answers don't address this problem so please don't mark this as duplicate.
Note2 : I discussed the problem with a professor. The problem is that I neglected spontaneous emission and with one photon it's just as strong as stimulated... Using the real Hamiltonian of the interaction (with electric field operators and light Fock states) there is no problem.

A:
Which means that although I entered a single photon with a |+⟩ polarization, I could measure 2 photons with |−⟩ polarization.

This is of no concern to the no-cloning theorem.
As you correctly point out, if $|0\rangle\mapsto|00\rangle$ and $|1\rangle\mapsto|11\rangle$ then you cannot have $|+\rangle\mapsto|++\rangle$. However, there is no problem with mapping $|+\rangle$ to some state which has some overlap with $|++\rangle$ and/or $|--\rangle$, which is indeed what happens, as you observe.


text:
Q: JQUERY load an array of elements into a DIV I have an array of DIV elements in an array called 'noactiveMsg'.
I want to load these DIV elements into a DIV called $('#chatCenterMembers').
I've tried:
noactiveMsg.appendTo($('#chatCenterMembers'));

But this doesn't work.
Can someone advice on the syntax to load an array of elements/objects into a div?
code to made the array:
var noactiveMsg=[];
 $('div.chatmember').each(function() {
 if($(this).children().children('div').hasClass('chatactivestatus_offline')) {
 alert('offline');
 noactiveMsg.push($(this));
 }
 });

A: If each element of your array is a jQuery object, you can try this:

Some sample html:

Some stuff below!

The jQuery stuff:

$(function(){
    var foo = [];
    foo.push( $('
hello
') );
    foo.push( $('
world
') );
    foo.push( $('
Adam
') );

    // this will fail because each element is a
    // separate jQuery object
    // $('div').append( foo );

    // instead try this
    $.each(foo, function(){
        $('div').append(this);
    })
});

see it work on jsFiddle
I also answered a similar question just recently

A: I think this is the code you need.
Assuming noactiveMsg is an array containing jQuery objects.

cnt = noactiveMsg.length();
for(i=0; i<cnt; i++) {
$('#chatCenterMembers').append(noactiveMsg[i].html());

}

A: You'll want to merge them all into one jQuery object:
var noactiveMsg = [$('1'), $('1')],
    collection;

$.each(noactiveMsg, function(i, e) {
    collection ? collection = collection.add(e) : collection = e;
});

EDIT:
Others have suggested adding every element in the array separately into the DOM. I would strongly advise you against it. Interacting with the DOM is an expensive operation, and should be avoided whenever possible.


text:
Q: React router v4 parameter going as undefined I have a route config like this:
/${URL.PRODUCT}/:category/:brand/:flavour/, with exact={true} and it loads the Product component.
On Product component I have this:
    constructor(props) {
    super(props)
    this.state = {
        selectedCategory: props.match.params.category || '',
        selectedFlavour: props.match.params.flavour || '',
        selectedBrand: props.match.params.brand || '',
    }
    s("PARAMS", JSON.stringify(props.match.params)); //console on server
    c("PARAMS", JSON.stringify(props.match.params)); // console on browser
}

Now, on some other component I have a click event, which does this:
clickHandler = (cardData) => {
        let path = `/${URL.PRODUCT}/${cardData.selectedCategory}/${cardData.selectedCard}/${cardData.slug}`;
        cardData.type === CONTENT_TYPE.FLAVOUR && !!cardData.slug && this.props.history.push(path);
    }

And cardData looks like this:
{
    id: 3
    image: "/some/imagepath/"
    name: "Diet Coke"
    selectedCard: "cocacola"
    selectedCategory: "softdrinnk"
    slug: "dietcoke"
    type: "flavour"
}

Its resulting in something like this: /product/softdrinnk/cocacola/dietcoke
Now the problem: As I am hitting this.props.history.push() its making a server call (which it should not) also, with a wrong URL: /product/softdrinnk/cocacola/undefined
This is what my console looks like on client:
PARAMS {"category":"softdrinnk","brand":"cocacola","flavour":"dietcoke"}
And this is what I receive on server:
PARAMS {"category":"softdrinnk","brand":"cocacola","flavour":"undefined"}
I have spend the whole day figuring out why this behaviour is happening.
Update:
Even if when I hardcoded the URL: /${URL.PRODUCT}/${cardData.selectedCategory}/${cardData.selectedCard}/dietcoke, Its ignoring the last parameter and still and passing undefined to the server
And when I hit browser refresh on this route, it works normally and loads all the data


text:
Q: Spring MVC Annotated Controller I have a controller which has a few actions, which are triggered by hitting various buttons on the page.  I would like to have a default action, but am unsure how to annotate the method.  Here is an example:
@Controller
@RequestMapping("/view.jsp")
public class ExampleController {

    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView displayResults() {
        ModelAndView mav = new ModelAndView("view");
        mav.addObject("queryResults", methodToQueryDBForListing());
        return mav;
    }

    @RequestMapping(method = RequestMethod.POST, params="submit=Action 1")
    public ModelAndView action1(@RequestParam("selectedItemKey") String key) {
        ModelAndView mav = new ModelAndView("action1");
        //Business logic
        return mav;
    }

    @RequestMapping(method = RequestMethod.POST, params="submit=Action 2")
    public ModelAndView action2(@RequestParam("selectedItemKey") String key) {
        ModelAndView mav = new ModelAndView("action2");
        //Business logic
        return mav;
    }

    //A few more methods which basically do what action1 and action2 do
}

How can I annotate a method which will act on a POST with any submit button pressed with no key selected?
I have tried:
@RequestMethod(method = RequestMethod.POST, params="!selectedItemKey")
@RequestMethod(method = RequestMethod.POST)

I'd really hate it if I had to set required = false on each of the methods which take RequestParams and then conditionally check to see if one comes in or not...  Is there a way to annotate this to work properly?

A: I would make this a path variable rather than a parameter, and would get rid of the .jsp:
@RequestMapping("/view")
...

@RequestMapping("/action1")
@RequestMapping("/action2")
@RequestMapping("/{action}")

It is more "restful".

A: The proper annotation is:
@RequestMapping(
  method = RequestMethod.POST,
  params = { "!selectedItemKey", "submit" }
)

It seems odd though, that it was not hitting this method until adding that second parameter.

A: I'm not so familiar with annotated spring-mvc but I can remember that when extending a MultiActionController you can specify a default entry point by defining the following spring config:
<bean name="myController"
class="foo.bar.MyController">
<property name="methodNameResolver">
    <bean class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
        <property name="defaultMethodName" value="init" />
    </bean>
</property>

package foo.bar

public class MyController extends MultiActionController {

    /**
     * Called when no parameter was passed.
     */
    public ModelAndView init(HttpServletRequest request,
            HttpServletResponse response) {
        return new ModelAndView("myDefaultView");
    }

    /**
     * action=method1
     */
    public void method1(HttpServletRequest request,
            HttpServletResponse response) {
        return new ModelAndView("method1");
    }

    /**
     * action=method2
     */
    public void method2(HttpServletRequest request,
            HttpServletResponse response) {
        return new ModelAndView("method2");
    }
}

So maybe in this instance you could solve this by configuring your controller over spring config instead of using annotations.


text:
Q: Convert a string into a time interval (?) I am loading in strings that represent time frames with the format DD days, HH:MM:SS, and I want to create a graph in which these time frames are the expression. That means that I need to convert them into some number-like format. Interval() doesn't seem to be working. Any ideas? Should I reformat the string prior to loading to something other than DD days, HH:MM:SS so that it is more easily usable?

A: There are lots of ways you could go about solving this. Your idea of reformatting prior to loading sounds like a good option, since QlikView doesn't support regular expressions.
I think the best way to solve your problem is to write a simple Python script that replaces the spaces, comma, and letters with a colon. Then, you'll have a much more workable string in DD:HH:MM:SS format. Of course, this assumes you have a flat file that you can easily tweak:
import re
myreg = re.compile('(\s(day|days),\s)')    ## we'll look for " day, " and " days, "
newfilestr = ""
with open('myfile.txt', 'r') as myfile:
    for line in myfile:
        newfilestr += re.sub(myreg, ':', line)
outputf = open('fixedtimeformat.txt', 'w')
outputf.write(newfilestr)
outputf.close()


text:
Q: laravel - Redirecting To External Domains with a string parameter I am developing a Laravel 5.6 project in localhost and I need to redirect it to an external website with a string parameter.
I found this on laravel 5.6 Documentation

Redirecting To External Domains

Sometimes you may need to redirect to a domain outside of your application. You may do so by calling the away method, which creates a RedirectResponse without any additional URL encoding, validation, or verification:
return redirect()->away('https://www.google.com');

I used the data from a form and created a variable including the data as requested inside the controller. Then added the parameter at the end line this.
return redirect()->away('https://sandbox.payhere.lk/pay/checkout')->with('$Payhere');

It redirects to required page and shows the error

"Error!!! Required String parameter 'rid' is not present "


text:
Q: 2 dice problem wrong expected value Suppose we have $2$ dice $(1,2,3,4,5,6)$ and we want to calculate the total number of unique combinations (order doesn't matter).
$n$ = number of values of dice
$r$ = length of output
I apply my formula for repeated unique combinations $C(n+r-1,r) = \dfrac {(n+r-1)!} {(n-r)! \, r!}$ and we get by substituting:
$C(7,2)  = \dfrac {7!}{4! \, 2!}$ which is equal to $3 \times 5 \times 7$ which is $105$.However my textbook says the correct result is $21$.

A: Here are the careless mistakes:
$$C(n+r-1, r)=\frac{(n+r-1)!}{\color{red}{(n-1)}!r!}$$
$$C(7,2) = \frac{7!}{\color{red}5!2!}=\frac{7\cdot 6}{2}=21$$


text:
Q: Best practise for managing shapefiles/symbology in QGIS One aspect of GIS that wasn't covered in my training was the best way to manage shapefiles within a project.
In my hypothetical example I have a shapefile with a number of attributes. I want to produce a map comparing 4 different combinations of various attributes.
So I want 4 map windows in my print composer, I then have three options for how to set up the layers (that I have thought of):
A) 1 layer, 1 shapefile. I then use the 'lock layers' and 'lock styles' for each  map window, adjusting the properties and styles of the shapefile for each desired attribute combination as I go. The problem is, there is no record of what rules or attributes I used if I come back to it in 6 months time.
B) 4 layers, 1 shapefile duplicated in each layer. I can set the propoerties and style for each layer to correspond with each submap but the shapefile itself still refers to the original .shp file.
C) 4 layers, 4 shapefiles. Duplicate the shapefile and load each separate shapefile into its own layer and set style and properties for each shapefile . This seems to cause performance issues for me.
So far, I tend to follow B, this lets me fine tune settings and styles with ease and also gives reasonable performance but I don't know whether this may give rise to other problems down the line. What is generally considered best practise in this situation for performance and stability?

A: I think this is a matter of personal preference. I tend to use the method associated with C). If I have copies (not duplicates) of the same shapefile, I can add unique attributes to each shapefile which would distinguish them from each other. This, for me, does not cause performance issues though.
In regards to A), remember that you can save your style as a .qml file which will store what styling properties/rules you used so when you come back to it at a later date, you can see exactly what you did.
In regards to B), you could have a single shapefile. But later on, you might need to add more attributes to the shapefile. This could be problematic if you're dealing with large datesets which could consequently increase the filesize. I personally try to avoid this as it normally degrades performance.
I'm sure others will provide a more insightful answer which hopefully would help you decide :)

A: Since a good few versions of QGIS ago, it is possible to do a variant of A), which is the cleanest option, without having to use 'lock layers' or 'lock styles'. It is possible to assign a rule-based symbology to a layer where the rules are applied according to variables.
Setting an item ID for each map item (in this example, 'Map 1'), it is then easy to configure the symbology to respond to which map item the features are shown in. Simply set a rule where the expression looks like:
@item_id LIKE 'Map 1' AND *whatever other filters you need to use*

The features will not get displayed in the main QGIS window so an all encompassing ELSE rule can be used to at least be able to visualise them while editing. Bear in mind, not all variables seem to be selectable from the expression builder but they can still be used in expressions. For a good primer on variables, check out this three part blog post.


text:
Q: Message Queuing on python 2.2 How to do a Message Queuing in python 2.2?
Must be in python 2.2, I need for a legacy system.
I've already looked a lot and found nothing, I'm already thinking that it can not be done.
Which I do not doubt, since python 2.2 is quite old.

A: I made a .jar that reads the queue and inserts in our database. And a listener in python that looks at the table.
Not python 2.2, but work's.


text:
Q: React-native fetch data periodically and schedule local notifications I need to set notifications daily multiple times. The timings data (which is variable) is being fetched by an API.
For this I probably need a background task that will periodically fetch the data for the week/day. That task should obviously run even when the app is closed/terminated because rarely an app is in the foreground/background. But all the libraries/packages (e.g expo's TaskManager/BackgroundFetch, react-native-background-fetch, react-native-background-task etc) I have searched have some limitations e.g. they wouldn't work when an app is terminated (swiped away from the recent apps list) or they wouldn't work for IOS when an app is terminated
I need an all-rounder library that would:

*

*execute background task even when an app is closed

*work for android + ios

It is such a common use case but I am unable to find any solution


text:
Q: How to properly read data from SqlDataReader in C#? Let us assume we have an open SqlConnection and execute an arbitrary query resulting in a table consisting of one column Foo which contains integers.
To read those integers I noticed two kinds of possibilities to access the values in the column:
using (var reader = command.ExecuteReader())
{
    if (reader.HasRows)
    {
        while (reader.Read())
        {
            // access value directly either by column name or index
            int i = (int)reader["Foo"];
            int j = (int)reader[0];

            // access value by using GetOrdinal
            int k = reader.GetInt32(reader.GetOrdinal("Foo"));
        }
    }
}

Both approaches result in the same values of course. I am using the first approach as it seems easier to me to use the column name to access the value directly instead of using it to get its index and then using that index to access the value.
But I am quite new to the subject so what are the best practices here? Current conventions? Differences in matters of performance?

A: All are correct way but reader["Foo"] and reader[0] are using the overloaded indexers defined. It's always easy/readable and recommended to use the column name in the indexer instead of using the index though. Not sure about any performance differences between them.
        int i = (int)reader["Foo"];
        int j = (int)reader[0];

A: Something like that:
using (var reader = command.ExecuteReader()) {
  // if (reader.HasRows) is redundant

  // do not repeat this in the loop
  int k_index = reader.GetOrdinal("Foo");

  while (reader.Read()) {
    // reader["Foo"] is not necessary int;
    // better practice is to convert since reader["Foo"] could be, say, Oracle Number
    int i = Convert.ToInt32(reader["Foo"]);
    // usually, reader[123] (instead of reader["MyField"]) syntax looks ugly, but
    // it may happen that, say, "id" is always the first field in the query -
    // so reader[0] syntax is reasonable
    int j = Convert.ToInt32(reader[0]);
    // what if reader[index] is declared as Int64 but contains Int32 values - convert
    int k = Convert.ToInt32(reader[k_index]);
  }
}

A: using reflector you can see the indexer [] internally is the same as calling the methods
public override object this[int i]
{
    get
    {
        return this.GetValue(i);
    }
}
public override object this[string name]
{
    get
    {
        return this.GetValue(this.GetOrdinal(name));
    }
}

so the actual difference is. if you know the position and care about performance use the int version of the methods.
 int j = (int)reader[0];//direct array access for some column
 int j = reader.GetInt32(0);

if you don't know the position or prefer readability use the string version
 //must first goto hash table and waist time looking for column index
 int j = (int)reader["price"]; //but at least we know the meaning of the column
 int j = reader.GetInt32(reader.GetOrdinal("price"));
 int j = (int)reader.GetValue(reader.GetOrdinal("price"));

and to finalize the difference bettween  GetInt32 and GetValue is just that GetInt32 does the type validation and cast for you, so if you know the type of data makes you life easier..
PS. the performance hit of looking up the index of the column by name is usually ignorable.. but.. is not to be dismissed, I have a project where GetOrdinal that is one of the most called functions hundreds of thousand of times, summing up to seconds of time, that I could have avoided by using ints, and now that I'm hitting bottlenecks, I can't rewrite the application.

A: You will use SqlDataReader a lot so keep it more simple as possible, specifying column name:
int i = (int)reader["Foo"];


text:
Q: No visual update on state change when using map I have the following code that renders in my class component.
When I change the state of toDisplay to another list, the log in the console shows the correct list of datasets, however, the display doesn't change.

            {this.state.toDisplay.length > 0 ? (
              console.log(this.state.toDisplay),
              this.state.toDisplay.map((dataset, i) => (

                  <DatasetInfo dataset={dataset} key={i} app={this.props.app} />

              ))
            ) : (

No Datasets

                  It appears there are no datasets to show in this category

            )}

I update the toDisplay state as follows:
  changeTab(event) {
    this.setState({ selectedTab: event.target.id });
    if (event.target.id === "1") {
      this.setState({ toDisplay: this.state.forSaleList });
    } else if (event.target.id === "2") {
      this.setState({ toDisplay: this.state.hiddenList });
    } else if (event.target.id === "3") {
      this.setState({ toDisplay: this.state.purchasedList });
    }
  }

This function is the on-click method for some tabs on the site

A: I suspect that you are updating the array wrongly: if you don't set it in your state with a new copy of the array, the console log will display the updated array, but it will not trigger a visual update of your component, because the state didn't really updated, since it is still the same array (with maybe some new items, but it doens't matter).
So in order to trigger an update, you should set a copy of the array in your local state:
// Modify the array as you wish
// And then, set it in the local state
setState({toDisplay: [...this.state.toDisplay]})

A: I managed to get the display to update by changing the key from i to the id of the dataset as below:
this.state.toDisplay.map((dataset, i) => (

                  <DatasetInfo dataset={dataset} key={dataset.id} app={this.props.app} />

              ))


text:
Q: Python : How to parse the json data and render it use webapp2 on GAE and deployed the search-result app? everyone : )
I have A database that can search like "http://key.xxxxxx.org:10093/?q="
when type the keyword in url (behind the =mark), it can show lots of json data.
Now i write a simple webapp on GAE use webapp2 : on the /search page, when i type the keyword,
it can parse the jsondata content on the /result page. Here is my part of code :
# -*- coding: utf-8 -*-

import os
import re
import httplib
import json
import urllib
from string import letters

import webapp2
import jinja2

template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),
                               autoescape = True)

def render_str(template, **params):
    t = jinja_env.get_template(template)
    return t.render(params)

def renderJson(query):
    conn = httplib.HTTPConnection('xxx.xxxxx.org:10093')
    conn.request('GET', '/?q=%s' % urllib.quote_plus(query))
    res = conn.getresponse()
    data = res.read()
    j = json.loads(data)
    results = []
    result = j['data']['group'][0]['resultitem']
    for l in result:
        for k,v in l.items():
            if k == 'word':
                results.append(l[k])
    return results

class BaseHandler(webapp2.RequestHandler):
    def render(self, template, **kw):
        self.response.out.write(render_str(template, **kw))

    def write(self, *a, **kw):
        self.response.out.write(*a, **kw)

class Search(BaseHandler):
    def get(self):
        self.render("search.html")

    def post(self):
        q = self.request.get('query')
        if q:
            self.redirect('/result/?q='+query)

class Result(BaseHandler):
    def get(self):
        q = self.request.get('query')
        self.render('result.html', query = q, result = renderJson(q))

app = webapp2.WSGIApplication([
                               ('/search', Search),
                               ('/result', Result)
                               ],
                              debug=True)

in the search.html, i wrote
<input type="text" name="q" value="{{query}}"></input>

and in result.html
<p>{{result}}</p>

A: For getting the parameter from the url you need to use:
q = self.request.get('query')

See the Getting Started guide and the webapp improved documentation.
Then you would pass that parameter to renderJson as renderJson(q), also in renderJson
the second line will need to quote the query string first (and pass the q argument)
conn.request('GET', '/?q=%s' % urllib.quote(query))

Finally for rendering the final output please read the Getting Started Guide.


text:
Q: How to clearing Tensorflow-Keras GPU memory? I am fitting a model in a for loop, but I am getting an error that my GPU's memory is full. I am using Keras in Anaconda Spyder IDE. My GPU is a Asus GTX 1060 6gb.
I have also used codes like: K.clear_session(), gc.collect(), tf.reset_default_graph(), del custom_model but none of them worked.
GPU properties say's 98% of memory is full:

Nothing flush GPU memory except numba.cuda.close() but will not allow me to use my GPU again. The only way to clear it is restarting kernel and rerun my code.
I am looking for any script code to add my code allow me to use my code in for loop and clear GPU in every loop.

A: Wrap up the model creation and training part in a function then use subprocess for the main work. When training is done, subprocess will be terminated and GPU memory will be free.
something like:
import multiprocessing

def create_model_and_train( ):
      .....
      .....

p = multiprocessing.Process(target=create_model_and_train)
p.start()
p.join()

Or you can create below function and call it before each run:
from keras.backend.tensorflow_backend import set_session
from keras.backend.tensorflow_backend import clear_session
from keras.backend.tensorflow_backend import get_session
import tensorflow
import gc

# Reset Keras Session
def reset_keras():
    sess = get_session()
    clear_session()
    sess.close()
    sess = get_session()

    try:
        del classifier # this is from global space - change this as you need
    except:
        pass

    print(gc.collect()) # if it does something you should see a number as output

    # use the same config as you used to create the session
    config = tensorflow.ConfigProto()
    config.gpu_options.per_process_gpu_memory_fraction = 1
    config.gpu_options.visible_device_list = "0"
    set_session(tensorflow.Session(config=config))


text:
Q: How to display (visualize) heatmap in Simulink I am about to use the Matlab function 'heatmap' to display (visualize) data from within the Simulink simulation.

The data which are inputting this Simulink block are individual signals in continuous-time simulation. The Simulink block should form the "matrix (image)" and display it. I am using the Matlab function block from within Simulink where I am calling the heatmap function as follows

Unfortunately, I am not able to display the heatmap, how can I display the heatmap from within the Simulink model?

A: I am doing it this way - are there any other better options?


text:
Q: console log return null i tried to do a popup and when i do my js in my html it work perfectly, but when i tried to separe my js of my html, my js file doesn't work and i don't know why...
i don't know if the problem its how i adapt my js or how my js is linked
if someone can help, it's will be really nice !
Here's my code, if you need anything else ask me ! :

    var modal = document.getElementById('popup2');

    var essai = document.getElementById('id02');
console.log(modal)

    essai.addEventListener("click", function () {

        modal.style.display = "block";

    })

    var span2 = document.getElementsByClassName("close")[0];

    // When the user clicks on  (x), close the modal
    span2.onclick = function () {
        essai.style.display = "none";
    }
.popup2{z-index: 3;
    display: none;
    padding-top: 100px;
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto;
    background-color: rgba(0, 0, 0, 0.82);
}
<!DOCTYPE html>

    <meta charset="utf-8">

    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Nejma Hamadi</title>

    <link href="vendor/bootstrap/css/bootstrap.css" rel="stylesheet">
    <link href="vendor/bootstrap/css/styles.css" rel="stylesheet">
    <link href="vendor/bootstrap/css/stylesGallery.css" rel="stylesheet">

    <link href="css/scrolling-nav.css" rel="stylesheet">
    <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

                ×

    <link href="https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.0.0/magnific-popup.min.css" rel="stylesheet">

A: In your HTML, you are using popup2 as a class name, not an id!
Therefore, you should replace var modal = document.getElementById('popup2'); by
var modal = document.getElementsByClassName('popup2')[0];
Another thing: make sure this code runs after the HTML has loaded, otherwise it will return undefined. To do so, wrap your code inside:
document.onload = function() {
  var modal = document.getElementsByClassName('popup2')[0];
  //your code here
}

A: you can do that with Jquery
$("#popup").hide(); //hidden in start
$("#openPopup").on("click",function(){
  $("#popup").show();
});
$("#closePopup").on("click",function(){
  $("#popup").hide();
});

see CodePen Demo


text:
Q: Custom Camera not saving the whole image I have built an android custom camera in this way:
    //CameraActivity.java

    public class CameraActivity extends AppCompatActivity implements CameraPreview.OnCameraStatusListener {

        String path, TAG = "CameraActivity";
        private CameraPreview cameraPreview;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            requestWindowFeature(Window.FEATURE_NO_TITLE);
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
            setContentView(R.layout.activity_camera);

            Button takePhoto = findViewById(R.id.takePhoto);
            takePhoto.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Log.e(TAG, "===takePhoto()===");

                    if (cameraPreview != null) {
                        cameraPreview.takePicture();
                    }
                }
            });

            //Start camera
            initCameraPreview();
        }

    private void initCameraPreview() {
        Log.e(TAG, "===initCameraPreview()===");

        cameraPreview = findViewById(R.id.cameraPreview);
        cameraPreview.setOnCameraStatusListener(this);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onCameraStopped(byte[] data) throws JSONException {
        Log.e("TAG", "===onCameraStopped===");
        File mSaveFile = getOutputMediaFile();
        saveToFile(data, mSaveFile);
    }

    public File getOutputMediaFile() {

        File mediaStorageDir =
            new     File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "CustomCameraPics");

        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.e(TAG, "failed to create directory");
                return null;
            }
        }

        long time = System.currentTimeMillis();

        File file = new File(mediaStorageDir.getPath() + File.separator + "myPic_" + time + ".png");

        path = file.getPath();
        Log.e("imagePath", path);

        return file;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public void saveToFile(byte[] bytes, File file) throws JSONException {

        Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

        try {

            FileOutputStream out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();

            Log.e("Image", "Saved");
            Toast.makeText(CameraActivity.this, "Image Saved",     Toast.LENGTH_SHORT).show();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

//activity_camera.xml

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

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <com.shank.mycamera.CameraPreview
            android:id="@+id/cameraPreview"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:text="Take pic"
            android:id="@+id/takePhoto"/>

    </RelativeLayout>

</RelativeLayout>

    //CameraPreview.java

    public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {

    private static final String TAG = "CameraPreview";
    private OnCameraStatusListener listener;

    private Camera camera;
    private SurfaceHolder holder;

    private Camera.PictureCallback pictureCallback = new Camera.PictureCallback() {

        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            try {
                camera.stopPreview();
            } catch (Exception e) {
            }

            if (null != listener) {
                try {
                    listener.onCameraStopped(data);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    public void takePicture() {
        Log.e(TAG, "===takePicture()===");
        if (camera != null) {
            try {
                camera.takePicture(null, null, pictureCallback);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public CameraPreview(Context context, AttributeSet attrs) {
        super(context, attrs);
        holder = getHolder();
        holder.addCallback(this);
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    public interface OnCameraStatusListener {
        void onCameraStopped(byte[] data) throws JSONException;
    }

    public void setOnCameraStatusListener(OnCameraStatusListener listener) {
        this.listener = listener;
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        Log.e(TAG, "==surfaceCreated==");
        camera = getCameraInstance();

        try {
            camera.setPreviewDisplay(holder);
        } catch (Exception e) {
            Log.e(TAG, "Error setting camera preview", e);
            camera.release();
            camera = null;
        }
        //update()

        if (camera != null) {
            camera.startPreview();

            Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
            for (int i = 0; i < Camera.getNumberOfCameras(); i++) {
                Camera.getCameraInfo(i, cameraInfo);
            }
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

        Log.e(TAG, "==surfaceChanged==");
        try {
            camera.stopPreview();
        } catch (Exception e) {

        }

        try {
            camera.setPreviewDisplay(holder);
            camera.startPreview();
        } catch (Exception e) {
            Log.e(TAG, "Error starting camera preview: " + e.getMessage());
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        Log.e(TAG, "==surfaceDestroyed==");
        camera.release();
        camera = null;
    }

    public static Camera getCameraInstance() {
        Camera camera = null;
        int cameraId = 0;
        boolean frontCameraFound = false;

        try {
            Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
            for (int i = 0; i < Camera.getNumberOfCameras(); i++) {
                Camera.getCameraInfo(i, cameraInfo);

                if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                    cameraId = i;
                    frontCameraFound = true;
                }
            }

            if (frontCameraFound) {
                camera = Camera.open(cameraId);
            } else {
                camera = Camera.open();
            }
            Camera.Parameters parameters = camera.getParameters();
            camera.setDisplayOrientation(90);
            parameters.setRotation(270);
            camera.setParameters(parameters);
        } catch (Exception e) {

            Log.e(TAG, "getCamera failed");
        }
        return camera;
    }
}

It saves the image when you click 'TAKE PIC' button.
My requirement: the whole image that the user can see on the screen in preview should be saved.
The problem I'm facing is that in some of the phones the image/bitmap saved doesn't contain everything that is shown to the user on screen.

A: As @CommonsWare has explained, there is no requirement that a captured picture should be same as preview picture. You can skip camera.takePicture() altogether, and in your cameraPreview.takePicture(), save the latest preview frame as bitmap.
The advantages of this approach are that your are guaranteed that the same image as the user sees in the preview is saved, and it happens with no delay.
The drawback is that the resolution and quality for image returned from camera.takePicture() may be noticeably better.
If you not satisfied with preview frame quality, you can use the same size for setPreviewSize() and for setPictureSize(), if the size is supported for both getSupportedPreviewSizes() and getSupportedPictureSizes(): usually you can find a satisfactory pair.
If you are not satisfied with the preview frame resolution, at least choose the same aspect ratio for setPreviewSize() and for setPictureSize(). Some devices produce really weird results when the two don't match.
But note that these steps can not guarantee that the captured image will be the same as previewed, even only because takePicture() inevitably happens with some delay.

One more remark: if you target Android N and above, consider switching from the deprecated Camera API to the camera2 API.


text:
Q: Why doesn't uninstalling psycopg2 using pip or sudo pip work? I am trying to uninstall psycopg2 in my virtual env.
When I do 'pip uninstall psycopg2'- I get an exception error:
Uninstalling psycopg2-2.9.1:
  Would remove:
    /opt/anaconda3/lib/python3.8/site-packages/psycopg2-2.9.1.dist-info/*
    /opt/anaconda3/lib/python3.8/site-packages/psycopg2/*
  Would not remove (might be manually added):
    /opt/anaconda3/lib/python3.8/site-packages/psycopg2/.dylibs/libcom_err.3.0.dylib
    /opt/anaconda3/lib/python3.8/site-packages/psycopg2/.dylibs/libcrypto.1.1.dylib
    /opt/anaconda3/lib/python3.8/site-packages/psycopg2/.dylibs/libgssapi_krb5.2.2.dylib
    /opt/anaconda3/lib/python3.8/site-packages/psycopg2/.dylibs/libk5crypto.3.1.dylib
    /opt/anaconda3/lib/python3.8/site-packages/psycopg2/.dylibs/libkrb5.3.3.dylib
    /opt/anaconda3/lib/python3.8/site-packages/psycopg2/.dylibs/libkrb5support.1.1.dylib
    /opt/anaconda3/lib/python3.8/site-packages/psycopg2/.dylibs/libpq.5.13.dylib
    /opt/anaconda3/lib/python3.8/site-packages/psycopg2/.dylibs/libssl.1.1.dylib
Proceed (y/n)? y
ERROR: Exception:
Traceback (most recent call last):
  File "/opt/anaconda3/lib/python3.8/shutil.py", line 791, in move
    os.rename(src, real_dst)
PermissionError: [Errno 13] Permission denied: '/opt/anaconda3/lib/python3.8/site-packages/psycopg2-2.9.1.dist-info/' -> '/opt/anaconda3/lib/python3.8/site-packages/~.ycopg2-2.9.1.dist-info'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/anaconda3/lib/python3.8/site-packages/pip/_internal/cli/base_command.py", line 189, in _main
    status = self.run(options, args)
  File "/opt/anaconda3/lib/python3.8/site-packages/pip/_internal/commands/uninstall.py", line 87, in run
    uninstall_pathset = req.uninstall(
  File "/opt/anaconda3/lib/python3.8/site-packages/pip/_internal/req/req_install.py", line 658, in uninstall
    uninstalled_pathset.remove(auto_confirm, verbose)
  File "/opt/anaconda3/lib/python3.8/site-packages/pip/_internal/req/req_uninstall.py", line 400, in remove
    moved.stash(path)
  File "/opt/anaconda3/lib/python3.8/site-packages/pip/_internal/req/req_uninstall.py", line 289, in stash
    renames(path, new_path)
  File "/opt/anaconda3/lib/python3.8/site-packages/pip/_internal/utils/misc.py", line 347, in renames
    shutil.move(old, new)
  File "/opt/anaconda3/lib/python3.8/shutil.py", line 803, in move
    rmtree(src)
  File "/opt/anaconda3/lib/python3.8/shutil.py", line 718, in rmtree
    _rmtree_safe_fd(fd, path, onerror)
  File "/opt/anaconda3/lib/python3.8/shutil.py", line 675, in _rmtree_safe_fd
    onerror(os.unlink, fullname, sys.exc_info())
  File "/opt/anaconda3/lib/python3.8/shutil.py", line 673, in _rmtree_safe_fd
    os.unlink(entry.name, dir_fd=topfd)
PermissionError: [Errno 13] Permission denied: 'RECORD'

I have tried doing 'sudo pip uninstall psycopg2', but it says no such file or directory exists?? And when I do 'pip list' it is there? Any ideas how to uninstall it?

A: I found the solution by doing: "sudo python3 -m pip uninstall psycopg2"

A: I think u don't have a permission to delete it cause u use a global python environment.
so u should make your own venv and tr

A: Try →
$ export PIP_BINARY=$(which pip); sudo $PIP_BINARY uninstall psycopg2

or use full path of pip binary manually →
$ which pip

# output should be like /opt/anaconda3/bin/pip

$ sudo /opt/anaconda3/bin/pip uninstall psycopg2


text:
Q: HTML - Como mostrar/esconder conteúdos ao clicar em um "link"? Preciso montar um FAQ nesse estilo:

Clico na pergunta, ela apresenta a resposta ao lado. Se eu clico em outra pergunta, a resposta deve alternar e mostrar a resposta referente a outra pergunta clicada.
Como posso fazer isso? Pelo o que pesquisei notei que preciso de um script, mas acabei de começar a aprender html justamente por conta do trabalho, então não conheço muito.. Alguma ideia?

A: Segue um pequeno exemplo de como fazer:

function mostraResposta(id){
  respostas = document.getElementsByClassName('faq'); //recupera todos elementos da classe faq
  for (var i = 0; i < respostas.length; i++) { // coloca todos eles invisiveis
    respostas[i].style.display = 'none';
  }

  clicada = document.getElementById(id); //recupera o id passado por argumento
  clicada.style.display = 'inherit'; //faz ele ser exibido conforme o item pai
}
#links {
  float: left;
  max-width: 50%;
}
#links li {
  cursor: pointer;
  transition: 0.3s ease;
  opacity: 0.7;
}

#links li:hover {
  opacity: 1;
}

#respostas {
  float: right;
  max-width: 50%;
}

.faq {
  margin: 20px;
  display: none; /* coloca todos como invisiveis inicialmente */
}

Lorem

Ipsum

Lorem Lorem Lorem Lorem Lorem Lorem Lorem
  Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem
  Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem
  Lorem Lorem Lorem Lorem Lorem Lorem Lorem

Ipsum Ipsum Ipsum Ipsum Ipsum Ipsum Ipsum
  Ipsum Ipsum Ipsum Ipsum Ipsum Ipsum Ipsum Ipsum Ipsum Ipsum Ipsum Ipsum
  Ipsum Ipsum Ipsum Ipsum Ipsum Ipsum Ipsum Ipsum Ipsum Ipsum Ipsum Ipsum
  Ipsum Ipsum Ipsum Ipsum Ipsum Ipsum Ipsum


text:
Q: Удалить тег из html Есть блок с текстом, в котором в некоторых местах есть br. При меньшей ширине окна текст принимает непрезентабельный вид и не выравнивается с text-align по ширине блока. Может есть способ, чтобы при определенной ширине окна, теги br удалялись из блока?

A: Media Queries вам помогут в этом деле:

@media only screen and (max-width: 500px) {
  br {
    display: none;
  }
  .text {
    text-align:justify;
  }
}

  Lorem ipsum dolor sit amet, consectetur
adipiscing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident,
sunt in culpa qui officia deserunt mollit anim id
est laborum. Sed ut perspiciatis, unde
  omnis iste natus error sit voluptatem
accusantium doloremque laudantium, totam
rem aperiam eaque ipsa, quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt, explicabo. Nemo enim ipsam
voluptatem, quia voluptas
  sit, aspernatur aut odit aut fugit,
sed quia consequuntur magni dolores eos, qui ratione voluptatem sequi nesciunt, neque porro quisquam est, qui dolorem ipsum, quia dolor
sit, amet, consectetur, adipisci velit, sed quia non numquam eius modi
  tempora incidunt, ut labore et dolore magnam aliquam quaerat voluptatem.

A: Вот, например, так можно скрывать теги "br" только для определенного радиуса ширины экрана. В примере для 750px и меньше теги убираются из блока с классом "parent-block". Для работы скрипта необходим jQuery
var w = screen.width;

function forMobile() {
    w = screen.width;
    if (w <= 750) {
        $('.parent-block').find('br').css('display', 'none');
    } else {
        $('.parent-block').find('br').css('display', 'block');
    }
}
forMobile();

$( window ).resize(function() {
    forMobile();
});

Вот css
@media screen and (max-width: 750px) {
   .parent-block br {
      display: none;
   }
}

Привык создавать плагины на js, которые делают порою нечто подобное, вот и пример с ним. И js скрипт и css делают одно и то же действие.


text:
Q: Insert an Incremental Dynamic Value in Visio I have a large spreadsheet with rows that do get rearranged a few times of a year (few hundred lines). I also have a Visio document that basically maps these rows with simple boxes and connectors. Boxes are basically a value from one column (say column B), and connectors represent values from another column (say column F).
I have also added row Id's on each of these connectors, aside from the value column F, however, as I said, the rows do get rearranged, so I was wondering if there was a way to create a variable and use it as part of a text in each of these connectors to go incrementally. This is to avoid modifying the row Id's when new ones are added, or they get rearranged.
I'm not looking for Visio to parse the Excel sheet. Simply to have a dynamically incremental variable that I can use to shift these numbers up and down in my Visio, so when I see the old value of, e.g. Val_from_Column_F (3), and now the same row has been moved to, say, row 12, now I need to display, Val_from_Column_F (12) -- a difference of 9. And have every other value in Visio to get incremented by 9 accordingly. That way, every row after 3, gets incremented equally by 9 and represents the current rows in the spreadsheet.


text:
Q: retrieve HMCharacteristic from NSPredicate I have an issue while retrieving the string from the NSPredicate. I am preparing the NSPredicate from HMCharacteristicWriteAction like below
 HMCharacteristicWriteAction *chWr = [conditionEvents1 objectAtIndex:a];

 NSPredicate *pred =  [HMEventTrigger predicateForEvaluatingTriggerWithCharacteristic:chWr.characteristic relatedBy:NSEqualToPredicateOperatorType toValue:chWr.targetValue];

If I print the pred object it prints like characteristic == <HMCharacteristic> AND characteristicValue == 1. I am trying to retrieve the value from the pred object for getting the HMCharacteristicObject.It is giving the NSString in return.How can I get the HMCHaracteristic from NSPredicate. Thank you for reading my post.


text:
Q: Find a word in a string I am trying to make this work.  Please help
function rsfp_onSelectDate(day)
{
if(day strpos('Sunday') !== false));
{
    alert("We are Closed on Sunday");
    return false;
}
else return true;
}

A: day strpos('Sunday')

doesn't look valid to me, you should try:
strpos($day, 'Sunday')

instead. From the online docs:

int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

*

*Find the numeric position of the first occurrence of needle in the haystack string.

As, as some witty commenter has remarked, you shouldn't just expect to make up syntax and expect it to work. This code seems to be some strange hybrid of PHP and JavaScript. JS would use indexOf rather than strpos but PHP has no built-in alert function as JS does. In addition, your day variable would be $day in PHP.


text:
Q: loop linear model with different variables condition in r I want to make a loop for the linear model but get a problem.
First, I write a loop(can not run) that extracts the beta value I wanted.
y <- c('y1', 'y2')
x1 <- c('a1', 'a2', 'a3')
x2 <- c('A', 'B')

for (y in y) {
  for (x1 in x1) {
    for (x2 in x2) {
      m <- lm(as.name(y) ~ as.name(x1) + as.name(x2), data = dat) %>% summary() %>% .$coefficients %>% .[2,1]

    }

  }

}

The combination of y, x1, and x2 in the for loop is not my expectation. The formula in lm model like this: expand.grid(y, x1, x2). And what I expected is all the combination of the same letter on the independent variable position. This is my original code:
m1 <- lm(y1 ~ a1 + A, dat) %>% summary() %>% .$coefficients %>% .[2,1]
m2 <- lm(y1 ~ a2 + A, dat) %>% summary() %>% .$coefficients %>% .[2,1]
m3 <- lm(y1 ~ a3 + A, dat) %>% summary() %>% .$coefficients %>% .[2,1]
m4 <- lm(y2 ~ a1 + A, dat) %>% summary() %>% .$coefficients %>% .[2,1]
m5 <- lm(y2 ~ a2 + A, dat) %>% summary() %>% .$coefficients %>% .[2,1]
m6 <- lm(y2 ~ a3 + A, dat) %>% summary() %>% .$coefficients %>% .[2,1]
m7 <- lm(y1 ~ b1 + B, dat) %>% summary() %>% .$coefficients %>% .[2,1]
m8 <- lm(y1 ~ b2 + B, dat) %>% summary() %>% .$coefficients %>% .[2,1]
m9 <- lm(y1 ~ b3 + B, dat) %>% summary() %>% .$coefficients %>% .[2,1]
m10 <- lm(y2 ~ b1 + B, dat) %>% summary() %>% .$coefficients %>% .[2,1]
m11 <- lm(y2 ~ b2 + B, dat) %>% summary() %>% .$coefficients %>% .[2,1]
m12 <- lm(y2 ~ b3 + B, dat) %>% summary() %>% .$coefficients %>% .[2,1]```

And this is my data.
Any help will be highly appreciated!
dat <- structure(list(y1 = c(0.838141931, 0.174850172, 0.116144283,
0.113778511, 0.494270733, 0.874482265, 0.325621743, 0.661045636,
0.452396096), y2 = c(0.487877797, 0.360726955, 0.380614137, 0.169760207,
0.359371965, 0.743837108, 0.156535906, 0.995989192, 0.331058618
), a1 = c(0.336537159, 0.446060609, 0.57586382, 0.09629329, 0.491634112,
0.988226873, 0.929105257, 0.605957031, 0.470720774), a2 = c(0.128615421,
0.831986313, 0.267777151, 0.313178319, 0.7776461, 0.863337292,
0.042818986, 0.830029959, 0.901586271), a3 = c(0.291053766, 0.546719865,
0.918797744, 0.976353885, 0.193777436, 0.953859399, 0.963312236,
0.191449484, 0.825034161), b1 = c(0.31510338, 0.5441007, 0.515466925,
0.030702511, 0.020932599, 0.334734486, 0.586588252, 0.562970761,
0.848337089), b2 = c(0.426787995, 0.350719803, 0.706471337, 0.346462166,
0.099766511, 0.219781154, 0.565047862, 0.50282167, 0.727813725
), b3 = c(0.799666435, 0.07225825, 0.409411895, 0.701122141,
0.529991257, 0.478439097, 0.79467065, 0.442156618, 0.026693511
), A = c(0.43143391, 0.662313075, 0.584967093, 0.866110621, 0.598682492,
0.14665666, 0.454315631, 0.448968611, 0.238969939), B = c(0.060625179,
0.410312393, 0.614411256, 0.127343899, 0.90370096, 0.882024428,
0.681389602, 0.56535592, 0.850829599)), class = c("spec_tbl_df",
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -9L), spec = structure(list(
    cols = list(y1 = structure(list(), class = c("collector_double",
    "collector")), y2 = structure(list(), class = c("collector_double",
    "collector")), a1 = structure(list(), class = c("collector_double",
    "collector")), a2 = structure(list(), class = c("collector_double",
    "collector")), a3 = structure(list(), class = c("collector_double",
    "collector")), b1 = structure(list(), class = c("collector_double",
    "collector")), b2 = structure(list(), class = c("collector_double",
    "collector")), b3 = structure(list(), class = c("collector_double",
    "collector")), A = structure(list(), class = c("collector_double",
    "collector")), B = structure(list(), class = c("collector_double",
    "collector"))), default = structure(list(), class = c("collector_guess",
    "collector")), skip = 1), class = "col_spec"))

A: I'm not sure if I got you right, but it seems you've organized your data in the wrong way. Maybe this is what you might want to:
new_dat = data.frame(
  y = c(rep(dat$y1, 3 + 3), rep(dat$y2, 3 + 3)),
  x = c(rep(c(dat$a1, dat$a2, dat$a3), 2),
        rep(c(dat$b1, dat$b2, dat$b3), 2)),
  z = c(rep(dat$A, 3 + 3), rep(dat$B, 3 + 3))
)

models = with(new_dat, mapply(function(y, x, z) model = lm(y ~ x + z),
                              y, x, z, SIMPLIFY = FALSE))

Let us know if that's exactly what you're looking for. If not, elaborate on it...

A: Using expand.grid you can create all combinations of y, x1 and x2. Create formula as strings using sprintf.
df <- expand.grid(y, x1, x2)
formula_strings <- sprintf('%s ~ %s + %s', df$Var1, df$Var2, df$Var3)
formula_strings

# [1] "y1 ~ a1 + A" "y2 ~ a1 + A" "y1 ~ a2 + A" "y2 ~ a2 + A"
# [5] "y1 ~ a3 + A" "y2 ~ a3 + A" "y1 ~ a1 + B" "y2 ~ a1 + B"
# [9] "y1 ~ a2 + B" "y2 ~ a2 + B" "y1 ~ a3 + B" "y2 ~ a3 + B"

Using sapply apply the model and extract coefficients from each.
values <- sapply(formula_strings, function(x)
                 lm(x, dat) %>% summary() %>% .$coefficients %>% .[2,1])
values

#y1 ~ a1 + A y2 ~ a1 + A y1 ~ a2 + A y2 ~ a2 + A y1 ~ a3 + A y2 ~ a3 + A
#  -0.254943   -0.005956   -0.006177    0.286670   -0.393284   -0.387501
#y1 ~ a1 + B y2 ~ a1 + B y1 ~ a2 + B y2 ~ a2 + B y1 ~ a3 + B y2 ~ a3 + B
#   0.506848    0.371615    0.182370    0.435684   -0.370723   -0.380668

A: If you need: y ~ b[1-3] + B and y ~ a[1-3] + A and don't need y ~ a[1-3] + B and y ~ b[1-3] + A, then you can set up the data.frame like this:
library(dplyr)

res = rbind(
expand.grid(response=c('y1', 'y2'),pre1=c('a1', 'a2', 'a3'),pre2='A',stringsAsFactors = FALSE),
expand.grid(response=c('y1', 'y2'),pre1=c('b1', 'b2', 'b3'),pre2='B',stringsAsFactors = FALSE)
)

From parts of your code, it seems like you only need the 2nd coefficient, so a simple base R method will be to use reformulate to construct the formula for every row:
res$coef = sapply(1:nrow(res),function(i){
predictor = as.character(res[i,c("pre1","pre2")])
response = res$response[i]
f = reformulate(predictor,response=response)
coefficients(lm(f,data=dat))[2]
})

       head(res)
  response pre1 pre2         coef
1       y1   a1    A -0.254942513
2       y2   a1    A -0.005955600
3       y1   a2    A -0.006177156
4       y2   a2    A  0.286669786
5       y1   a3    A -0.393284033
6       y2   a3    A -0.387500900

A tidy solution will be something like this, where we nest the models first
library(purrr)
library(broom)
library(tidyr)

res = rbind(
expand.grid(response=c('y1', 'y2'),pre1=c('a1', 'a2', 'a3'),pre2='A',stringsAsFactors = FALSE),
expand.grid(response=c('y1', 'y2'),pre1=c('b1', 'b2', 'b3'),pre2='B',stringsAsFactors = FALSE)
)

res = res %>%
mutate(model=1:n()) %>%
nest(param=c(c(response, pre1, pre2))) %>%
mutate(
fit = map(param,~
lm(reformulate(c(.$pre1,.$pre2),response=.$response),data=dat)),
tidied=map(fit,tidy)
)

The model and results are nested in a tibble:
    res
    # A tibble: 12 x 4
   model param            fit    tidied
   <int> <list>           <list> <list>
 1     1 <tibble [1 × 3]> <lm>   <tibble [3 × 5]>
 2     2 <tibble [1 × 3]> <lm>   <tibble [3 × 5]>
 3     3 <tibble [1 × 3]> <lm>   <tibble [3 × 5]>
 4     4 <tibble [1 × 3]> <lm>   <tibble [3 × 5]>

And if you need the 2nd coefficient:
res %>% unnest(c(param,tidied)) %>% filter(term==pre1)
    # A tibble: 12 x 10
   model response pre1  pre2  fit    term  estimate std.error statistic p.value
   <int> <chr>    <chr> <chr> <list> <chr>    <dbl>     <dbl>     <dbl>   <dbl>
 1     1 y1       a1    A     <lm>   a1    -0.255       0.390   -0.653   0.538
 2     2 y2       a1    A     <lm>   a1    -0.00596     0.479   -0.0124  0.990
 3     3 y1       a2    A     <lm>   a2    -0.00618     0.246   -0.0251  0.981
 4     4 y2       a2    A     <lm>   a2     0.287       0.268    1.07    0.325
 5     5 y1       a3    A     <lm>   a3    -0.393       0.176   -2.24    0.0664
 6     6 y2       a3    A     <lm>   a3    -0.388       0.233   -1.66    0.148
 7     7 y1       a1    B     <lm>   a1     0.507       0.541    0.937   0.385
 8     8 y2       a1    B     <lm>   a1     0.372       0.510    0.729   0.493
 9     9 y1       a2    B     <lm>   a2     0.182       0.391    0.466   0.657
10    10 y2       a2    B     <lm>   a2     0.436       0.319    1.37    0.221
11    11 y1       a3    B     <lm>   a3    -0.371       0.310   -1.19    0.277
12    12 y2       a3    B     <lm>   a3    -0.381       0.276   -1.38    0.217


text:
Q: How to display the number of search results (custom search script) Im try makeing search function for my site, this is the code http://pastebin.com/GN1NUE7E
But i need help to display the number of search results.

A: You're already calling mysql_num_rows(), which tells you how many rows are in your result. Consider the following use in the example from the documentation:
<?php

  $link = mysql_connect("localhost", "mysql_user", "mysql_password");
  mysql_select_db("database", $link);

  $result = mysql_query("SELECT * FROM table1", $link);
  $num_rows = mysql_num_rows($result);

  echo "$num_rows Rows\n";

?>

You have the following in your code:
if( mysql_num_rows( $raw_results ) > 0 )

You're checking to see how many results were returned. All you would need to do is assign the value of mysql_num_rows() to a variable, or call it directly.

A: Just save the result of function mysql_num_rows:
$rows_num = mysql_num_rows($raw_results);

And then print it:
echo $rows_num;


text:
Q: Get default output audio device with NAudio I want to get the default output audio device (i.e. my speakers) using NAudio, to get the master sound volume as in this question.
I am trying to use MMDeviceEnumerator.GetDevice(), but the id it takes is a string, not the device number. Here's the code I've written so far:
        var enumerator = new MMDeviceEnumerator();

        for (int i = 0; i < WaveOut.DeviceCount; i++)
        {
            var cap = WaveOut.GetCapabilities(i);
            Console.WriteLine("{0}: {1}", i, cap.ProductName);

            var device = enumerator.GetDevice(???);
        }

        Console.WriteLine();

        Console.ReadLine();

I've tried passing the various Guids from the capabilities, as well as the device id in string format, to GetDevice() but none of them work.
How do I get the default device?

A: You are mixing two completely different audio APIs here. MMDeviceEnumerator is part of WASAPI, the new audio API introduced in WindowsVista, and WaveOut.DeviceCount uses the old Windows audio APIs.
To use WASAPI to get the default audio device, you use code like this:
var enumerator = new MMDeviceEnumerator();
enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Console);

There are actually three different types of default audio output device, depending on the purpose (role):
    /// <summary>
    /// Games, system notification sounds, and voice commands.
    /// </summary>
    Console,

    /// <summary>
    /// Music, movies, narration, and live music recording
    /// </summary>
    Multimedia,

    /// <summary>
    /// Voice communications (talking to another person).
    /// </summary>
    Communications,


text:
Q: Modulus in QGIS Raster Calculator I have the same question like the one aked here:
How to get the "absolute value" of a raster cell in QGIS?
I came up with the same solution for the problem some time ago. However I showed this solution to a software developer some days ago, and he was very amused. Is there a build in function in QGIS to acquire the modulus of a real number?

A: Raster calculator does not have a built-in modulus function, but you can try:
 ( "ras1@1" > 0 ) * "ras1@1" +  ( "ras1@1" < 0 ) * ( -1 ) * "ras1@1"

*

*If the cell value is negative, ( "ras1@1" > 0 ) returns 0, while ( "ras1@1" < 0 ) returns 1. The output cell value is ( -1 ) * "ras1@1".

*If the cell value is positive, ( "ras1@1" > 0 ) returns 1, while ( "ras1@1" < 0 ) returns 0. The output cell value is "ras1@1".

*If the cell value is 0, both ( "ras1@1" > 0 ) and ( "ras1@1" < 0 ) return 0. The output cell value is 0, too.

A: The solution is to use the geoalgorithm r.mapcalc in the GRASS section of he Processing Toolbox. The number of supported operators and functions is by far bigger than the Raster Calculator:
 Operator   Meaning                    Type        Precedence
 --------------------------------------------------------------
 -          negation                   Arithmetic  12
 ~          one's complement           Bitwise     12
 !          not                        Logical     12
 ^          exponentiation             Arithmetic  11
 %          modulus                    Arithmetic  10
 /          division                   Arithmetic  10
 *          multiplication             Arithmetic  10
 +          addition                   Arithmetic   9
 -          subtraction                Arithmetic   9
 <<         left shift                 Bitwise      8
 >>         right shift                Bitwise      8
 >>>        right shift (unsigned)     Bitwise      8
 >          greater than               Logical      7
 >=         greater than or equal      Logical      7
 <          less than                  Logical      7
 <=         less than or equal         Logical      7
 ==         equal                      Logical      6
 !=         not equal                  Logical      6
 &          bitwise and                Bitwise      5
 |          bitwise or                 Bitwise      4
 &&         logical and                Logical      3
 &&&        logical and[1]             Logical      3
 ||         logical or                 Logical      2
 |||        logical or[1]              Logical      2
 ?:         conditional                Logical      1

function                description                                     type
---------------------------------------------------------------------------
abs(x)                  return absolute value of x                      *
acos(x)                 inverse cosine of x (result is in degrees)      F
asin(x)                 inverse sine of x (result is in degrees)        F
atan(x)                 inverse tangent of x (result is in degrees)     F
atan(x,y)               inverse tangent of y/x (result is in degrees)   F
cos(x)                  cosine of x (x is in degrees)                   F
double(x)               convert x to double-precision floating point    F
eval([x,y,...,]z)       evaluate values of listed expr, pass results to z
exp(x)                  exponential function of x                       F
exp(x,y)                x to the power y                                F
float(x)                convert x to single-precision floating point    F
graph(x,x1,y1[x2,y2..]) convert the x to a y based on points in a graph F
graph2(x,x1[,x2,..],y1[,y2..])
                        alternative form of graph()                     F
if                      decision options:                               *
if(x)                   1 if x not zero, 0 otherwise
if(x,a)                 a if x not zero, 0 otherwise
if(x,a,b)               a if x not zero, b otherwise
if(x,a,b,c)             a if x > 0, b if x is zero, c if x < 0
int(x)                  convert x to integer [ truncates ]              I
isnull(x)               check if x = NULL
log(x)                  natural log of x                                F
log(x,b)                log of x base b                                 F
max(x,y[,z...])         largest value of those listed                   *
median(x,y[,z...])      median value of those listed                    *
min(x,y[,z...])         smallest value of those listed                  *
mode(x,y[,z...])        mode value of those listed                      *
nmax(x,y[,z...])        largest value of those listed, excluding NULLs  *
nmedian(x,y[,z...])     median value of those listed, excluding NULLs   *
nmin(x,y[,z...])        smallest value of those listed, excluding NULLs *
nmode(x,y[,z...])       mode value of those listed, excluding NULLs     *
not(x)                  1 if x is zero, 0 otherwise
pow(x,y)                x to the power y                                *
rand(a,b)               random value x : a <= x < b                     *
round(x)                round x to nearest integer                      I
round(x,y)              round x to nearest multiple of y
round(x,y,z)            round x to nearest y*i+z for some integer i
sin(x)                  sine of x (x is in degrees)                     F
sqrt(x)                 square root of x                                F
tan(x)                  tangent of x (x is in degrees)                  F
xor(x,y)                exclusive-or (XOR) of x and y                   I

Internal variables:
 row()                  current row of moving window                    I
 col()                  current col of moving window                    I
 nrows()                number of rows in computation region            I
 ncols()                number of columns in computation region         I
 x()                    current x-coordinate of moving window           F
 y()                    current y-coordinate of moving window           F
 ewres()                current east-west resolution                    F
 nsres()                current north-south resolution                  F
 area()                 area of current cell in square meters           F
 null()                 NULL value


text:
Q: jQuery Ajax load and getScript I'm trying to set up my site so that content in the main area is loaded via javascript (some pages take a while to render). However, I've run into a bit of a logical problem when using jQuery.load(), jQuery.getScript and jQuery.ajax().
I need to be able to load certain javascript files via getScript so that I can use these functions etc inside the loaded content.

*

*index.php - The main file being displayed (also contains #loading)

*js/script.js - The file containing the load code

*js/*.js - Several javascript files I need to be able to use inside #maincontent after the load

*load.php - The file being loaded into #maincontent

script.js:
$(document).ready(function() {
$('#loading').fadeIn('fast');
$('#maincontent').load('load.php', function() {
    $('#loading').fadeOut('fast');
    $('#maincontent').fadeIn('slow');
});

$('#navigation li a').click(function() {
    $('#maincontent').fadeOut('fast');

    $.getScript('js/jquery.contextMenu-1.01.js');
    $.getScript('js/jquery-1.5.1.min.js');
    $.getScript('js/jquery-ui-1.8.12.custom.min.js');
    $.getScript('js/jquery.qtip-2.0.0.min.js');
    $.getScript('js/ajax.js');

    $.ajax({
        method: 'get',
        url: 'load.php',
        data: 'page=' + $(this).attr('rel'),
        beforeSend: function() {
            $('#loading').fadeIn('fast');
        },
        complete: function() {
            $('#loading').fadeOut('fast');
        },
        success: function(html) {
            $('#maincontent').fadeIn('slow');
            $('#maincontent').html(html);
        }
    });
});

$.getScript('js/jquery.contextMenu-1.01.js');
$.getScript('js/jquery-1.5.1.min.js');
$.getScript('js/jquery-ui-1.8.12.custom.min.js');
$.getScript('js/jquery.qtip-2.0.0.min.js');
$.getScript('js/ajax.js');
});

As you can see, I'm trying to load load.php first without any URL parameters and any interaction from the user. Although load.php is loaded correctly every time, the same can't be said for the javascript code. Sometimes it works, other times I have to refresh the page a few times before I get a clean console (no errors).
The errors in the console suggest to me that the js code isn't loaded properly before it is being used inside load.php. This is especially true if load.php takes a while (tested with PHP sleep(5) function).
Let me know if I need to clarify anything :)

A: If the problem is the timing of the loads, you should consider using the latest version of jQuery with deferred behavior.
You could, for instance, do:
    var wait1 = $.getScript('js/jquery.contextMenu-1.01.js');
var wait2 = $.getScript('js/jquery-1.5.1.min.js');
var wait3 = $.getScript('js/jquery-ui-1.8.12.custom.min.js');
var wait4 = $.getScript('js/jquery.qtip-2.0.0.min.js');
var wait5 = $.getScript('js/ajax.js');
$.when(wait1, wait2, wait3, wait4, wait5).then(function() {
    $.ajax({
        method: 'get',
        url: 'load.php',
        data: 'page=' + $(this).attr('rel'),
        beforeSend: function() {
            $('#loading').fadeIn('fast');
        },
        complete: function() {
            $('#loading').fadeOut('fast');
        },
        success: function(html) {
            $('#maincontent').fadeIn('slow');
            $('#maincontent').html(html);
        }
    });
}, function() { handleErrorsFunction()});

This will wait until all of the getScript calls return and then do the ajax call to load.php (or it will trigger the handleErrorsFunction() if one of the above fails).

A: You shouldn't really load all of those scripts with getScript.  You will need some (or all?) of them every time, so why not just include them on the page.  In addition, since your'e using jquery to load jquery, I'm going to say you already have it included on the page.  So don't try to load it again.


text:
Q: Lower branch of Lambert W function in mathematica I am interested in values of the Lambert W function, which is defined as the solution to the equation
$
z = W(z) e^{W(z)} .
$
The solution is not, however, single-valued, but branches into two solutions for $z < 0$. See for example the first figure in the Wikipedia page:

In Mathematica, I can get the part corresponding to the upper branch of the solution with ProductLog[z] and even different branches of it on the complex plane with ProductLog[k, z]. However, I don't find any way of computing the values of the lower branch of the solution to the equation above, i.e. the function that is, in the Wikipedia article, denoted as $W_{-1}(z)$. Is there a way to compute values of this function in Mathematica?

A: Expanding my comment into an answer, ProductLog can take two arguments, k and z, namely:
ProductLog[k, z]

There's some information to be found under the Details & Options of the documentation, but instead I turned to MathWorld, which has this to say on the matter:

The plot above shows the function along the real axis. The principal
  value of the Lambert W-function is implemented in Mathematica as
  ProductLog[z]. Different branches of the function are available in
  Mathematica as ProductLog[k, z], where k is any integer and k = 0
  corresponds to the principal value. Although undocumented,
  LambertW[k, z] autoevaluates to ProductLog[k, z] in Mathematica.

Hence, if k = 0 gives the principal value, I think that using ProductLog[-1, z] should be the solution you're after for $W_{-1}(z)$.
I'm not sure why the documentation isn't as clear on this.

A: Try this:
    lst = Select[
  Table[{z, (FindRoot[w + Log[w] == Log[z], {w, -1000, -1},
        Method -> "Secant", AccuracyGoal -> 3, PrecisionGoal -> 3] //
       Chop)[[1, 2]]}, {z, -0.5, -0.009, 0.002}], Im[#[[2]]] == 0 &];

which gives the list with the structure {z,W}. This plots the list
    ListPlot[Select[lst, Im[#[[2]]] == 0 &],
 PlotRange -> {{-0.4, 0.1}, {-6, 1}}, AxesStyle -> Arrowheads[0.03],
 AxesLabel -> {Style["z", 16, Italic], Style["W", 16, Italic]}]

It should look like follows:

There is a still more simple approach to this question. Just let us plot the function using the ParametricPlot:
 ParametricPlot[{W*Exp[W], W}, {W, -6, 0},
 PlotRange -> {{-0.4, 0.1}, {-6, 1}}, AspectRatio -> 0.6,
 AxesStyle -> Arrowheads[0.03],
 AxesLabel -> {Style["z", 16, Italic], Style["W", 16, Italic]}]

Obviously, it should look very close to the first one:

If you need a table of the solution (e.g., zversus Wyou can make the list using the same idea:
lst2 = Table[{W*Exp[W], W} // N, {W, -6, 0, 0.3}]

yielding
(*  {{-0.0148725, -6.}, {-0.019072, -5.7}, {-0.0243895, -5.4}, \
{-0.0310934, -5.1}, {-0.0395028, -4.8}, {-0.0499905, -4.5}, \
{-0.0629814, -4.2}, {-0.0789435, -3.9}, {-0.0983654, -3.6}, \
{-0.121714, -3.3}, {-0.149361, -3.}, {-0.181455, -2.7}, {-0.217723, \
-2.4}, {-0.257158, -2.1}, {-0.297538, -1.8}, {-0.334695, -1.5}, \
{-0.361433, -1.2}, {-0.365913, -0.9}, {-0.329287, -0.6}, {-0.222245, \
-0.3}, {0., 0.}}   *)

I made a small step to have it short.
Have fun!


text:
Q: Hiding fields a form in via CSS So I am trying to hide some of the fields in a form. The input type="" section is fairly easy to hide via ID, however I can't get around to how can I edit the label class.
I did try the :nth-child() selector after reading a couple of posts and sites but can't seem to get it working. Here's what I did. Any suggestions of what I'm doing wrong and how I can improve?:
CSS
#fc-calc-result-wraps:nth-child(2n) {
  display: none;
}

HTML

    Total At Retirement:
    <input type="text" class="control num" id="edFV" maxlength="14" size="16" disabled="">

    Contributions:
    <input type="text" class="control num" id="edNumPmts" maxlength="3" size="16" disabled="">

     Total Invested:
    <input type="text" class="control num" id="edTotalInvested" maxlength="14" size="16" disabled="">

    Interest Earned:
    <input type="text" class="control num" id="edInterest" maxlength="14" size="16" disabled="">

    Last Deposit Date:
<input type="text" class="control num" id="edFVDate" maxlength="14" size="16" disabled="">

A: nth-child depends on the element itself, not the children of an element. So the following CSS means: "Hide an element with the class input-group if it is the second child of an element with the class fc-calc-result-wraps".
.fc-calc-result-wraps > .input-group:nth-child(2) {
    display: none;
}


text:
Q: OnEdit / OnFocus Hook or Similar in Bespin Embedded? I'm trying to implement a hook when text is edited in a bespin embedded instance.  Ideally, I'd simply like to know when the instance has gained or lost focus to capture the user action.

A: Not sure when you last checked out bespin but in the newer releases there is a textChanged event you can subscribe to:
editor.textChanged .add(function((oldRange, newRange, newText)) {
    console.log('textChanged', JSON.stringify(newText));
});


text:
Q: CSS class not being applied even when exported react-toolbox I am using react-toolbox and react-css-themr to supply theme. I create my contextTheme and supply it through ThemeProvider. Everything's seems fine. I am using webpack, the styles are exported and loaded in the  attribute of my page, so there is no problem with the importing the css.
EDIT: I can clearly see the context theme is loaded to the website, as I can observe RT objects

my contextTheme file looks like this and is named contextTheme.js
export default {
  RTAutocomplete: require('./assets/style/themes/autocomplete.module.css'),
  RTButton: require('./assets/style/themes/button.module.css')
};

I can see custom theme in  tag like this
.autocomplete-module--autocomplete--tESXbPMw {
  padding: 0
}

.autocomplete-module--autocomplete--tESXbPMw .autocomplete-module--suggestions--t6ziL7OQ {
    background-color: red;
    border-color: blue;
    border-radius: 0
}

theme provider looks like this
      <ThemeProvider theme={contextTheme}>
        <Router store={s} history={h}>
          { routes }
        </Router>
      </ThemeProvider>

resulting html element still has only default style applied, because no style is attached to it.

In case my webpack css config looks like this. I am not sure if that is relevant, but just in case.
            {
              test: /\.scss|\.css$/i,
              use: [
                "style-loader",
                {
                  loader: "css-loader",
                  options: {
                    importLoaders: 1,
          modules: {
            exportGlobals: true,
            mode: "local",
            auto: undefined,
            localIdentName: "[name]--[local]--[hash:base64:8]",
          },
          sourceMap: shouldUseSourceMap,
                  }
                },
                {
                  loader: "postcss-loader",
                  options: {
                    postcssOptions: {
                      plugins: [
                        [
                          "postcss-preset-env",
                          {
                            // Options
                          },
                        ],
                      ],
                    },
                  },
                },
              ],
              sideEffects: true,
            },


text:
Q: r return ngram from a vector which contains specific string I want to generate ngram keywords from a vector, given a specific string.
For example, let's say I would need bigram, for each element of the vector I want to extract relevant bigrams and concatenate all the bigrams which has the keyword ncd.
have <- c('add the ncd mse to the website', 'setup new ncd staffs on t&ta for wireless. all new ncd should go to horizon', 'map out current ncd post locations on 1st, 2nd floors')

want_bigram <- c('the ncd | ncd mse', 'new ncd | ncd staffs | new ncd |ncd should', 'current ncd | ncd post')

Thank you

A: You can do this with the tidytext library.
library(tidytext)

want <- have %>%
  as_tibble() %>%
  mutate(row = row_number()) %>%
  unnest_tokens(bigrams, value, token = "ngrams", n = 2) %>%
  filter(str_detect(bigrams, "ncd")) %>%
  group_by(row) %>%
  summarize(text = paste0(bigrams, collapse = " | ")) %>%
  pull(text)

Output:
> want
[1] "the ncd | ncd mse"
[2] "new ncd | ncd staffs | new ncd | ncd should"
[3] "current ncd | ncd post"

A: Using str_extract_all you can extract strings with with one word before and after 'ncd' and combine them with mapply.
library(stringr)

mapply(function(x, y) paste(c(x, y), collapse = ' | '),
    str_extract_all(have, '(\\w+ ncd)'), str_extract_all(have, '(ncd \\w+)'))

#[1] "the ncd | ncd mse"
#[2] "new ncd | new ncd | ncd staffs | ncd should"
#[3] "current ncd | ncd post"


text:
Q: AVVideoCompositionCoreAnimationTool is not animating custom properties during export with AVAssetExportSession I'm trying to add an animated CALayer over my video and export it with AVAssetExportSession.
I'm animating the layer using CABasicAnimation set to my custom property.
However, it seems that func draw(in ctx: CGContext) is never called during an export for my custom layer, and no animation is played.
I found out that animating standard properties like borderWidth works fine, but custom properties are ignored.
Can someone help with that?
func export(standard: Bool) {
    print("Exporting...")
    let composition = AVMutableComposition()
    //composition.naturalSize = CGSize(width: 300, height: 300)

    // Video track
    let videoTrack = composition.addMutableTrack(withMediaType: .video,
                                                 preferredTrackID: CMPersistentTrackID(1))!
    let _videoAssetURL = Bundle.main.url(forResource: "emptyVideo", withExtension: "mov")!
    let _emptyVideoAsset = AVURLAsset(url: _videoAssetURL)
    let _emptyVideoTrack = _emptyVideoAsset.tracks(withMediaType: .video)[0]
    try! videoTrack.insertTimeRange(CMTimeRange(start: .zero, duration: _emptyVideoAsset.duration),
                                    of: _emptyVideoTrack, at: .zero)

    // Root Layer
    let rootLayer = CALayer()
    rootLayer.frame = CGRect(origin: .zero, size: composition.naturalSize)

    // Video layer
    let video = CALayer()
    video.frame = CGRect(origin: .zero, size: composition.naturalSize)
    rootLayer.addSublayer(video)

    // Animated layer
    let animLayer = CustomLayer()
    animLayer.progress = 0.0
    animLayer.frame = CGRect(origin: .zero, size: composition.naturalSize)
    rootLayer.addSublayer(animLayer)

    animLayer.borderColor = UIColor.green.cgColor
    animLayer.borderWidth = 0.0
    let key = standard ? "borderWidth" : "progress"
    let anim = CABasicAnimation(keyPath: key)
    anim.fromValue = 0.0
    anim.toValue = 50.0
    anim.duration = 6.0
    anim.beginTime = AVCoreAnimationBeginTimeAtZero
    anim.isRemovedOnCompletion = false
    animLayer.add(anim, forKey: nil)

    // Video Composition
    let videoComposition = AVMutableVideoComposition(propertiesOf: composition)
    videoComposition.renderSize = composition.naturalSize
    videoComposition.frameDuration = CMTime(value: 1, timescale: 30)

    // Animation tool
    let animTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: video,
                                                       in: rootLayer)

    videoComposition.animationTool  = animTool

    // Video instruction > Basic
    let videoInstruction = AVMutableVideoCompositionInstruction()
    videoInstruction.timeRange = CMTimeRange(start: .zero, duration: composition.duration)
    videoComposition.instructions = [videoInstruction]

    // Video-instruction > Layer instructions
    let layerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: videoTrack)
    videoInstruction.layerInstructions = [layerInstruction]

    // Session
    let exportSession = AVAssetExportSession(asset: composition,
                                             presetName: AVAssetExportPresetHighestQuality)!
    exportSession.videoComposition = videoComposition
    exportSession.shouldOptimizeForNetworkUse = true
    var url = FileManager.default.temporaryDirectory.appendingPathComponent("\(arc4random()).mov")
    url = URL(fileURLWithPath: url.path)
    exportSession.outputURL = url
    exportSession.outputFileType = .mov
    _session = exportSession

    exportSession.exportAsynchronously {
        if let error = exportSession.error {
            print("Fail. \(error)")
        } else {
            print("Ok")
            print(url)
            DispatchQueue.main.async {
                let vc = AVPlayerViewController()
                vc.player = AVPlayer(url: url)
                self.present(vc, animated: true) {
                    vc.player?.play()
                }
            }
        }
    }
}

CustomLayer:
class CustomLayer: CALayer {

    @NSManaged var progress: CGFloat

    override init() {
        super.init()
    }

    override init(layer: Any) {
        let l = layer as! CustomLayer
        super.init(layer: layer)

        print("Copy. \(progress) \(l.progress)")
        self.progress = l.progress
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }

    override class func needsDisplay(forKey key: String) -> Bool {
        let needsDisplayKeys = ["progress"]
        if needsDisplayKeys.contains(key) {
            return true
        }
        return super.needsDisplay(forKey: key)
    }

    override func display() {
        print("Display. \(progress) | \(presentation()?.progress)")
        super.display()
    }

    override func draw(in ctx: CGContext) {
        // Save / restore ctx
        ctx.saveGState()
        defer { ctx.restoreGState() }

        print("Draw. \(progress)")
        ctx.move(to: .zero)
        ctx.addLine(to: CGPoint(x: bounds.size.width * progress,
                                y: bounds.size.height * progress))
        ctx.setStrokeColor(UIColor.red.cgColor)
        ctx.setLineWidth(40)
        ctx.strokePath()
    }
}

Here's a full sample project if someone is interested:
https://www.dropbox.com/s/evkm60wkeb2xrzh/BrokenAnimation.zip?dl=0


text:
Q: How to add a report/custom page to ActiveAdmin? I am using ActiveAdmin for my Ruby on Rails application. My model consists of a couple entites such as "Plan", "Country", etc. I would like to have custom page for reporting purposes. This page should work on a collection of selected plans. So, I need scopes and filters. Currently one page associated with "Plan" model for CRUD operations. I don't want to add anything else to my data model or database since I have everything I need in my current model. How could I make such a page and access it through the menu?
Could I associate another page with my "Plan" model as follows?
ActiveAdmin.register Plan do
  menu label: 'Report', parent: 'Planning', priority: 2
  ...
end

Could I have a custom page working on set of plans selected using scopes and filters?
ActiveAdmin.register_page 'Report' do
   menu parent: 'Planning', priority: 2
   ...
end

Or, how could I add a new page/route to the currently associated page with "Plan" model for reporting? Can collection_action help me? If yes, how could I exactly bring a collection of Plans and show them?

A: You can register your ActiveRecord model several times in ActiveAdmin as a new resource:
ActiveAdmin.register Plan, as: 'PlanReport' do
  menu label: 'Report', parent: 'Planning', priority: 2
  ...
end

In this file you can use all of the ActiveAdmin features like scope and filters.
https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#rename-the-resource


text:
Q: Disconnecting a ZIF connector I'm trying to disconnect a ZIF connector (or at least I think that's what it is).  Here's me trying to disconnect it:

As you can see, I have been able to slide the 2 brown things at the end towards the cable, but then I tried to lift the white cover (see photo) and even push the white cover towards the cable, but neither is working.
Any suggestions?
Thanks.

A: Zero Insertion Force, or ZIF connectors, come in all sorts of shapes and sizes - yes, this is one.
Not even all of them will even have a clip that lifts. The one that you have here has that brown sliding tab, the tab is slightly angled internally so that when pushed in, it provides an upward / downward force on the cable and connector, holding it in place.
After pulling the brown tab out until it contacts its stops you should be able to just gently remove the cable.
To reinstall, stick it in but do not force it (zero insertion force), and then just push the brown tab back in.


text:
Q: what is purpose of 'named' in Lagom In the following code, I think that the services are given a name hello. Who uses this information? ServiceLocator?
named("hello")
      .withCalls(
        pathCall("/api/hello/:id", hello _),
        pathCall("/api/hello/:id", useGreeting _),
      )

A: This name hello is name of the service used by service locator.
Note, to register with the service locator, you would need to set withAutoAcl:
named("hello")
      .withCalls(
        pathCall("/api/hello/:id", hello _),
        pathCall("/api/hello/:id", useGreeting _),
      ).withAutoAcl(true)

Without providing withAutoAcl(true), the service would start but will not be registered with the service locator. And hence you would need to make a call directly to it (on its port), rather than via the service gateway (which by default is 9000).
By marking it true, service gateway gets configured automatically, to forward the hello related service calls to your implementaion.