text:
Q: Access variable of import class from Controller how can i access the $cleantext variable of my import class from my controller to pass it to my view?
This is my Import Class:
class ExcelImport implements ToCollection
{
    /**
    * @param Collection $collection
    */

    public function collection(Collection $collection)
    {
        $array = $collection->toArray();
        $outervalues = array_values($array);
        $new_array = [];

        foreach ( $outervalues as $key => $value_inner_array  )
        {
            foreach ($value_inner_array as $key => $innervalue)
            {
               array_push($new_array, $innervalue);
            }

        }

        $text = implode(',',$new_array);
        $clean_text = str_replace(","," ", $text);

        $newText =  new fulltext([
            'text' => $clean_text
        ]);

        $newText->save();

    }
}

And this is my Controller:
class ExcelController extends Controller
{
     public function ExcelIndex ()
     {
         return view('CV_Test.excel');
     }

     public function ExcelToArray (Request $excelFile)

    {
         $excelFile->validate([

            'excelfile' => 'required|mimes:xlsx,xls,csv,html,ods',

             ]);

         Excel::import(new ExcelImport, $excelFile->file('excelfile'));

       return view('CV_Test.excel');

        }
}

I need to get the variable here to pass it via "compact" to my view.
Or is the approach totally wrong? I cant manage to do it :(

A: class ExcelImport implements ToCollection
{
    public $clean_text;

    /**
    * @param Collection $collection
    */

    public function collection(Collection $collection)
    {
        $array = $collection->toArray();
        $outervalues = array_values($array);
        $new_array = [];

        foreach ( $outervalues as $key => $value_inner_array  )
        {
            foreach ($value_inner_array as $key => $innervalue)
            {
               array_push($new_array, $innervalue);
            }

        }

        $text = implode(',',$new_array);
        $this->clean_text = str_replace(","," ", $text);

        $newText =  new fulltext([
            'text' => $clean_text
        ]);

        $newText->save();
    }
}

And then, after calling collection() method, you can do:
$excelImport = new ExcelImport
$clean_text = $excelImport->clean_text


text:
Q: Find the equation of a curve where $\frac{dy}{dx}=2x+y$ at all points
Find the equation of the curve which passes through the origin and is such that $\frac{dy}{dx}=2x+y$ at all points $(x,y)$ on the curve, giving the equation in the form $y=f(x)$.

I checked with WolframAlpha, and the first step listed was to multiply both sides by $e^{\int-1dx}$ - which seems strange (I've never covered this way of dealing with integrands before). Is there a simpler and more intuitive approach?

A: The method of integrating factors is generally the standard way to approach linear first-order ODEs (that aren't separable or exact).
Consider what happens when we multiply both sides of the ODE by some function of $x$ (say $\mu(x)$) and do a bit of rearranging:
$$
\mu(x) \cdot y' - \mu(x) \cdot y = \mu(x) \cdot 2x
$$
If we squint at the LHS hard enough, it sort of looks familiar. Recall that Product Rule says that:
$$
(fg)' = f \cdot g' + f' \cdot g
$$
This matches the LHS, provided that:

*

*$g = y$

*$f = \mu(x)$

*$f' = -\mu(x)$

Differentiating both sides of the second condition and combining with the third condition, we obtain a separable ODE:
\begin{align*}
\frac{d\mu}{dx} &= -\mu \\
\frac{-1}{\mu} \, d\mu &= dx \\
\int \frac{-1}{\mu} \, d\mu &= \int dx \\
-\ln|\mu| &= x + C \\
\ln|\mu| &= -x - C \\
|\mu| &= e^{-x - C} \\
\mu(x) &= (\pm e^{-C})e^{-x}
\end{align*}
Taking $C = 0$ (and dropping the $\pm$), we have $\mu(x) = e^{-x}$. Substituting, we can now apply Product Rule in reverse:
\begin{align*}
e^{-x}\cdot y' - e^{-x} \cdot y &= e^{-x} \cdot 2x \\
(e^{-x}y)' &= e^{-x} \cdot 2x \\
e^{-x}y &= \int 2xe^{-x} \, dx\\
e^{-x}y &= -2xe^{-x} - 2e^{-x} + D \\
y(x) &= De^x - 2x - 2
\end{align*}
Since the curve passes through the origin, we may plug in the point to get:
$$
0 = De^0 - 0 - 2 \iff D = 2
$$
so we conclude that:
$$
y(x) = 2e^x - 2x - 2
$$

A: NOTE:
This answer gives notes on why and how you do the calculations stated in other answers, as simple as I can explain it.

This is a differential equation (DE)! You are asked to find the curve $y=y(x)$, so note that $y$ is a function, and you have differente derivatives of $y$ in the equation:
$$\frac{d}{dx}y(x)=2x+y(x)\Rightarrow\frac{d}{dx}y(x)-y(x)=2x\qquad(1)$$
The DE has the function $y$ as the unknown. Therefore, the thing is to know what methods can you use to solve it.
In this case, you have first degree linear ordinary DE. That is because the highest derivative is the first derivative (degree 1) and it's linear.
In this case, you can use the method of the integrating factor $\mu$.
In the general case of the DE
$$\frac{d}{dx}y+P(x)\cdot y=Q(x)$$
This integrating factor is calculated as:
$$\mu = e^{\int P(x)\,dx}=\exp\bigg\{\int P(x)\,dx\bigg\}$$
So, for your equation $(1)$, you have:
$$\mu = \exp\bigg\{\int P(x)\,dx\bigg\}=\exp\bigg\{\int -1\,dx\bigg\}=\exp\{-x\}=e^{-x}$$
Then, you can solve easily multiplying $(1)$ by $\mu$, as said in the other answer.
HINT:
Step 2 of the other answer is because:
$$\begin{array}{rcl}
\frac{d}{dx}(y\cdot\mu)&=&\frac{d}{dx}(y)\cdot\mu+y\cdot\frac{d}{dx}(\mu)\\
&=& y'\mu + \mu\cdot P\cdot y
\end{array}$$
Note that, because of the Chain Rule,
$$\frac{d}{dx}(\mu)=\frac{d}{dx}\bigg(e^{\int P\,dx}\bigg)=e^{\int P\,dx}\cdot\frac{d}{dx}\bigg(\int P\,dx\bigg)=e^{\int P\,dx}\cdot P=\mu\cdot P$$

A: Step 1: Find the multiplier $\mu = e^{\int -1 dx} = e^{-x}$
Step 2: Rewrite equation as: $\left(e^{-x}y\right)' = 2xe^{-x}$
Step 3: Integrate both sides: $e^{-x}y = \displaystyle \int 2xe^{-x} dx = -2xe^{-x} - 2e^{-x} + C$.
Step 4: Solve for $y$:  $y = Ce^x - 2x - 2$, $C$ is a real constant. The initial condition that $y(0) = 0 \Rightarrow 0 = C - 2 \Rightarrow C = 2$. Thus: $y = 2e^x - 2x - 2$.
Step 5: Check the answer.

A: Rewrite as y' - y = 2x.
Homogeneous solution y = ex, from y' - y = 0.
Assume solution y = u*v. y' = u'v + uv'.
u'v + uv' - u*v = 2x
u*v' = 2x
v' = 2x * e-x
Integrate by parts.
v = -2x*e-x - 2*e-x
y = uv = -2x - 2
But, include the homogeneous solution ex with a constant K
y = K * ex - 2x - 2

A: This is called a first order linear differential equation.
Consider $\frac{dy}{dx}+P(x)y=Q(x)$ this is the first order linear differential equation.
To solve such a equation consider the following process,
1)Multiply both side by a assumed function, say g(x)
$g(x)\frac{dy}{dx}+P(x).g(x).y=Q(x).g(x)$
2) Select g(x) in such a way that LHS become the derivative of y.g(x)
i.e., $g(x)\frac{dy}{dx}+P(x).g(x).y=\frac{d[y.g(x)]}{dx}$
3) Simplifying the expression, we get.
$P(x)=\frac{g'(x)}{g(x)}$
4)Integrating and simplifying we get, $g(x)=e^{\int P(x).dx}$
5) This factor is called the integrating factor.
6)Putting $g(x)$ in original equation we would get the equation as,
$e^{\int P(x).dx}\frac{dy}{dx}+P(x).e^{\int P(x).dx}.y=Q(x).e^{\int P(x).dx}$
7)Which can be written as,
$\frac{d[y.e^{P(x).dx}]}{dx}=Q(x)e^{\int P(x).dx}$
8) Integrating both sides and simplifying the solution is,
$y=e^{-\int P(x).dx}.[\int(Q(x).e^{\int P(x).dx})dx+c]$
The function of the integrating factor, or multiplier is to put the LHS of the equation in an explicit derivative of either x or y , so that "dx" or "dy" can be easily taken to the RHS which is Q(x).g(x) or Q(y).g(y) that is also single a valued function in x or y. So that it can be easily integrated with respect to "dx" or "dy".

redpajama_set_name: RedPajamaStackExchange


text:
Q: dynamically set Path.Data for System.Windows.Shapes.Path I'm writing the following code to create a chart with System.Windows.Shapes.Path.
now I'm setting it's PathFigure in the xaml code:
<Grid FlowDirection="LeftToRight">
    <Canvas  HorizontalAlignment="Center" Name="PitchCanvas" VerticalAlignment="Center" Margin="30,0,370,470">
        <Canvas.RenderTransform>
            <ScaleTransform ScaleX="{Binding ElementName=SignalScaleSlider, Path=Value}" />
        </Canvas.RenderTransform>
        <Path Data="M 10,450 L 10,10 M 26,450 L 26,10 M 42,450 L 42,10 M 58,450 L 58,10 M 74,450 L 74,10 M 90,450 L
              90,10 M 106,450 L 106,10 M 122,450 L 122,10  M 138,450 L 138,10 M 154,450 L 154,10 M 170,450 L 170,10
                  M 202,450 L 202,10 M 234,450 L 234,10 M 266,450 L 266,10 M 350,450 L 350,10
                  M 10,350 L 350,350 M 10,330 L 350,330 M 10,310 L 350,310 M 10,290 L 350,290 M 10,270 L 350,270 M 10,250 L 350,250
                  M 10,230 L 350,230 M 10,210 L 350,210 M 10,190 L 350,190 M 10,170 L 350,170 M 10,150 L 350,150 M 10,130 L 350,130
                  M 10,110 L 350,110 M 10,90 L 350,90 M 10,70 L 350,70 M 10,50 L 350,50 M 10,30 L 350,30 M 10,10 L 350,10
                  " Height="454" Name="RangeSignalPath1" Stroke="Silver" StrokeThickness="0.5" />
        <Path Data=" M 10,450 L 350,450  M 10,330 L 350,330 M 10,230 L 350,230 M 10,130 L 350,130 M 10,30 L 350,30"
                  Name="RangeSignalPath2" Stroke="Silver" StrokeThickness="1" Height="387" />

