text:
Q: Raspberry Pi Pico - Micropython - Get/Set mode of IO-Pin Is there a way to get/set the mode of a Pin object in MicroPython on the Raspberry Pi Pico?
The standard library has a Pin.mode() function, but it is not supported on the Pi Pico.
Is there a way to directly change/get the mode of a pin instance?
The only workaround for at least reading the pin mode I came up with is using a regular expression:
import re
from machine import Pin

def is_input(pin: Pin):
    """
    Returns True, if the pin object's mode is set as INPUT, else False.
    """
    return re.search(r'mode=(\w*)', str(pin)).group(1) == 'IN'

p = Pin(0, Pin.IN)
print(is_input(p)) #True
p = Pin(0, Pin.OUT)
print(is_input(p)) #False

A: I wrote a wrapper class to around the machine.Pin class which keeps track of the mode and pull setting and allows to change their values by re-initializing the underlying machine.Pin instance.
import machine.Pin

class Pin:
    """
    Wrapper around machine.Pin which keeps track of mode and pull settings.
    """

    def __init__(self, id, mode=machine.Pin.IN, pull=None, **kwargs):
        """
        :param id: GPIO number of the Pin
        :param mode: GPIO mode. Either machine.Pin.IN or machine.Pin.OUT; Defaults to machine.Pin.IN
        :param pull: GPIO pu/pd. Either machine.Pin.PULL_UP, machine.Pin.PULL_DOWN, None; Default to None
        :param kwargs: optional kw-only arguments for machine.Pin constructor
        """

        self._mode = mode
        self._pull = pull
        self._id = id
        self._pin = machine.Pin(id, mode=mode, pull=pull, **kwargs)

    def __getattr__(self, item):
        if item != '_pin':
            return getattr(self._pin, item)

    def __setattr__(self, key, value):
        if not hasattr(self, key) and hasattr(self._pin, key):
            setattr(self._pin, key, value)
        else:
            super().__setattr__(key, value)

    def mode(self, mode=None):
        """
        Get/set pin mode (input/output) by re-initializing pin.

        :param mode: Either machine.Pin.IN or machine.Pin.OUT
        :return: returns the current mode (machine.Pin.IN or machine.Pin.OUT) if mode was not provided.
        """

        if mode is None:
            return self._mode
        else:
            self._pin = machine.Pin(self._id, mode=mode, pull=self._pull)
            self._mode = mode

    def pull(self, pull=None):
        """
        Get/set pin pull-up/pull-down by re-initializing pin.

        :param pull: machine.Pin.PULL_UP, machine.Pin.PULL_DOWN, None
        :return: returns the current pull setting (machine.Pin.PULL_UP, machine.Pin.PULL_DOWN, None) if pull was not \
        provided.
        """

        if pull is None:
            return self._pull
        else:
            self._pin = machine.Pin(self._id, mode=self._mode, pull=pull)
            self._pull = pull


text:
Q: Bootstrap error iOS 5.0 simulator in Xcode 4.2 I have tried to clean out all targets and caches, restart Xcode, reset the simulator, kill all simulator processes and also restart my laptop,  but nothing works and the following error still shows:

Couldn't register com.yourcompany.myApp with the bootstrap server. Error: unknown error code. This generally means that another instance of this process was already running or is hung in the debugger.

A: Many have had this kind of error like here.
I restarted my Mac and this error did not reappear.

A: If you are running a Universal app in the simulator, build for the other device after you get this error.
So, if you got the error for the iPad sim, build for the iPhone without hitting "Stop" or closing the iPad sim.  That will build for the iPhone in this case, then once it's running, build for the iPad...or vice versa.  This is a quick fix without restarting, but it seems to stop working after a while.
It's also sometimes related to some of the AppDelegate methods like applicationWillTerminate, applicationWillEnterForeground, etc.  Check your appDelegate methods for any bugs.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to traverse up the dom with Jquery If I have this:

or if the title before doesn't exist then this title

this title

    some other stuff

    I am here

Not this title

As I understand $(':header') should find headers. What I need it to find the first header upwards from $('#this').

A: It's hideous, but it's a chunk that works for any level of nesting:
var $this = $('#this');

$this.add($this.parents()).map(function() {
  return $(this).prevAll(':header').eq(0);
}).get().pop();

Expanded:
$this.add(
  $this.parents()        // Adds $this's parents to the current selecor
).map(function() {       // Iterates over the selector
  return $(this)         // Returns each element's
    .prevAll(':header')  // Closest sibling header, vertically
    .eq(0);              // The first one
})
.get()                   // Gets the array from the jQuery object
.pop();                  // Trick for getting the last element

Demo: http://jsfiddle.net/xtQ2M/5/ (try deleting stuff)

A: var headers = $('#this')
        .prevAll(':header')  // all header within parent of `#this`
        .add($('#this')
                      .parent() // go to parent of `#this`
                       .prev(':header') // got the header out of `#this` parent
          );  // output [h1, h2];

DEMO
To get h1, use headers[0];
To get h2, use headers[1];
Also can use
$('#this')
         .prevAll(':header')  // all header within parent of `#this`
         .add($('#this')
                        .parent() // go to parent of `#this`
                        .prev(':header') // got the header out of `#this` parent
          ).
          .eq(0); // output: h1, if you use .eq(2) will get h2

A: You should be able to use $(this).closest('h2'); or $(this).closest('header'); It's hard to tell with your sample code. See jQuery.closest() for more info.

A: This seems to be a pretty readable way to do it in case you want to change some part of your logic in the future:
var target = $('#this'),
    closestHeader = target.siblings(':header');

while (!closestHeader.length) {
    target = target.parent();
    closestHeader = target.siblings(':header');
}
closestHeader = closestHeader[0];

Note: This will get stuck if there are absolutely no headers on the page, so you might want to add a check for that first.
See demo


text:
Q: How to show the same flutter app with different API urls depending on the user who enters? I have an application that is used by different users and diferents API urls, I need to have only  one app for the different users to enter and send the url of the API that corresponds to each user, but how can I do that validation?

A: I think you can assign roles to each user, then have a class that encompasses the different urls available to each role the user belongs too, then at the entry of the app (authentication) check the user role and use your state management to enable the api that should be available to the user based on their roles.
Your question is not specific enough but I do hope this helps