Is there any way to write it's Path'Data dynamically (in c# code) instead of xaml code?
as you see it takes a lot of time to set the values of it but with a for loop it will be more simple.

A: Create the string as you like. Use Geometry.Parse(), it returns a Geometry object that you assign to RangeSignalPath1.Data:
Geometry g = Geometry.Parse(<your string>);
RangeSignalPath1.Data = g;


text:
Q: PHP - How do I add a name to an array I am building an array (json encoded) and returning it to the caller.  My output currently looks like this:
[{"org_id":1,"org_name":"Org 1"},{"org_id":4,"org_name":"Org 4"}]

I want to add a name so that output looks like this:
{
  "orgs" : [
    {"org_id":1,"org_name":"Org 1"},
    {"org_id":4,"org_name":"Org 4"}
  ]
}

Here is my current code:
// if orgs were found then
if ( is_array($orgs) && !empty($orgs) ) {

  $json_orgs = json_encode($user_orgs);

// else return an empty array
} else {
    $user_orgs = array();
}

I am fairly new to OO coding, so I have not figured out how to initialize an object so that "orgs" is present.  Maybe I don't even need an object.  Any help would be greatly appreciated.

A: Before you json encode the array, just wrap it in another one:
$newArray = ['orgs' => $yourCurrentArray];

Then you json encode the new variable instead.
If you rather not create a new array, you can simply do:
json_encode(['orgs' => $yourCurrentArray]);

This doesn't really have anything to do with OOP since you're just working with arrays. Associative arrays becomes objects when encoded into JSON.

A: You can achieve this by adding a key, for example:
// variable holding your data
$data;
// return statement in your controller
return ['orgs' => $data];

A: You didn't say exactly how you're generating the JSON at the moment, or from what object/variable in PHP, or with what structure (there is more than one possible way).
But in general, here's how you could do it with an associative array:
$data = array (
  'orgs' =>
  array (
    0 =>
    array (
      'org_id' => 1,
      'org_name' => 'Org 1',
    ),
    1 =>
    array (
      'org_id' => 4,
      'org_name' => 'Org 4',
    ),
  ),
)

And then json_encode that to get the JSON.
(Hint: you can simply do the process in reverse to generate this example code from the desired JSON.)

A: You just need to decode this with json_decode() and then you get like this
array (
0 =>
array (
'org_id' => 1,
'org_name' => 'Org 1',
),
1 =>
array (
'org_id' => 4,
'org_name' => 'Org 4',
),
)
then you need to add parant array on it
array( "orgs"=> array (
0 =>
array (
'org_id' => 1,
'org_name' => 'Org 1',
),
1 =>
array (
'org_id' => 4,
'org_name' => 'Org 4',
),
)
)
then again encode it and you will get your answer


text:
Q: Nginx doesn't serve asset files This is my config:
server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/public;
    index index.php;

    location ~* ^.+.(jpg|jpeg|gif|css|png|js|ico|txt|srt|swf)$ {
        root /var/www/public;
    }

    location ~ \.php$ {
        fastcgi_pass php-fpm:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PHP_VALUE "error_log=/var/log/nginx/application_php_errors.log";
        fastcgi_buffers 16 16k;
        fastcgi_buffer_size 32k;
        include fastcgi_params;
    }

    location / {
        try_files $uri $uri/ /index.php?q=$uri&$args;
    }

    location ~ /\.ht {
           deny all;
    }
}

My css files is placed in /var/www/public/css/test.css. When I go to localhost:1234/css/test.css i get nginx's 404 error. Normal pages like index page (localhost:1234) work.
When I edit config:
location ~* ^.+.(jpg|jpeg|gif|css|png|js|ico|txt|srt|swf)$ {
    return 200 debug;
    root /var/www/capitol/public;
}

I get debug message.
I've tried a lot of solutions from similar questions but none of them works.

A: I resolve problem by reinstalling nginx (not sure if it was necessary) and using this config:
server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/public;
    index index.php;

    location / {
            try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
        fastcgi_pass php-fpm:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PHP_VALUE "error_log=/var/log/nginx/application_php_errors.log";
        fastcgi_buffers 16 16k;
        fastcgi_buffer_size 32k;
        include fastcgi_params;
    }
}


text:
Q: Are there CPUs that perform this possible L1 cache write optimization? When the CPU with an L1 cache does a write, what normally happens is that (assuming that the cache line that it is writing to is already in the L1 cache) the cache (in addition to updating the data) marks that cache line as dirty, and will write the line out with the updated data at some later time.
One possible optimization would be to have the cache compare the contents of the write and the previous contents of the cache, and if they're the same, don't mark the line as dirty.  Because this might allow the cache to avoid write-backs on occasion, I can see how the CPU manufacturer might see this as worth the gates needed to do this logic.
My question: are there CPUs that perform this optimization?
Background as to why I'm asking: I'm writing some code that needs to have constant memory accesses; that is, someone who is able to listen into the behavior of the cache should not be able to deduce what I'm doing.  Some of my accesses are writes, and in the obvious way to implement this code, a lot of the writes will be writing the same data that's already there. I need to do the writes because, depending on the data, the data I'm writing may or may not be the same, and it's important to perform the same action regardless.  If the CPU optimizes by not actually writing a 'no-change-write', that would mean that the behavior of the cache would vary depending on what I'm doing, which would subvert my goal.
So, is there a CPU that tries to optimize writes in this way?

A: From hours of searching, I wasn't able to find a CPU that uses this specific optimization. Most of the optimizations mentioned usually related to hit/miss with read/write operations and data access:
(pages 7 and )
https://cseweb.ucsd.edu/classes/fa14/cse240A-a/pdf/08/CSE240A-MBT-L15-Cache.ppt.pdf
However, that doesn't mean that this optimization can't be performed. In general, it is possible to programmatically access the size of a CPU cache line. It is also possible to access current values in cache registers - but it's somewhat dangerous to do so. If you access the wrong registers at a bad time, you could be tampering with ones related to a running program. Or you could inadvertently modify the contents of the lines you're trying to read.
Obtaining current value in register's cache
Furthermore, all of the theoretical solutions require some form of software implementation (assembler). The closest I've found relates to the ARM architecture, which appears to allow for cache manipulation. In addition to this, you would also need to know the size of a cache line for your desired CPU. You could carefully read the cache contents to a secondary location in memory, in line-sized increments, and compare it to data that is about to be written to the registers (or L1 cache lines, in this case).
Read CPU cache contents
From there, you could devise a software-based system that prevents identical rewrites. While this is a bit simplified, it is so because the solution has to be applicable for any CPU that exists.
Another possibility that I found related to Cache coherence:
Relevant passage from a Wikipedia article about acche coherence
The main point that caught my attention, in relation to this issue, was the Snarfing description:

It is a mechanism where a cache controller watches both address and data in an attempt to update its own copy of a memory location when a second master modifies a location in main memory. When a write operation is observed to a location that a cache has a copy of, the cache controller updates its own copy of the snarfed memory location with the new data.

In other words, there are possibly mechanisms already in place. It's just that they might not be used for the optimization you have suggested. You would have to implement software that performed the read/write comparison.

A: Writing to L1 cache is a very, very time critical operation.
Writing the exact same data back seems to be rather rare. An optimisation that speeds things up in this particular case isn't going to get a lot of speedup in total.
On the other hand, this optimisation requires a comparison of old data and new data on every single write to cache memory. What makes this worse, is that it requires that the data to be written has to be actually available at the time of the write!
That is usually not the case on a modern CPU. The data to be written may still be being calculated for example. The cache can still go ahead, load the cache line if needed, mark the cache line as modified and so on, even before the calculation is finished. All the book keeping can already be performed except for the actual modification of the cache line. If you want to compare newly written result and old cache line data, that isn't possible.
As an example, if you have C code a [i] = x / y; the division x / y takes an extraordinary long time to perform on most CPUs. However, most of the work needed to handle storing the result to a [i] has happened long before the division finishes; the only thing missing is the move of eight result bytes to the cache line. An operation flushing the cache line will automatically wait until the division is finished. An operation reading a [i] will likely be redirected to get the result straight from the divider.

A:
One possible optimization would be to have the cache compare the
  contents of the write and the previous contents of the cache, and if
  they're the same, don't mark the line as dirty

Won't such optimization double the time CPU needs to write something into cache? Because each cache line write will now be accompanied with a compare operation, which is not free.
So, actually the optimization now will depend on the very vague factor: how many times an average software rewrites its cacheable memory with the same data.

A: Note: A more comprehensive version of this answer is on StackOverflow and I recommend you read that one for the most up-to-date information.
I found evidence that some modern x86 CPUs from Intel, including Skylake and Ice Lake client chips, can make this optimization, but at the L2 <-> L3 boundary, not at the L11, in at least one specific case:
An all zero cache line is written to with additional zeroes, so that it remains fully zero.
That is, a "zeros over zeros" scenario.
For example, this plot shows the performance (the circles, measured on the left axis) and relevant performance counters for a scenario where a region of varying size is filed with 32-bit values of either zero or one, on Skylake client:

Filling with zeroes both performs better and shows about half of the write bandwidth to DRAM. On Ice Lake, the optimzation takes effect more often and the write bandwidth drops close to zero.
You can find more detail on the above-mentioned StackOverflow answer, and in this blog post where I cover it in more detail. There is an addendum for Ice Lake, which as mentioned exhibits this effect more strongly here.

1 Of course, it is possible that the "is all zero" state is detected at the L1 and propagated outwards for ultimate use at the L2 <-> L3 boundary.


text:
Q: While installing Ubuntu: black cloud builds up at mid screen; and 0.0 B disk space message I have been trying to install Ubuntu Desktop 20.04 LTS 64-bit from a CD. I have American Mega Trends motherboard, with AMD Athlon 450 processor 3.20 GHZ. I am getting "CMOS CheckSum Bad", then I press F1 to load default values.
As I go thru the installation stages, I get the following problems:
1- at each stage at first the screen is normal, then after a few seconds a sort of small black cloud (3"x4")  builds up in the middle of the screen with some fragmented lines. but I am still able to click and go thru the next stage.
2- at the 4th stage it says "you need at least 8.6 GB disk space, the computer has only 0.0 B"
I have installed a brand new Samsung 500 GB SSD, and I un-plugged and re-plugged the hard drive few times to make sure the connections are right. I tried to install Windows 7 before, but currently I do not have any OS on the drive yet. I like to run just the Ubuntu with no partition.
Also I like to re-format the drive to get rid of any residue from previous installations, but I guess that option comes toward the end of the installation.
I used a different CD just in case there was a problem with the CD. But the problem still remains. I have also tried "Try Ubuntu". It installs it, but when next time I reboot, I get into BIOS screen with options F2 Set Up, F6 Instant Flash, F11 Boot Menu. Basically back to square one.
Any comments/solutions appreciated,
Thanks!


text:
Q: what is the maximum Size of .sql file that can be uploaded to sql azure management portal??? I am trying to run the .sql file in SQL AZURE MANAGEMENT PORTAL. The size of the .sql file is 9.3GB. When I try to open it, I could not. Please tell what is the maximum size of .sql file that can be opened and executed.
Thanks!

A: I don't think your 9.3 GB is a problem.
please read
Azure SQL Database Web vs Business Edition


text:
Q: Updating State of Parent component from Child Component (Tab Navigator) I am new to React and React Native and I am trying to build an cooking recipe app. I am trying to update my dish state in DishTabNavigator.js from DishIngredients.js so that I can send the data to firebase from DishTabNavigator.js, however I do not know how I can update the state. I tried lifting the state up but I couldn't do it. Been stuck on this for a day now. Any help would be appreciated
DishTabNavigator.js
const Tab = createMaterialTopTabNavigator();

export default function MyTabs({ navigation }) {
  const [dish, setDish] = useState([{ ingredients: [] }]);
  React.useLayoutEffect(() => {
    navigation.setOptions({
      headerRight: () => (
        <TouchableOpacity style={styles.iconright}>
          <Text>Send dish to Firebase</Text>
          <FontAwesome name="save" size={24} color="black" />
        </TouchableOpacity>
      ),
    });
  });
  return (
    <Tab.Navigator>
      <Tab.Screen
        name="Ingredient"
        component={DishIngredients}
        ingredients={dish}
      />
    </Tab.Navigator>
  );
}