text:
Q: Query firestore database on timestamp field I'm relatively new with firestore (and programming) and wasn't able to find a solution to my problem online.
Looking to query documents in an existing collection.  The documents all have a timestamp field.
When I attempt to query for all documents ">" or "<" right now, the query works fine.  When I attempt to query for ">" or "<" 7 days ago, the query returns nothing.  I'm sure that I'm probably just missing something small.  Thanks for any help!
These return documents as expected:
var today = new Date();
db.collection("****").where('display', '==', true).where('createdAt', '>', today).get().then(function(querySnapshot) {

and
var today = new Date();
db.collection("****").where('display', '==', true).where('createdAt', '<', today).get().then(function(querySnapshot) {

These don't return anything:
var today = new Date()-604800000;
db.collection("****").where('display', '==', true).where('createdAt', '>', today).get().then(function(querySnapshot) {

and
var today = new Date();
db.collection("****").where('display', '==', true).where('createdAt', '>', today-604800000).get().then(function(querySnapshot) {

and just for the heck of it
var today = new Date()-1;
db.collection("****").where('display', '==', true).where('createdAt', '>', today).get().then(function(querySnapshot) {

I've seen others request a look at what the field looks like in Firestore so here is a pic:
sorry it's a link
Please let me know if there is anything else that might be helpful.  Thanks!
EDIT TO SHOW NEXT ATTEMPT:
var config = {****};
firebase.initializeApp(config);

const db = firebase.firestore();
const settings = {/* your settings... */ timestampsInSnapshots: true};
db.settings(settings);

var today = new Date();
var yesterday = date.setDate(today.getDate() - 1);
db.collection("****")
    .where('display', '==', true)
    .where('createdAt', '>', yesterday)
    .get()
    .then(function(querySnapshot) {console.log(createdAt)});

A: Ok. So I got some assistance from a very helpful Google developer.
This ended up working.
var beginningDate = Date.now() - 604800000;
var beginningDateObject = new Date(beginningDate);

db.collection("****")
    .where('display', '==', true)
    .where('createdAt', '>', beginningDateObject)
    .get()
    .then(function(querySnapshot) {console.log(/* ... */)});


text:
Q: How much video can you record on a 64 GB iPhone 12? I'm considering a phone upgrade, but don't really need a lot of storage.
Approximately, how much of different resolutions video, can one record onto a 64GB iPhone 12?
How many minutes of video would a gigabyte of HDR Video Recording with "Dolby Vision" contain? How can I research this without knowing the technical specifics of a format I cannot access until I purchase a phone?
I'm not looking for very exact answers, just an approximation of HD video sizes and lengths in the context of the camera tech used in this specific phone.

A: The Camera settings on iPhone 12 shows

*

*4K @ 60fps is 440MB per minute.

*4K @ 30fps is 190MB per minute.

I don't have an iPhone 12 to know exactly how much space is reserved by iOS but supposing it's 15 GB that leaves 110 minutes of 4k60 or 257 minutes of 4k30.

A: In addition to the other answers, in iOS's camera settings there's a little summary of the amount of data each minute of video at different resolutions/FPS. You can see this summary of how much space it takes per each minute of video in Settings>Camera>Record Video
This is what is says for my iPhone XS, so it would be different on an iPhone 12 with the latest hardware.


text:
Q: Is primary objective mandatory for activities? I want to know if primary objective is mandatory for activities?
Thank you

A: No, you don't have to declare a primary objective for each activity. In fact if you don't declare a primary objective, the LMS will create one for you since the LMS uses the primary objective in the rollup and sequencing  processes. However, if you create local objectives, you have to declare a primary objective in your manifest file.


text:
Q: Individual Checkbox on HTML Table I am currently displaying my HTML data through a PHP script into my Table on the Website.
No here's the problem: I want to have a checkbox besides every entry on the website, the user can then check or uncheck the checkbox, his decision is then sent via a submit button. But in my PHP script i dont think im able to create an individual checkbox for every entry so that my Script knows which assignment is done or not done.
I hope this makes any sense, if not feel free to ask.
My Code:

Fach
Name
Abgabedatum
    Erledigt

<?php
$conn = mysqli_connect("localhost:3306", "xnmmgfa1_Lernjournal", "Lernjournal2021", "xnmmgfa1_LJ");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Fach, Name, Abgabedatum FROM Lernauftraege";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "
" . $row["Fach"]. "	" . $row["Name"] ."	"
. $row["Abgabedatum"].  "	" . "<input type='checkbox' id'erledigt' name='$id'>" . "
";
}
echo "
";
} else { echo "0 results"; }
$conn->close();
?>
    <button type="submit" name="b_erledigt">Senden</button>

```

A: You can use the array notation as input name.
<input type="checkbox" name="userselection[]" value="$row['id']"/>

And in your PHP code that handles the submitted form
$userselection = $_POST['userselection'];
foreach ($userselection as $selectedId) {
  /* whatever you wanna do with the selected rows... */
}


text:
Q: Superposition of QWidget in PyQt5 I don't know why but my 2 custom widgets(SquareCalc, LinePainting) when i use them in QXBoxLayout(twoWidgets) , there are being superimposed each other one.
I'm using python 3.5.2 with PyQt5
This is my code:
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QColor, QPainter, QPen
from PyQt5.QtWidgets import (QApplication, QWidget,
                             QGridLayout, QVBoxLayout, QHBoxLayout,QLabel, QLineEdit, QPushButton)

class SquareCalc(QWidget):
    def __init__(self):
        super().__init__()

    def initUI(self):

        self.setGeometry(0,0,100,100)
        self.inputLine = QLineEdit()
        self.outputLine = QLineEdit()
        self.outputLine.setReadOnly(True)

        self.inputLine.returnPressed.connect(self.calc)
        self.calcButton = QPushButton("&Calc")
        self.calcButton.clicked.connect(self.calc)

        lineLayout = QGridLayout()
        lineLayout.addWidget(QLabel("num"), 0, 0)
        lineLayout.addWidget(self.inputLine, 0, 1)
        lineLayout.addWidget(QLabel("result"), 1, 0)
        lineLayout.addWidget(self.outputLine, 1, 1)

        buttonLayout = QHBoxLayout()
        buttonLayout.addWidget(self.calcButton)

        mainLayout = QVBoxLayout()
        mainLayout.addLayout(lineLayout)
        mainLayout.addLayout(buttonLayout)

        self.setLayout(mainLayout)

    def calc(self):
        n = int(self.inputLine.text())
        r = n**2
        self.outputLine.setText(str(r))

class LinePainting(QWidget):
    def __init__(self):
        super().__init__()

    def initPainting(self):
        self.setGeometry(0, 0, 300, 300)
        self.setWindowTitle('Pen styles')
        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self)
        self.show()

    def paintEvent(self, e):

        qp = QPainter()
        qp.begin(self)
        self.drawLines(qp)
        qp.end()

    def drawLines(self, qp):

        pen = QPen(Qt.black, 2, Qt.SolidLine)

        qp.setPen(pen)
        qp.drawLine(20, 40, 250, 40)

        pen.setStyle(Qt.DashLine)
        qp.setPen(pen)
        qp.drawLine(20, 80, 250, 80)

        pen.setStyle(Qt.DashDotLine)
        qp.setPen(pen)
        qp.drawLine(20, 120, 250, 120)

        pen.setStyle(Qt.DotLine)
        qp.setPen(pen)
        qp.drawLine(20, 160, 250, 160)

        pen.setStyle(Qt.DashDotDotLine)
        qp.setPen(pen)
        qp.drawLine(20, 200, 250, 200)

        pen.setStyle(Qt.CustomDashLine)
        pen.setDashPattern([1, 4, 5, 4])
        qp.setPen(pen)
        qp.drawLine(20, 240, 250, 240)

class twoWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.widget1 = SquareCalc()
        self.widget2 = LinePainting()

        mainLayout = QHBoxLayout()
        mainLayout.addWidget(self.widget1)
        mainLayout.addWidget(self.widget2)

        self.setLayout(mainLayout)
        self.setWindowTitle("Mix line/factorial")
        self.widget2.initPainting()
        self.widget1.initUI()
        self.show()

if __name__ == '__main__':

    app = QApplication(sys.argv)
    main_window = twoWidget()
    main_window.setStyleSheet(open("lol.qss", "r").read())
    main_window.show()

sys.exit(app.exec_())

A: I find the problem , i just need no put a fixed size to my widget SquareCalc,
just add
self.setFixedSize(sizeX,sizeY)

In replace of :
self.setGeometry(0, 0, 300, 300)

Just because QPainter no need to have a minimum size , on the contrary QLineEdit() and QPushButton(), yes


text:
Q: Why don't electrons just "pile up" on the positive side of a battery? Consider an extremely simple circuit:

simulate this circuit – Schematic created using CircuitLab
Since electrons are negatively charged, the current will flow towards the positive side of the battery. Why do they not "stop" there? Since passing through the battery will send them to a region with a negative charge which should repel them?

A: It takes energy to pile up free electrons into one end of the battery since electrons want to repel each other. Naturally, you don't want this to happen in a battery that you want to keep running since the repulsion of the electrons would quickly reach equilibrium with the the energy being produced by the battery to move them and bring everything to a standstill.
But, the electrons are piling up in a sense. After all, they can't just disappear but the catch is free electrons. They are piling up but do not remain as as free electrons. What is happening is that there are two different chemical reactions occurring at the anode and cathode working in tandem. At the cathode there is an exothermic chemical reaction that releases both energy and free electrons, and at the anode there is another chemical reaction that consumes free electrons, incorporating them into the product molecule.
The reaction at the anode does not also necessarily need to be exothermic. It could be endothermic; It just needs to consume less energy than is produced by the reaction at the cathode so that the battery produces a net positive of energy.
In this way, the battery produces energy with the electrons as the energy carriers, and generates new free electrons that pile up at the cathode thus repelling each other to move towards the anode through the circuit (there is a barrier inside the battery separating the anode and cathode), while the reaction at the anode prevents the electrons from piling up there which would result in repulsion that would eventually stop the flow of energy and electrons.
When charging a rechargeable battery, everything is opposite in terms of energy and electrons.

A:
Since electrons are negatively charged, the current will flow towards
the positive side of the battery. Why do they not "stop" there? Since
passing through the battery...

Current is the flow of charge, not necessarily electrons.
The electrons don't pass through the battery. They come out from the negative terminal and go back into the positive terminal, and that's it.
Here's an illustration of how it works in a Li-ion battery:-

When charging the battery, the charger sucks electrons out of the cathode ('+' terminal), and pushes electrons into the anode ('-' terminal). This 'pumps' lithium ions through the electrolyte from the cathode (+) to the anode (-). The electrons can't move through the electrolyte, so they all 'pile up' at the anode.
When an external circuit is connected the electrons flow through the wires from the anode back to the cathode, and the lithium ions move back through the electrolyte to meet them.
It is the ions inside the battery that transport charge. Thus current flows there, but electrons don't.
The other important thing to note is that no matter how much current flows, each electron only does (at most) one round trip from one plate to the other, while each ion shuttles from one side of the battery to the other.
This is why a battery can only store a limited amount of charge. Once all the ions have been pushed from one side to the other, that's it - the battery is 'full'.


text:
Q: PHP mysqli query result repeats last row when returning multiple rows Hi all I have the following function:
Function Query($sql, $parameters, &$results, $result_types = null)
{
    if($this->debug)
        $this->OutputDebug('Query: '.$sql);
    $results = array();
    $statement = $this->db->stmt_init();
    if(!$statement->prepare($sql))
        return $this->SetError($statement->error);
    $prepared = array();
    $types = '';
    $tp = count($parameters);
    $v = $parameters;
    for($p = 0; $p < $tp;)
    {
        switch($t = $v[$p++])
        {
            case 's':
            case 'i':
            case 'd':
                $v[$p] = (IsSet($v[$p]) ? $v[$p] : null);
                break;
            case 'b':
                $v[$p] = (IsSet($v[$p]) ? ($v[$p] ? 'Y' : 'N') : null);
            case 't':
            case 'dt':
            case 'ts':
                $t = 's';
                break;
        }
        $types .= $t;
        if($this->debug)
            $this->OutputDebug('Query parameter type: '.$t.' value: '.$v[$p]);
        $prepared[] = &$v[$p++];
    }
    array_unshift($prepared, $types);
    if(!call_user_func_array(array($statement, 'bind_param'), $prepared)
    || !$statement->execute())
    {
        $error = $statement->error;
        $statement->close();
        return $this->SetError($error);
    }
    $fields = $statement->field_count;
    if($fields)
    {
        $row = $bind = array();
        for($f = 0; $f < $fields; ++$f)
        {
            $row[$f] = null;
            $bind[$f] = &$row[$f];
        }
        if(!call_user_func_array(array($statement, 'bind_result'), $bind))
        {
            $statement->close();
            return $this->SetError($statement->error);
        }
        $rows = array();
        $i = 0;
        while(($success = $statement->fetch()) !== null)
        {
            if(!$success)
            {
                $statement->close();
                return $this->SetError($statement->error);
            }
            if(IsSet($result_types))
            {
                $tc = count($result_types);
                for($c = 0; $c < $tc; ++$c)
                {
                    if(!IsSet($row[$c]))
                        continue;
                    switch($result_types[$c])
                    {
                        case 'b':
                            $row[$c] = ($row[$c] === 'Y');
                            break;
                    }
                }
            }
            $rows[] = $row;
        }
        $results['rows'] = $rows;
    }
    elseif(strlen($error = $statement->error))
    {
        $statement->close();
        return $this->SetError($error);
    }
    else
    {
        $results['insert_id'] = $statement->insert_id;
        $results['affected_rows'] = $statement->affected_rows;
    }
    $statement->close();
    return true;
}

Now lets assume a simple table called roster as follows:

*

*id      player      team

*116        6          2

*117        6          3

*118        3          5

Now lets call the function:
$parameters = array(
    'i', 0
);
$result_types = array('i');
$this->Query( 'SELECT id FROM roster WHERE player != ? ORDER BY id', $parameters, $results, $result_types);

From this I would expect to get 116, 117 & 118 returned as part of the array from $results.  Instead I get 118, 118 & 118!!
A print_r(array_values($results)); returns:
Array ( [0] => Array ( [0] => Array ( [0] => 118 ) [1] => Array ( [0] => 118 ) [2] => Array ( [0] => 118 ) ) )

What have I done wrong here please?


text:
Q: How can I fix my VBA code in Excel to delete certain chart legend entries based on their value? I have a graph with 5 series of data.  I want all 5 series to show up on the graph, but I only want 3 of them to show up in the legend.  I'd like for the legend entries to be deleted based on the name of the series... "Target Range Upper" and "Target Range Lower" should be excluded from the legend.
I've got code that I think should work, but I'm getting an error message and I can't figure out why.
Here is the code I've tried:
Sub Charts_RemoveLegendEntry()
Dim i As Long
Dim cht As Chart
Dim lgd As Legend
 Set cht = ActiveChart
   Set lgd = cht.Legend
   For i = cht.SeriesCollection.Count To 1 Step -1
         Select Case cht.SeriesCollection(i).Name
         Case "Target Range Upper", "Target Range Lower"
                 lgd.LegendEntries(i).Delete
         Case Else
                 ' do nothing
         End Select
   Next
End Sub

Oddly, if I swap the bottom portion around like this:
Select Case cht.SeriesCollection(i).Name
Case "Target Range Upper", "Target Range Lower"
     ' do nothing
Case Else
     lgd.LegendEntries(i).Delete
End Select

The Macro works perfectly - just doing the inverse of what I want.  It gets rid of the legend entries I want to keep and keeps the ones I want to delete.  I'm not understanding why it doesn't work both ways.
I'll need to do this for a couple other graphs in the workbook as well, but if I can figure 1 out, I should be able to adjust for the others.
*UPDATE EDIT
Changing For i = cht.SeriesCollection.Count To 1 Step -1 to For i = lgd.LegendEntries.Count To 1 Step -1 worked for this graph.  However, I tried to recreate the macro for a different graph on a different worksheet and I am now getting a "Run-time error '91': Object variable or With block variable not set" error message.  What am I missing?  Here is my 2nd code for the next worksheet...
    Sub Charts_RemoveLegendEntry2()
    Dim i As Long
    Dim cht As Chart
    Dim lgd As Legend
     Set cht = ActiveChart
       Set lgd = cht.Legend
       For i = lgd.LegendEntries.Count To 1 Step -1
             Select Case cht.SeriesCollection(i).Name
             Case "Total", ""
                     lgd.LegendEntries(i).Delete
             Case Else
                     ' do nothing
             End Select
       Next
End Sub

It appears to be breaking on the For i = lgd.LegendEntries.Count To 1 Step -1 line.


text:
Q: Laravel Multi-language Support I am trying to get my website to support multiple languages, but my code does not work:
Route:
Route::get('lang/{lang}', function($lang){
    Session::put('lang', $lang);
    return Redirect::to('/');
});

Main page:
[Farsi]
[English]

Language folders:
fa folder have messages.php:
return array(
    'mainpage'=>'صفحه اصلی',
);

en folder have messages.php:
return array(
    'mainpage'=>'Main Page`,
);

Now I am trying to use this array to have multi-language support and I am using this code to switch between languages:
{{ Lang::get('messages.mainpage') }}

A: Problem solved, Thanks to @rezakho,
after adding this line to route.php:
if ( Session::has('lang') ) {
        App::setLocale(Session::get('lang'));
    }

or you change before on filters.php file:
App::before(function($request)
{
    if ( Session::has('lang') ) {
        App::setLocale(Session::get('lang'));
    }
});


text:
Q: php script that includes class structure doesn't work I have a php script running on centos 5.x
When i use a code like
$db->connect();

php script doesn't work.I use php myscript.php
and it does nothing.
..
..
..
$db->connect();
echo "Hello world";

when i run above script it does nothing.Nothing means the like this;
[root@xxxxxxx update_call_history]# php update_call_history.php  {press enter}
[root@xxxxxxx update_call_history]#
but if i change the script like this
echo "hello world";

it works.I think my php doesnt run class structured script,Is there any missing module or what.
Thanks for advance...

A: If all the information you've been able to gather is "doesn't work" you need to do two things:

*

*Configure your environment to generate and display/log all error messages.

*Check the return value of the function calls, test whether it was successful and print the exact error message if not.

A: php-mysql module wasn't installed so it couldn't connect to database.

A: Make sure that:

*

*mysql server is on

*you have turned on error reporting

*you are specifying correct credentials


text:
Q: Why am I getting SSLError in google-analytics in iOS 9.3.2 and 10.0.1? I have integrated Google Analytics 3.15. It is working fine for all other iOS versions than iOS 9.3.2 and 10.0.1. I am getting following error in to this.
NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9802)
Dispatch error: Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={NSURLErrorFailingURLPeerTrustErrorKey=<SecTrustRef: 0x1701157b0>, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9802, NSErrorPeerCertificateChainKey=(
"<cert(0x1018ed200) s: *.google-analytics.com i: Google Internet Authority G2>",
"<cert(0x1018efa00) s: Google Internet Authority G2 i: GeoTrust Global CA>",
"<cert(0x1018f0200) s: GeoTrust Global CA i: Equifax Secure Certificate Authority>"

I have setup Info.plist on the basis of following analysis. On Terminal I have hit following command:
/usr/bin/nscurl --ats-diagnostics --verbose https://ssl.google-analytics.com

I have got one more information by hitting following command.
curl -kvI https://ssl.google-analytics.com

Output of the above command:

Please find my info.plist for ATS:

I have tried with following links:

*

*iOS9 GoogleAnalytics and NSAppTransportSecurity

*Google Analytics (iOS SDK) without SSL

*App TranSport security, allow arbitrary load not working after upgrade to IOS 10.1
Please help me to understand what is the mistake I am doing here.

A: Thanks for the comments but after lots of research I came to know that reason for error.I have fixed by just changing the Date and Time of iPhone to Automatic from Manual.I know it's very simple fix but it took 5 days to analyze and fix.


text:
Q: how to save checkbox value in array form? How to save multiple checkbox value into database? now the value is storing in different rows. example: i selected value 1 and 2.so the value 1  in 1 row and value 2 in another row.
blade
  <form enctype="multipart/form-data" action="/report/{{$postqs->id}}"
     method="POST">

   <input type="checkbox" name="item[]" value="one" />1
   <input type="checkbox" name="item[]" value="two" />2
   <input type="checkbox" name="item[]" value="three" />3

 Others:

 <textarea name="report" id="report" class="form-control"></textarea>

 <input type="hidden" name="_token" value="{{ csrf_token() }}">
 <input type="submit" class="pull-right btn btn-sm btn-primary">

</form>

Report model
protected $fillable = ['report','postqs_id','user_id','item'];

Store controller :
   public function store(Request $request,Postqs $postqs,$id,Report $report,
   Admin_report $admin_report)
{

    foreach ($request->input("item") as $key=>$value){
        $add_item = new Report;
         $add_item->item= $value;
         $add_item->user_id= Auth::user()->id;
         $add_item->postqs_id=$id;
         $add_item->save();

        return back();

    }

A: You should separate items as key and value so that you can save the value and the error it gives you shows that it needs user_id, so add the user_id to it., and your code should look like this:
foreach ($request->input("item") as $key=>$value){
       $add_item = new Report;
        $add_item->item= $value;
        $add_item->user_id= Auth::user()->id;
        $add_item->postqs_id=$id;
        $add_item->save();
}

Because you want the value of the checkboxes, not the key. In the way you do it, it saves key and value together in the item column.
#Update
In this situation (saving array into DB) you don't put item input into foreach loop, and just save it as what it is, before that you must tell to your model to treat that as an array by putting $casts property into Report model:
protected $casts = [
        'items'=>'array',
    ];

This way it should save as array into items column. after that you just save items like this code below:
        $add_item = new Report;
        $add_item->item= $request->input("item");
        $add_item->user_id= Auth::user()->id;
        $add_item->postqs_id=$id;
        $add_item->save();

Note that there is no need for foreach loop in this scenario.

A: It seems you need to add user_id to insert a new Report.
$user = auth()->user();

foreach ($request->input("item") as $item){
    $add_item = new Report;
    $add_item->user_id= $user->id;
    $add_item->item= $item;
    $add_item->save();
}


text:
Q: Converting c++ struct to c# struct Can anybody tell me how do I convert the following struct to c#
typedef struct DES_ks
{
    union
    {
        DES_cblock cblock;
        /* make sure things are correct size on machines with
         * 8 byte longs */
        DES_LONG deslong[2];
    } ks[16];
} DES_key_schedule

A: You will need to look up the typedef's for DES_cblock and DES_LONG to translate this. However, to get you started, you'll want to read up on StructLayoutAttribute. The way to translate C unions into C# is to use an explicit layout structure:
[StructLayout(LayoutKind.Explicit)]
public struct DES_ks
{
  [FieldOffset(0)]
  public DES_cblock cblock;
  [FieldOffset(0)]
  [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
  public DES_LONG[] deslong;
}

Thanks to @Konrad for fixing my temporary insanity; because you want to produce a union, you need all of the fields to overlap in memory. This is achieved in C# by telling the compiler to lay them out at the same offset, in this case 0.

A: C# does not have unions.. The closest you can come is using FieldOffset. However, if your struct isn't being passed directly to external functions, you're likely better off using a more OO approach. I'd suggest just creating a struct with arrays of both types and set the one you aren't using to null.


text:
Q: Designing a grism spectrometer I have read about grism spectrometers, e.g. in the work by F. Sigernes, and would like to try to make my own. However, I have some practical questions regarding the design:

*

*F. Sigernes uses camera lenses as front and focusing lens. Could I use single lenses instead? Or would e.g. chromatic aberration make it impractical?

*As I understand it, a very narrow slit is impractical. But when making the calculations for the sensor and wavelengths I'd like to use, I get that the slit width should be 500μm (compared to F. Sigernes' 25μm). Could this have some practical implications?

I have not been able to find any more information regarding practical grism spectrometer design, so any pointers regarding this would also be appreciated.

A: The grism spectrometer works on the same basic principles as any standard grating spectrometer, so you should be able to find more information by looking at those. The main differences, of course, are that the grism spectrometer uses refractive optics and a different dispersive element.
Choosing optics and a slit for this design will involve a series of tradeoffs. It basically all comes down to throughput and resolution (and practicality, including cost). Since you're building this yourself and want to use single lenses, I'm assuming that you're sensitive to cost.
First, what spectral resolution and overall bandwidth do you need? This will determine how wide your slit can be, for a given grating (resolution is nearly proportional to slit width, assuming your camera has a small pixel size).  The higher the groove density of the grating/grism, the more diffractive. So you can get the same spectral resolution with a higher groove density and a larger slit width. But the trade-off with this configuration is that you'll have a lower field of view (lower overall spectral range) since the with more diffraction you're essentially "zooming in" in the spectrum. Also, more diffractive gratings are more polarization- and frequency-sensitive in their diffraction efficiency, which may or may not be problematic.
On the other hand, if you use a narrower slit and less diffractive grating, then for the same resolution you have smaller light throughput. So, the next question would be how much light do you have? The throughput you need is generally tough to gauge since it depends on many factors. Better to just try it, but be aware of the general tradeoffs. Actually, the slit width/throughput trade-off also depends on the focusing power of your initial lens. You'll basically want to choose the focal lengths for the first two lenses (those around the slit) to focus the light enough to get most of it through the slit, and then recollimate it expanded to be about the size of the grism.
Regarding chromatic aberration, again this depends on the specifics of your setup: how much resolution you need, your bandwidth of interest, the geometry of your setup (chromatic aberration is irrelevant for a big setup with long-focal-length lenses). Decent AR-coated achromatic doublets are available for less than $100 from, say, ThorLabs, if you think it will be necessary.
You also want to make sure that spherical aberration isn't a problem. The key to this is to either use achromatic lenses or large lenses (for which the beam is a small-ish fraction of the diameter). If you have a lot of spherical aberration, the edges of your spaces image will be bad.
Good luck! Have fun!


text:
Q: Why is $120^{128}+1$ a prime number Wolfram Alpha says that the number $120^{128}+1$ is prime.  I wonder if that is in fact true, and if so, what is an argument for it.
Thank you for your interest!

A: If given the correct command, WolframAlpha can tell us that $22$ is a primitive root modulo $120^{128}+1$.

*

*PowerMod[22, 120^128/{1, 2, 3, 5}, 120^128 + 1] computes the list $\{ 22^{120^{128}}, 22^{120^{128}/2}, 22^{120^{128}/3}, 22^{120^{128}/5} \}$ modulo $120^{128}+1$.

*The fact that $22^{120^{128}} \equiv 1 \pmod {120^{128}+1}$ tells us that the order of $22$ modulo $120^{128}+1$ is a divisor of $120^{128}$.

*The fact that $22^{120^{128}/2} \not\equiv 1 \pmod {120^{128}+1}$ tells us that the order of $22$ modulo $120^{128}+1$ is not a divisor of $120^{128}/2$. Similarly, the order of $22$ modulo $120^{128}+1$ is not a divisor of $120^{128}/3$ nor a divisor of $120^{128}/5$.

*Since $2$, $3$, and $5$ are the only primes dividing $120^{128}$, we conclude that the only divisor of $120^{128}$ that is not a divisor of any of $120^{128}/2$, $120^{128}/3$, or $120^{128}/5$ is $120^{128}$ itself.

*Therefore the order of $22$ modulo $120^{128}+1$ is exactly $120^{128}$, which implies that $120^{128}+1$ is prime.

($22$ is simply the first primitive root I found; the smallest three primitive roots are $19$, $22$, and $29$.)

A: I can't find any public documentation of how WolframAlpha does primality testing. The simplest generally applicable option for numbers this large is the Fermat primality test, which for a positive integer $p$ means randomly choosing integers $a \in [2, p-2]$ and testing whether or not $a^{p-1} \equiv 1 \bmod p$. With $p = 120^{168}$ this computation can be done using binary exponentiation without too much hassle; the only prime factors of $120$ are $2, 3, 5$ we could do it by repeatedly taking second, third, and fifth powers, and for fifth powers we could use $5 = 2^2 + 1$ to speed the calculation up a bit too.
Unfortunately the Fermat primality test is really a compositeness test; if it finds $a$ such that $a^{p-1} \not \equiv 1 \bmod p$ then $p$ is composite, but if it doesn't then $p$ is only a probable prime. By finding more and more values of $a$ that probability can be driven arbitrarily low but it's still not a proof. There are variants here like the Solovay-Strassen primality test, the Miller-Rabin primality test, or the Baillie-PSW primality test.
For $p$ such that the prime factorization of $p - 1$ is known we can also apply the test Greg Martin describes which is called the Lucas primality test, which I just learned about right now. This one really is a primality test: if a number passes then it is provably prime.
Mathematica has a function ProvablePrimeQ which generates certificates proving that numbers are prime based on elliptic curve primality tests; I don't know if this is what WolframAlpha is doing. It might be some heuristic combination of tests depending on what seems like it would be easiest to apply?
Edit: Documentation linked to on Wikipedia says that Mathematica's PrimeQ function uses a variation of the Baillie-PSW test:

PrimeQ first tests for divisibility using small primes, then uses the Miller–Rabin strong pseudoprime test base 2 and base 3, and then uses a Lucas test. There are no known composite numbers that pass this procedure.


text:
Q: maven scope test with selenium What is the difference when we use scope as test for some dependency in pom.xml file for a selenium project.
Example : Difference between
<dependency>
 <groupId>org.seleniumhq.selenium</groupId>
 <artifactId>selenium-java</artifactId>
 <version>3.141.59</version>
 <scope>test</scope>
</dependency>

AND
<dependency>
 <groupId>org.seleniumhq.selenium</groupId>
 <artifactId>selenium-java</artifactId>
 <version>3.141.59</version>
</dependency>

A: The default scope is compile.
This scope adds the dependency to the project at compile-time and will also be exported when you create a JAR with dependencies (or similar)
The test scope adds the dependency just for test sources(e.g. Unit tests/located in src/test in most cases). It can only be accessed from test sources and will not be export(except to a test JAR)
If you only need selenium in the test code of the project, I recommand using the test scope.

A: Dependency Scope in Maven
The Dependency scope is used to limit the transitivity of a dependency which also effects the classpath used for various build related tasks.
Currently the following 6 dependency scope are supported by maven:

*

*compile: compile scope is the default scope which is used if none is specified. Compile dependencies are available in all classpaths of a project. These dependencies are propagated to dependent projects.

*

*Exmaple:
<scope>compile</scope>

*provided: provided scope is almost similar to compile but indicates you expect the JDK or a container to provide the dependency at runtime.

*

*Exmaple:
<scope>provided</scope>

*runtime: runtime scope indicates that the dependency is not required at compile time but only for execution. It is in the runtime and test classpaths, but not the compile classpath.

*

*Exmaple:
<scope>runtime</scope>

*test: test scope indicates that the dependency is not required for normal use of the application and is only available for the test compilation and execution phases. This scope is not transitive.

*

*Exmaple:
<scope>test</scope>

*system: system scope is similar to provided except that you have to provide the JAR which contains it explicitly. The artifact is always available and is not looked up in a repository.

*

*Exmaple:
<scope>system</scope>

*import: import scope is only supported on a dependency of type pom in the <dependencyManagement> section. It indicates the dependency to be replaced with the effective list of dependencies in the specified POM's  section.

*

*Exmaple:
<scope>import</scope>


text:
Q: PHP using DOM to extract img src, and keep its place within text So I'm building a simple HTML scraper, in the text there are some images for the symbols and what I need is to get the src of this img tags, but keep them in the same place as the img tags where in the text.
--question rewritten due to me being asking the wrong thing.

A: Well, I'd really suggest using a proper HTML parsing library to do this, but if it's really simple you can get away with a regex like /<img[^>]*alt="(\d+?)"/ or so.

A: if you want to get the name= part from the src attribute which is /Handlers/Image.ashx?size=small&name=3&type=symbol you can try this
<?php
$src = '/Handlers/Image.ashx?size=small&name=3&type=symbol';
$x = preg_replace('/^.*name=([^&]*).*$/i','[$1]',$src);
echo $x;
?>

A: Since you're using DOM parser so you can extract image's src attribute in a variable. After that use following code:
$imgsrc = '/Handlers/Image.ashx?size=small&name=3&type=symbol';
$url = parse_url($imgsrc);
$query = htmlspecialchars_decode($url['query']);
parse_str($query, $arr);
echo $arr['name'] . "\n"; // prints 3


text:
Q: How can I recreate this query in ActiveRecord I know this sounds like a "do my homework for me" question, but I've been struggling with recreating this query with ActiveRecord for a while and am now wondering if it's possible to do this without resorting to using ActiveRecord::Base.connection.execute
The structure is basically:
Member has_many orders and transactions
I need to display all the members who have placed an order, the total amount from orders, and the number of transactions for a given date range ordered by the total amount.
I can get the data I need with the following query:
SELECT members.*,
SUM(orders.amount) AS total_amount,
COUNT(transactions.id) AS total_transactions
FROM members
INNER JOIN orders ON (orders.member_id = member.id)
LEFT JOIN transactions ON (transactions.member_id = members.id)
WHERE orders.created_at BETWEEN "2012-03-01" AND "2012-04-01"
GROUP BY member.id
ORDER BY total_amount DESC

Is it possible to formulate this query via ActiveRecord?

A: This is how I'd do it through ActiveRecord:
Member.includes(:orders, :transactions).select("SUM(orders.amount) as total_amount").where("orders.created_at BETWEEN '2012-03-01' AND '2012-04-01'").group('members.id').order('total_amount DESC')

This includes a lot of raw SQL snippets. If you want to replace those with actual Ruby code you can do that by using Member.arel_table creatively. See the Arel documentation for information on how to do that.


text: Q: Max size VHD on exFat-drive? I have an exFat drive (LaCie Fuel) that is 2 TB. On this drive I try to create a 127 GB VHD using Computer Management in Windows 7 but it fails with an error "The requested operation could not be completed due to a file system limitation.". Both VHD and exFat supports files that are significantly bigger than so. What is the problem? Any workarounds?


text:
Q: How to add report_tensor_allocations_upon_oom to RunOptions in Keras I'm trying to train a neural net on a GPU using Keras and am getting a "Resource exhausted: OOM when allocating tensor" error.  The specific tensor it's trying to allocate isn't very big, so I assume some previous tensor consumed almost all the VRAM.  The error message comes with a hint that suggests this:

Hint: If you want to see a list of allocated tensors when OOM happens, add report_tensor_allocations_upon_oom to RunOptions for current allocation info.

That sounds good, but how do I do it?  RunOptions appears to be a Tensorflow thing, and what little documentation I can find for it associates it with a "session".  I'm using Keras, so Tensorflow is hidden under a layer of abstraction and its sessions under another layer below that.
How do I dig underneath everything to set this option in such a way that it will take effect?

A: Currently, it is not possible to add the options to model.compile. See: https://github.com/tensorflow/tensorflow/issues/19911

A: OOM means out of memory. May be it is using more memory at that time.
Decrease batch_size significantly. I set to 16, then it worked fine

A: TF1 solution:
Its not as hard as it seems, what you need to know is that according to the documentation, the **kwargs parameter passed to model.compile will be passed to session.run
So you can do something like:
import tensorflow as tf
run_opts = tf.RunOptions(report_tensor_allocations_upon_oom = True)

model.compile(loss = "...", optimizer = "...", metrics = "..", options = run_opts)

And it should be passed directly each time session.run is called.
TF2:
The solution above works only for tf1. For tf2, unfortunately, it appears there is no easy solution yet.

A: Got the same error, but only in case, the training dataset was about the same as my GPU memory. For example, with 4 Gb video card memory I can train the model with the ~3,5 GB dataset. The workaround for me was to create the data_generator custom function, with yield, indices, and lookback.
The other way I was suggested was to start learning true tensorflow framework and with tf.Session (example).

A: OOM is nothing but "OUT OF MEMORY".
TensorFlow throws this error when it runs out of vRAM while loading batches into memory.
I was trying to train a Vision Transformer on CIFAR-100 dataset.
GPU:
GTX 1650 w/ 4GB vRAM
Initially, I had the batch_size set to 256, which was totally insane for such a GPU, and I was getting the same OOM error.
I tweaked it to batch_size = 16 (or something lower, which your GPU can handle), training works perfectly fine.
So, always choose a smaller batch_size if you are training on laptops or mid-range GPUs.


text:
Q: How to use css3 to achieve a ball bounce effect? In fact I have almost successs:
I have a div needed to bounce :

This is card

then I use css3 animate to achieve bounce effect:
.container{
    width: 100%;
    height: 100%;
    -moz-perspective: 1000px;
}
.flipcard{
    background: red;
    width: 200px;
    height: 300px;
    position: absolute;
    top: 40px;
    left: 20px;
    -webkit-transform-style: preserve-3d;
    -webkit-transition:all 0.6s ease-in-out;
}
.allowhover:hover{
    -webkit-animation-name: bounce;
    -webkit-animation-duration: 1.5s;
    -webkit-animation-iteration-count: infinite ;
    -webkit-animation-direction: normal;
}

@-webkit-keyframes bounce {
   25% {
     top:7px;
   }
   45% {
     top:40px;
   }
   64% {
      top:19px;
   }
   76% {
      top:40px;
   }
   96%{
      top: 25px
   }
   100% {
      top:40px;
   }
}

now the online example is here :http://jsfiddle.net/GEEtx/
It seems work, but not good enough,how should I set the key-frames parameter to make it bounce more like a ball?Is there a formula to calculate the bounce height and countaccording to the element's width and height, or the time?

A: With little trial and error we can figure out the bounce effect as needed.
There is this formula that is used in all jQuery easing plugins to get the bounce effect.
        easeInBounce: function (x, t, b, c, d) {
                return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
        },
        easeOutBounce: function (x, t, b, c, d) {
                if ((t/=d) < (1/2.75)) {
                        return c*(7.5625*t*t) + b;
                } else if (t < (2/2.75)) {
                        return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
                } else if (t < (2.5/2.75)) {
                        return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
                } else {
                        return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
                }

// t: current time, b: begInnIng value, c: change In value, d: duration

So applying this to current CSS keyframes.
d : the animation duration. //1.5 : 1500
b : top value at the start // 0
c : change in value //40px
t : Current time // 10
With some more work on it by applying these we might find out the values needed for the bounce effect in CSS.
I also found this CSS3 3D Bouncing Ball tutorial
Hope that might help you.


text:
Q: Binary operator cannot be applied to operands of type Int and String - Swift 2.3 -> Swift 3.2 conversion error While converting from Swift 2.3 to 3.2 I received below error.

Error : Binary operator cannot be applied to operands of type Int and String

for this if Condition i.e if (error?.code)! == "-112" which is shown in below line.
if (error?.code)! == "-112"
{
     print("hello")
}

A: Error itself says it's different types Int and String.
You can need to typecast one or another in same form and them compare.
if (String(error?.code)!) == "-112"){
  print("hello")
}

A: Swift is a language with a strong type system. You can compare only values of the same type.
Since the left side is Int anyway use an Int value for the right side. Creating a string is unnecessarily expensive. Don't do that.
The most efficient (and safe) solution is
if error?.code == -112
{
     print("hello")
}

A: You need to type-cast your error code result to a string, like so:
if String(error?.code)!) == "-112" {
print("Hello")
}

Essentially, you are taking the error?.code, "casting" it as a string by placing it in a string "container mould" and unwrapping the value (retrieving the casted result).
In addition, if you are working with an API response, you have to account for all other error codes in the else/if statement to make sure all responses are handled properly (just in case you are).


text:
Q: Local Storage - Sempre substitui o ultimo dado Tenho este código:
var ClienteArray = [];

$('#btn-save').click(function(){
    var cliente = JSON.stringify({
        Code : $('#stn-code').attr('value'),
        Name   : $('#stn-name').attr('value')
    });
    ClienteArray.push(cliente);
    localStorage.setItem('ClienteArray', JSON.stringify(ClienteArray));
    alert('Registro adicionado.');
    return true;

});

    $("#test").html(localStorage.getItem('ClienteArray'));

Ele pega os dados colocados em um input e passar para o localStorage em Json um array de dados. Mas toda vez que eu clico no botão salvar, ao invés de ele colocar um novo dado no array ele apaga o antigo e faz um novo array, mas preciso que ele não apague esse antigo.
Alguém tem alguma ideia?

A: Assumo que bastaria carregar o array antes de atualizá-lo:
var ClienteArray = JSON.parse(localStorage.getItem('ClienteArray') || '[]');

$('#btn-save').click(function(){
    var cliente = JSON.stringify({
        Code : $('#stn-code').attr('value'),
        Name   : $('#stn-name').attr('value')
    });
    ClienteArray.push(cliente);
    localStorage.setItem('ClienteArray', JSON.stringify(ClienteArray));
    alert('Registro adicionado.');
    return true;

});

    $("#test").html(localStorage.getItem('ClienteArray'));

Obs: não foi testado.

A: Wagner, sei que o seu caso é bem mais simples, mas caso precise, você pode utilizar o Storage.js, ele serve como uma abstração para diversas tecnologias de armazenamento, tais como o IndexedDB, WebSQL e Storage (seja Local ou Session)
mas note, agora você não está trabalhando com um simples array, mas com entidades que são armazenadas em um esquema bem semelhante a um banco de dados, então é interresante que informe um id para cada registro.
então você pode usar o método getAll para listar todos os seus registros e o set para fazer um upsert.:
storage(function (storage) {
  storage.getAll("Pessoa", function (pessoas) {
    console.log("consulta realizada com sucesso");
  });
}, "LocalStorage");

storage(function (storage) {
  storage.set("Pessoa", pessoa, function () {
    console.log("pessoa inserida com sucesso");
  });
}, "LocalStorage");

segue o exemplo completo, porem o mesmo não funciona em sandbox, porém você pode conferir o mesmo no JSFiddle

faker.locale = "pt_BR";
var gerarPessoa = function () {
  var pessoa = {};
  pessoa.id = newGuid();
  pessoa.Nome = faker.name.firstName();
  pessoa.Sobrenome = faker.name.lastName();
  pessoa.Nascimento = faker.date.past(50, new Date(1990, 1, 1));
  pessoa.Telefone = faker.phone.phoneNumber();
  pessoa.Email = faker.internet.email(pessoa.Nome, pessoa.Sobrenome);
  return pessoa;
}

var newGuid = function() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
  }
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
}

var appendPessoa = function(pessoa) {
  if (typeof pessoa.Nascimento == "string")
    pessoa.Nascimento = new Date(pessoa.Nascimento);
  var linha = document.importNode(tmplPessoa, true);
  linha.querySelector("td:nth-child(1)").textContent = pessoa.Nome;
  linha.querySelector("td:nth-child(2)").textContent = pessoa.Sobrenome;
  linha.querySelector("td:nth-child(3)").textContent = pessoa.Nascimento.toLocaleDateString();
  linha.querySelector("td:nth-child(4)").textContent = pessoa.Telefone;
  linha.querySelector("td:nth-child(5)").textContent = pessoa.Email;
  pessoas.appendChild(linha);
}

var gerar = document.getElementById("gerar");
var tmplPessoa = document.getElementById("tmplPessoa").content;
var pessoas = document.querySelector("#pessoas tbody");
var database = null;

storage(function (storage) {
  database = storage;
  database.getAll("Pessoa", function (pessoas) {
    pessoas.forEach(appendPessoa);
  });
}, "LocalStorage");

gerar.addEventListener("click", function () {
  var pessoa = gerarPessoa();
  database.set("Pessoa", pessoa, function () {
    console.log();
  });
  appendPessoa(pessoa);
});
table {
  width: 100%;
}

<input id="gerar" type="button" value="Gerar Pessoa" />

      Nome
      Sobrenome
      Nascimento
      Telefone
      Email

<template id="tmplPessoa">

</template>


text:
Q: Intel Xeon X3430 for Hyper-V I'm looking for a compute to run Hyper-V. Does an Intel Xeon X3430, 4C, 2 meet Hyper-V hardware-requirements?

A: http://ark.intel.com/products/42927/Intel-Xeon-Processor-X3430-8M-Cache-2_40-GHz
Advanced Technologies
Intel® Turbo Boost Technology   Yes
Intel® vPro Technology  No
Intel® Hyper-Threading Technology   No
Intel® Virtualization Technology (VT-x) Yes
Intel® Virtualization Technology for Directed I/O (VT-d)    Yes
Intel® Trusted Execution Technology Yes

So, you've got 4 cores, 8M cache, and VT-x and VT-d.  No Hyperthreading, so you only get 4 cores and 4 threads.
Yes, It's fine for Hyper-v, if a little limited on threads.


text:
Q: unable to define dynamic ng-model for Multiselect checkboxes with angular-Selectize I am trying to achieve Multiselect dropdown with checkboxes by using selectiz.js. I am able to customize my dropdown using render option in selectize. However if i click one of the checkboxes it will click all the others checkboxes which is not desired. I understand that this is because all the options are binded to one ng-model. I tried to make it dynamic but everything seems to fail Under selectize render options. I will really appreciate if some one can help me with this issue. I have tried to put the simplest version here. Also please note I amusing Icheck plugin for checkboxes.

Multi Selelct

  <input id="dropdown" config="assigneeConfig" options="assigneesOptions" position="bottom" ng-model="model" selectize/>

"use strict";
 angular.module('checkBoxes')
.controller('selectizeDropdownCtrl',
    function ($rootScope, $scope, $compile) {

        //================================================================
        // Initialize Data
        //================================================================

        $scope.assigneesOptions = [
            {
                "id": "1",
                "name": "Mercury, Freddie"
            },
            {
                "id": "2",
                "name": "Morty, Rick"
            }
        ];

    $scope.assigneeConfig = {
            autoBind: true,
            valueField: 'id',
            labelField: 'name',
            maxItems: null,
            placeholder: 'Select...',
            render: {
                option: function (item, escape) {

                    var html= '
' +
                        '
'+
                   '<input type="checkbox" ng-model= "checkboxesModel"  icheck/>'+
                   ' ' + escape(item.name) + ''++
                         '
';
                    return $compile(html)($scope)
                }
            },

        };

    });


text:
Q: Basic Query, View questions I try to make this query
to create a view which will list top 10 products  most purchased in previous 6 months.
CREATE VIEW Top10product6month_VW AS
SELECT ProductID
FROM (select ProductID,SYSDATE - OrderDate AS OrderAge
      from DD_OrderLine
      WHERE SYSDATE - OrderDate <= 183)
Where ROWNUM <= 10;

and I could not get top10.
My OrderLine table is
CREATE TABLE DD_OrderLine
(
OrderDate DATE,
SUMofPrice NUMBER(8,2),
OrderID NUMBER(6),
ProductID NUMBER(6),
CONSTRAINT DD_orderid_productid_pk PRIMARY KEY (OrderID,ProductID )
);

and records are
INSERT INTO DD_OrderLine (OrderDate,SUMofPrice, QuantityPurchased,OrderID,ProductID)
VALUES ((to_date('2013/9/25', 'yyyy/mm/dd')),000010.00,1,000117,001116);
--
INSERT INTO DD_OrderLine (OrderDate,SUMofPrice, QuantityPurchased,OrderID,ProductID)
VALUES ((to_date('2013/9/14', 'yyyy/mm/dd')),000010.00,1,000118,001112);
--
INSERT INTO DD_OrderLine (OrderDate,SUMofPrice, QuantityPurchased,OrderID,ProductID)
VALUES ((to_date('2013/9/14', 'yyyy/mm/dd')),000010.00,1,000118,001111);
--
INSERT INTO DD_OrderLine (OrderDate,SUMofPrice, QuantityPurchased,OrderID,ProductID)
VALUES ((to_date('2013/9/15', 'yyyy/mm/dd')),000010.00,1,000119,001111);

INSERT INTO DD_OrderLine (OrderDate,SUMofPrice, QuantityPurchased,OrderID,ProductID)
VALUES ((to_date('2013/9/15', 'yyyy/mm/dd')),000010.00,1,000119,001112);

INSERT INTO DD_OrderLine (OrderDate,SUMofPrice, QuantityPurchased,OrderID,ProductID)
VALUES ((to_date('2013/9/24', 'yyyy/mm/dd')),000010.00,1,000120,001115);

INSERT INTO DD_OrderLine (OrderDate,SUMofPrice, QuantityPurchased,OrderID,ProductID)
VALUES ((to_date('2013/9/24', 'yyyy/mm/dd')),000010.00,1,000120,001114);

INSERT INTO DD_OrderLine (OrderDate,SUMofPrice, QuantityPurchased,OrderID,ProductID)
VALUES ((to_date('2013/9/24', 'yyyy/mm/dd')),000010.00,1,000120,001113);

INSERT INTO DD_OrderLine (OrderDate,SUMofPrice, QuantityPurchased,OrderID,ProductID)
VALUES ((to_date('2013/9/24', 'yyyy/mm/dd')),000010.00,1,000120,001112);
----
INSERT INTO DD_OrderLine (OrderDate,SUMofPrice, QuantityPurchased,OrderID,ProductID)
VALUES ((to_date('2013/9/24', 'yyyy/mm/dd')),000010.00,1,000120,001111);

INSERT INTO DD_OrderLine (OrderDate,SUMofPrice, QuantityPurchased,OrderID,ProductID)
VALUES ((to_date('2013/9/24', 'yyyy/mm/dd')),000010.00,1,000120,001116);

INSERT INTO DD_OrderLine (OrderDate,SUMofPrice, QuantityPurchased,OrderID,ProductID)
VALUES ((to_date('2013/9/24', 'yyyy/mm/dd')),000010.00,1,000120,001117);

INSERT INTO DD_OrderLine (OrderDate,SUMofPrice, QuantityPurchased,OrderID,ProductID)
VALUES ((to_date('2013/9/30', 'yyyy/mm/dd')),000010.00,1,000121,001112);

INSERT INTO DD_OrderLine (OrderDate,SUMofPrice, QuantityPurchased,OrderID,ProductID)
VALUES ((to_date('2013/9/30', 'yyyy/mm/dd')),000010.00,1,000122,001112);

Are there any ways to count ProductID and make top 10?
Thank you so much

A: How about:
SELECT ProductID
FROM (select ProductID, SUM(QuantityPurchased) AS cnt
      from DD_OrderLine
      WHERE SYSDATE - OrderDate <= 183
      GROUP BY ProductID
      ORDER BY cnt DESC)
Where ROWNUM <= 10;

A: Unfortunately you cannot specify the ORDER BY clause in an Oracle view (Here more details, search ORDER BY and you will find it)
Anyway, in case you need a query where you store the top ten results, even if not ordered, you can use:
CREATE VIEW Top10product6month_VW
AS
SELECT ProductID
  FROM (select ProductID,
               SYSDATE - OrderDate AS OrderAge
          from DD_OrderLine
         WHERE SYSDATE - OrderDate <= 183
      order by QuantityPurchased desc)
 Where ROWNUM <= 10;


text:
Q: Links are not able to be clicked I am using a bootstrap template. (http://brybell.me/br1) The links in the bottom nav bar do not work correctly. The browser recognizes that it is a link, and you can right click and open it in a new page, but you can't click on it directly. I am unsure what the issue is, however my friend mentioned z-index?
Here is the nav html.

Terms of Service

Privacy Policy

Contact

And here is the CSS.
header.main.fixed {
position:fixed;
background:#44606e;
top:0;
width:100%;
left:0;
height:80px;
margin-top:0;
z-index:1000000;
}

header.main {
position:relative;
z-index:10000;
height:80px;
margin-top:-80px;
background:rgba(0,0,0,0.5);
}

header.main > .container {
position:absolute;
z-index:1000;
left:50%;
margin-left:-470px;
}

a.logo {
float:left;
position:relative;
top:10px;
}

nav.main {
float:right;
}

nav.main ul {
margin:0;
}

nav.main ul li {
margin:0;
}

nav.main ul li a img {
color:#FFF;
display:block;
text-shadow:1px 1px 2px rgba(0,0,0,0.25);
padding:10px;
line-height:20px;
}

nav.main ul li a.linkage {
color:#FFF;
display:block;
text-shadow:1px 1px 2px rgba(0,0,0,0.25);
padding:30px 10px;
line-height:20px;
}

header.fixed nav.main ul li a.active {
background:rgba(0,0,0,0.2);
}

header.main .mobile-nav {
margin-top:25px;
}

I am fairly unfamiliar with z-index, so this is confusing for me. I see now that it must have something to do wit the 100000 z index in header.main.fixed.
Any help is greatly appreciated! :]
There is also this JS which some think may be causing issues:
$('nav.main a').click(function(e) {
    e.preventDefault();
    $target = $(this).attr('href');
    $padding = $($target).css('padding-top');
    $padding = $padding.substring(0, $padding.length - 2);
    $padding = parseInt($padding);
    $position = $($target).offset().top - $padding;
    $('html, body').animate({
        scrollTop: $position
    }, 1000, 'easeInQuart');
});

A: There is a javascript error on the page.

(Checked with firebug)
custom.js (row 160) TypeError: $padding is undefined

Wrong code:
$padding = $padding.substring(0, $padding.length - 2);

A: Y see your ! code ! and the Javasript !! is Broken !
This are your error:
Uncaught TypeError: Cannot read property 'length' of undefined
inspect the element to see the problem!
This is triggered when you click in Yous  links!!
Sorry for my English ! ^^

A: Its not a CSS issue. You probably have some Javascript binding to the hyperlinks. I've tried unbinding from firebug, then the click event works.

A: You have prevented default event handler for the hyperlinks, that line is causing the links to go to the pages. Disabling that line should work. But what actually are you trying to do with the JS code?


text:
Q: Flex DividedBox children are displayed outside I am using a DividedBox in Flex which contains only a datagrid at first. When I click on an Item on the Datagrid, a second element with a width of 0% (Spark Group) is added to the divided box to display an image.
The thing is, when the second element is added to the DividedBox, the image is partially displayed outside the DividedBox, and I don't want to have this behavior.
Here is the interesting code :
<mx:DividedBox direction="horizontal" id="divider" borderColor="red" borderStyle="solid" borderVisible="true" right="10" left="10" top="10" bottom="10">
    <s:Group width="100%" height="100%">
        <!--datagrid-->
    </s:Group>
</mx:DividedBox>

And here is the piece of code that adds the second child of the dividedBox (simplified code) :
private var _pdf_preview:Group = new Group();
[Bindable]
[Embed(source="assets/image/llama.jpg")]
private var imgClass:Class;

protected function itemOnClickHandler(event:MouseEvent):void
{
    _pdf_preview = new Group();
    var img:Image = new Image();
    img.source = imgClass;
    _pdf_preview.addElement(img);
    _pdf_preview.percentWidth = 0;
    divider.addElement(_pdf_preview);
}

And here is a screen of the problem (Btw, don't notice my skills on Gimp :) ). As a new user I can't bind images to my post : screen showing my problem the red border show the limits of the dividedBox
Thank you.
I hope there are not too much fault, english is not my native language. Sorry for any english mistakes.
PS : I couldn't add the "DividedBox" tags because it was not existing before, and I'm a "new user" so I can't create new tags.

A: You can use the clipContent property to cut off the image at the edge of the DividedBox:
<mx:DividedBox clipContent="true" />

When using Spark containers, clipAndEnableScrolling is the property you need to achieve the same goal.
I would also like to note that you usually don't require to dynamically add components through ActionScript. You can use 'states' instead. For example:
<s:states>
    <s:State name="normal" />
    <s:State name="image" />
</s:states>

<mx:DividedBox clipContent="true">
    <s:DataGrid />
    <s:Image includeIn="image" />
</mx:DividedBox>

Now all you need to do to show the Image, is set the currentState to image.


text:
Q: Stopping my loop from running when a condition is met I am trying to code a game of snap in JS. When the cards are the same, the console will log 'SNAP!' OK, but it will not stop. Am I adding the break; in at the wrong part?
for (mattCounter = 0; mattCounter < mattDeck.length; mattCounter++) {
  for (jamesCounter = 0; jamesCounter < jamesDeck.length; jamesCounter++) {
    if (mattDeck[mattCounter] === jamesDeck[jamesCounter]) {
      console.log('SNAP!');
      break;
    } else {
      console.log('Go again...');
    }
  }
};

A: The break will stop only the second for, meaning this one:
for (jamesCounter = 0; jamesCounter < jamesDeck.length; jamesCounter++)

The best option is to set a flag, initially false, and then set it to true besides making the loop break.
Then if the flag is set to true, break also the first for.
var flag = false;
for (mattCounter = 0; mattCounter < mattDeck.length; mattCounter++) {
    for (jamesCounter = 0; jamesCounter < jamesDeck.length; jamesCounter++) {
        if (mattDeck[mattCounter] === jamesDeck[jamesCounter]) {
            console.log('SNAP!');
            flag = true;
            break;
        } else {
            console.log('Go again...');
        }
    }
    if (flag) {
       break;
  }
};


text:
Q: Recyclerview cannot be scrolled? I have this screen.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp">

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

        <android.support.v7.widget.RecyclerView
            android:id="@+id/my_recycler_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:scrollbars="vertical"/>

    </RelativeLayout>

    <Button
        android:id="@+id/btn_sync"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:onClick="DoUpload"
        android:text="Sync with server"
        />
</LinearLayout>

It looks like this (which is OK):

So I add more datas, now it looks like this:

The RecyclerView cannot be scrolled, and the button is hidden. How to fix this?

A:     <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp">
<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
     <android.support.v7.widget.RecyclerView
            android:id="@+id/my_recycler_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scrollbars="vertical"
            android:layout_weight="1"/>
    <Button
        android:id="@+id/btn_sync"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_gravity="center_horizontal"
        android:onClick="DoUpload"
        android:text="Sync with server"/>
    </LinearLayout >
</LinearLayout>

just copy this code and use it will be working fine

A: I have edited the code for you this will solve the problem and button will be at the end of RecyclerView
<?xml version="1.0" encoding="utf-8"?>
        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:padding="5dp">

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

                <android.support.v7.widget.RecyclerView
                    android:id="@+id/my_recycler_view"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:scrollbars="vertical" />

                <Button
                    android:id="@+id/btn_sync"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/my_recycler_view"
                    android:layout_gravity="center_horizontal"
                    android:onClick="DoUpload"
                    android:text="Sync with server" />
            </RelativeLayout>

        </LinearLayout>

A: Try this,
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp">

    <RelativeLayout
        android:layout_above="@id/btn_sync"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/my_recycler_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:scrollbars="vertical"/>

    </RelativeLayout>

    <Button
        android:id="@+id/btn_sync"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:onClick="DoUpload"
        android:text="Sync with server"
        android:layout_alignParentBottom="true"
        />
</RelativeLayout>

A: Try using constraint layout like below
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:padding="5dp">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toTopOf="@id/btn_sync"
        android:scrollbars="vertical" />

    <Button
        android:id="@+id/btn_sync"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:onClick="DoUpload"
        android:text="Sync with server" />

</android.support.constraint.ConstraintLayout>

This layout should keep the button from hiding and recyclerview will scroll when more data items are added.

A: used nestedScrollView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

   <android.support.v4.widget.NestedScrollView
        android:id="@+id/nestedScrollView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:overScrollMode="never">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/recyclerView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

        </LinearLayout>
     </android.support.v4.widget.NestedScrollView>
</LinearLayout>


text:
Q: Track onchange selections in a menu jpg I'm not a javascript guy and have run into an issue configuring Google Analytics to track image downloads as and event.  The client has a site that uses a onChange call that pulls a lite java-script that then send the end user to the image page.  is there a easy way to fix the following to track events in Google.  Everything that I have tried failed.  Any help would be appreciated.
<script type="text/javascript" language="javascript">
function doIt(theURL)
{
var myPop = window.open(theURL)
}
</script>

<select name="menu2" onchange="if (this.selectedIndex != 0)     doIt(this.options[this.selectedIndex].value)">
    <option selected>Select screen resolution:</option>
    <option value="../images/x.jpg">1600 x 1200</option>
    <option value="../images/y.jpg">1280 x 960</option>
    <option value="../images/zx.jpg">1024 x 768</option>
    <option value="../yz.jpg">800 x 600</option>
  </select>
</p>
<p> </p>
</div>

A: In my experience, tracking events with Google Analytics is as simple as calling this function at the right moment:
_trackEvent(category, action, opt_label, opt_value, opt_noninteraction)

So in your case that could go into doIt:
<script type="text/javascript" language="javascript">
function doIt(theURL)
{
  _trackEvent("downloads", "images", theUrl)
  var myPop = window.open(theURL)
}
</script>

Or you could consider passing the width or height of the selected image into doIt too and then use that as the value (fourth parameter to _trackEvent). This parameter shows up as a numeric value in the Google Analytics dashboard, so it'll be summed and aggregated (not too useful for you) and you can numerically sort on it.


text:
Q: Can't link any framework using Carthage or CocoaPods I've tried to add a few Icon-font projects to my Cocoa Touch Framework using both CocoaPods as well as Carthage, but keep getting ld: framework not found SomeIconFont
Things I've tried to do:

*

*Dragged and dropped latest .framework into Linked Framework and Libraries

*Have tried to add a Copy Files with destination Frameworks in Build Phases before Link Binary with Libraries phase

*Have added the carthage copy-frameworks Run Script for the framework with $(SRCROOT)/Carthage/Build/iOS/SomeIconFont.framework

*Have set Build Active Architecture Only to Yes at both, the Project level as well as the target

*Architecture for both is Standard

*Have set Framework Search Paths for both, Project as well as Target to $(SRCROOT)/Carthage/Build/iOS and $(PROJECT_DIR)/Carthage/Build/iOS respectively

*Have tried Cleaning, resetting DerivedData
My last options are animal-sacrifice and an underwater hand-stand, but of course, they're only second to reinstalling Xcode and its few GB again. I'm only posting this question because quite honestly, completely beaten by this problem for the last 48 hours

A: At the end of 2 gruelling days (what I've saved you from!), I've finally managed to fix this:
Underneath Framework Search Paths, you shall see Debug and Release, and both house a Any Architecture | Any SDK.
Simply setting Any Architecture | Any SDK to $(inherited) fixed this issue for me. Of course, this will not work if you haven't set the top-level to $(SRCROOT)/... as shown in the OP, as it will only mimic the parent element's value!
Why this is not a duplicate of one of the hundred other questions/blogs you'll find online: nearly all relevant posts as of writing this are for an Application, and not a Dynamic Library/Cocoa Touch Framework


text:
Q: Предупреждение в функции qsort Компилятор выдает предупреждение: passing argument 4 of 'qsort' from incompatible pointer type [-Wincompatible-pointer-types]|
и замечание: expected 'int (*)(const void *, const void *)' but argument is of type 'int (*)(Athlet *, Athlet *) {aka int (*)(struct _Athlet *, struct _Athlet *)}'
Код программы:
#include <stdio.h>
#include <stdlib.h>

typedef struct _Athlet
{
    double m;
    double s;
} Athlet;

Athlet read_athlet()
{
    Athlet at;
    scanf("%lf %lf", &at.m, &at.s);
    return at;
}

int cmp_by_s(Athlet *a1, Athlet *a2)
{
    return a1->s - a2->s;
}

int main()
{
    int n = 0, max = 1, tmp = 0, i = 0;
    Athlet *A = NULL;
    scanf("%d", &n);
    A = (Athlet *)malloc(n*sizeof(Athlet));
    if (NULL == A)
        exit(-1);
    for (i = 0; i < n; i++)
        A[i] = read_athlet();

    qsort(A, n, sizeof(Athlet), cmp_by_s);
        tmp = A[0].m;
    for (i = 1; i < n; i ++)
    {
        if (A[i].s >= tmp)
        {
            max++;
            tmp += A[i].m;
        }
    }
    printf("%d", max);
    return 0;

}

(Это решение задачи: написать программу, которая находит «башню» из атлетов максимальной высоты. Атлеты характеризуются двумя параметрами – массой и силой. Сила равна максимальной массе, которую атлет может держать на плечах. Известно, что если атлет тяжелее, то он точно сильнее. Входом является число атлетов n и n пар (масса, сила))

A: Это не должно компилироваться. Если вы получаете предупреждение, а не ошибку, значит настройки компилятора недостаточно строгие.
qsort принимает функцию вида int foo(const void *a, const void *b). Параметры должны быть именно const void *.
int cmp_by_s(Athlet *a1, Athlet *a2) {...} нужно заменить на:
int cmp_by_s(const void *a1_ptr, const void *a2_ptr)
{
    const Athlet *a1 = (const Athlet *)a1_ptr;
    const Athlet *a2 = (const Athlet *)a2_ptr;
    return a1->s - a2->s;
}


text:
Q: How to get CDN with @ in it in CSHTML(Razor) page How to get CDN with @ in it in CSHTML(Razor) page
lets suppose we have @ in the CDN and we want that script in CSHTML(Razor) page

but its giving error

how can i add this CDN as script

A: I faced same issue while working in a .Net Core app.
You need to escape the @ symbol inside the cdn url. Simply replace @microsoft with @@microsoft.

A: @ is its own escape character. Simply put in @@. Alternatively you can store the URL as a string variable and use that.


text:
Q: How to convert ObjectSet from Entities to IEnumerable of Models? I am building a test application using MVC3, Razor, and Entity Framework 4.1 with a schema-first approach (as apposed to a code-first approach), in a repository pattern. I would like to avoid accessing data objects in my view, and access a model instead, but I am having a problem. As far as I can tell, the data objects are being returned from the data layer as ObjectSet, but my View needs IEnumerable, and I don't know how to cast one to the other.
Here is some code, to help clarify.

Model ...
namespace TestSolution.Models
{
    public class ProjectModel
    {
        [HiddenInput]
        public int Id { get; set; }

        [Required]
        [StringLength(255, ErrorMessage = "The name cannot be more than 255 characters long.")]
        [Display(Name = "Name")]
        public string Name { get; set; }

        [Required]
        [Display(Name = "Description")]
        public string Description { get; set; }
    }
}

Repository ...
public IQueryable<ProjectModel> GetProjects()
{
    return Db.Project;
}

Entities ...
public ObjectSet<Project> Project
{
    get
    {
        if ((_Project == null))
        {
            _Project = base.CreateObjectSet<Project>("Project");
        }
        return _Project;
    }
}

Controller ...
public ActionResult Index()
{
    IEnumerable<TestSolution.Models.ProjectModel> model = _projectRepository.GetProjects();
    return View(model);
}

View ...
@model IEnumerable<TestSolution.Models.ProjectModel>

Error I am getting when building ...
Cannot implicitly convert type 'System.Data.Objects.ObjectSet<TestSolution.Project>' to 'System.Linq.IQueryable<TestSolution.Models.ProjectModel>'. An explicit conversion exists (are you missing a cast?)

Does this question make sense? I am just not sure where go from here ... any advise you guys can give me would be awesome. :)
EDIT: I was able to solve this with Kyle's suggestion by changing my Repository code to ...
public IQueryable<ProjectModel> GetProjects()
{
  return Db.Project.Select(i => new ProjectModel() { Id = i.Id, Name = i.Name, Description = i.Description });
}

A: The problem isn't converting from ObjectSet<T> to IEnumerable<T> (ObjectSet<T> implements IEnumerable<T>).
The problem is converting from TestSolution.Project to TestSolution.Models.ProjectModel.  You will need to write some conversion code, maybe something similar to the below:
model.Select(i => new ProjectModel() { /* Set properties here. */ });


text:
Q: ECommandService Discouraged access I'm trying to inject the ECommandService into a Part of my application, and I've added the plugin org.eclipse.e4.core.commands;bundle-version="0.10.2" to the dependencies of my application (plugin.xml), but when I declare the
@Inject private ECommandService commandService;

I'm getting a warning saying:
Discouraged access: The type ECommandService is not accessible due to
restriction on required library C:\Data\andrelop\transnet\eclipse-
kepler\plugins\org.eclipse.e4.core.commands_0.10.2.v20130515-1857.jar

Is this normal or Am I adding the wrong dependency?

A: This is normal for a number of e4 APIs. These APIs have not yet been finalized so they are left 'discouraged' - but you have to use them for e4 applications. There is a chance that they may change in future Eclipse releases.
You can turn off the warning in Preferences > Java > Compiler > Errors/Warning in the Deprecated and restricted API section change Discouraged reference (access rules) to ignore. Or you can use @SuppressWarning("restriction") on your class.
Eclipse bug 412373 will list the APIs which will finalized in Eclipse 4.4 (Luna), but currently it is empty. Some e4 APIs were finalized when 4.3 was released.


text:
Q: Action Bar Tabs at the bottom? I'm trying to place the action bar tabs at the bottom of my app, but I need some help with it (if it's even possible).
The code:
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        ActionBar.Tab tabA = actionBar.newTab().setText("Games");
        ActionBar.Tab tabB = actionBar.newTab().setText("Apps");
        ActionBar.Tab tabC = actionBar.newTab().setText("Themes");

        tabA.setTabListener(new ActionBarTabListener());
        tabB.setTabListener(new ActionBarTabListener());
        tabC.setTabListener(new ActionBarTabListener());

        actionBar.addTab(tabA);
        actionBar.addTab(tabB);
        actionBar.addTab(tabC);

A: It kind of goes against the Android guidelines to put tabs on the bottom, but a split action bar should be able to accomplish what you're trying to do.

A: There is another way to this but you have to use FrgamentTabHost.
Here is the code.
layout/activity_main.xml
enter <android.support.v4.app.FragmentTabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <FrameLayout
        android:id="@android:id/tabcontent"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />
      <TabWidget
        android:id="@android:id/tabs"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"/>
</LinearLayout>

You have to place TabWidget below the FrameLayout.
layout/fragment_layout.xml
enter code here<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:background="#eaecee">

<TextView
    android:id="@+id/text"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_vertical|center_horizontal"
    android:text="@string/hello_world"
    android:textAppearance="?android:attr/textAppearanceMedium" />

MainActivity.java

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;

public class MainActivity extends FragmentActivity {
    private FragmentTabHost mTabHost;

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

        setContentView(R.layout.activity_main);
        mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);

        mTabHost.addTab(
                mTabHost.newTabSpec("tab1").setIndicator("Tab 1", null),
                FragmentTab.class, null);
        mTabHost.addTab(
                mTabHost.newTabSpec("tab2").setIndicator("Tab 2", null),
                FragmentTab.class, null);
        mTabHost.addTab(
                mTabHost.newTabSpec("tab3").setIndicator("Tab 3", null),
                FragmentTab.class, null);
    }
}

FragmentTab.java

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class FragmentTab extends Fragment {

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_layout, container, false);
        TextView tv = (TextView) v.findViewById(R.id.text);
        tv.setText(this.getTag() + " Content");
        return v;
    }
}

I hope it would help you.


text:
Q: Use REST API with Neo4j? Over the last couple of months I've been building up a Neo4j database. I'm finding Neo4j & Cypher really easy to use and definitely appropriate for the kind of data that I'm working with.
I'm hoping there's someone out there who can offer a few pointers on how to get started with the REST API. I don't have any experience coding in Java and I'm finding the Neo4j documentation a little tricky to follow. From what I understand, it should be possible to send a REST request via a straightforward http URL (like this http://localhost:7474/db/data/relationship/types), which would retrieve some data in a JSON.
My end goal is some form of very high level dashboard to summarise the current status of my database, to show the data from a few high level Cypher queries like this one:
    match (n) return distinct(n.team), count(n)

Any advice you can offer would be greatly appreciated.

A: You would better use the http transactional endpoint where you can send Cypher query statements like the one in your questions.
The default endpoint is http://yourserverurl:7474/db/data/transaction/commit
The Neo4j documentation to use it from Java :
http://neo4j.com/docs/stable/server-java-rest-client-example.html#_sending_cypher
Using the transactional endpoint has the benefit of being able to send multiple statements in one transaction which will result in the operation being committed or rolled back.
The ReST API is like any other http api, the only guidelines to follow are the body contents and cypher query parameters which are well explained in the Neo4j documentation : http://neo4j.com/docs/stable/rest-api.html


text:
Q: on 18.04 "sudo apt-get install libboost-all-dev" failing, .deb files timeout via synaptic and browser as well sudo apt-get install libboost-all-dev
results in:
Err:1 http://us.archive.ubuntu.com/ubuntu bionic/main amd64 libboost1.65-dev
amd64 1.65.1+dfsg-0ubuntu5
Connection failed [IP: 91.189.91.26 80]
E: Failed to fetch
http://us.archive.ubuntu.com/ubuntu/pool/main/b/boost1.65.1/libboost1.65-
dev_1.65.1+dfsg-0ubuntu5_amd64.deb  Connection failed [IP: 91.189.91.26 80]

Can't access 4 .deb files directly via browser either:
http://us.archive.ubuntu.com/ubuntu/pool/main/b/boost1.65.1/
Browser Screenshot
Text list of files that can't be downloaded from browser in case image fails:
libboost1.65-dev_1.65.1+dsfg-0ubuntu5_amd64.deb
libboost1.65-dev_1.65.1+dsfg-0ubuntu5_i386.deb
libboost1.65-dev_1.65.1+dsfg-0ubuntu6_amd64.deb
libboost1.65-dev_1.65.1+dsfg-0ubuntu6_i386.deb
Is this just broken, or is something else going on?


text:
Q: In django1.4, where to create the app is better
Possible Duplicate:
Where should i create django apps in django 1.4?

In Django version 1.4, the structure has changed, the manage.py get out to the top level.
Use the tutorial in the django webiste, the project's name is mysite, the structure is like this:
mysite/
manage.py
mysite/
    __init__.py
    settings.py
    urls.py
    wsgi.py

and I want to create a app. In the tutorial, It place the app right next to the manage.py, so the app is on the top level too, just like this:
mysite/
manage.py
mysite/
    __init__.py
    settings.py
    urls.py
    wsgi.py
polls/
    __init__.py
    models.py
    tests.py
    views.py

so:

*

*what is the different if  I create the app in the secend level(as right next to the settings.py) ?

*if I create the app on the top level, and there is some static file, the mysite and the polls all should to use, so where to place the static/ directory ?

A: Django changed the project layout to end the dreaded era of myproject.myapp.something imports. When you have those type of imports scattered around your codebase, you can't move anything around or re-use the app(s) in another project. The new layout (apps at the same level as project), makes the imports app-relative, rather than project-relative, simplifying things greatly.
The only thing that should go in the root directoy of your code is your app directories, your project directory and manage.py. Anything project-wide (settings, templates, static files, etc, should go in the project directory.
That said, STATIC_ROOT should point to myproject/static, but you should not manually create that directory, nor manually put anything in it. Static files tied to a particular app, should go in that app's static directory. Any project-wide static files should go in an entirely different directory (not the same as either STATIC_ROOT or MEDIA_ROOT). You then add that directory to STATICFILES_DIRS, so Django will include it in development and when running the collectstatic management command.

A: You can use a template to start the project, like this:
https://github.com/goinnn/django-base-template

In these templates the place of the applications is defined already


text:
Q: Why SQL function always returning empty result set? Following function I have write which accept xml and returns table as result.
CREATE FUNCTION FunctionTest(@ID INT,@XML_Details xml)
RETURNS @RESULT TABLE
(
    Value1 INT,
    Value2 INT
)
AS
BEGIN
    DECLARE @tbl_Xml_Result Table
    (
        Value1 INT,
        Value2 INT
    )

    INSERT INTO @RESULT(Value1,Value2)
    SELECT
        l.v.value('Value2[1]','INT'),
        l.v.value('Value1[1]','INT')
    FROM @XML_Details.nodes('/Listings/listing')l(v)
    RETURN
END

And following is the code I using to run against above function but it always returning Empty result.
DECLARE @tbl_Xml_Result Table
(
        Value1 INT,
        Value2 INT
)
INSERT INTO @tbl_xml_Result
values(1,2),(2,3),(3,4),(4,5),(5,6)

DECLARE @xml_Temp xml

SET @xml_Temp = (   SELECT *
                    FROM @tbl_xml_Result
                    FOR XML PATH('Listing'),ROOT('Listings')
                )

DELETE FROM @tbl_xml_Result
INSERT INTO @tbl_xml_Result(Value1,Value2)
Select
    T.Value1,
    T.Value2
FROM FunctionTest(1,@xml_Temp) T

select * from @tbl_Xml_Result

A: First of all avoid multiline function when it is possible. Inline UDFs have better pefromance.
Second XQuery is case-sensitive and you don't have '/Listings/listing' path.
Third: you probably want to filter using @ID.
CREATE FUNCTION FunctionTest(@ID INT,@XML_Details xml)
RETURNS  TABLE
AS
RETURN(
    SELECT Value1, Value2
    FROM (SELECT
            l.v.value('(Value2)[1]','INT') AS Value2,
            l.v.value('(Value1)[1]','INT') AS Value1
          FROM @XML_Details.nodes('/Listings/Listing')l(v)) AS sub
    WHERE Value1 = @ID
    )
GO

DECLARE @tbl_Xml_Result Table(Value1 INT,Value2 INT);
INSERT INTO @tbl_xml_Result(Value1, Value2)
values(1,2),(2,3),(3,4),(4,5),(5,6);

DECLARE @xml_Temp xml  = (SELECT *
                          FROM @tbl_xml_Result
                          FOR XML PATH('Listing'),ROOT('Listings'));

SELECT T.Value1,
       T.Value2
FROM FunctionTest(1,@xml_Temp) T;

LiveDemo

A: The problem in the 19th line of your function:
    FROM @XML_Details.nodes('/Listings/listing')l(v)

*listing - and you need Listing


text:
Q: when i try to run this code i have the following error :Warning: QT_DEVICE_PIXEL_RATIO is deprecated. Instead use: import pandas as pd
from pandas import DataFrame
import matplotlib.pyplot as plt

data = pd.read_csv("cost_revenue_clean.csv")

X = DataFrame(data, columns = ['production_budget_usd'])
y = DataFrame(data, columns = ['worldwide_gross_usd'])

plt.scatter(X, y)
plt.show

the error I have:
Warning: QT_DEVICE_PIXEL_RATIO is deprecated. Instead use:
   QT_AUTO_SCREEN_SCALE_FACTOR to enable platform plugin controlled per-screen factors.
   QT_SCREEN_SCALE_FACTORS to set per-screen factors.
   QT_SCALE_FACTOR to set the application global scale factor.


text:
Q: Configure httpd to same settings as stock CentOS/RHEL 7? I'm trying to upgrade httpd 2.4.6 to 2.4.25 with http/2 enabled on my CentOS 7.2. Since 2.4.6 is the latest version available on the yum repository, I understood that I must compile it myself.
By default, the freshly-complied httpd is being installed to a different path than the default package shipped with the yum repository.
How can I configure, compile and install it with exactly the same settings like the stock CentOS official version, effectively upgrading the current version?
My apachectl -V output is:
Server version: Apache/2.4.6 (CentOS)
Server built:   Jul 18 2016 15:30:14
Server's Module Magic Number: 20120211:24
Server loaded:  APR 1.4.8, APR-UTIL 1.5.2
Compiled using: APR 1.4.8, APR-UTIL 1.5.2
Architecture:   64-bit
Server MPM:     prefork
  threaded:     no
    forked:     yes (variable process count)
Server compiled with....
 -D APR_HAS_SENDFILE
 -D APR_HAS_MMAP
 -D APR_HAVE_IPV6 (IPv4-mapped addresses enabled)
 -D APR_USE_SYSVSEM_SERIALIZE
 -D APR_USE_PTHREAD_SERIALIZE
 -D SINGLE_LISTEN_UNSERIALIZED_ACCEPT
 -D APR_HAS_OTHER_CHILD
 -D AP_HAVE_RELIABLE_PIPED_LOGS
 -D DYNAMIC_MODULE_LIMIT=256
 -D HTTPD_ROOT="/etc/httpd"
 -D SUEXEC_BIN="/usr/sbin/suexec"
 -D DEFAULT_PIDLOG="/run/httpd/httpd.pid"
 -D DEFAULT_SCOREBOARD="logs/apache_runtime_status"
 -D DEFAULT_ERRORLOG="logs/error_log"
 -D AP_TYPES_CONFIG_FILE="conf/mime.types"
 -D SERVER_CONFIG_FILE="conf/httpd.conf"

A: The "right" way to do it is build or adapt an rpm package. On top of making sure that you get the same configuration, you avoid breaking future updates.
I usually start my rpm work based on the closest version I can find for the target platform. In your case I have found an rpm of the same exact version:
https://codeit.guru/en_US/2017/01/apache-httpd-2-4-25-built-against-openssl-1-0-2j-with-http2-for-red-hat-enterprise-linux-and-centos/
With minimal edits you should be able to adapt the SRPM provided by codeit to suit your needs