DishIngredients.js
class DishIngredients extends Component {
  constructor(props) {
    super(props);
    this.state = {
      ingredients: [],
      textInput: [],
    };
//Add TextInput
  addTextInput = (index) => {
    let textInput = this.state.textInput;
    textInput.push(
      <TextInput
        style={styles.textInput}
        onChangeText={(text) => this.addValues(text, index)}
      />
    );
    this.setState({ textInput });
  };

//Function to add values into the states
  addValues = (text, index) => {
    let dataArray = this.state.ingredients;
    let checkBool = false;
    if (dataArray.length !== 0) {
      dataArray.forEach((element) => {
        if (element.index === index) {
          element.text = text;
          checkBool = true;
        }
      });
    }
    if (checkBool) {
      this.setState({
        ingredients: dataArray,
      });
    } else {
      dataArray.push({ text: text, index: index });
      this.setState({
        ingredients: dataArray,
      });
    }
  };

  //function to console the output
  getValues = () => {
    console.log("Data", this.state.ingredients);
    this.props.ingredients = this.state.ingredients;
    console.log(this.props.ingredients);
  };

  render() {
    return (
      <View>
        <View style={styles.icon}>
          <View style={{ margin: 10 }}>
            <TouchableOpacity>
              <Ionicons
                name="add"
                size={24}
                color="black"
                onPress={() => this.addTextInput(this.state.textInput.length)}
              />
            </TouchableOpacity>
          </View>
          <View style={{ margin: 10 }}>
            <Button title="Remove" onPress={() => this.removeTextInput()} />
          </View>
        </View>
        {this.state.textInput.map((value) => {
          return value;
        })}
        <Button title="Get Values" onPress={() => this.getValues()} />
      </View>
    );
  }
}

export default DishIngredients;

A: You could use React Context
const DishContext = React.createContext({
  dish: [],
  setDish: () => {},
});

export const useDishContext = () => React.useContext(DishContext);

export const AppDishProvider = ({children}) => {
  const [dish, setDish] = useState([{ingredients: []}]);

  const defaultDish = {
    dish,
    setDish,
  };

  return (
    <DishContext.Provider value={defaultDish}>{children}</DishContext.Provider>
  );
};

Then
/** Wrap your TabNavigator with AppDishProvider */
<AppDishProvider>
  <YourTabNavigator />
</AppDishProvider>

Then
/**
 * In DishIngredients, or your TabNavigator...
 * You get access to dish-state, and setDish using your
 * custom-hook `useDishContext`
 */

 const { dish, setDish } = useDishContext();

And if you're using class-based component
class DishIngredient extends React.Component {
  static contextType = DishContext;

  /**
   * Current context-value could be accessed by
   * `this.context`
   */

  render() {
    const {dish, setDish} = this.context;
    /** .... */
  }
}

Assuming you're not having redux wired in your app... ReactContext is your way to go...

A: Without changing a lot in your current code you can do like this
const addIngredient = (ingredient) => {
    // TODO: ingredient
  };

  return (
    <Tab.Navigator>
      <Tab.Screen name="Ingredient">
        {(props) => (
          <DishIngredients
            {...props}
            ingredients={dish}
            addIngredient={addIngredient}
          />
        )}
      </Tab.Screen>
    </Tab.Navigator>
  );

As you see there is a function addIngredient (You can rename as you wish) that will be introduced as prop in DishIngredients like this.props.addIngredient(<Your Ingredient text>).
ReactContext also a nice solution above but I think, this will force your app re-render every time your context changes. It might impact on your performance.


text:
Q: ReactJS sort by Asc/Desc not rendering sorted list from nested component Project Overview
I am currently learning ReactJS and am creating a Pokedex app that allows the user to sort Pokemon objects by specific properties (name, type, hp, etc). The end product should have a search input to filter by pokemon name, a drop-down selector for sort criteria, and buttons for sort Ascend and sort Descend. State being tracked is  searchQuery, sortBy, sortSelected, and pokeData(my data file).
Full code can be viewed here: https://github.com/julianne-vela/Pokedex-React/tree/dev
File Structure: SearchPage.js > SideBar.js > SortMenu.js
Problem

onClick button in SortMenu is not rendering sorted Pokemon list.
Expected Result: Click Asc/Desc button in SortMenu -> Pokemon list renders in sorted order based on criteria selected in drop-down and Asc/Desc button clicked.
Actual Result: Drop-down is updating state with correct sort criteria selected but button is not triggering any action when clicked.
What I've tried

Using destructured props throughout project
const {
    sortBy,
    sortSelected,
} = this.state

Currently passing the following props from SearchPage.js to child SideBar.js:
sortByValues={sortBy} // Array of sort criteria options stored in state
sortSelected={sortSelected} // Currently selected sort criteria from drop-down
handleSortSelected={this.handleSortSelected} // event handler to update state with currently selected sort criteria
sortAsc={this.sortAsc} // function to trigger Asc sort onClick
sortDesc={this.sortDesc} // function to trigger Asc sort onClick

SortMenu.js Code
import React, { Component } from 'react';

export default class SortMenu extends Component {
    render() {
        const {
            sortByValues,
            handleSortSelected,
            sortAsc,
            sortDesc,
        } = this.props

        const options = sortByValues.map(option => <option value={option} key={option}>{option}</option>)

        return (
            <aside>
                {/* DropDown Sort By */}
                <select className='dropdown'
                    onChange={handleSortSelected}>
                    {options}
                </select>

                {/* Sort Ascending/Descending Buttons */}
                <button className='sortBtn' value='ascending' onClick={sortAsc}>Ascending</button>
                <button className='sortBtn' value='descending' onClick={sortDesc}>Descending</button>

            </aside >
        )
    }
}

I feel it's important to note that we are using strictly class components and therefore are not using constructor(props) in this project. Instead, I am using arrow functions throughout to implicitly bind this where needed.
To reiterate my goal: I need to dynamically render the pokemon list based on the sort criteria selected in the drop-down list as well as the ascend/descend button clicked. The list should update onClick.
I have been working on this for 3 days and have gone through so many iterations of sort functions that I can't even see straight anymore. I'm thinking this might be a simple over-sight due to the sheer amount of code I'm writing as well as the fact that this is a new language (I'm already proficient in Vanilla JS).
Any guidance here would be GREATLY appreciated as I'm really at a wall at this point. I don't know what else to try in order to render the sorted list.
Update
Also, would it be easier if I were to create a toggle button instead of two separate buttons for Asc/Desc?
Thank you!
Update 2
Currently I am rendering my pokemon objects in a module component that I'm calling within the SearchPage.js component. Here is the code for the Pokemon List:
export default class PokemonList extends Component {

    render() {
        const { filteredPokemon } = this.props

        return (
            <content className='pokemon-list float'>
                {filteredPokemon.map(pokeObject =>
                    <PokeItem
                        key={pokeObject._id}
                        pokeImage={pokeObject.url_image}
                        pokeName={capFirstLetter(pokeObject.pokemon)}
                        pokeType={capFirstLetter(pokeObject.type_1)}
                        pokeHp={pokeObject.hp}
                        pokeAtt={pokeObject.attack}
                        pokeDef={pokeObject.defense}
                    />)}
            </content>
        );
    }
}

This is pulling the filtered pokemon from my filter method on SearchPage.js:
const filteredList = pokeData.filter(pokeObject => {
            return pokeObject['pokemon'].includes(this.state.searchQuery) || pokeObject['type_1'].includes(tFilterSelected);
        });

To sort the items, I'm using two separate arrow functions. These are housed in the first section of the SearchPage.js component (outside of render and return):
sortAsc = () => {
        this.setState(prevState => {
            this.state.pokeData.sort((a, b) => (a[this.state.sortSelected] - b[this.state.sortSelected]))
        })
    }

    sortDesc = () => {
        this.setState(prevState => {
            this.state.pokeData.sort((a, b) => (b[this.state.sortSelected] - a[this.state.sortSelected]))
        })
    }

Update 3
Added project to CodeSandbox. Can view here: https://codesandbox.io/s/pokedex-react-crflb

A: A comparator function that subtracts the arguments would work fine for sorting numbers but would fail on strings since it would return NaN.
sortAsc = () => {
  const { pokeData, sortSelected } = this.state
  this.setState({
    pokeData: [...pokeData].sort((a, b) => {
      if (a[sortSelected] > b[sortSelected]) {
        return 1
      }

      if (a[sortSelected] < b[sortSelected]) {
        return -1
      }

      return 0
    })
  })
}

sortDesc = () => {
  const { pokeData, sortSelected } = this.state
  this.setState({
    pokeData: [...pokeData].sort((a, b) => {
      if (a[sortSelected] > b[sortSelected]) {
        return -1
      }

      if (a[sortSelected] < b[sortSelected]) {
        return 1
      }

      return 0
    })
  })
}

Working CodeSandbox


text:
Q: How do I keep PostgreSQL connection open? So basicly I create my db client like this:
client = new pg.Client(conString);
client.connect();

but after some time of innactivity on the db, the clients probably drops the connection and gives me this error:
"Error: read ECONNRESET"

I tried doing this to keep it open:
db.client.on('error', function(e){
    db.client.connect();
});

But that doesn't work and I still get the error. Anyone dealt with this before and has any idea how to solve it?

A: It sounds like you're probably encountering issues with connections being dropped due to expiry of NAT connection tracking tables or similar.
Enable TCP keepalives, either server-side or if your client supports it, client-side.
If you can't use TCP keepalives you could instead send empty queries, i.e. send the empty string as a query. This is valid and legal in PostgreSQL and will force a round-trip between client and server but won't add any noise to the logs.


text:
Q: Grails - Where to put test files and how to load them I'd like to ask where is the best place for test files in grails (i.e. data.xml). Is it test/ folder?
How can I load test files in Integration test easily?
Thanks,
Mateo

A: in test/integration/resources
and then, i.e. if you use spock for testing, you can do something like that:
def mediaBundlerService = Mock(MediaBundlerService)
mediaBundlerService.getPath(_) >> [path: new File('test/integration/resources/test-bundle/').absolutePath + "/"]


text:
Q: Determine whether a MATLAB GUI edittextbox is is use Basically I have a really complex Matlab GUI, where the user can add different strings by an editextbox (the one you can type in). The problem is that I assigned different functions to different keyboard button pushdowns, for example 's' and 'e' are in use. Every time you try to type in for example 'snake' the functions assigned to 's' and 'e' are executed. Is there any way to determine wheter I clicked in the edittextbox, and it is in use -> like a logical value so i can block the keypressfunctions by checking it.

A: Within your callback, you can use gco to get the current object. You can then check if this is the graphics handle to your edit box.
fig = figure('WindowKeyPressFcn', @(s,e)keypress());

hedit = uicontrol('Style', 'edit');

function keypress()
    if ~isequal(gco, hedit)
        disp('Window Key Press')
    end
end

If on the other hand you didn't set a global key press callback (using WindowKeyPressFcn) and you instead set the KeyPressFcn of each uicontrol individually, just specifying a different (or no) KeyPressFcn for the edit box would work.


text:
Q: My mapview does not zoom on the first pass into the view controller Can anybody help me please? I'm new to xcode and am baffled by what I think is a small problem. For some reason the first time my map is opened from my initial view controller the pin is dropped but the map does not zoom to the correct region even though the latitude and longitude are correct.
When I go back to the first view controller and launch it again the zoom works.
My code is in the view controllers implementation file under viewdidload.
-(void)viewDidLoad {
[super viewDidLoad];
NSLog(@"lat in map %@", eventLat);
NSLog(@"long in map %@", eventLong);
[mapview setMapType:MKMapTypeStandard];
[mapview setZoomEnabled:YES];
[mapview setScrollEnabled:YES];

MKCoordinateRegion region = { {0.0, 0.0 }, {0.0, 0.0 } };
region.center.latitude = [eventLat doubleValue];
region.center.longitude = [eventLong doubleValue];
region.span.latitudeDelta = 0.01f;
region.span.longitudeDelta = 0.01f;

[mapview setRegion:region animated:YES];

MMAnnotate *ann = [[MMAnnotate alloc] init];
ann.title = @"Test Title";
ann.subtitle = @"Test Subtitle";
ann.coordinate = region.center;
[mapview addAnnotation:ann];

}

A: You should try doing that in viewDidAppear instead. If you're prepared for it to zoom to that location every time the view appears. viewDidLoad is too early in the mapview cycle.


text:
Q: How to update a specific column in Firebase with Laravel? I am using Kreait\Firebase. I hope you are familiar with it. This is my code
public function firebase() {
  $serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/private-again.json');

  $firebase = (new Factory)
  ->withServiceAccount($serviceAccount)
  ->withDatabaseUri('https://private.firebaseio.com/')
  ->create();

  $update   = ['id'  => 1];

  $database = $firebase->getDatabase();

  $reference = $database->getReference('user/details')
  ->orderByChild('id')
  ->equalTo('2')
  ->update($update);

  print_r('Good');die;
}

So, What I am trying to do here is, I want to update the id which is equal to 2 to 1. But it throws an error like this Call to undefined method Kreait\Firebase\Database\Query::update(). And, I do not know if I am doing it okay or not.
P.S.: I was able to get the snapshot so that part went good with equal to 2.


text:
Q: HttpHandler using Default Namespace I have a HttpHandler called Handler that I compile into a DLL and put in the /bin folder of my ASP.NET app. Then I have a .ashx file:
<% @ webhandler language="C#" class="Handler" %>

but I get a cannot create type 'Handler' error.
However, if I wrap Handler in a gratuitous namespace, say foo, and change the .ashx to
<% @ webhandler language="C#" class="foo.Handler" %>

it works fine. Why can't I use no namespace, er, the default namespace? Microsoft omits a namespace in many examples of HttpHandlers on the msdn website.

A: Thi is because of the nature of .Net Assemblies. Any Reference Type or ValueType must be wrapped around a namespace. Namespaces are used for logical grouping. In your case, your class 'Handler' is user-defined reference type. Any assembly can have one or many root namespaces at the root but it can not have a reference type or a value type at the root. In fact when you create a New Class Library Project in the Applications Tab of the Project Properties, it has an option to Specify the Default NameSpace for your Class Library Project. So whenever you create a New Class in your Project it will wrap it around this Default NameSpace specified in the ProjectProperties.Application.DefaultNameSpace.
If you wish to see this in action then try opening your .Net Assembly with IL Disassemblar that comes with .Net SDK.


text:
Q: Why does my op-amp circuit always give near zero output? I have an op-amp design same with the picture seen below with TLC271.I have an analog sensor that goes as Vin. I am giving 3.3V from an arduino to power it. And reading values from an analog pin.
The problem is that the output gives between 0mV-8mV while sensor and resistors are connected.
r2=220 ohm| rf=22k ohm| sensor gives output between 0-200 mV

*Image taken from http://www.electronics-tutorials.ws/opamp/opamp_3.html
*I also have a zigbee module connected to arduino and a 5V 1A powerbank which powers the arduino.

A: The data sheet says pin 8 (bias select) needs to be connected as shown below: -

A 3V3 power supply is OK as is the way you have connected R2 so ignore the other answer.

A: Looking at the datasheet for the TLC271, I see that the minimum supply volyage is 3V. That is most probably your problem. You are going to have to use a higher voltage, eg 5V.
Then we have the problem of biasing of the opamp. You cannot just stick 5V and earth on there if you want any negative swing on the output. You need to do a bit more reading on the subject, there is plenty of information about this out there.


text:
Q: QProgressbar with 2 Labels with differend alignment When a Client connects to my application a new QProgressbar will show and display his set name and display some more information. This works fine. But based on the length of the name it doesn't look perfect if multiple people connect. And it is getting harder to read.
What i want is two labels. One For the name which is left aligned and one on the right side for the other information with right alignment

So is there a way to display two different labels on top of the progressbar and have one aligned to the left and one to the right?

A: Such behaviour is not provided by standard Progress Bar, you must subclass and implement your behaviour yourself.


text:
Q: Using Clojure Spec with Datomic entities Say I have the following specs:
(s/def :person/age number?)
(s/def :person/name string?)

(s/def ::person (s/keys :req [:person/name :person/age]))

Then I fetch an entity from Datomic:
(def person-entity (d/entity (d/db conn) [:person/name "Mr entity"]))

If I try to check conformance with the spec it fails because entities are not maps:
(s/explain ::person person-entity)

val: #:db{:id 17592186069950} fails spec: :some-ns/person predicate: map?

My app has functions that take entities as arguments and would like to avoid having to reify entities to maps everywhere just to get spec instrumentation to work in development.
How should I go about validating entities through spec?

A: Although it is true that your namespaces are a bit off (you should be using :person/name instead of ::name), there is also a restriction in spec that could be lifted. Currently s/keys requires that all input collections conform to the clojure.core/keys predicate. Datomic entities are not maps, and so do not pass that check (and hence the error about the map? predicate).
I've filed a bug report here: http://dev.clojure.org/jira/browse/CLJ-2041 Feel free to upvote/follow the ticket if you wish.


text:
Q: Install4j: How to submit proxy settings to the autoupdater? We will use either ApplicationLauncher.launchApplicationInProcess or  ApplicationLauncher.launchApplication.
How do we pass host, port, userid, and password to it?
Passing the information using a file would be a no-go because the password might be a user password.

A: Proxy settings are passed to the update downloader with the arguments
-DproxySet=true
-DproxyHost=...
-DproxyPort=...
-DproxyAuth=true
-DproxyUser=...
-DproxyPassword=...

More generally, you can set installer variables in the update downloader via special arguments passed to ApplicationLauncher. An argument
-Vkey=value

sets the installer variable named key to the value. In all text fields of the update downloader configuration, you can use it with the syntax
${installer:key}

You can configure default values for these installer variables on the "Installer variables" tab of the update downloader configuration so that it also works when called without those arguments.


text:
Q: jquery slideshow without thumbnails? I'm trying to find a plugin for a simple slideshow without thumbnails.
I am working on the php side of the project so I can't spend more time on creating a slideshow.. so I thought I might just use a simple plugin for the slideshow that I need.
most of the ones on google has thumbnails or very bloated.. all i need is a light weight and basic (responsive if possible) out of the box slideshow for quick implementation into my project.
PS. I'm not asking anyone to write me a code. if you know any plugins then please do share.
something close to the image bellow:

any help would be appreciated.
Thanks

A: Did you try BX Slider? It is just a content slider, and capable of sliding basic LI or DIV content.
Installation:

<link href="/lib/jquery.bxslider.css" rel="stylesheet" />

HTML:

JS:
$(document).ready(function(){
  $('.bxslider').bxSlider();
});


text:
Q: Good and CLEAN way to check this? (JS + HTML) I am trying to make a system that will check what radio button is pushed. (Side note there WILL always be 1 checked.) The code I have so far is rather lacking and I'm not entirely sure how to improve. Any help??
NOTE: I have multiple 'systems' that look just like this, so I'll give you just 1 chunk. That being said, there are multiple chunks like this. I need a way to make this easy on my end.
HTML:

Storage

                            <input name="STORAGE" type="radio" id="STORAGE" checked>

320GB Western Digital Caviar Blue 3.5" 7200RPM HDD

                            <input name="STORAGE" type="radio" id="STORAGE2">

500GB Western Digital WD5000AAKX 3.5" 7200RPM HDD

+$55

                            <input name="STORAGE" type="radio" id="STORAGE3">

1TB Western Digital WD10EZEX 3.5" 7200RPM HDD

+$55

                            <input name="SSD" type="radio" id="SSD" checked>

                            <input name="SSD" type="radio" id="SSD2">

120GB A-Data ASP550SS3-120GM-C SSD

+$40

JS:
    function Check(){
    if(document.getElementById('STORAGE3').checked & HDD3Clicked==0){
        if (HDD2Clicked>0) {
            HDD2Clicked = 0;
            HDD3Clicked = 1;
        }else{
            HDD3Clicked = 1;
            Adding(+55);
            console.log("Adding");
        }
    }else if (document.getElementById('STORAGE2').checked & HDD2Clicked==0) {
        if (HDD3Clicked>0) {
            HDD2Clicked = 1;
            HDD3Clicked = 0;
        }else{
            HDD2Clicked = 1;
            Adding(+55);
            console.log("Adding");
        }
    }else if (document.getElementById('STORAGE').checked & HDD3Clicked>0) {
        HDD3Clicked = 0;
        Adding(-55);
        console.log("Subtracting");
    }else if(document.getElementById('STORAGE').checked & HDD2Clicked>0){
        HDD2Clicked = 0;
        Adding(-55);
        console.log("Subtracting");
    }

    setTimeout(function() {Check()}, 5000);
}

A: If you can use jQuery it's fairly simple...
var clickedID;
$(document).ready(function(){
  $('radio').on('click'),function(){
    clickedID = $(this).attr("id");
  });
});

That will give you the id of whichever radio element has been clicked. Then you can do with it what you'd like.

A: var radioButtons = selectorQueryAll("input[type=radio]:checked");

for (button in radioButtons) {
    console.log(button.id);
}

1) Return all checked radio buttons
2) Output their ID to console.

A: If you don't want to use jQuery, this is a pure javascript solution:
<input type="radio" name="radioGroup" onclick="handleClick(this);" value="1"/>
<input type="radio" name="radioGroup" onclick="handleClick(this);" value="2" />


text:
Q: git ls-files excluding files from .myignorefile I want to get all files from a repository but ignoring files that are not listed or don't match in the .gitignore file using regular expressions or some kind of options such as "exclude-from=.myignorefile".
Let's say these are my files after I do git ls-files:

*

*.gitignore

*index.html

*assets/app.less

*assets/app.css

*assets/app.js

But I don't want the assets/app.less and .gitignore files to be shown. Is there any option to accomplish this? I thought exclude-from was going to do the job but I misunderstood it:
Read exclude patterns from <file>; 1 per line.

Edit: I don't list those files in the .gitignore file because I want to track them but I don't want to use them for something else, lets say not uploading them to an ftp server.

A: I don't think git ls-files can do this. But you can pipe its output to grep (or other) and exclude whatever you want, for example:
$ git ls-files | grep -v -e ^.gitignore -e ^assets/app.less
index.html
assets/app.css
assets/app.js


text:
Q: How do I load a random document from CouchDB (efficiently and fairly)? I would like to load a random document out of a set of documents stored in a CouchDB database. The method for picking and loading the document should conform to the following requirements:

*

*Efficiency: The lookup of the document should be efficient, most importantly the time to load the document must not grow linearly with the total number of documents. This means the skip query argument cannot be used.

*Uniform distribution: The choice should be truly random (as far as possible, using standard random number generators), every document should have equal chances of being chosen.
What is the best way to implement this in CouchDB?

A: After giving this some more thought, I came up with a solution. For completeness sake, I will first show two simple approaches and explain why they are flawed. The third solution is the one I'm going with.
Approach 1: Skip
This is the trivial solution: You have a simple view (let's call it random) with a map function that emits all documents you want to choose from and the built-in _count reduce function. To pick a random document, follow these steps:

*

*Find the total number of documents N in the view by calling:
http://localhost:5984/db/_design/d/_view/random

*Pick random number 0 <= i < N

*Load the i'th document:
http://localhost:5984/db/_design/d/_view/random?reduce=false&skip=i&limit=1
This approach is bad because it doesn't scale well for large numbers of documents. According to this section of "CouchDB - The Definitive Guide" the skip argument should only be used with single-digit values.
The solution above would have to loop through i documents before returning the chosen one. In SQL terms it's the equivalent of a full table scan as opposed to an index lookup.
Approach 2: Random Number in Document
With this approach, a random number is generated for each document at creation time and stored in the document. An example document:
{
  _id: "4f12782c39474fd0a498126c0400708c",
  rand: 0.4591819887660398,
  // actual data...
}

The random view then has the following map function:
function(doc) {
  if (doc.rand) {
    emit(doc.rand, doc);
  }
}

These are the steps to pick a random document:

*

*Pick a random number 0 <= r < 1

*Load the document:
http://localhost:5984/db/_design/d/_view/random?startkey=r&limit=1

*If no document is returned (because r is larger than the largest random number stored in the database), wrap around and load the first document.

This is very fast and looks great at first sight. However, there's a serious flaw: not all documents have the same chance of being picked.
In the most simple example, there are two documents in the database. When I choose a random document a very large number of times, I want each document to come up half of the time. Let's say the documents were assigned the random numbers 0.2 and 0.9 at creation time. So document A is picked when (r <= 0.2) or (r > 0.9) and document B is chosen when 0.2 < r <= 0.9. The chance of being picked is not 50% for each document, but 30% for A and 70% for B.
You might think the situation improves when there are more documents in the database, but it really doesn't. The intervals between documents get smaller, but the variation in interval size get's even worse: Imagine three documents A, B and C with the random numbers 0.30001057, 0.30002057 and 0.30002058 (no other documents are in between). The chances of B being chosen are 1000 times greater than C being chosen. In the worst case, two documents are assigned the same random number. Then only one of them can be found (the one with the lower document id), the other is essentially invisible.
Approach 3: A combination of 1 and 2
The solution I came up with combines the speed of approach 2 with the fairness of approach 1. Here it is:
As in approach 2, each document is assigned a random number at creation time, the same map function is used for the view. As in approach 1, I also have a _count reduce function.
These are the steps for loading a random document:

*

*Find the total number of documents N in the view by calling:
http://localhost:5984/db/_design/d/_view/random

*Pick random number 0 <= r < 1

*Calculate random index: i = floor(r*N)
My goal is to load the i'th document (as in approach 1). Assuming the distribution of random numbers is more or less uniform, I'm guessing the i'th document has a random value of approximately r.

*Find the number of documents L with a random value lower than r:
http://localhost:5984/db/_design/d/_view/random?endkey=r

*See how far off our guess is: s = i - L

*if (s>=0)
http://localhost:5984/db/_design/d/_view/random?startkey=r&skip=s&limit=1&reduce=false

*if (s<0)
http://localhost:5984/db/_design/d/_view/random?startkey=r&skip=-(s+1)&limit=1&descending=true&reduce=false
So, the trick is to guess the random number assigned to the i'th document, look that up, see how far we're off and then skip the number of documents by which we missed.
The number of documents skipped should remain small even for large databases, since the accuracy of the guess will increase with the number of documents. My guess is that s remains constant when the database grows, but I haven't tried and I don't feel qualified to prove it theoretically.
If you have a better solution, I'd be very interested!

A: If insert performance is not an issue you could try to make number non random e.g. make it doc_count + 1 at the time of creation. Then you could look it up with a random number 0 <= r < doc_count. But that would either require to synchronize the creation of documents or have sequence external to couchdb, e.g. an SQL database.
Best regards
Felix

A: How about "abusing" a view's reduce function?
function (keys, values, reduce) {
    if (reduce)
      return values[Math.floor(Math.random()*values.length)];
    else
      return values;
}

A: I agree with @meliodas:
Here's the distribution of option 2 (n=1000):
{ 0.2: 233,
  0.9: 767 }

And with swapping startkey/endkey half the time:
{ 0.2: 572,
  0.9: 428 }

Not sure what happens to the distribution when you look at more data, but it initially seems a bit more promising. This is without using option 1 at all, which I don't think is necessary.

A: Approach 2b: Sequential Number in Document
This approach is similar to Approach 2 mentioned in this answer . That Approach 2 uses random numbers twice (once in the document itself and once in the process of picking a document). This Approach 2b will only use random numbers on the picking process and use sequential integers on the documents. Note that it will not work, if documents are deleted (see below). Here is how it works:
Add sequential integers to your documents at creation time:
{
    _id: "4f12782c39474fd0a498126c0400708c",
    int_id : 0,
    // actual data...
}

another doc
{
    _id: "a498126c0400708c4f12782c39474fd0",
    int_id : 1,
    // actual data...
}

and just count up by one with each document.
The view random has the same map function (although you might want to change its name to something other than "random"):
 function(doc) {
   if (doc.int_id) {
     emit(doc.int_id, doc);
   }
 }

These are the steps for loading a random document:

*

*Find the total number of documents N in the view by calling:
http://localhost:5984/db/_design/d/_view/random

*Pick random number 0 <= r < 1

*Calculate random index: i = floor(r*N)

*Load the document:
http://localhost:5984/db/_design/d/_view/random?startkey=i&limit=1
This way we chose an even distribution of int_id from 0 to N-1 by design. Then, we pick a random index (between 0 and N-1) and use it on that even distribution.
Note
This approach does not work anymore, when documents in the middle or at the beginning are deleted. The int_id has to start at 0 and go up to N-1.


text:
Q: angular 6 ngx-treeview custom styling I am using ngx-treeview component in my angular 6 project. My tree-view items are very lengthy. So, I'm trying to apply text-overflow:ellipsis in the ./treeview-container .row-item. snippet goes like this
  :host /deep/ .treeview-container .row-item {
    margin-bottom: .3rem;
    flex-wrap: nowrap;
    width:100px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

width is set to 100px and my text is truncated but the ellipsis is not applied. Could you support me in applying custom css?
Also I need to display full text on hovering. Does ":hover" works on treeview-item?
PS: I tried the same for ./treeview-item also but didn't work.


text:
Q: Winning single-pile, variable limits Nim
Possible Duplicate:
Winning strategy for a matchstick game

The rules of this variant of Nim are as follows:
Starting at zero, each player counts up between 1-N numbers. The person that counts a number L loses. N and L are declared at the start of the game by one player, the other player chooses who goes first.
For example, a game where N=2, L=9 might go like this:
P1: 1, 2
P2: 3
P1: 4, 5
P2: 6, 7
P1: 8

I'm trying to find an algorithm that can win the game for any value of N and L.
So far, I've come up with the following.
c = current number
if going first:
  while L-c > N:
    count n numbers
  once L-c <= N:
    count (L-c) numbers

Is there a better way of doing this?

A: First we need to show that it is possible for the computer to always win. We can do this, since for any value of N and L, there is an optimal strategy that will allow one of the players to always win. Hence, if the computer lets the person pick N and L it then decides whether to play first or second.
Now we have to show that there is an optimal strategy for one of the players, for any value of N & L. If $1 < L < N+2$ then it is easy to see that the first player wins because all they have to do is to count to $L-1$ and then they win. If $L = N+2$ then no matter what player one does in the first round, player two can then count to $L-1$ and win. But what if we have large $L$?
We can re-phrase the game, and instead of saying players take turns to count up to $N$ numbers, they take turns to take up to $N$ away from $L$ If we look at it this way, it is easy now to see that if $(N+1)+1<L<2(N+1)+1$ then player one wins, since in their first turn they can take $L-(N+2)$ away from $L$. From player two's point of view, their first turn is now the same as playing a new game where they go first, and $L = N+2$ which we have already shown means that they will lose.
You can now argue inductively or iteratively, whichever you prefer to show that player 1 can always win if $L$ is not congruent to 1 modulo $N+1$ and that player 2 can always otherwise, by reducing any game we are given to one we already know how to win.
Finally now we have shown that we can write such a program, we just need to write it! (as well as translate our new game of taking things off $L$ to counting up to it. Tell it to play first if player 1 will win and second if player 2 will win. At each step, tell it to count up to the highest number it can that is congruent to 1 mod $N+1$ and then, with a bit of thought, we can see from our earlier argument why this means it will always win.


text:
Q: Time-reversal operator in Phase Space Representation Consider the simplest possible case in which the time reversal operator $\hat{\mathrm{T}}$ is given by the operation of complex conjugation $\hat{\mathrm{K}}$.
We can view $\mathrm{T}$ is an anti-untary operator on the Hilbert space of our quantum system. In particular, we can determine its action on the momentum operator $\hat{\mathbf{p}}$ as
$$
\hat{\mathrm{T}} \hat{\mathbf{p}} \hat{\mathrm{T}}^{-1} = - \hat{\mathbf{p}}. \hspace{2cm}(1)
$$
Question: How can we describe this operation within the phase space formulation of quantum mechanics? Can the form of this operation be derived from the Wigner transformation?
Some ideas: In this case, all non-commutativity of quantum mechanics is absorbed into the Moyal product, denoted by the binary $\star$ operation. The relation above will be transformed to its phase-space counterpart
$$
\mathrm{T} \star \mathbf{p} \star \mathrm{T}^{-1} = - \mathbf{p}.
\hspace{2cm}(2)
$$
It seems to me that the phase-space representation $\mathrm{T}$ of the operator $\hat{\mathrm{T}}$ should be rather non-trivial. My suspicion is that it will still contain the operation of complex conjugation (because the relations above should also hold when we consider the canonical momentum in electromagnetic fields).
The difficulty arises because $\mathbf{p}$ is now a real $c$-number and not a complex operator. Thus, $\mathrm{T}$ must have a dependence on position and momentum.
Conjecture: Based on these observations, I would conjecture that
$$
\mathrm{T} = \mathcal{U}(\mathbf{x},\mathbf{p})\mathrm{K},
$$
where $\mathcal{U}$ is a yet to be determined $\star$-unitary function on phase space. One thing which can easily be done is a translation $t$ by $\mathbf{p}'$, i.e.,
$$
t(\mathbf{p'})\star \mathbf{p} \star t(\mathbf{p'})^{-1} = \mathbf{p} +\mathbf{p}'.
$$
This operation is easily defined. After we take the limit $\mathbf{p'}\to -2 \mathbf{p}$ we get the desired result. Can we incorporate this into the conjectured form?
EDIT 1: Following the discussion in the comment section we could interpret the statement (2) from above as an integral operator, let's call it $\tilde{\mathrm{T}}$ which acts via the functional
$$
\tilde{\mathrm{T}}[f(\mathbf{x},\mathbf{p})] = \int \text{d}\mathbf{x}'\text{d}\mathbf{p}' \delta(\mathbf{x}-\mathbf{x}')\delta(\mathbf{p}+\mathbf{p}') f(\mathbf{x}',\mathbf{p}')
$$
Because of its operational definition, it is clear that this coincides with the Wigner transformation $\mathcal{W}$ of Eq. (1). It remains to show, that we can write this in terms of a $\star$-product, i.e.
$$
\tilde{\mathrm{T}}[f(\mathbf{p})] = \mathcal{W} [  \hat{\mathrm{T}} f(\hat{\mathbf{p}}) \hat{\mathrm{T}}^{-1} ]
\overset{\text{to show}}{=}
\mathrm{T} \star f( \mathbf{p} ) \star \mathrm{T}^{-1}.
$$
EDIT 2: I might have found some additional constraints. If we assume that $\mathrm{T} \star \mathrm{T}^{-1} = \mathrm{T}^{-1} \star \mathrm{T} = 1 $, Eq. (2) can be used to derive
$$
\left\lbrace \mathrm{T} ~\overset{\star}{,} ~\mathbf{p} \right\rbrace= 0,
$$
which is only fulfilled for $\mathrm{T} = 0$ which is not a solution to the original problem. This means $\mathrm{T}^{-1}$ cannot coincide with the $\star$-inverse of $\mathrm{T}$.

A: I might have found a possible route. Consider the parity operator
$$
\hat{\Pi} = \int\text{d}\mathbf{x}\text{d}\mathbf{x}'~\delta(\mathbf{x} + \mathbf{x}')~ |\mathbf{x}\rangle\langle \mathbf{x}'|.
$$
Its Wigner transform is given by
$$
\Pi = (\pi \hbar)^d~ \delta(\mathbf{x})\delta(\mathbf{p}).
$$
This means we have to interpret $\Pi$ in a distributional sense. We can show that
$$
\Pi \star \mathbf{p} \star \Pi = - \mathbf{p}.
$$
proof.
For simplicity, we consider the one-dimensional case. Here we have
$$
\delta(p)\delta(x) \star p  = p~\delta(p)\delta(x) + \frac{i \hbar}{2} \delta(p)\delta'(x)
$$
As we interpret this in a distributional sense we view $p~\delta(p)$ as equivalent to $0$ (this is the sloppy part, I guess one could improve here). Thus
$$
\delta(p)\delta(x) \star p  \star \delta(p)\delta(x) = \frac{i\hbar}{2}
\delta(p)\delta'(x) \star \delta(p)\delta(x)
$$
This term can be simplified as
$$
\delta(p)\delta'(x) \star \delta(p)\delta(x)
=  \Big(\delta(p) \star \delta(x) \Big) \partial_x \Big( \delta(x) \star \delta(p) \Big)
$$
In one dimension, one has the identity
$$
\delta(x) \star \delta(p)  = \frac{2}{h} \exp \left\lbrace \frac{2i xp}{\hbar}\right\rbrace,
$$
which is why we find
$$
\delta(p)\delta'(x) \star \delta(p)\delta(x)
=  \frac{8 i}{h^2 \hbar} p
$$
Multiplying by $(\pi \hbar)^2$  from the definition of $\Pi$ and the factor $i \hbar /2 $ we finally obtain
$$
\Pi \star \mathbf{p} \star \Pi = - \mathbf{p}.
$$
$\square$
I think this is a promising way to a proper definition of $\mathrm{T}$. The missing piece is how complex conjugation looks like in the Wigner transformation. I'll extend this answer later on.
Let me continue... Let us consider a scalar phase space function $A$ and its quantum counterpart, the observable $\hat{A}$. They are related by the Wigner transformation
$$
A(\mathbf{x},\mathbf{p}) = \int \text{d}x'~e^{-i \mathbf{x}'\cdot\mathbf{p}/\hbar} ~ \Big\langle \mathbf{x} + \frac{\mathbf{x}'}{2} \Big|\hat{A}\Big|\mathbf{x} - \frac{\mathbf{x}'}{2} \Big\rangle .
$$
So we see that the action of complex conjugation on phase space has the result
$$
K A(\mathbf{x},\mathbf{p} ) K = A^\ast(\mathbf{x},-\mathbf{p}),
$$
which coincides with the Wigner transformation of $\hat{K}\hat{A}\hat{K}$. From this we might argue that $K$ is the Wigner transformation of $\hat{K}$, but its action is independent $\star$-product and we have
$$K\star A \star K = K~A~K$$
At the moment this is the only consistent way I know of. As Cosmas Zachos points out, $K$ is a really different object compared to parity $\Pi$ introduced above. But defined in the outlined way it keeps the symplectic structure intact, we have
$$
K \star [ x \overset{\star}{,} p ] \star K = - [ x \overset{\star}{,} p ]= - i \hbar =K \star (i\hbar) \star K
$$
For spinless systems we then identify $K$ as the operator of time reversal.
Let me know what you think of this


text:
Q: How do you make structural changes to Azure SQL Server DBs when you don't have access via SSMS? We're no longer allowed to have access to UAT/PROD environments via SSMS at my organization. The way our deployment process works is tied to git pushes. So when you push to the DEV branch, the DEV web code and DB is updated, likewise when pushing to the QA branch and the UAT branch.
The problem is when there is a structural change to the DB, very often the deployment fails with the error data loss may occur. In the past, with on-prem solutions, when we would publish the DB, if we encountered the data loss may occur error we could uncheck Block incremental deployment if data loss might occur in Visual Studio and the deployment would work. We never incurred any data loss either. Since this option is no longer available, it was suggested we use pre and post deployment scripts.
What do I need to put in the pre and post deployment scripts to prevent the data loss error? Our Visual Studio DB Project already contains all the table/view/SP/function definitions.

A: It's really depending on the nature of changes you are facing but an example could be a schema change on a table.
You can do this:

*

*Rename the existing table in a pre-deployment script.

*With the existing table missing the table in focus will be created as per the new schema definition.

*In a post-deployment script copy from the renamed original table to the new version.

Depending on the nature of the target you may of course need to take care of dropping and recreating foreign key constraints.
Beware of the option 'drop objects not in source'.


text:
Q: Creating web site works in my portfolio I would like to work on creating some web sites for my portfolio(I already have one and it's created with wordpress), but I don't know what to do with domain and stuff. Should I purchase a domain and a hosting for each web site I create??

A: Well, it is completely your decision. You can access your sites with temporary URLs if your hosting provider offers. If you want to access each wordpress sites with separate domains like; http://example.com http://example2.com, you will have to register the domains and point them to your hosting providers' server.
Basically, you will get nameservers from them which you can set from your domain control panel (From where you purchase domain).


text:
Q: Get stock_data from Magento API get request I know I can get stock data when making a request for an individual product:
http://magentohost/api/rest/products/:id
But please tell me there is a way to get stock_data when requesting a list:
http://magentohost/api/rest/products
I'm trying to do large imports (>10k products) that include all this data, and doing it one-by-one is way too slow.
Anyone know a way around this?

A: http://magentohost/api/rest/stockitems

provides the list of product with stock inventory details for REST API.


text:
Q: lwip tcp/ip checksum error LWIP: SSI output lengths may cause TCP/IP checksum errors
I am using LWIP 1.4.1 running on an ARM LPC4357 (LPCOpen 2.1.12, date 5/15/2014).
I am using httpserver_raw and have added a few SSI handlers.
I find that the system is sensitive to both the size of the line that contains the tag and the number of bytes the SSI handler outputs.
The tag is included in output.
When expanding the tag:
\r\n
spacespace<!--#s_add-->\r\n

(two spaces proceed the tag, forum formatting!)
The browser fails to receive the output & Wireshark reports a checksum error when the tag is expanded with 1, 3, 5, 7 etc characters.
The browser receives the output & Wireshark reports OK when the tag is expanded with 2, 4, 6, 8 etc characters.
If I remove a space from before the tag then the situation is reveresed.
Additionally if the tag is greater than 129 characters (suspect 122) then output is always ok (not seen a fault yet).
When the SSI output is >=129 bytes then http_write() function is being called with lengths 122 (header and tag), 122 (initial part of SSI) and 7 (remaining part of SSI).
Having the second tcp_write() of 122 seems to cure the checksum problem.
(Splitting the SSI output into segments is itself an oddity. The sending in chunks of upto 122 seems to be driven by the size of the resource file upto the tag).
I have inspected the SSI output using UART printf()'s and in Wireshark and all appears to be correct, there are no corruptions in the output. http_write() lengths are correct as is the output.
I have tracked as far as tcp_write() at which point I start to doubt myself; surely tcp_write() cannot be broke?
Has anyone used LWIP SSI on an embedded target or indeed tcp_write()?

A: Commenting/removing:
    #define LWIP_CHECKSUM_ON_COPY
seems to resolve.


text:
Q: Does sendBeacon set cookie headers when it queues the request?  function trackClickAndForward() {
         navigator.sendBeacon("https://www.example.com/tracker");
         window.location.href = "https://www.example.com/homePage";
    }

Another way of asking this question. Is it guaranteed that sendBeacon's analytics request to 'www.example.com/tracker' will not include any cookies that may be set on the *.example.com domain from the "www.example.com/homePage" response?


text:
Q: Call a php function in MVC using AJAX? I am currently migrating an already built web application to MVC, and I'm figuring out that I'm too newbie to do some kind of changes.  There are some ajax calls that are freaking me out.  I'll try to be as clear as possible, but due to my inexperience I'm not sure if I won't let some important information by the way.
The point is in the old application, things go this way:
In the php code:
    if ($action_user == 'show_alerts') {
        $list = array();
        $query = "SELECT alert_type FROM alert_contact WHERE NOT
        deleted AND user_email=" . typeFormat($email);
        $result = mysqli_query($db, $query) or die('Error in query "'.$query . '": ' . mysqli_error($db));
        while ($db_field = mysqli_fetch_assoc($result)) {
        $list[] = $db_field['alert_type'];
        }
        echo json_encode($list);

In the jquery code:
    $.ajax({
            type: 'POST',
            url: 'userpost.php',
            data: $('#userForm').serialize(),
            cache: false,
            dataType: 'json'

Here comes my problem, and since I don't have an userpost.php file anymore, I have to send it to the index.php and call my users component by a get petition, which I don't like, but I coudn't find another way to do it. And, what is even worse, I don't know at all how ajax is getting the variables that it needs.  It must be a pretty basic mistake, but I recognize my skills at this point are't so good. That's what I'm doing in my version:
In the php code:
    if ($action_user == 'show_alerts') {
            $list = ModelUser::getAlertContact($act_email);
            echo json_encode($list);//I predict that ajax don't reach this line, but not sure
    }

In the jquery code:
$.ajax({
        type: 'POST',
        url: 'index.php?option=users',
        data: $('#userForm').serialize(),
        cache: false,
        dataType: 'json',
    success: function(data) {
        alert ('gotcha');
        $.each(alertsarray, function(index, value) {
            if ($.inArray(value, data) === -1) {
                $("#sub" + value).prop("checked", false);
                $('#alert' + value).removeClass("list_alert_sub");
            }
            else {
                $("#sub" + value).prop("checked", true);
                $('#alert' + value).addClass("list_alert_sub");
            }
        });
    },
    error: function(data) {
        alert("¡Error (ajax)!");
    }
});

Any help would be appreciated, and if there's some more information I've missed, please let me know. Thanks in advance.
UPDATE:
I've been making some progress but don't seem to find a real solution.  Now I know that the url has to be the controller, so I'm using 'components/userpost/controller.php' as it, and it reaches the ajax call, cause the success alert is showing up. The problem is the MVC way, because I send ajax to the controller, but since I don't have a reload in the page, all the includes are failing so they are obviously not being loaded, and I'm getting errors like this:

PHP Warning:  include(components/userpost/model.php): failed to open
  stream: No such file or directory in
  /var/www/html/viewer_mvc/components/userpost/controller.php on line 3,
  referer: http://localhost/viewer_mvc/index.php

Really hope you guys can show me where am I failing, and if there's a special way to do these thing in MVC.

A: For the JQuery call it makes a POST request to index.php?option=users with JSON data. The form with the ID userForm is serialized using the Jquery serialize method.

The .serialize() method creates a text string in standard URL-encoded notation. It can act on a jQuery object that has selected individual form controls

$.ajax({
    type: 'POST',
    url: 'index.php?option=users',
    data: $('#userForm').serialize(),
    cache: false,
    dataType: 'json'

Now for your PHP sample
if ($action_user == 'show_alerts') {
    $list = ModelUser::getAlertContact($act_email);
    echo json_encode($list);//I predict that ajax don't reach this line, but not sure
}

This code will be looking for variables that probably don't exist anymore if it is a different file i.e. is there an $action_user variable?
To start reimplementing it you will need to add the logic so that it checks the POST variable if your not using the framework code. So if you have a form element with the name 'name' then that will be available in your PHP script POST variable
$_POST['name']

A: [How to call a PHP function in MVC using AJAX]

$.ajax({
        type: 'POST',
        url: 'save-user.php',
        data: { fname: "manish", email: "manishkp@com",  role:"admin"},
        success: function(data) {
         console.log(data);
    if(data == 'error')
    {
     $('#Register_error').text('Must Be filled...');
     $('#Register_error').show();
    }
   else {
                                        $('#Register_error').hide();
     $('#Register_success').text('Successfully submit');
     $('#Register_success').show();
    }
  }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<?php

  $fname = $_POST['fname'];
  $email = $_POST['email'];
  $role = $_POST['role'];

  if(!empty($fname) && !empty($email) && !empty($role))
  {
                      #MYSQL CONNECTION QUERY #
                       echo"success";
                }
                 else{
                         echo "error";
                }
?>


text:
Q: Downloading Multiple pdf files on One click in zip I have some pdf files in folder 3_day_notice_fad_pdf. Now I have to download pdf files in zip form, based on query condition.
<?php
 include("connection.php");
extract($_REQUEST);
$query=mysql_query("select fad_html_name from fad_record where t_id='$word'") or die(mysql_error());
while($result=mysql_fetch_array($query,MYSQL_ASSOC))
{
extract($result);
$movies_id[] = "3_day_notice_fad_pdf/$fad_html_name";
}
 $movies_id = array();

 //print_r($movies_id);
  $zipname = 'file.zip';
  $zip = new ZipArchive;
   $zip->open($zipname, ZipArchive::CREATE);
  foreach ($movies_id as $file) {
   $zip->addFile($file);
  }
  $zip->close();
  header('Content-Type: application/zip');
  header('Content-disposition: attachment; filename='.$zipname);
  header('Content-Length: ' . filesize($zipname));
  readfile($zipname);
  ?>

Zip file is working perfectly, but it is downloading all the files present in folder 3_day_notice_fad_pdf. It is not validating with condition where t_id='$word' in query.

A: You are doing several bad things here.

*

*Do not pass query strings directly to SQL. It will lead to SQL injection and your application will be compromised. See here: https://stackoverflow.com/a/60496/2520628

*You are clearing your files array just after loop
Corrected code:
<?php
 include("connection.php");
$word = $_REQUEST['word'];
$query=mysql_query("select fad_html_name from fad_record where t_id='$word'") or die(mysql_error());
while($result=mysql_fetch_array($query,MYSQL_ASSOC))
{
$movies_id[] = "3_day_notice_fad_pdf/" . $result['fad_html_name'];
}

  $zipname = 'file.zip';
  $zip = new ZipArchive;
  $zip->open($zipname, ZipArchive::CREATE);
  foreach ($movies_id as $file) {
    $zip->addFile($file);
  }
  $zip->close();
  header('Content-Type: application/zip');
  header('Content-disposition: attachment; filename='.$zipname);
  header('Content-Length: ' . filesize($zipname));
  readfile($zipname);
  ?>


text:
Q: Returning Periodic Data I have a table full of information for various times of the day but I want to pull data for each item on a half hour cycle. I have wrote the following piece of SQL to pull back the information for every half hour but there is a problem with it and I can't seem to rectify it!
AND DATEPART(minute, MyTimestamp) in (0, 30)

At first this seemed to work just fine but when I actually looked at the information in more detail I realized that it was returning data for the following times:
00:00:00
00:00:30
00:30:00
00:30:30

But in reality it should be only returning these times:
00:00:00
00:30:00

A: The minute part of 00:00:30 is 0 so its returned, to eliminate non-zero seconds add another clause:
where DATEPART(minute, MyTimestamp) in (0, 30)
  and DATEPART(second, MyTimestamp) = 0

or only include times with seconds modulo 30 mins;
where datediff(second, cast(MyTimestamp as date), MyTimestamp) % 1800 = 0

A: Are you guaranteed to have an entry exactly on the hour and exactly on the half-hour? You're concerned about the entry that comes in 30 seconds after the (half-)hour but what if that is the first entry of that time frame?
Here is a solution that divides the entries into half-hour segments and then selects the first (earliest) entry of each segment.
First I had to gen up some sample data. I used the old standby, AdventureWorks. The Sales.SalesOrderHeader table has an OrderDate field that would fit the bill, but it has no time values. So let's supply some. I picked the first day of data and used it to create a test table in SQL Fiddle using random values to fill in some hour, minute and second values.
There are plenty of entries on that one day. Let's look at the raw data: SQL Fiddle
ID          OrderDate
----------- -----------------------
43684       2011-05-31 01:14:05.000
43673       2011-05-31 01:20:41.000
43674       2011-05-31 01:40:22.000
43681       2011-05-31 02:00:32.000
...
43688       2011-05-31 20:18:45.000
43672       2011-05-31 21:49:50.000
43693       2011-05-31 22:46:08.000
43670       2011-05-31 23:14:22.000

(43 row(s) affected)

Now let's separate each timestamp into half-hour segments: SQL Fiddle
ID          OrderDate               Hour        HalfHour
----------- ----------------------- ----------- -----------
43684       2011-05-31 01:14:05.000 1           0
43673       2011-05-31 01:20:41.000 1           0
43674       2011-05-31 01:40:22.000 1           1
43681       2011-05-31 02:00:32.000 2           0
....
43688       2011-05-31 20:18:45.000 20          0
43672       2011-05-31 21:49:50.000 21          1
43693       2011-05-31 22:46:08.000 22          1
43670       2011-05-31 23:14:22.000 23          0

(43 row(s) affected)

Now we can group by the Hour and HalfHour fields and take the earliest timestamp of each period: SQL Fiddle
Hour        HalfHour    MinDate
----------- ----------- -----------------------
1           0           2011-05-31 01:14:05.000
1           1           2011-05-31 01:40:22.000
2           0           2011-05-31 02:00:32.000
3           1           2011-05-31 03:56:33.000
....
20          0           2011-05-31 20:18:45.000
21          1           2011-05-31 21:49:50.000
22          1           2011-05-31 22:46:08.000
23          0           2011-05-31 23:14:22.000

(30 row(s) affected)

That's all we need to complete the task. Join one result set with the other to get the first entry of each half-hour segment: SQL Fiddle.
Here is the final query. It's not exactly what you will find at SQL Fiddle -- it is the one that uses the AdventureWorks database (if you have that database installed and SQL Fiddle is having one of its periodic hissy fits). If you use AdventureWorks, remember to load values into the time portion of the OrderDate field. Also, note that this is written for a single day. To work for time frames longer than one day, you will have to group by day as well as hour and half-hour.
with
ByHalfHour as(
    select  soh.SalesOrderID ID, soh.OrderDate,
            DatePart( HOUR, soh.OrderDate ) as Hour,
            Case when DatePart( MINUTE, soh.OrderDate ) < 30 then 0 else 1 end as HalfHour
    from    Sales.SalesOrderheader soh
    where   soh.OrderDate >= '2011-05-31'
        and soh.OrderDate < '2011-06-01'
),
MinHalfHour as(
    select  Hour, HalfHour, Min( OrderDate ) as MinDate
    from    ByHalfHour
    group by Hour, HalfHour
)
select  bhh.*
from    ByHalfHour  bhh
join    MinHalfHour mhh
    on  mhh.Hour    = bhh.Hour
    and mhh.HalfHour= bhh.HalfHour
    and mhh.MinDate = bhh.OrderDate
order by bhh.Hour, bhh.HalfHour;


text:
Q: SKView warning logs When running my SwiftUI & SpriteKit app, I get the following messages in the logs:

2019-11-18 21:58:57.631912+0000 PixelBattles[2812:1215803]
SKView: ignoreRenderSyncInLayoutSubviews is NO. Call _renderSynchronouslyForTime without handler

What am I doing wrong to receive this log, and should I worry about it? Could it be a bug?
Could it be that SwiftUI cannot figure out how to do the layout for an SKView?
Major edit:
If you need code, you can see it in the previous edits. Below I state why I don't think it is any longer relevant.
I have sent Apple some feedback (FB7456217). I have removed the code, as I no longer suspect it is an issue to do with my code. I created a blank game project, no SwiftUI, and still got the same warning log instantly.
So even with the default project template, the log still appeared for device and simulator. I will update on this issue if I get a useful response.

I still haven't heard anything back - has anyone got any new information since when I posted this over half a month ago? I still have these warnings!

A: This is Apple's response to this issue:

Hi! You don't really need to fix that. That's a log message that was
left by mistake in SpriteKit framework. It was removed and will no
longer appear in the future SpriteKit versions. Thanks!

A: just figured this out for myself.
In your code change
if let scene = SKScene(fileNamed: "GameScene")
to
if let scene = GameScene(fileNamed: "GameScene")

A: I believe you'll also get this warning if you have UIKit subviews of the SKView.


text:
Q: PHP : preg_match_all none xhtml attributes I want to improve my code but I do not know how to write the regexp.
I want to get all none xhtml attributes in a tag.

So after the preg match I want to get :
array(
  0 => "required",
  1 => "autocomplete"
);

$balise = <input id="myId" class="myClassA myClassB myClassC" required autocomplete/>;
I actually use this preg_match_all("/(?<=\s)[\w]+(?=[\s\/>])/i", $balise, $attributs);
But with the regexp I get :
array(
  0 => "myClassB",
  1 => "required",
  3 => "autocomplete"
);

I do not want to get myClassB...
can anyone help me to write my regex ?
Thx

A: You can add the negative look-ahead (?![^=]*?") to make sure the next " doesn't precede the next =, that way you're getting only words that aren't within a quoted value. Single-quote the string so that the " in the regex won't terminate it.
preg_match_all('/(?<=\s)[\w]+(?=[\s\/>])(?![^=]*?")/i', $balise, $attributs);


text:
Q: Converting a Win2D CanvasRenderTarget to a BitmapImage? I'm trying to write a function which accepts my ICanvasEffect as a parameter (which in my case is a Win2D BlendEffect), and I want to convert the CanvasRenderTarget to a BitmapImage so that I can use it in a UWP Image control:
    private async Task<BitmapImage> GetBitmapImage(CancellationToken ct, ICanvasImage effect)
    {
        using (var target = new CanvasRenderTarget(CanvasDevice.GetSharedDevice(), 320f, 240f, 96))
        {
            using (var ds = target.CreateDrawingSession())
            {
                // Draw the image with the supplied ICanvasImage
                ds.DrawImage(effect);
            }

            //await target.SaveAsync(outputStream, CanvasBitmapFileFormat.Jpeg).AsTask(ct);
        }
    }

As you see in the commented code, CanvasRenderTarget has a SaveAsync method I can use to save it to a Stream, but how?

A: Figured it out:
    using (var stream = new InMemoryRandomAccessStream())
    {
        await target.SaveAsync(stream, CanvasBitmapFileFormat.Jpeg).AsTask(ct);

        var bmp = new BitmapImage();

        stream.Seek(0);
        await bmp.SetSourceAsync(stream);
    }

A:
As you see in the commented code, CanvasRenderTarget has a SaveAsync method I can use to save it to a Stream, but how?

If you want to save it to stream, you could refer to Win2D samples.
There's many samples show that how to use CanvasRenderTarget.SaveAsync() method.
For example, Win2D-Samples/ExampleGallery/Infrastructure/AppIconGenerator.cs#L217


text:
Q: Apache port being automatically forwarded I'm trying to have two different directory associated to two different ports. (8001 and 8004), but whenever I try to access port 8004 in a browser, it redirects automatically to port 8001.
Here's some extract of the config files that seems relevant:
In httpd.conf:
Listen 80
Listen 8001
Listen 8004

Removed comment to line:
Include etc/apache24/extra/httpd-vhosts.conf

In file httpd-vhosts.conf:
<VirtualHost *:8001>
  DocumentRoot "<path_to_site_1>"

  <Directory "<path_to_site_1>">
    Require all granted
  </Directory>
  <Directory "<path_to_site_1>">
    AllowOverride All
    RewriteEngine on
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !=/favicon.ico
    RewriteRule ^ index.php [L]
  </Directory>
</VirtualHost>

<VirtualHost *:8004>
  DocumentRoot "path_to_site_2"

  <Directory "path_to_site_2">
    Require all granted
  </Directory>
  <Directory "path_to_site_2">
    AllowOverride All
    RewriteEngine on
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !=/favicon.ico
    RewriteRule ^ index.php [L]
  </Directory>
</VirtualHost>

Here's a list of things I've tried, that didn't change anything:

*

*Having the VirtualHost declaration in httpd.conf

*Changing the order of the Virtual host declaration

*Changing port 8004 to another port

*Clear the browser cache and try a different browser

If I comment Listen 8001, it breaks everything.
Port 80 seems to point to the default www directory of this FreeBSD installation and still works properly, for phpMyAdmin is installed there and is still accessible.
Maybe of note, it's a FreeBSD installation running on Oracle VM VirtualBox.
Thank you for any help or ideas to follow.

A: Unfortunately, in this case, the comportment wasn't due to Apache configuration but to the website installations. One was a WordPress installation and the other was a Drupal installation. I wasn't aware that by moving those website in the directory structure, they would no longer point at the right place. WordPress was doing the redirection.
The issue was solved with two different solution, one for each platform.
For WordPress:
In the file functions.php, located in the theme directory:

*

*Add the following lines:
update_option( 'siteurl', '<new_url>' );
update_option( 'home', '<new_url>' );

*In the browser, fefresh the website a few time

*Remove both lines from the file

For Drupal:
(using drush) In the directory where the website is located:
drush cache-rebuild

The combination of both commands solved the issue with both installation.


text:
Q: Docker: unable to execute the mount command inside an ubuntu 16.10 container My container images is derived from ubuntu 16.10
When container starts, it downloads an Android rom .zip image, then extract from it new system.new.dat and convert into an .img file (so it's now containing and ext4 partition)
system.img: Linux rev 1.0 ext4 filesystem data,
            UUID=57f8f4bc-abf4-655f-bf67-946fc0f9f25b
            (extents) (large files)

Then try to mount it (system is an actual empty but existing directory)
sudo mount -t ext4 -o loop ./system.img /system

But I got this
mount: <path_to_>/system: mount failed: Unknown error -1

I'm not aware of the cause. What can I do to mount this file?

A: Actually resolved adding the --privileged switch at the docker run command


text:
Q: Here in the context below I use past and future tense together in one sentence. Is it wrong? Do watch this movie. It won't leave you disappointed and the closure of this film truly lived up to the expectation.

A:
It won't leave you disappointed and the closure of this film truly lived up to the expectation.

Note that expectation is normally used in the plural.
In the first clause, won't is an abbreviation for will not (future tense), so you are actually mixing future and past. It is perfectly OK, and often happens, that you use different tenses in different clauses of a sentence... as long as you use the right tenses.
There are several possibilities, depending on the exact meaning of expectations. If you are talking about your own expectations, past tense is fine, because you have already seen the film:

It won't leave you disappointed, and the closure of this film truly lived up to my expectations.

If you are talking about the expectations of the person you are talking to, you must use future tense, because they will see the film in the future.

It won't leave you disappointed, and the closure of this film will truly live up to your expectations.

If you are talking about the expectations of people in general, you are talking about a universal truth- something that was true, is true, and always will be true. You use present tense to talk about universal truths, for example

water boils at 100 degrees

Your sentence referring to people in general would therefore be

It won't leave you disappointed, and the closure of this film truly lives up to expectations.


text:
Q: Windows Phone Authenticated Cloud storage application I'm looking at creating a cloud storage application for a project. I wish to use C#, and it will be using a location based authentication system. It will work as follows: The user wishes to login. They enter their credentials, and the web based portion will verify the location (and some other attributes of the device) of the user using the mobile device. If correct, the phone will send an acknowledgement to the web portion, which in turn will send a one time code to the device, which the user will then use to login to the cloud storage.
My question is as follows: What technologies will be necessary for this project? I will obviously need the relevant SDK for the windows phone part, but what will I need for the cloud storage portion in terms of languages, SDKs? Could I use Google, or Amazon Cloud?
Many Thanks

A: I would look at Azure Mobil services. It handles authentication for google, facebook, MSN, etc. It  would also be a viable solution if you want to move your application to other platforms.
You can sign up for a free thirty day trial to check it out.
http://azure.microsoft.com/en-us/documentation/articles/mobile-services-dotnet-backend-windows-phone-get-started/


text:
Q: Convert Thrift object to SHA1 digest I am a newbie in Python. I try to work with server using Thrift protocol
struct AuthSalt {
    1: required i64 client,   /* random data */
    2: required i64 server,   /* data from previous answer */
}

struct AuthRequest {
    1: required AuthSalt bootstrap,
    2: required string who,           /* login */
    3: required string signature,     /* SHA-1: bootstrap + password + who + bootstrap. */
}

exception NotAuthorisedException {
    1: required string description
}

service Bookworm {
    AuthResponse Authenticate( 1: required AuthRequest a, 2: required string locale )
        throws ( 1: NotAuthorisedException e )
}

I need to create SHA1 digest using this algoritm: bootstrap + password + who + bootstrap.
To create bootstrap I use this:
dig = hashlib.sha1
bootstrap = AuthSalt(0, 0)
dig.update(bootstrap)
dig.update(password + who)
dig.update(bootstrap)

But update method argument type only string and I can't understand how to convert bootstrap to a string.
In C++ this code looks like:
SHA_CTX c;
            ::SHA1_Init(&c);
            ::SHA1_Update(&c, &bootstrap, sizeof(bootstrap));
            ::SHA1_Update(&c, password.c_str(), password.size());
            ::SHA1_Update(&c, who.c_str(), who.size());
            ::SHA1_Update(&c, &bootstrap, sizeof(bootstrap));
            ::SHA1_Final(digest, &c);

Can someone explain how to do it using python?
Thanks in advance!

A: I suppose that str(bootstrap) instead of bootstrap should work.

A: This is what I was need:
for x in tuple(struct.pack("Q",bootstrap.client)):
  dig.update(x)

Convert i64 into 8 bytes and update hash with every byte


text:
Q: Install of python firebase-admin on Apple Silicon/M1 fails, grpico fails The python firebase admin SDK isn't installing on Apple Silicon/M1. I've tried fixes in other posts here and on Github and they haven't worked. It's unclear to me if they work for anyone.

*

*Github discussion

*related Stack Overflow post
Installation Problem
The command pip install firebase-admin fails when it tries the setup script for the grpico package, which is a dependency of firebase.
I've tried the install with python 3.8.2, 3.9.4, and 3.9.5. All the versions failed. I've tried it inside a venv and globally, both failed.
My understanding of what's going on so far is:

*

*grpico is a dependency of firebase-admin (version 5.0.0), so pip install firebase-admin will try to install grpico (version 1.38.0)

*grpico is only compiled for x86, so upon trying the setup steps for grpico, something (pip maybe) starts running a bunch of clang commands, attempting to compile a version for arm.

*Some part of the compile fails and spits out a crazy looking error.

ERROR: Command errored out with exit status 1: /Users/brown/Developer/parse-tools/env/bin/python -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] ...

My setup:

*

*Big Sur 11.4

*Python 3.9.5 (installed with homebrew) in a venv

*pip 21.1.3

*firebase-admin 5.0.0

*grpico 1.38.0

If someone has a working fix, please explain how it works. I'm not a huge fan of pasting random commands into the terminal without understanding what they do.

A: Success - Simple but Mysterious
After reading every crazy guide on how to install grpcio, I was able to get it working with only two steps.

*

*Set 2 environment variables to tell the setup script to do something different. Run the following commands in terminal:

export GRPC_PYTHON_BUILD_SYSTEM_OPENSSL=1
export GRPC_PYTHON_BUILD_SYSTEM_ZLIB=1
What do these ENV vars do? Who knows. No one has bothered to explain or communicate around this issue at all. Classic.

*Run pip3 install firebase-admin. This worked for me.


text:
Q: Identifying jquery dom element without looping Is there a way to identify the element directly in variable d instead of looping using each function. Please find the below DOM

<!DOCTYPE html>

    <title></title>

Actually my html is dynamic, just for illustration purpose i have provided this. I donot want to use $("#totaldiv #imgfour").hide(); (or) $("#totaldiv>#imgfour").hide();

A: Since you have ids on the images, this is a one liner:
$("#imgfour").hide();

A: Should be
$('img#imgfour').hide();

Also why are you selecting by id in #totaldiv then looking for a different id?

A: If you don't want to loop and don't want to access the id directly, you could still use .filter().
var d = $("img", "#totaldiv").filter("#imgfour");

A: 1) Add each img element a class

2)  Hide/display all the elements which have 'myimage' class ,and then display/hide a specific element using id selector;
  $('.myimage').hide();
  $('.myimage#id4').show();

I hope this can help you .


text:
Q: Load report failed in C#.net I created one application in C# .Net for viewing crystal report.
But when i try to execute,it shows "load report failed" error message.
May i know the reason.
And what are the  viewer files to be install for viewing report.
Developed the report in Crystal report 2008.

A: This usually happens. Try the following

*

*Check your code. Try this here

*Check your data table name and column names. They needs to be the same (case insensitive) as that of database

*Check your database connectivity.

*Check if you have any spelling errors in your code that specifies the name of your report file.

*Check if you have installed all the right components for crystal report to work

*Open crystal report and try to update connection to your data source

*Try debugging by removing all fields and blankly showing the report. If it works, it should be problem with your code else it could be problem with crystal report  or connectivity.

Let me know if any of this works for you