text:
Q: Bootstrap Button Collapse to second line I am wondering if there is a way to get the buttons to automatically grow vertically to display the entire label rather then cut it off using bootstrap and font awesome.
Code:

Social Media:

          Like us on Facebook

          Follow us on Twitter

          Watch us on YouTube

Current Output:
____Small screen_____________large screen

... large screen is good but i want the small screen buttons to have output like:
Like us on   <-first line
facebook     <-second line

A: Definitely, the answer above(by Ryan) would work word-wrap: break-word; but some highlights about Bootstrap.
Bootstrap tend to have some hidden CSS.
Especially the one: overflow: hidden; which sometimes doesn't make work-wrap work!
Lastly, Try to inspect the website in order to see what exactly is happening to you code.
Hope this address your issue!


text:
Q: Ordered linked list gives null pointer when trying to insert largest value  public void insert(int data)
        {
            Node newNode = new Node(data);
            Node current = head;
            Node prev = null;

            if(head == null)
            {
                head = newNode;
            }
            else
            {
                while(data > current.data && current != null)
                {
                    prev = current;
                    current = current.next;
                }

                if(prev == null)
                {
                    newNode.next = current;
                    head = newNode;
                }
                else
                {
                    prev.next = newNode;
                    newNode.next = current;
                }
            }

This is an insert method for an ordered link list, smallest integer going to the head. Everything goes fine with this method until I try to insert a larger value than the value that I first added. when I try to add a new larger value it gives a null pointer exception, and this is the only time it give it.  I feel as though my logic is fine when I checked it, anyone have any ideas?

A: You should change the order of conditions inside
while(data > current.data && current != null)

So it should be
while(current != null && data > current.data)

That's because Java && operator starts with checking from the left, so no matter if current is null or not it will try to call data on this

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible to solve a differential equation without analytical term? I have been confused by this differential equation for several days. I have an equation like this:
$my′′(t)=cV′(y(t))−ny′(t)$
Where m,c,n are known parameters. And V(y(t)) is a two dimensional coordinate data set $(y(t1),V1),(y(t2),V2),...,(y(ti),Vi)$ and I don't know the exact analytical expression of $V(t)$. So, is it possible to solve this differential equation? By what kind of method or algorithm?
I know maybe I could solve this equation by fitting the data set $V(y(t))$, and obtain an analytical expression, then substitute it into the equation and solve it. But that maybe inaccurate and sometimes it is difficult to fit the curve. So is it possible to solve this kind of equation that contains a term without analytical expression in other methods?
For example, let m=1, c=0.05, n=0.01, and let $V'(y(t))$:
data=Table[{t,Sin[t]},{t,0,2,0.02}]

How to solve this equation use Mathematica?

A: A good way of doing it is by defining an interpolating function. In order to do this you should use the Interpolation function.
Assuming that your data is stored in data (as in your own example data=Table[{t,Sin[t]},{t,0,2,0.02}]),
you can just write :
V=Interpolation[data]
From now you will be able to use the V function as well as their derivatives.

A: Yes you can solve your problem using Interpolation  and NDSolveValue as follows.
First define V'[...]
 vs = Interpolation[Table[{t, Sin[t]}, {t, 0, 2, 0.02}]]

Second define the initial value problem (You have to define initial conditions!)
m = 1; c = .05; n = .01;
Y = NDSolveValue[{m y''[t] == c vs[y[t]] - n y'[t], y[0] == 0,y'[0] == 1}, y, {t, 0,10}]
Plot[Y[t], {t, 0, 10}, AxesLabel -> {t, y[t]}]

That's it.


text:
Q: get the value from a custom data attribute with plain Javascript and without using getElementById I need to get the custom data attributes from these fields.
<input type="text" name="FirstName" data-type="string" placeholder="First name" autocomplete="off" >

<input type="text" name="phone" data-type="number" placeholder="Last name" autocomplete="off" >

This is the code to select the fields without using getElementById:
 var elements = this.elements;

            this.elements = document.getElementsByTagName('input');
            var elements = this.elements;
            var group = elements.length;

            for (var i = 0; i < group; i++) {

                this.controller.validate({
                    field: elements[i],
                    value: elements[i].value,
                    dataType: e.target.getAttribute('data-type'), //   <---- ERROR: This is undefined
                    optional: e.target.getAttribute('data-optional')//   <---- ERROR: This is undefined
                });

            }

using the element.getAttribute('data-type') works fine in Chrome and Firefox but it Fails on internet explorer
The challenge:

I need to get the value of these custom attributes from any browser:

*

*I can't use any third party libraries.

*I can't use getElementById because these fields are dynamic.

any ideas?

A: Now that you've updated your question we can see that your error is in calling getAttribute on e.target which may not exist depending on how you listened to the event, and which browser you are in.
Surely, it would be better to just attach an all-round validation handler to the inputs, ignore e and simply check all the inputs at once for validation.
The contents of that handler may look something like this:
var elements = document.getElementsByTagName('input');

for (var i = 0; i < elements.length; i++) {

  var type = elements[i].getAttribute('data-type');
  var optional = elements[i].getAttribute('data-optional');

  console.log('type/optional:', type, optional);

  this.controller.validate({
    field: elements[i],
    value: elements[i].value,
    dataType: type,
    optional: optional
  });
}

If you insist on using the event, then perhaps you should only check the particular input that has dispatched the event, mitigating the need for getElementsByTagName:
var target = e.target ? e.target : e.srcElement;

var type = target.getAttribute('data-type');
var optional = target.getAttribute('data-optional');

console.log('type/optional:', type, optional);

this.controller.validate({
  field: target,
  value: target.value,
  dataType: type,
  optional: optional
});

Please note that data-optional does not exist as attributes in your markup, so their value is null.

A: I prefer to use;
document.querySelectorAll('[data-type]');


text:
Q: OpenGL gluLookat not working with shaders on When i want to use gluLookat and have the shaders on it doesnt move the "camera" when i turn the shaders off it works correctly.
Is there something missing in my shaders, i cant figure out what.
void display(void)
{
    glClear(GL_COLOR_BUFFER_BIT);
    glClearColor(0.8, 0.8, 0.8, 0);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt(0.5,0,1,0.5,0,0,0,1,0);
    glColor3f(0, 0, 0);
    glDrawArrays(GL_TRIANGLES, 0, 6);
    glDrawArrays(GL_LINES, 6, 6);
    glDrawArrays(GL_TRIANGLES, 12,6);
    glDrawArrays(GL_LINES, 18, 4);
    glDrawArrays(GL_TRIANGLES, 22, 6);
    glColor3f(1, 0.7, 0);
    glDrawArrays(GL_TRIANGLES, 28, 6);
    glFlush();
}

Vertex Shader:
#version 450 core  // 420, 330 core , compatibility
in vec4 position

out vec4 Color;
void main()
{
 gl_Position = position;
}

Fragment Shader:
#version 450 core  // 420, 330 core , compatibility
in vec4 Color;
layout(location=0) out vec4 fColor;
void main()
{
 fColor = vec4(0,0,0,0);
}

Move the "camera" to where i want it to be with shaders on

A: When you use a shader program, then the vertex coordinate attributes are not magically processed, by the current matrices. The shader program has to do the transformations of the vertex coordinates.

You've 2 possibilities, either you use a compatibility profile context and use a lower glsl version (e.g. 1.10).
Then you can use the built in uniform gl_ModelViewProjectionMatrix (see GLSL 1.10 secification) and the fixed function matrix stack will work:
#version 110
attribute vec4 position

// varying vec4 Color;

void main()
{
     // ...

     gl_Position = gl_ModelViewProjectionMatrix * position;
}

But note this is deprecated since decades. See Fixed Function Pipeline and Legacy OpenGL.

I recommend to use a library like OpenGL Mathematics to calculate the view matrix by lookAt() and a uniform variable:
#version 450 core  // 420, 330 core , compatibility
in vec4 position

// out vec4 Color;

layout(location = 7) uniform mat4 view_matrix;

void main()
{
    gl_Position = view_matrix * position;
}

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>

// [...]
{
    // [...]

    glUseProgram(program);

    glm::mat4 view = glm::lookAt(
        glm::vec3(0.5f,0.0f,1.0f), glm::Vec3(0.5f,0.0f,0.0f), glm::Vec3(0.0f,1.0f,0.0f));
    glUniformMatrix4fv(7, 1, GL_FALSE, glm::value_ptr(view);

    // [...]
}

The uniform location is set explicite by a Layout qualifier (location = 7).
glUniformMatrix4fv sets the value of the uniform at the specified location in the default uniform block. This has to be done after the progroam was installed by glUseProgram.


text:
Q: Android connecting two devices for bidirectional communication same as like Xender app I want to understand how xender app works programmatically ?
I want to implement same feature in my app to transfer files and messages without internet connection.
Is their any library which can help me ?
Android 2.3 must be supported to my app.
I research many stack Overflow questions but not helpful.
WiFi p2p, WiFi direct and NsdManager all having limitations to support lower android versions, it not give support to below android 4.0 version.

A: wifi p2p is what xender uses. But that feature sadly needs android api level 14 or greater. If you want to share files offline anyway on lower api, the only way is to connect the 2 devices on the same local n/w using wifi hotspot or something, once connected you can start the apps and everything should work just like xender.


text:
Q: Saving Microphone Stream to mp3 or wave I recording sound from Microphone in Windows Phone device. Using Xna.Framework.Audio.Microphone I store the sound in MemoryStream. I can save it to PCM format. However It will be much better to convert it to mp3 file. If converting to mp3 is impossible then maybe somebody at least knows how to convert it to wav.
Thanks for your answers.

A: Here is a brief example I created showing how to save wp7 recorded audio as a wav stream:
http://damianblog.com/2011/02/07/storing-wp7-recorded-audio-as-wav-format-streams/

A: Here's a great thread which answers this question:
http://social.msdn.microsoft.com/Forums/en-US/windowsphone7series/thread/59af6c3b-0dd1-4fa0-8438-d7f82e655109

It is a simple WAV file with its
  header missing. Therefore, Windows has
  no clue about the format.
  Unfortunately, the current WP7 OS API
  (as far as I know) doesn't offer any
  service to create a WAV file (the RIFF
  header + the raw PCM data). The RIFF
  header is not complicated and well
  documented. It is fairly simple to
  write the managed code to create one
  using the known PCM format which, as
  you already know, is 16bit/mono.

Or alternatively, if you're only trying to save/play it on the wp7 device ...

You should be able to use;
 SoundEffect sePlay = new SoundEffect(yourSavedByte[], mic.SampleRate, AudioChannels.Mono);
 sePlay.Play();

to playback your audio byte[]. I
  record, save, and playback using just
  the byte[] on WP7. You shouldn't need
  anything more then the raw byte[] if
  you use the SoundEffect class for
  playback.


text:
Q: What is the Action of #define in this Instance? As part of my homework, I've been given this code to help with the task they've given us... to create a basic shell that supports piping, background processes, and a number of builtin commands, etc. I've read through the code they've given us for parsing...
I'm familiar with the #define keyword in C, however, I've not seen it used like in the below code: namely, what is c for? I'm guessing it has been assigned to mean a character but I'm not sure:
#define PIPE  ('|')
#define BG    ('&')
#define RIN   ('<')
#define RUT   ('>')

#define ispipe(c) ((c) == PIPE)
#define isbg(c)   ((c) == BG)
#define isrin(c)  ((c) == RIN)
#define isrut(c)  ((c) == RUT)
#define isspec(c) (ispipe(c) || isbg(c) || isrin(c) || isrut(c))

Any help or advice much appreciated.

A: The last five #define statements you give define macros, each taking an argument, which is here always called c. Your first four #define statements are also, technically, macros, but they don't need an argument - they are simply substituted for their 'values' when encountered; frequently, programmers refer to macros with no argument as tokens, with the PIPE token here having a token value of ('|').
Later on in the file (possibly) there will be cases where one or more of these macros is called, and that call will have a value for the actual argument, like this, for example:
if (ispipe(test_arg)) ++npipes;

This macro "call" will be replaced (by the pre-processor) with the following expansion:
if (((test) == ('|')) ++npipes;

And, similarly, for the other #define XXX(c) macros.
Note: It is quite common to add (lots of) parentheses in macro definitions, just to be sure that the code does what you 'think' it will after the pre-processor has done its stuff.
Feel free to ask for further explanation and/or clarification.

A: #define is not a function, it is a preprocessor directive.
c could be anything. If you write ispipe(42), then the preprocessor will change it into ((42) == PIPE). If you write ispipe(while(1);), then the preprocessor will change it into ((while(1);) == PIPE), which will dumbfound the compiler when it reads it.
The preprocessor is blind, and does not know much about C syntax, and nothing of its semantics; the only way to understand what c is supposed to be is either to reverse-engineer the intended usage, or to ask whoever wrote the code without comments to tell you what they meant.
After the edit, it is rather reasonable to expect that c should be a char, in order to be meaningfully compared to '|' and similar. But even passing 0xDEADBEEF should compile correctly (returning FALSE).


text:
Q: start activity even when phone is locked I would like to start an activity like the one used when an alarm starts ringing and a dialog dismiss appears even when the phone is locked and I am able to click it. I have this code from this site but I don't know how to call it when I extend using broadcastreceiver. It always says

the method getWindow() is undefined type for...

I always seemed to get this error everytime I code, what does that mean.
public void unlockScreen() {
    Window window = getWindow();
    window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
            + WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
            + WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
            + WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
}

A: Register boradcast reciever for SCREEEN_ON intent.
As screen gets on your braodcast reciever onRecieve(..) will execute, Start your actitvity with flags as you have written in your post in onRecieve method.


text:
Q: Track scroll position according to visible section I am having some trouble tracking the scroll position. I am trying to set a variable according to what section is visible.
My html looks like this

BLA BLA

MJALLO!

MJALLO!

MJALLO!

MJALLO!

As said, i am trying to track the $(document) position and match it with a section id. I have for this the following jQuery
$(document).ready(function () {
var window = $(window);
var view = "";

 if (window.scrollTop == $("#one").offset().top)
   {view = "1";}
 else if (window.scrollTop == $("#two").offset().top)
   {view = "2";}
 else if (window.scrollTop == $("#three").offset().top)
   {view = "3";}
 else if (window.scrollTop == $("#four").offset().top)
   {view = "4";}
 else if (window.scrollTop == $("#five").offset().top)
   {view = "5";}
});

The section are styled as full frame blocks but i can't get any reaction on this if statement.
I am new to jQuery and js so a bit explanation would be appreciated ;)
Thanks in advance.

A: You need to wrap the ifs in a "on scroll" function:
$( document ).scroll(function() {
  if(....)
});

https://api.jquery.com/scroll/


text:
Q: Add two values that return from API I'm going to be calling a REST endpoint to return back data for two datapoints into a lightning component in SF. This is only needed from a UI standpoint visually on the lightning component.
This may be more of a general question. Is there a way to add External data point 1  + external data point 2 and show that sum . e.g. 10+10= 20 .  Since we are calling a REST endpoint externally , not sure if SF is able to add those two or if it's dependent on getting the sum of those amounts externally.
thanks!

A: If you're writing a component, you can script this a number of ways. For example:
let values = await Promise.all(
  [method1(), method2()]
)
let sum = values.reduce((accum, value) => accum + value, 0)

You could also accomplish this in a Flow, as well.


text:
Q: Docker - orchardup/mysql container does not start on Ubuntu 14.04 Found a strange problem with orchardup/mysql container, which is one of the most starred trusted mysql containers.
Container does not start on ubuntu host.
I've tried to run it on Ubuntu 14.04 using:
docker run -d -p 3306:3306 -e MYSQL_ROOT_PASSWORD=mypass orchardup/mysql

Container is not visible with:
docker.io ps

It is visible using:
docker.io ps -a

A: The default version of Docker on Ubuntu 14.04 is version 0.9.
You can try to use newest docker version:
deb https://get.docker.io/ubuntu docker main

And install a package with:
sudo apt-get install lxc-docker.

You can also change the default driver to the devicemapper by adding line below to /etc/default/docker
DOCKER_OPTS="--storage-driver=devicemapper"


text:
Q: Trying to make an html button on click open url in new tab i'm trying to make button on click open URL in new tab, when i click on the html button it's just redirect me to the page without opening new tab. how can i fix it?
Here is the code
  <button target="_blank" onclick="window.location.href='https://myhearing.co.il';" class="btn-view-site">View
                website</button>

A: This won't work because the target is invalid for a button.
Either use an <a> tag OR do window.open()
Here is an example with window.open():
<button onclick="window.open('https://myhearing.co.il')" class="btn-view-site">View website</button>


text:
Q: Compare Strings ignoring accents in SQL (ORACLE) I would like to know if there is an easy way to compare two text values ignoring the accents and upper case. Im working with an Oracle database.
I already searched for an answer but honestly I don't understand what they proposed in here Accent and case insensitive collation in Oracle with LIKE. I tried that and it didn't work for me. Basically all I want to do is two compare to text values like 'pepé' and 'pepe' and obtain true as answer.
is it possible to do it without the LIKE instruction?
Thank You!

A: use the nlssort function in the following way:
select * from <your_table> where utl_raw.cast_to_varchar2((nlssort(<inspected_column>, 'nls_sort=binary_ai'))) like 'pe%';

The nlssort call transforms accented characters to their linguistic bases and ignores case in comparisons.
Original source is this article (verified on 12c).

A: This works for Ç and the rest of characters in PT-BR (Portuguese - Brazil):
SELECT CONVERT( 'ÃÕÑ ÁÉÍ Ç', 'SF7ASCII' ) FROM DUAL;
Result: **AON AEI C**

Check your database version:
SELECT * FROM V$VERSION;
   Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
    PL/SQL Release 11.2.0.1.0 - Production
    "CORE   11.2.0.1.0  Production"
    TNS for Linux: Version 11.2.0.1.0 - Production
    NLSRTL Version 11.2.0.1.0 - Production

A: Oracle Setup:
CREATE TABLE TABLE_NAME ( value ) AS
SELECT 'pepé' FROM DUAL;

-- Not necessary to create an index but it can speed things up.
CREATE INDEX value_without_accent_idx
  ON TABLE_NAME ( CONVERT( value, 'US7ASCII' ) );

Query:
SELECT *
FROM   table_name
WHERE  CONVERT( value, 'US7ASCII' ) = 'pepe';

Output:
VALUE
-----
pepé

A: From this thread you can do the following:
select * from your_table
where upper(utl_raw.cast_to_varchar2((nlssort(your_column, 'nls_sort=binary_ai')))) like upper('%word%')

A: Since Oracle 12.2 there is the collate keyword which can be used with binary_ci for a case insensitive search and with binary_ai for both case and accent insensitive. This is also a more index-friendly method, but I am not aware of the exact details regarding indexes.
SELECT age
FROM persons
WHERE name = 'pepe' COLLATE binary_ai
Matches on: Pepé
Source:
https://blogs.oracle.com/sql/post/how-to-do-case-insensitive-and-accent-insensitive-search-in-oracle-database

A: As shown in the following blog:
https://eduardolegatti.blogspot.com/2013/04/ignorando-caracteres-acentuados.html
The @AJPerez reply is valid but you might have problem by using it with LIKE operator.
As @Just Cavin suggested, execute it before your query: (Versions after 10g R2)
ALTER SESSION SET NLS_SORT='WEST_EUROPEAN_AI'; -- Accent Insensitive
ALTER SESSION SET NLS_COMP='LINGUISTIC'; -- Case Insensitive


text:
Q: Ограчение видимости отдельных сайтов на VDS На vds есть несколько сайтов, запуская bash команды из php можно увидеться всю структуру севера и все сайты которые на нем крутятся.
Файловая структура следующая
/var/www/example.ru/public_html/index.php

Как ограничить права просмотра, что бы выше директории public_html ни чего видно не было?
ОС: Ubuntu 14 LTS

A: Bash команды можно ограничить только правильной настройкой прав доступа для юзеров. Для каждого сайта должен быть свой юзер, это можно сделать если настроить apache2-mpm-itk.


text:
Q: AWS S3 Ruby Stream Download: Retry connection during chunk download I was wondering if someone could help me with a streaming download issue I am having?
Currently I have a large GZipped XML file stored in a s3 bucket that I need to download, decompress, and parse daily using ruby. Because of the size of the file I opted to download the large file in chunks and perform the necessary parsing on each of the chunks like so:
module S3Stream
  def self.call(credentials)
    Enumerator.new do |yielder|
      connection = Fog::Storage.new(credentials)
      bucket = connection.directories.new(key: 'bucket_name')

      bucket.files.get('file_name.tar.gz') do |chunk, remaining_bytes, total_bytes|
        yielder << chunk
      end
    end
  end
end

Returning the Enumerator object allows me to process each part of the chunk later in the script (i.e. Unzip and parse the XML contained within)
This all needs to run on a schedule, so I have a detached Heroku dyno running the ruby script for me (my Rails site is deployed to Heroku as well). It runs fine locally, but after about an hour on Heroku (sometimes less depending on the size of the dyno) the script fails with this error message:
Errno::ECONNRESET: Connection reset by peer

My issue is that when this fails in the middle of my stream, I am not sure how to retry the download starting at chunk where the connection got reset.
Fog's stream downloading documentation is sparse, and switching to the AWS SDK for Ruby seems to give even less information to the block (i.e. no remaining or total bytes parameters).
Any ideas? Thanks in advance!
UPDATE 1
My most recent attempt, involved keeping track of the byte location of the last chunk worked with (i.e. total_bytes - remaining_bytes) before the connection got reset. Fog allows you to set a custom header in the options parameter of the get method:
  bucket.files.get('file_name.tar.gz', header: {'Range' => "bytes=#{@last_byte}-"}) do |chunk, remaining_bytes, total_bytes|
    yielder << chunk
  end

So when the stream got reset I would just try and pick off from where I left off in a new stream by using the HTTP Range header.
However, Fog seemed to ignore this header and after some digging I found that it is not an accepted HTTP header attribute in the fog-aws gem:
https://github.com/fog/fog-aws/blob/ab8b720a277712b0d924be74c4db1502692efa44/lib/fog/aws/models/storage/file.rb#L12-L27
Next, I will attempt to perform these same steps but with the aws-sdk gem, which looks like it supports the HTTP Range header


text:
Q: pass UNiqueIdentifier to another asp.net page I have coded this page
I need to pass the uniqueidentifier to another page, i have try these ways :
e.Row.Cells[1].Text = "" + e.Row.Cells[0].Text + "";

and this
 Response.Redirect("~/Clientes.aspx?Nome=" + e.Row.Cells[0].Text);

what the best and secure way to pass the GUID to another page ???
Thanks
Alejandro Carnero

A: In the codebehind of your first page, store the unique identifier in a Session variable, and then redirect to the "Clients" page normally:
Session["myUniqueID"] = e.Row.Cells[0].Text;
Response.Redirect("~/Clientes.aspx");

Then, in the codebehind of "Clientes.aspx", retreive it:
protected void Page_Load(object sender, EventArgs e)
{
    string myUniqueID = Session["myUniqueID"].ToString();
}

Note: I use "Page_Load" as an example, you could put this code in whatever method you want.

A: I have solved this way , source page :

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns ="False"
        CellPadding="4" ForeColor="#333333" GridLines="None" Width="770px" >
        <AlternatingRowStyle BackColor="White" />
    <Columns>
      <asp:HyperLinkField Text="Mostrar Cadastro"  DataNavigateUrlFields="idcliente"
       DataNavigateUrlFormatString="~/Clientes.aspx?ID={0}"
       />
      <asp:BoundField DataField="idcliente"  HeaderText="ID"   />
      <asp:BoundField DataField="nome" HeaderText="Nome"    />
      <asp:BoundField DataField="endere" HeaderText="Endereço" />
      <asp:BoundField DataField="Tel" HeaderText="Telefone" />
      <asp:BoundField DataField="pedido" HeaderText="Pedido" />

Destiny page :
       protected void Page_Load(object sender, EventArgs e)
    {
       LblIDCliente.Text  = Request.QueryString["ID"];
    }


text:
Q: How to find $\ker T$ from matrix representation over polynomial finite field?
Let $\mathbb F$ be a finite field of 5 elements (essentially $\mathbb Z_5$).
$T:\mathbb F_3[x] \to \mathbb F_3[x]$ is a linear map defined by the representation matrix:
  $$
[T]_B=\begin{pmatrix}
1&2&3\\
1&0&4\\
0&1&2
\end{pmatrix}
$$
  with the basis $B=(1, 1+x,1+x+x^2)$. Find $\text{ker}T$.
$\mathbb F_3[x]$ is a space of polynomials of form $ax^2+bx+c$ over $\mathbb F$.

We know that if a vector $v\in \text{ker}T$ then $[v]_B$ is in the nullity space of $[T]_B$.
If we row reduce $[T]_B$ and solve the system for $a_1x_1+a_2x_2+a_3x_3=0$:
$$
\begin{align}
\begin{pmatrix}
1&2&3\\
1&0&4\\
0&1&2
\end{pmatrix}\\Row_2\to Row_2-Row_1 \Rightarrow \begin{pmatrix}
1&2&3\\
0&3&1\\
0&1&2
\end{pmatrix}\\
Row_3\to Row_3-3^{-1}Row_2\Rightarrow \begin{pmatrix}
1&2&3\\
0&3&1\\
0&0&0
\end{pmatrix}\\
Row_2\to 3^{-1}Row_2\Rightarrow \begin{pmatrix}
1&2&3\\
0&1&2
\end{pmatrix}
\end{align}
$$
So:
$$
x_2=-2x_3=3x_3 \quad(??)\\
x_1=-2x_2-3x_3=3\cdot 3x_3+2x_3=4x_3+2x_3=x_3 \quad(??)
$$
and the general solution is: $(x_3,3x_3,x_3)$ from which follows that $\text{ker}T=span\{1,3,1\}$.
I'm not sure whether my calculations are correct especially when calculating the general solution.
Also I'm not sure how/whether to take into consideration that a vector belonging to $\text{ker}T$ is actually a polynomial.

A: Even without reducing, you could write down this:
$\ker(T)=\{v\in V | T(v)=0\}$
So, from your matrix you see that:
$$\begin{pmatrix}
1&2&3\\
1&0&4\\
0&1&2
\end{pmatrix}\begin{pmatrix}x_1\\x_2 \\x_3 \end{pmatrix}=0 \iff \begin{equation} \begin{cases}x_1+2x_2+3x_3=0\\x_1+4x_3=0\\x_2+2x_3=0 \end{cases}\end{equation}$$
From which you obtain that: \begin{equation} \begin{cases}z=\alpha\\y=-2\alpha\\x=-4\alpha \end{cases}\end{equation} So the solution is $\text{Span}(-4,-2,1)=\text{Span}(1,3,1)$

A: The row reduction is
\begin{align}
\begin{pmatrix}
1&2&3\\
1&0&4\\
0&1&2
\end{pmatrix}
&\to
\begin{pmatrix}
1&2&3\\
0&3&1\\
0&1&2
\end{pmatrix}
&& R_2\gets R_2-R_1
\\&\to
\begin{pmatrix}
1&2&3\\
0&1&2\\
0&1&2
\end{pmatrix}
&& R_2\gets 3^{-1}R_2
\\&\to
\begin{pmatrix}
1&2&3\\
0&1&2\\
0&0&0
\end{pmatrix}
&& R_3\gets R_3-R_2
\\&\to
\begin{pmatrix}
1&0&4\\
0&1&2\\
0&0&0
\end{pmatrix}
&& R_1\gets R_1-R_2
\end{align}
This means that the third variable is free, so a basis of the null space of the matrix is given by the single vector
$$
\begin{pmatrix} -4 \\ -2 \\ 1 \end{pmatrix}
=
\begin{pmatrix} 1 \\ 3 \\ 1 \end{pmatrix}
$$
This vector gives the coordinates of the generator of the kernel with respect to $B$. Therefore a basis for the kernel is given by the single polynomial
$$
1\cdot 1+3\cdot(1+x)+1\cdot(1+x+x^2)=4x+x^2
$$


text:
Q: Find list of Equipment on GPIB bus I need to query the test equipment on a GPIB bus.
I tried looking through NationalInstruments.VisaNS.
NationalInstruments.NI4882.AddressCollection.GetEnumerator();
i.e. GPIB::6::INSTR, GPIB::7::INSTR, ......GPIB::20::INSTR.

A: If you are using Vb or C# use Visa32.bas or Visa32.cs from the sample programs disk
int DefaultSessionId= 0;
int SessionId= 0;
int LastStatus = 0;
string Address = "GPIB0::6" ; //any address

//Session Open
LastStatus = visa32.viOpenDefaultRM(out DefaultSessionId);

//Connection Open
LastStatus = visa32.viOpen(DefaultSessionId, Address + "::INSTR", 0, 0, out sessionId);
LastStatus = visa32.viSetAttribute(SessionId, visa32.VI_ATTR_TERMCHAR, 13);// Set the termination character to carriage return (i.e., 13);
LastStatus = visa32.viSetAttribute(SessionId, visa32.VI_ATTR_TERMCHAR_EN, 1);// Set the flag to terminate when receiving a termination character
LastStatus = visa32.viSetAttribute(SessionId, visa32.VI_ATTR_TMO_VALUE, 2000);// Set timeout in milliseconds; set the timeout for your requirements

//Communication
LastStatus = visa32.viPrintf(SessionId, command + "\n");//device specific commands to write
StringBuilder message = new StringBuilder(2048);
LastStatus = visa32.viScanf(SessionId, "%2048t", message);//Readback

//Session and Connection Close
visa32.viClose(SessionId);
visa32.viClose(DefaultSessionId);

Reference from


text:
Q: Compute Alias values in MYSQL **Check the answer below, my QUERY is poorly written when I posted it  **
Friends,
I am using MySQL , I am trying to get the earnings. but gives me an error in using alias.
SELECT DISTINCT DATE_FORMAT(date_time, '%Y-%m-%d') date_change,
   sum(total) AS sumTotal, sum(-2) as MOD ,  seller_id,
  SUM(sumTotal - MOD) as earnings
FROM orders where status="Complete"
group by date_change ASC;

Please help me to compute earnings column

A: If you use Goup  by you don't need  distinct
you can't use column alias in select you must repeat the code
and you can add   an order by param (ASC) to the group by
SELECT  DATE_FORMAT(date_time, '%Y-%m-%d') date_change,
sum(total) AS sumTotal, sum(-2) as yourMODcods ,  seller_id,
SUM(total - 2) as earnings
FROM orders where status="Complete"
group by date_change ;

A: Table result , see image here
credits to the comments and answers above this section
This is my final query.
SELECT DATE_FORMAT(date_time, '%Y-%m-%d') date_change, SUM(-2) AS
cods, sum(total) AS sumTotal,SUM(total - 2) as earnings FROM orders
where status="Complete" AND seller_id =20 group by date_change

What I learned from here is

*

*The difference of Group and Select Distinct

*Don't use mod as a column name

*simplify the computation in a query


text:
Q: Is there a way to only import certain objects form a JSON website in Python? I am working on a project and I need to import like 200 BIG lists from different URLs. This takes around 3 seconds for each and I cant wait that long for the program to finish. But there is only two objects in the website for each one that I need, so I am wondering if there is a way to import ONLY those two objects instead of the entire JSON from each URL.

A: First, is it downloading the docs that is taking the time, or parsing them in Python once you have them?  Better measure.  If it's downloading, there's not much you can do unless the source APIs provide a way to request only part of the documents.
If parsing is the bottleneck, you still have to parse (there's no way to zero in on a part of a JSON doc without parsing), but you might try going to a non-Python parser for that part of the task only, like invoking command-line jq through Subprocess.


text:
Q: Why IsWindowVisible makes callback of EnumDesktopWindows runs only once? See the following code.
The MyEnumProc runs only one time with the following code. But if I commented out the IsWindowVisible(wnd);, it runs many times.
Why IsWindowVisible make this happened(run only one time)? I thought IsWindowVisible just a function to check the wnd's attributes?
codes of test.c:
#include <windows.h>
#include <stdio.h>
BOOL CALLBACK MyEnumProc( HWND wnd, LPARAM lParam )
{
    printf("run\n");
    IsWindowVisible(wnd);
}

int main( void )
{
    EnumDesktopWindows( NULL, MyEnumProc, 0 );
    printf("end\n");
    return 0;
}

My environment is:
Windows XP SP3.
gcc 3.4.6(mingw)
compiled option is: gcc -o test.exe test.c
I did the compile and run the test.exe in the cmd.exe.

A: You have to return a value. I would expect your compiler to be warning you that you are not. If it is not warning you then you should change the options to make it do so.
The documentation states:

To continue enumeration, the callback
  function must return TRUE; to stop
  enumeration, it must return FALSE.

This capability to terminate enumeration exists to allow you to short-circuit an enumeration. Once you have found the item you want there is no need to continue receiving callbacks. There are numerous Windows API functions that follow this idiom.

A: EnumDesktopWindows expects you to return a value from your MyEnumProc:
return TRUE;

Read the documentation for more information.


text:
Q: Do the stormtroopers wear their stormtrooper armor when they mop the floors? Finn mentions that he was in sanitation, and his knowledge of First Order bases and ships seems predicated on the fact that he cleans up around those bases/ships (which seems like it should be beneath a stormtrooper, but, that's not the point of this question). Does he wear his stormtrooper armor while working sanitation? If not, what does a stormtrooper wear while performing sanitation duties?

A: As I pointed out in another answer, stormtroopers don't pull sanitation duty, that's something that falls to stormtrooper cadets.
Assuming the training regime is similar to that of the former Empire, a cadet would wear a soft jacket and trousers.


text:
Q: Maps in R, how to add labels to grids and points I'm fairly new to mapping coordinates with R, looking around and trying to merge together different tutorials, I managed to get to a point where at least the map I plot makes sense.
The code so far is as follows
library(oce)
lat <- c(-77.2, -79.7, -80.7, -80.6)
long <- c(123.5, 126.1, 122.2, 121.6)
cord <- data.frame(lat, long)

par(mar=c(1.5, 1.5, 0.5, 0.5))
mapPlot(coastlineWorld, longitudelim=c(-180, 180), latitudelim=c(-90, -70),
        projection="+proj=stere +lat_0=-90", col='gray', grid=FALSE)
mapGrid(  dlongitude = 30,
          dlatitude = 5,
          col = "darkgray",
          lty = "solid",
          lwd = 0.5 * par("lwd")
        )
mapPoints(cord$long, snowpit$lat, pch=2, col="black")

As I said, the map makes sense and I get what I "need", in the sense that I get the right projection of Antarctica with four dots representing some places on the continent.
What I'm struggling with is a bunch of things that are needed in order to be able to just print this and used it for a report.

*

*most importantly: I have no idea how to save this. I thought it was based on ggplot but when I use ggsave it seems to do... nothing.

*I need to add labels on the side of the dots. Looking online I've seen people using text() to do so but I don't understand how to do it

*the grid is almost readable... but it's weird: is that a way to have all the longitudes ticks around the entirety of the map and the latitude displayed on the "circles"

*how do I change the size of the dots? again, thinking it was based on ggplot, I tried to just use size="" with an integer value but it gives me an error

A: look at this tutorial for "oce" library:
oce library tutorial


text:
Q: How can I add QtCharts library to my project? I was trying to add QtCharts library to my project but an error occurred:
Target "PTP3" links to target "Qt6::Charts" but the target was not found. Perhaps a find_package() call is missing for an IMPORTED target, or an ALIAS target is missing?

I installed Qt5::Charts and Qt6::Charts via Qt MaintenanceTool but the issue remained. Anyone knows how to fix it?
I'm using Qt Creator 7.0.2. Here is my Cmake file. I followed the instructions from https://doc.qt.io/qt-6/qtcharts-index.html but it didn't help.:

cmake_minimum_required(VERSION 3.5)

project(PTP3 VERSION 0.1 LANGUAGES CXX)

set(CMAKE_INCLUDE_CURRENT_DIR ON)

set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

find_package(QT NAMES Qt6 Qt5 COMPONENTS Widgets Charts REQUIRED)
find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Widgets REQUIRED)

set(PROJECT_SOURCES
        main.cpp
        footballmatches.cpp
        footballmatches.h
        footballmatches.ui
        pivottable.h
        pivottable.cpp
        pivottable.ui
        stadiumschart.h
        stadiumschart.cpp
        stadiumschart.ui
        some_qml.qml
)

if(${QT_VERSION_MAJOR} GREATER_EQUAL 6)
    qt_add_executable(PTP3
        MANUAL_FINALIZATION
        ${PROJECT_SOURCES}
    )
# Define target properties for Android with Qt 6 as:
#    set_property(TARGET PTP3 APPEND PROPERTY QT_ANDROID_PACKAGE_SOURCE_DIR
#                 ${CMAKE_CURRENT_SOURCE_DIR}/android)
# For more information, see https://doc.qt.io/qt-6/qt-add-executable.html#target-creation
else()
    if(ANDROID)
        add_library(PTP3 SHARED
            ${PROJECT_SOURCES}
        )
# Define properties for Android with Qt 5 after find_package() calls as:
#    set(ANDROID_PACKAGE_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/android")
    else()
        add_executable(PTP3
            ${PROJECT_SOURCES}
        )
    endif()
endif()

target_link_libraries(PTP3 PRIVATE Qt${QT_VERSION_MAJOR}::Widgets)
target_link_libraries(PTP3 PRIVATE Qt${QT_VERSION_MAJOR}::Charts)

set_target_properties(PTP3 PROPERTIES
    MACOSX_BUNDLE_GUI_IDENTIFIER my.example.com
    MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION}
    MACOSX_BUNDLE_SHORT_VERSION_STRING ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}
    MACOSX_BUNDLE TRUE
    WIN32_EXECUTABLE TRUE
)

if(QT_VERSION_MAJOR EQUAL 6)
    qt_finalize_executable(PTP3)
endif()

A: you should have both these lines in your Cmake File for adding one of the qt libs to your project for example for qt charts you need these:
find_package(Qt5Charts REQUIRED)

target_link_libraries(${PROJECT_NAME}

     Qt5::Charts

)

Be sure to add  target_link_libraries at the end of your CMakeLists.txt file.


text:
Q: Where is iptables script stored on DD-WRT filesystem? I have an ASUS RT-N16 router that I've flashed with the open-source DD-WRT firmware.  According to my ssh login, I'm running:
DD-WRT v24-sp2 mega (c) 2010 NewMedia-NET GmbH
Release: 08/07/10 (SVN revision: 14896)

I'd like to be able to customize the iptables rules, but before I do that, I'd like to see the output of the built-in rules that get configured when manipulating the browser/GUI interface settings.  I am aware of the firewall script tab in the browser interface for entering custom firewall rules, but I can't find someplace to see the output.
On a full-blown Linux system, the iptables rules would be stored somewhere like /etc/sysconfig/iptables.  Where would I find these on a DD-WRT filesystem?  I can do
iptables -L -vn --line-numbers

and see them output, but what I'm looking for is more of what the iptables-save command might output... so that I can incorporate the appropriate rules into my custom script.
I understand that this build does not have an iptables-save command.  I don't necessarily want the command itself, just output that it generates.  If there was something like /etc/sysconfig/iptables, I wouldn't care about having iptables-save.  I've seen that there may be different builds of DD-WRT that give something like iptables-save, but I'm not at the point where I'm ready or willing to flash the router again.  Maybe as a last resort.
EDIT:
The usual Linux locations for startup scripts and the like, (e.g., /etc/init.d, /etc/rc, ...) do not seem to have anything useful (at least in the build of DD-WRT that I have installed).  For example, taking a look in /etc/init.d:
[/etc/init.d]# ll
-rwxr-xr-x    1 root     root           84 Aug  7  2010 rcS
-rwxr-xr-x    1 root     root           10 Aug  7  2010 S01dummy
[/etc/init.d]# cat rcS
#!/bin/sh
for i in /etc/init.d/S*; do
  $i start 2>&1
done | logger -s -p 6 -t '' &
[/etc/init.d]# cat S01dummy
#!/bin/sh

A: Looking in
/tmp/.ipt
/tmp/.rc_firewall

gives exactly what I was looking for: the iptables rules as they would normally be in a file like /etc/sysconfig/iptables.
I had earlier found this:
dd if=/dev/mem | strings | grep -i iptables

...and fortunately, it works on the pared-down DD-WRT filesystem.  It didn't give precisely what I was looking for, but it output quite a bit of info I hadn't been able to pinpoint any other way (or at least not with a single command).
Still have to determine which things are actually in effect by comparing with the output of
iptables -L -vn --line-numbers
iptables -L -vn -t nat --line-numbers
iptables -L -vn -t mangle --line-numbers

I also discovered that the grep command actually does work [my apologies for initially stating that it didn't-- I would've sworn it didn't work the last times I had tried.  Mea maxima culpa.]  Using grep, I found that the
/lib/services.so

also has a wealth of iptables configuration in it.

A: There are many *WRT distribution variants, and different devices are set up in different ways, so I'm not sure whether this applies to your configuration, but it probably does.
The basic *WRT configuration has a read-only root filesystem, so it cannot save customizations in the filesystem. Instead, the startup loads various (variant-dependent) settings from NVRAM, which is organized as a simple list of key-value pairs. The firewall rules are stored in variant-dependent NVRAM entries. Look for one whose name contains firewall or whose value contains iptables, or some such.
Run ssh ROUTER_HOSTNAME nvram export --dump >nvram.txt to explore your router's NVRAM content at your leasure.

A: I have the same problem and I tried to create a symblink from iptables to iptables-save which was advised on their wiki page DD-WRT_V24_.26_iptables-save, but it did not work for me.
To solve this I made a shell file showing the contents of /tmp/.ipt.
/jffs/bin/iptables-save:
#!/bin/sh
cat /tmp/.ipt

NOTE: The wiki page (DD-WRT_V24_.26_iptables-save) is about "Firewall Builder" - I haven't tested this solution with "Firewall Builder".


text:
Q: WearableActionDrawer peek view does not hide I'm trying to use WearableActionDrawer in my app.  Previously I was using 'com.google.android.support:wearable:2.0.0-alpha1' and my layout looks like this:
<?xml version="1.0" encoding="utf-8"?>
<android.support.wearable.view.drawer.WearableDrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:rectLayout="@layout/rect_activity_main"
    app:roundLayout="@layout/round_activity_main"
    tools:context="com.example.grant.wearableclimbtracker.MainActivity"
    tools:deviceIds="wear">

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id = "@+id/content_frame">
        <android.support.wearable.view.GridViewPager
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/pager"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </android.support.v4.widget.NestedScrollView>

    <android.support.wearable.view.drawer.WearableNavigationDrawer
        android:id = "@+id/top_navigation_drawer"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:background="@color/dark_grey"/>

    <android.support.wearable.view.drawer.WearableActionDrawer
        android:id="@+id/bottom_action_drawer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/grey" />
</android.support.wearable.view.drawer.WearableDrawerLayout>

After I switched to 'com.google.android.support:wearable:2.0.0' the behavior changed.  The action drawer used to stay out of view until I swiped up to reveal the action menu, but now there is a peek view of the drawer that doesn't go away unless I open the menu and select something.  Is this the intended behavior?  It takes up a lot of real-estate:

Any advice would be much appreciated.

A: It was as I suspected, when NestedScrollingChild height matched the parentview, the action drawer peeks.  The only way I could get it to hide was to increase the NestedScrollingChild view by 1dp:
// get the screen width
DisplayMetrics metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);

// set height of framelayout to be slightly larger than view
mSessionLayout = rootView.findViewById(R.id.sessionLayout);
mSessionLayout.setMinimumHeight(metrics.heightPixels+1);


text:
Q: How can I get tile collisions working in Pygame with a tile map of sprites? I need help figuring out tile collisions for a platformer I'm currently making in Pygame. I have movement, with gravity working, as well as a tile map, but I don't really understand how to get collisions with the sprites working. I did make a list that appends all of the tiles that aren't 0 (so 1 or 2) into a list called tile_collisions (see line 113) but I don't really know what to do with that. Also, you can ignore the commented-out code, that was just a failed attempt. I'm trying to make this as simple as possible, without classes, because those aren't allowed for this assignment.
https://github.com/Night-28/Treble-Quest.git
^ The "main.py" file won't run without all of the pngs so if you do want to run it, you might have to download all of them, sorry!
import pygame as py
from tile_map import map

# Pygame setup
py.init()

clock = py.time.Clock()

# COLOURS
bg_colour = (110, 121, 228)
sky_colour = (190, 220, 255)
start_colour = (225, 225, 225)

screen_width = 1280
screen_height = 720
screen = py.display.set_mode((screen_width, screen_height))

p_sprite = py.image.load("plant_drone.png")
p_rect = p_sprite.get_rect()
p_rect.centery = screen_height - 32

grass_block = py.image.load("grass_block.png")
dirt_block = py.image.load("dirt_block.png")

# def collisions(rect, tiles):
#   collider_list = []
#   for tile in tiles:
#       if rect.colliderect(tile):
#           collider_list.append(tile)
#   return collider_list
#
# def move(rect, movement, tiles):
#   collision_types = {"top": False, "bottom": False, "right": False, "left": False}
#
#   rect.x += movement[0]
#   collider_list = collisions(rect, tile)
#   for tile in collider_list:
#       if movement[0] > 0:
#           rect.right = tile.left
#           collision_types["right"] = True
#       elif movement[0] < 0:
#           rect.left = tile.right
#           collision_types["left"] = True
#
#   rect.y += movement[1]
#   collider_list = collisions(rect, tile)
#   for tile in collider_list:
#       if movement[1] > 0:
#           rect.bottom = tile.top
#           collision_types["bottom"] = True
#       elif movement[1] < 0:
#           rect.top = tile.bottom
#           collision_types["top"] = True
#
#   return rect, collision_types

# MAIN MENU
def menu():
    py.display.set_caption("Game Menu")
    while True:
        start()
        py.display.update()
        clock.tick(60)

# START OPTION (BLINKING TEXT)
def start():
    start_font = py.font.Font('Halogen.otf', 50)

    bg = py.image.load("GM Treble Quest V2.png")
    bg_rect = py.Rect((0, 0), bg.get_size())
    screen.blit(bg, bg_rect)

    n = 0
    while True:
        start = start_font.render(("Press Enter To Play"), True, start_colour)

        if n % 2 == 0:
            screen.blit(start, (450, 625))
            clock.tick(50000)

        else:
            screen.blit(bg, bg_rect)
        n += 0.5

        py.display.update()
        clock.tick(3)

        for event in py.event.get():
            if event.type == py.QUIT:
                exit()

            elif event.type == py.KEYDOWN:
                if event.key == py.K_RETURN:
                    play()

# GAME
def play():
    py.display.set_caption("Treble Quest")
    player_y, player_x = p_rect.bottom, 32

    velocity_x, velocity_y = 5, 0
    ground = 480
    gravity_factor = 0.35
    acl_factor = -12

    while True:
        clock.tick(100)
        vertical_acl = gravity_factor
        screen.fill(sky_colour)
        screen.blit(p_sprite, p_rect)

# TILE MAP
        tile_collisions = []
        y = 0
        for row in map:
            x = 0
            for tile in row:
                if tile == 1:
                    screen.blit(dirt_block, (x * 32, y * 32))
                if tile == 2:
                    screen.blit(grass_block, (x * 32, y * 32))
                if tile != 0:
                    tile_collisions.append(py.Rect(x * 32, y * 32, 32, 32))
                x += 1
            y += 1

        screen.blit(p_sprite, p_rect)

#   player_movement = [0, 0]
#       if moving_right == True:
#           player_movement[0] += 2
#       if moving_left == True:
#           player_movement[0] -= 2
#       player_movement[1] += player

# MOVEMENT
        for event in py.event.get():
            if event.type == py.QUIT:
                exit()

            if event.type == py.KEYDOWN:
                if velocity_y == 0 and event.key == py.K_w:
                    vertical_acl = acl_factor

        velocity_y += vertical_acl
        player_y += velocity_y

        if player_y > ground:
            player_y = ground
            velocity_y = 0
            vertical_acl = 0

        p_rect.bottom = round(player_y)

        keys = py.key.get_pressed()

        player_x += (keys[py.K_d] - keys[py.K_a]) * velocity_x
        p_rect.centerx = player_x

        py.display.update()

menu()

A: Your code is almost there.
A simple way to do collisions is to iterate through the bunch of rectangles created when you process the map tiles.  Check each rectangle to see if it would intersect the player's position.
When your player needs to move, calculate where the move intends to go (don't actually move the player yet).  Then check if the target location will  overlap with any of the blocker-tiles.  If there is no overlap, then move the player.  Otherwise the player stops.
In the example code below, I've implemented a illustrative version of this.   While this method is simple, and works (mostly), it suffers from a few issues:

*

*If the velocity is high enough, the player's "next position" may jump right through a blocker tile.  This is because the code only tests the destination, not the in-between locations.

*Also when a potential collision happens, the player just stops.  But at high speeds, the player rectangle may stop a few pixels before the collision tile, rather than against the tile, which would be more what a player would expect.

Really you should test to cover these failures.  The second issue is easy to fix by calculating how far the player can move in the desired direction, and only move this lesser amount.

Note that I didn't really understand your movement algorithm.  There seems to be a velocity, but no stopping.  Given I was just illustrating collisions, I hacked it into some kind of working state that suited what I needed to show.
import pygame as py
#from tile_map import map

map = [ [ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 ],
        [ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 ],
        [ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 ],
        [ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 ],
        [ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 ],
        [ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 ],
        [ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 ],
        [ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 ],
        [ 0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0 ],
        [ 0,0,0,0,0,0,0,0,1,2,1,0,0,0,0,0,0,0 ],
        [ 0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0 ],
        [ 0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0 ],
        [ 0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0 ],
        [ 0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0 ],
        [ 0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0 ],
        [ 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2 ] ]

# Pygame setup
py.init()

clock = py.time.Clock()

# COLOURS
bg_colour = (110, 121, 228)
sky_colour = (190, 220, 255)
start_colour = (225, 225, 225)

screen_width = 1280
screen_height = 720
screen = py.display.set_mode((screen_width, screen_height))

def fakeBitmap( width, height, back_colour, text=None, text_colour=(100,100,100) ):
    """ Quick function to replace missing bitmaps """
    bitmap = py.Surface( ( width, height ) )
    bitmap.fill( back_colour )
    if ( text != None and len( text.strip() ) > 0 ):
        font = py.font.SysFont( None, 10 )
        text_bitmap = font.render( text, True, text_colour, back_colour )
        bitmap.blit( text_bitmap, text_bitmap.get_rect(center = bitmap.get_rect().center ) )
    return bitmap

#p_sprite = py.image.load("plant_drone.png")
p_sprite = fakeBitmap( 32, 32, ( 128,128,0), "PLAYER" )
p_rect = p_sprite.get_rect()
p_rect.centery = screen_height - 32

#grass_block = py.image.load("grass_block.png")
#dirt_block = py.image.load("dirt_block.png")
grass_block = fakeBitmap( 32, 32, ( 0,200,0 ), "grass_block.png" )
dirt_block  = fakeBitmap( 32, 32, ( 102,49, 0 ), "dirt_block.png")

# MAIN MENU
def menu():
    py.display.set_caption("Game Menu")
    while True:
        start()
        py.display.update()
        clock.tick(60)

# START OPTION (BLINKING TEXT)
def start():
    #start_font = py.font.Font('Halogen.otf', 50)
    start_font = py.font.SysFont( None, 16 )

    #bg = py.image.load("GM Treble Quest V2.png")
    bg = fakeBitmap( 1280, 1024, ( 0,0,128 ), "GM Treble Quest V2.png" )
    bg_rect = py.Rect((0, 0), bg.get_size())
    screen.blit(bg, bg_rect)

    n = 0
    while True:
        start = start_font.render(("Press Enter To Play"), True, start_colour)

        if n % 2 == 0:
            screen.blit(start, (450, 625))
            clock.tick(50000)

        else:
            screen.blit(bg, bg_rect)
        n += 0.5

        py.display.update()
        clock.tick(3)

        for event in py.event.get():
            if event.type == py.QUIT:
                exit()

            elif event.type == py.KEYDOWN:
                if event.key == py.K_RETURN:
                    play()

def playerCanMoveTo( player_next, blockers ):
    """ Is a player allowed to move to player_next, or will that mean
        colliding with any of the rectangles defined in blockers """

    can_move = True

    # Simple check, is the destination blocked
    for block_rect in blockers:
        print( "is Player [%d,%d %d %d] inside Block [%d,%d %d %d]" % ( player_next.x, player_next.y, player_next.width, player_next.height, block_rect.x, block_rect.y, block_rect.width, block_rect.height ) )
        if ( block_rect.colliderect( player_next ) ):
            can_move = False
            break  # don't need to check further

    return can_move

# GAME
def play():
    py.display.set_caption("Treble Quest")
    player_y, player_x = p_rect.bottom, 32

    velocity_x, velocity_y = 5, 0
    ground = 480
    gravity_factor = 0.35
    acl_factor = -12

    # Only need to do this once, moved away from main loop
    tile_collisions = []
    y = 0
    for row in map:
        x = 0
        for tile in row:
            if tile != 0:
                tile_collisions.append(py.Rect(x * 32, y * 32, 32, 32))
            x += 1
        y += 1

    while True:
        clock.tick(100)
        vertical_acl = gravity_factor
        screen.fill(sky_colour)
        screen.blit(p_sprite, p_rect)

        # TILE MAP
        y = 0
        for row in map:
            x = 0
            for tile in row:
                if tile == 1:
                    screen.blit(dirt_block, (x * 32, y * 32))
                if tile == 2:
                    screen.blit(grass_block, (x * 32, y * 32))

                x += 1
            y += 1

        screen.blit(p_sprite, p_rect)

        # MOVEMENT
        for event in py.event.get():
            if event.type == py.QUIT:
                exit()

            elif event.type == py.KEYDOWN:
                if velocity_y == 0 and event.key == py.K_w:
                    vertical_acl = acl_factor

        velocity_y += vertical_acl
        player_y += velocity_y

        if player_y > ground:
            player_y = ground
            velocity_y = 0
            vertical_acl = 0

        p_rect.bottom = round(player_y)

        keys = py.key.get_pressed()

        # Accelerate left/right [A] <-> [D]
        if ( keys[py.K_a] ):
            velocity_x -= 1
            velocity_x = max( -5, velocity_x )
        elif ( keys[py.K_d] ):
            velocity_x += 1
            velocity_x = min( 5, velocity_x )

        # Is the player allowed to move?
        target_rect = p_rect.copy()
        target_rect.centerx += velocity_x
        # Check where the player would move to, is allowed
        if ( playerCanMoveTo( target_rect, tile_collisions ) ):
            player_x += velocity_x
            p_rect.centerx = player_x
            print( "moving %d" % ( velocity_x ) )
        else:
            velocity_x = 0
            print( "blocked" )

        py.display.update()

menu()


text:
Q: SELECT positions that's still available I'm developing an voting system, and i have a problem of selecting available position based on the limitation per vote on each position.
tblposition
pos_no      pos_name    limit
1           pres        1
2           vpres       2
3           senator     5

tblcandidates
cand_no     cand_name    cand_pos
1           john         pres
2           kim          vpres

therefore :
pres - 0 left
vpres - 1 left
senator - 5 left
Expected positions to be output :
 pos_name
 | vpres    |
 | senator  |

but i get wrong output using this statement
SELECT pos_name FROM tblposition
WHERE limit > (SELECT COUNT(cand_pos)
               FROM tblcandidates, tblposition
               WHERE tblcandidates.cand_pos = tblposition.pos_name)

Can anybody help me fix my statement to produce correct output

A: I would just a quite different approach to solve this:
SELECT
*

FROM
tblposition a

WHERE
a.limit > (SELECT COUNT(*) FROM tblcandidates x WHERE x.cand_pos = a.pos_name)

This should now work if you spin it!
Feel free to ask if you have any questions.


text:
Q: display block in navbar responsive CSS3 and media queries I want to create a navbar responsive with html and CSS3. I use media queries for display or none a link bar that toggle menu (display on/off).
This code run correctly but I want to change display links menu in one line per link (or 2 maximum). But all the change in my code display always all the link in a same line.
for big screen my menu is on 1 line and for smaller screen the menu is toggle and display in 1 line per link (or 2 maximum).
My display block in media queries seem to be not run.
Can you help me to understand why media queries don't change my display engine for my link please.
HTML code

link 1

link 2

link 3

link 4

link 5

    Menu

JSFiddle : JSFiddle
Thanks for your support

A: You originally started selecting the lis by:
#navigation li

But when it got to media queries, you started to being more general about your selection for example:
@media only screen and (max-width : 320px){
nav li
{
    display: block;
    float: none;
    width: 100%;
}

So, if you inspect the element, you will see that the #navigation li is overriding the media queries. Try changing your selection to:
@media only screen and (max-width : 320px)
{
#navigation li
{
    display: block;
    float: none;
    width: 100%;
}


text:
Q: InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found. (.net core 5) I use .net 5 web api to create my application.
I put [Authorize] top of my controller.
I use Identityserver4 as auth-server.(localhost:5000)
and here is my startup.cs class:
 public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {

        services.AddControllers();
        services.AddDbContext<MyContext>(opts =>
            opts.UseInMemoryDatabase("MyDb"));

        services.AddAuthentication("bearer")
            .AddIdentityServerAuthentication(opts =>
            {
                opts.Authority = "http://locallhost:5000";
                opts.RequireHttpsMetadata = false;
                opts.ApiName = "myApi";
            });
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "CustomerApi", Version = "v1" });
        });

    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseSwagger();
            app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "CustomerApi v1"));
        }

        app.UseAuthentication();
        app.UseRouting();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

but I get below error:
error
please guide me to resolve my problem.
I search much time but the answers is for .net 3.1 .

A: I typically have this setup:
app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");

});

I would also not use AddIdentityServerAuthentication (Used by older version of IdentityServer) and instead focus on using AddJwtBearer method instead. See the documentation here

A: Your code is ok.
but you should write:
 services.AddAuthentication("Bearer")

instead of
 services.AddAuthentication("bearer")

After that you might run correctly.


text:
Q: ConcurrentMessageListenerContainer isn't acting concurrent I'm trying to create a multi-threaded listener, but all of the messages execute in the same thread.  When run, the thread ID is always the same, even thought the KafkaListerContainerFactory is (correctly) the one that I instantiated.  If I send 7 messages nearly simultaneously, I would expect the first three to process concurrently, then the next three concurrently, and then the last one.  What I see is that the first processes to completion, then the second, then the third, etc.  Am I misunderstanding something, or just misconfiguring?
This is my listener:
@Component
public class ExampleKafkaController {
    Log log = Log.getLog(ExampleKafkaController.class);

    @Autowired
    private KafkaListenerContainerFactory kafkaListenerContainerFactory;

    @KafkaListener(topics = "${kafka.example.topic}")
    public void listenForMessage(ConsumerRecord<?, ?> record) {
        log.info("Got record:\n" + record.value());
        System.out.println("Kafka Thread: " + Thread.currentThread());
        System.out.println(kafkaListenerContainerFactory);

        log.info("Waiting...");
        waitSleep(10000);

        log.info("Done!");
    }

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @Value("${kafka.example.topic}")
    public String topic;

    public void send(String payload) {
        log.info("sending payload='" + payload + "' to topic='" + topic + "'");
        kafkaTemplate.send(topic, payload);
    }

    private void waitSleep(long ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

And this is my application with the new config:
@SpringBootApplication
@ComponentScan("net.reigrut.internet.services.example.*")
@EntityScan("net.reigrut.internet.services.example.*")
@EnableKafka
@Configuration
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Autowired
    ConsumerFactory<Integer,String> consumerFactory;

    @Bean
    KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<Integer, String>> kafkaListenerContainerFactory() {
        ConcurrentKafkaListenerContainerFactory<Integer, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(consumerFactory);
        factory.setConcurrency(3);
        System.out.println("===========>" + consumerFactory);
        System.out.println(factory);
        return factory;
    }
}

A: With Kafka, concurrency is limited to the number of partitions in the topic. If there is only one partition, you will only receive messages on one thread, regardless of the container's concurrency setting.
You should provision the number of partitions to be greater than or equal to the concurrency you desire. If the number of partitions is greater than the concurrency, the partitions will be distributed across the consumer threads.
Only one consumer in a group can consume from a partition.


text:
Q: Java program will compile but not run in command prompt public class ProjectOne
{
    public static void main (String[] args)
    {
        int i, count1 = 0, count2 = 0, count3 = 0;
        int sum1 = 0, sum2 = 0, sum3 = 0, total;

        for(i=1; i<1000; ++i) //creates loop that will iterate for every number
        {
            if (i%3 == 0)

                count1 += 1; //gathers total #'s <1000 that can be divided by 3

            if (i%5 == 0)

                count2 += 1; //same as above, but divisible by 5

            if (i%3 == 0 && i%5 ==0)

                count3 += 1; //gathers count for where sets intersect

            for (i=1; i<=count1; ++i)

                sum1 += 3*i; //creates sum for all multiples of 3

            for (i=1; i<=count2; ++i)

                sum2 += 5*i; //creates sum for all multiples of 5

            for (i=1; i<= count3; ++i)

                sum3 += 15*i; //creates sum for where sets intersect

        }

        total = (sum1 + sum2) - sum3; //totals two sums while subtracting
                                        //the intersections that would double
        System.out.print (total); // prints total value
    }
}

Okay so I'm running through Project Euler trying to work on some of coding skill and mathematics (I'm relatively new and am learning Java for a class). Either way, I create this piece of code that is supposed to sum all of the multiples of 3 and 5 that are less than 1000. I go to compile the code and it compiles just fine but when I go to run it the command prompt (I'm running Windows 8.1 by the way) sits there doing nothing and responding to nothing, the cursor just sitting there blinking. I'm used to programming using Python's IDLE and so have little practice with command prompt. Am I just being impatient or is there something that is not functioning quite the way it should?

A: You are resetting your i variable in your for loop, causing it to never end. try this modified code:
public class ProjectOne
{
    public static void main (String[] args)
    {
        int i, count1 = 0, count2 = 0, count3 = 0;
        int sum1 = 0, sum2 = 0, sum3 = 0, total;

        for(i=1; i<1000; ++i) //creates loop that will iterate for every number
        {
            if (i%3 == 0)

                count1 += 1; //gathers total #'s <1000 that can be divided by 3

            if (i%5 == 0)

                count2 += 1; //same as above, but divisible by 5

            if (i%3 == 0 && i%5 ==0)

                count3 += 1; //gathers count for where sets intersect

            for (int j=1; j<=count1; ++j)

                sum1 += 3*j; //creates sum for all multiples of 3

            for (int j=1; j<=count2; ++j)

                sum2 += 5*j; //creates sum for all multiples of 5

            for (int j=1; j<= count3; ++j)

                sum3 += 15*j; //creates sum for where sets intersect

        }

        total = (sum1 + sum2) - sum3; //totals two sums while subtracting
                                        //the intersections that would double
        System.out.print (total); // prints total value
    }
}

I hope this will be your solution.

A: You are not missing anything about the command prompt. You have created an infinite loop - your program is doing the same thing over and over again.
Recall that in Java (and C, and many languages with C-derived syntax), a for loop like this one:
for (i=1; i<= count3; ++i)
    sum3 += 15*i; //creates sum for where sets intersect

does the same as this:
i=1;
while(i <= count3)
{
    sum3 += 15*i; //creates sum for where sets intersect
    ++i;
}

which means that your code is equivalent to this: (I've also changed the formatting slightly and removed the comments for brevity)
i=1;
while(i<1000)
{
    if (i%3 == 0)
        count1 += 1;

    if (i%5 == 0)
        count2 += 1;

    if (i%3 == 0 && i%5 ==0)
        count3 += 1;

    i=1;
    while(i <= count1)
    {
        sum1 += 3*i;
        ++i;
    }

    i=1;
    while(i <= count2)
    {
        sum1 += 5*i;
        ++i;
    }

    i=1;
    while(i <= count3)
    {
        sum1 += 15*i;
        ++i;
    }

    // HERE

    ++i;
}

Notice that each time the program gets to the line I marked "HERE", i will be equal to count3 + 1 (since if it was less than or equal to count3 then it would still be in the loop just before "HERE").
The next instruction is ++i, which just adds 1 to i. So at the end of the loop (just before the }, i will be equal to count3 + 2 (that is count3 + 1 + 1).
count3 is the number of multiples of 15 that your program has encountered so far, so that will be 0 at the start. So this effectively resets i to 2 just before the end of the loop, and i never gets past 2.
You probably meant to use a different variable in your inner for loops:
for (int j=1; j<=count1; ++j)
    sum1 += 3*j; //creates sum for all multiples of 3

for (int j=1; j<=count2; ++j)
    sum2 += 5*j; //creates sum for all multiples of 5

for (int j=1; j<= count3; ++j)
    sum3 += 15*j; //creates sum for where sets intersect

Notice that I have changed i to j (and declared j in each loop; this way each loop gets a separate variable called j, but you could declare it once at the start of main if you wanted and it would make no difference).
Your program will still not work properly (it will give you a wrong answer), but this will fix the infinite loop which is what you asked about.


text:
Q: insert an item and sub item from list view i have a problem with my list view, i display an item and subitem , i want to insert the two in database but it doesn't work !! the error is that i can't cast it to a text view
please someone help me.
This is the error that i get :
    java.lang.ClassCastException: android.widget.TwoLineListItem cannot be cast to android.widget.TextView

Here the code of List View :
    String[] databaseColumnNames = new String[] { DBAdapter.col_N_Ordre,DBAdapter.col_Nom_prénom};
    int[] toViewIDs = new int[] { android.R.id.text1,android.R.id.text2 };

    SimpleCursorAdapter myCursordapter = new SimpleCursorAdapter(this,android.R.layout.simple_expandable_list_item_2 , cursor, databaseColumnNames, toViewIDs);

    ListView list = (ListView) findViewById(android.R.id.list);

    list.setAdapter(myCursordapter);

Here the code of insertion :
  list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(final AdapterView<?> arg0, View arg1,
                final int position, long arg3) {

Toast.makeText(getApplicationContext(), " " + position, Toast.LENGTH_LONG).show();
    final String s = ((TextView)arg1).getText().toString();
    db.insertest(s);

The query is :
   public long insertest(String region) {
      ContentValues initialValues = new ContentValues();
          initialValues.put(col_Region,region);
      //initialValues.put(col_Provence_prefecture );
          return db.insert(MENAGE,null, initialValues);
  }

A: Put following code in your listview item click listener
TextView v1 = (TextView)arg1.findViewById(android.R.id.text1);
String first = v1.getText().toString();
TextView v2 = (TextView)arg1.findViewById(android.R.id.text2);
String second = v2.getText().toString();

ContentValues cv = new ContentValues();
cv.put(DBAdapter.col_Region, first);
cv.put(DBAdapter._id, second);
myCursordapter.notifyDataSetChanged();
list.setAdapter(adapter);

DBAdapter sql_Adapter = new DBAdapter(context);
sql_Adapter.open();

db.insertest(cv);
sql_Adapter.close();


text:
Q: Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at I am getting the following error code:

Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /srv/disk1/1365341/www/pokeronline.atspace.eu/tables/NewTable.php:1) in /srv/disk1/1365341/www/pokeronline.atspace.eu/tables/NewTable.php on line 2

session_start() is the very first thing in my file.
I can't find a solution to it, I already spent like 3 hours trying to figure it out.
<?php
    session_start();
    require 'config.php';
    ?>
    <?php

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="cache-control" content="no-cache" />
<title>NewTable</title>

Config.php
<?php
/**
 * Config and making connection
 */
$cfg['db_server'] = 'xxx'; // db server
$cfg['db_user'] = 'xxx'; // user name
$cfg['db_pass'] = 'xxx'; // pass
$cfg['db_name'] = 'xxx'; // DB name

//connect to database
$conn = @mysql_connect ($cfg['db_server'], $cfg['db_user'], $cfg['db_pass']);
$select = @mysql_select_db ($cfg['db_name'], $conn);

if (!$conn) {
    die ('
Unable o connect to the database
');
}

if (!$select) {
    die ('
Unable o connect to the database
');

Can somebody help?
@EDIT: FIXED.I created another php file, opened it in a different editor ( Adobe Dreamweaver in my case) and saved the file again. Before I used "all types" and wrote NewTable.php . Now I used php files from the list, and unchecked the include BOM tick box. Works perfectly now. Thank you all for time taken to help and I really appreciate it.

A: How to fix "Headers already sent" error in PHP
Output can be:
Unintentional:

*

*Whitespace before <?php or after ?>

*UTF-8 Byte Order Mark

*Previous error messages or notices

Intentional:

*

*print, echo and other functions producing output (like var_dump)

*Raw  areas before

You should definitely read the article about regarding output buffering. Still there is a quickfix: turn on phps output buffering.
E.G. ini_set('output_buffering', 'On');.
http://www.wallpaperama.com/forums/php-how-to-enable-output-buffering-in-php-ini-file-gallery-settings-code-t413.html

A: Try
   <?php session_start();
        require 'config.php';
        ?>

A: <?php
    session_start();
    require 'config.php';
    ?>
    <?php

?>

This thing makes no sense! just write following:
<?php
  session_start();
  require_once("config.php");
?>

And save you .php file as ANSI that should work ;)


text:
Q: Numbers or Letters for BodyPix - Person Segmentation in the Web Browser using TensorFlow.js Running real-time person and body part segmentation in the browser using TensorFlow.js is excellent!
Link: https://github.com/tensorflow/tfjs-models/tree/master/body-pix
How I can include numbers or letters for the different body parts segmentation instead of using different colors on the video overlay?
Thank you so much!


text:
Q: I need to trigger a script when a specific slide is shown (flexslider) In flexslider when a on specific slide (like just slide #2) i need to excecute some javascript when that slide is shown.

A: Try to use callback function of Flexslide, which fires after each slider animation completes.
Try to use setTimeout() function if your jQuery gets executed few micro-seconds before stable slide view.
https://woocommerce.com/flexslider/
after: function(){
}


text:
Q: How to make frisby.js scripts "pause" during chained executions of apis I want to test a session timeout using Frisby.js.  So I want to call our login API and call an API to demonstrate the user is logged in.
Then I want frisby.js to wait 20 minutes for the session to timeout and verify that an further calls fail due to session timeout.  How do I get the frisby.js script to "sleep()"?

A: Turns out that there's an undocumented waits() method that effectively tells frisby to sleep.
For example,
frisby.create('Sleep test')
  .get('http://www.citibikenyc.com/stations/json')
  .expectStatus(200)
  .inspectJSON()
  .waits(5000)
.toss();

Will wait for 5 seconds before execution.

A: Using setTimeout results in expects not being executed, as explained here:
https://github.com/vlucas/frisby/issues/200
Easiest way I found was to do a .get to http://httpbin.org/delay/3 to delay 3 seconds, then in the .after of this request you do what you wanted to do.

A: Use a timeout :
   setTimeout(function(){
    //do whatever after 20 minutes
   },1200000); //20 min = 1200000ms


text:
Q: centered text/equations inside align environment is there a way to insert a centered line of text or mathematics inside an align-environment?
For example, in the code below, I'd like to have the \vdots between the equations above and below horizontally centered, completely ignoring the alignment markers:
\documentclass{article}
\begin{document}
\begin{align}
  f(1) &= 1 \\
  f(2) &= 2 \\
  \vdots & \\
  f(n) &= n f(n-1)
\end{align}
\end{document}

A: Like this?
\documentclass{article}
\usepackage{mathtools}
\begin{document}
\noindent X\hrulefill X
  \begin{align}
  f(1) &= 1 \\
  f(2) &= 2 \\
  \shortintertext{\hfil    \vdots \hfil}
  f(n) &= n f(n-1) xxxxxxx
\end{align}
\end{document}

A: The "official" way of doing this is
\documentclass{article}
\usepackage{mathtools}
\begin{document}
\begin{align}
  f(1) &= 1 \\
  f(2) &= 2 \\
       &\vdotswithin{=} \nonumber \\
  f(n) &= n f(n-1) xxxxxxx
\end{align}
\end{document}

But this doesn't answer the question, though. So… why would you like \vdots that ignore the content of align in a "text" line?


text:
Q: Change background color of Linkbutton of Gridview I want to change the LinkButton background color inside the OnRowDataBound event using C# ASP.NET. I am explaining my code below.
index.aspx:
<asp:GridView ID="comnt_Gridview" runat="server" AutoGenerateColumns="false" Width="100%" CssClass="table table-striped table-bordered margin-top-zero" OnRowDataBound="comnt_Gridview_RowDataBound"  DataKeyNames="Bnr_ID"  >
    <Columns>
        <asp:TemplateField HeaderText="Sl. No" ItemStyle-CssClass="col-md-1 col-sm-1">
            <ItemTemplate>
                <%# Container.DataItemIndex + 1 %>
            </ItemTemplate>

            <ItemStyle CssClass="col-md-1 col-sm-1"></ItemStyle>
        </asp:TemplateField>

        <asp:TemplateField HeaderText="Health ID" ItemStyle-CssClass="col-md-1 col-sm-1" ItemStyle-HorizontalAlign="Center">
            <ItemTemplate>
                <asp:Label ID="healthid" runat="server" Text='<%#Eval("Health_ID") %>'></asp:Label>
            </ItemTemplate>

            <ItemStyle HorizontalAlign="Center" CssClass="col-md-1 col-sm-1"></ItemStyle>
        </asp:TemplateField>

        <asp:TemplateField HeaderText="Name" ItemStyle-CssClass="col-md-1 col-sm-1" ItemStyle-HorizontalAlign="Center">
            <ItemTemplate>
                <asp:Label ID="Name" runat="server" Text='<%#Eval("Health_Comment_Name") %>'></asp:Label>
            </ItemTemplate>

            <ItemStyle HorizontalAlign="Center" CssClass="col-md-1 col-sm-1"></ItemStyle>
        </asp:TemplateField>

        <asp:TemplateField HeaderText="Email" ItemStyle-CssClass="col-md-2 col-sm-2" ItemStyle-HorizontalAlign="Center">
            <ItemTemplate>
                <asp:Label ID="Email" runat="server" Text='<%#Eval("Health_comment_Email") %>'></asp:Label>
            </ItemTemplate>

            <ItemStyle HorizontalAlign="Center" CssClass="col-md-2 col-sm-2"></ItemStyle>
        </asp:TemplateField>

        <asp:TemplateField HeaderText="Web Url" ItemStyle-CssClass="col-md-2 col-sm-2" ItemStyle-HorizontalAlign="Center">
            <ItemTemplate>
                <asp:Label ID="Url" runat="server" Text='<%#Eval("Health_Comment_Website") %>'></asp:Label>
            </ItemTemplate>

            <ItemStyle HorizontalAlign="Center" CssClass="col-md-2 col-sm-2"></ItemStyle>
        </asp:TemplateField>

        <asp:TemplateField HeaderText="Comments" ItemStyle-CssClass="col-md-3 col-sm-3" ItemStyle-HorizontalAlign="Center">
            <ItemTemplate>
                <asp:Label ID="lblRemark" runat="server"
                    Text='<%# Eval("Health_Comment_Message").ToString().Length > 100? (Eval("Health_Comment_Message") as string).Substring(0,100) + " ..." : Eval("Health_Comment_Message")  %>'
                    ToolTip='<%# Eval("Health_Comment_Message") %> '> </asp:Label>
            </ItemTemplate>

            <ItemStyle HorizontalAlign="Center" CssClass="col-md-3 col-sm-3"></ItemStyle>
        </asp:TemplateField>

        <asp:TemplateField HeaderText="Status" ItemStyle-CssClass="col-md-1 col-sm-1" ItemStyle-HorizontalAlign="Center">
            <ItemTemplate>
                <asp:Label ID="Url" runat="server" Text='<%#Eval("Health_Comment_Status") %>'></asp:Label>
            </ItemTemplate>

            <ItemStyle HorizontalAlign="Center" CssClass="col-md-1 col-sm-1"></ItemStyle>
        </asp:TemplateField>

        <asp:TemplateField HeaderText="Action" ItemStyle-CssClass="col-md-2 col-sm-2" >
            <ItemTemplate>

 /

                            <asp:LinkButton ID="accept" CssClass="btn btn-xs btn-inactive" CommandName="Accept" runat="server" style="padding:1px 2px;" Text="Accept" OnClick="accept_click"></asp:LinkButton>
                            <asp:LinkButton ID="reject" runat="server" Text="Reject" CommandName="Reject"
                                CssClass="btn btn-xs btn-success active"  style="padding:1px 2px;"
                                onclick="reject_Click" ></asp:LinkButton>

            </ItemTemplate>

            <ItemStyle CssClass="col-md-2 col-sm-2"></ItemStyle>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

index.aspx.cs:
protected void comnt_Gridview_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if (e.Row.Cells[6].Text=="R")
        {
            e.Row.Cells[6].Text = "Rejected";
        }
    }
}

I want to change the LinkButton color to red inside the above if statement. If text will be R, the reject button will red. How can I do this?

A: You can simply find your link button and update its color and text like this:-
protected void comnt_Gridview_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if (e.Row.Cells[6].Text=="R")
        {
             LinkButton myLinkButton = (LinkButton)e.Row.FindControl("myLinkButton");
             myLinkButton.Text = "Rejected";
             myLinkButton.ForeColor = System.Drawing.Red;
         }
     }
}

Please note here I have considered your Link button's id to be myLinkButton. You need to update that accordingly.

A: You can cast LinkButton and access all of its properties:
if (e.Row.Cells[6].Text=="R")
{
    //cast LinkButton
    LinkButton linkBtn = (LinkButton)e.Row.FindControl("reject") as LinkButton;
    linkBtn.BackColor = Color.Red;

    linkBtn.Text = "Rejected";
}


text:
Q: Items collection must be empty before using ItemsSource in Silverlight Inside custom control I'm trying to bind my ItemsControl.ItemsSource and get error. Here is how template looks:
<Style TargetType="controls:IdattFilterBox">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="controls:IdattFilterBox">
                    <ScrollViewer HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Auto">
                        <ItemsControl x:Name="PART_ItemsControl">
                            <ItemsControl.ItemTemplate>
                                <DataTemplate>
                                    <Grid HorizontalAlignment="Stretch">
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="*" />
                                            <ColumnDefinition Width="*" />
                                            <ColumnDefinition Width="*" />
                                            <ColumnDefinition Width="*" />
                                        </Grid.ColumnDefinitions>
                                        <TextBlock Text="{Binding Caption}" />
                                        <ComboBox Grid.Column="1">
                                            <ComboBoxItem Content="Contains" />
                                            <ComboBoxItem Content="Begins with" />
                                            <ComboBoxItem Content="Ends with" />
                                        </ComboBox>
                                        <TextBox Grid.Column="2" Text="{Binding FieldFilter1, Mode=TwoWay}" />
                                        <TextBox Grid.Column="3" Text="{Binding FieldFilter2, Mode=TwoWay}" />
                                    </Grid>
                                </DataTemplate>
                            </ItemsControl.ItemTemplate>
                                                                                <Border Grid.ColumnSpan="2" x:Name="ValidationErrorElement" BorderBrush="#FFDB000C" BorderThickness="1" CornerRadius="1" Visibility="Collapsed">
                            <ToolTipService.ToolTip>
                                <ToolTip x:Name="validationTooltip" DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}" Placement="Right" PlacementTarget="{Binding RelativeSource={RelativeSource TemplatedParent}}" Template="{StaticResource ValidationToolTipTemplate}">
                                    <ToolTip.Triggers>
                                        <EventTrigger RoutedEvent="Canvas.Loaded">
                                            <BeginStoryboard>
                                                <Storyboard>
                                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="IsHitTestVisible" Storyboard.TargetName="validationTooltip">
                                                        <DiscreteObjectKeyFrame KeyTime="0">
                                                            <DiscreteObjectKeyFrame.Value>
                                                                <System:Boolean>true</System:Boolean>
                                                            </DiscreteObjectKeyFrame.Value>
                                                        </DiscreteObjectKeyFrame>
                                                    </ObjectAnimationUsingKeyFrames>
                                                </Storyboard>
                                            </BeginStoryboard>
                                        </EventTrigger>
                                    </ToolTip.Triggers>
                                </ToolTip>
                            </ToolTipService.ToolTip>
                            <Grid Background="Transparent" HorizontalAlignment="Right" Height="12" Margin="1,-4,-4,0" VerticalAlignment="Top" Width="12">
                                <Path Data="M 1,0 L6,0 A 2,2 90 0 1 8,2 L8,7 z" Fill="#FFDC000C" Margin="1,3,0,0"/>
                                <Path Data="M 0,0 L2,0 L 8,6 L8,8" Fill="#ffffff" Margin="1,3,0,0"/>
                            </Grid>
                        </Border>
                        </ItemsControl>
                    </ScrollViewer>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

In code I' trying to set this PART's ItemSource:
this.WrapperItemsControl.ItemsSource = filterData;

On this line I get error(error message in subject). Why can't I set ItemsSource and what this error means? I want controls in DataTemplate to bind to objects that stored in filterData.
EDIT:
PART_ItemsControl is what my WrapperItemsControl
this.WrapperItemsControl = GetTemplateChild(PartItemsControl) as ItemsControl;

EDIT2:
Screenshot showing that there is one item (Border?) Where does it come from?!

EDIT3
DOH! I placed validation border in a wrong spot

A: You can't use ItemsSource if you manually add items to your ItemsControl. For example, you would get an error if you tried this:
<ItemsControl ItemsSource="{Binding MyItems}">
    <ListBoxItem>Item1</ListBoxItem>
    <ListBoxItem>Item2</ListBoxItem>
</ItemsControl>

You may think you're not doing that, but you actually are. You're adding a single item to your ItemsControl, and that item is of type DataTemplate. Look:
<ItemsControl ...>
    <DataTemplate ... />

That syntax means "create a DataTemplate and add it to the ItemsControl's Items property". (Items is the default property for ItemsControl, so any elements you nest under ItemsControl, if you don't otherwise specify, get added to Items.)
I think you intended to assign that DataTemplate to the ItemsControl's ItemTemplate property, rather than adding it to Items. Try this instead:
<ItemsControl ...>
    <ItemsControl.ItemTemplate>
        <DataTemplate ... />
    </ItemsControl.ItemTemplate>
</ItemsControl>


text:
Q: How to get AVERAGE from two tables using JOIN in Codeigniter I have a table structure as given below, i want to get the avg rating of each post, for that i am writing following query to join and get records but it gives syntax error :
$this->db->select($query = $this->db->query('SELECT * FROM post,AVG(`rating`) AS `avg_rating` JOIN review ON `post`.`id` = `review`.`post_id`');

A: Two problems found:

*

*your code is incorrect. Codeigniter expects a certain format when it comes to creating queries, follow the manual here to understand in more depth.

*you are getting the average rating but you are not grouping thus ending with one result, rather than one result per each post.
This is how I would rewrite your model method:
function getRatingInfo(){
    $this->db->select("*, AVG(rating) AS avg_rating");
    $this->db->from("post p");
    $this->db->join("review r", "p.id=r.post_id");
    $this->db->group_by("post_id");
    $query = $this->db->get();
    return $query->result();
}

A: you dint use group by and to execute use like this $this->db->query(" your sql");
$this->db->query('select rating.post_id,avg(rating.rating) as `avg_rating` from rating,post where rating.post_id=post.id group by rating.post_id');


text:
Q: Group by not used not contained in aggregate function or group by clause I am trying to group by errorType but keep getting this error.
Column 'fid_crm_sp_recon.URL' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
SELECT URL, Name, statusCode, ErrorType
FROM fid_crm_sp_recon
GROUP BY ErrorType

A: As mentioned in the comments, you're simply not setting up your group by correctly.  Here are just a couple of possibilities to get you on the right path:
-- Group by all columns
SELECT URL, Name, statusCode, ErrorType
FROM fid_crm_sp_recon
GROUP BY URL, Name, statusCode, ErrorType;

-- Run aggregates on the non-grouped columns
SELECT MIN(URL) AS MinURL
    , MAX(Name) AS MaxName
    , AVG(statusCode) AS AvgStatusCode -- Assuming a number here, just an example
    , ErrorType
    , COUNT(*) AS Num
FROM fid_crm_sp_recon
GROUP BY ErrorType;

A: group by should always be used with aggregate function after select clause or apply group by to all selected columns
 SELECT URL, Name, statusCode, ErrorType  FROM fid_crm_sp_recon  GROUP BY URL, Name, statusCode, ErrorType

you can go through these links
http://www.techonthenet.com/sql/group_by.php
http://www.w3schools.com/sql/sql_groupby.asp


text:
Q: Is there anything like preprocessor directives in SQL Server, particularly like #DEFINE? Whenever I have complicated fields in my SELECT my GROUP BY ends up looking like a trash fire since GROUP BY can't see my aliases defined in SELECT. But if there was something like #DEFINE then I could macro that problem away.
Is there anything like that?

A: Yes it is called SQLCMD Mode:

:setvar <var> <value>

:SETVAR DATABASENAME "adventureworks2014"
USE $(DATABASENAME);

:setvar col_list "col1,col2,col3"
SELECT $(col_list), COUNT(*) AS cnt
FROM tab
GROUP BY $(col_list);

EDIT:
In my opinion the proper way is to use CROSS APPLY:
SELECT s.col1, s.col2, COUNT(*) AS cnt
FROM t
CROSS APPLY (SELECT col1 = complex_expression, col2 = complex_expression2) AS s
            -- the expression is defined once at the same level
GROUP BY s.col1, s.col2;

A: This isn't akin to a preprocessor directive, but one way to clean up the messy GROUP BY statements is to package the complicated SELECT statements into a subquery, and then perform the GROUP BY from an outer query. This helps to clean things up a bit.
For example:
SELECT
    dataset.keyvalue,
    SUM(dataset.amt) as total
FROM
(SELECT
    field1 + field2 + field3 as keyvalue,
    OrderQty as amt
FROM dbo.table1) as dataset
GROUP BY dataset.keyvalue


text:
Q: Ajax object IE: Youtube videos not properly loading Once a first page is loaded nomally in my website, I request all other pages body contents with javascript ajax (ajaxObject).
I simply grab the body innerHTML with ajaxObject (javascript) and replace the actual one:

On a page, I have youtube objects for embed videos:
<object type="application/x-shockwave-flash" data="http://www.youtube.com/v/1ahKNnolR30" height="315px" width="420px"><param name="movie" value="http://www.youtube.com/v/1ahKNnolR30"></object>

In Firefox everything is fine if I either load the page using the address or with that ajax code.
With IE, it works only if I go to the page using the address.
When I try to use the ajax code the videos appear as the image below.
I tried it with IE tester, all versions give me the same error behaviour.
Does anyone have a fix for this maybe?

As you can see, it looks like the object video is there, but looks like IE is not interpreting it because its loaded by ajax.


text:
Q: Bad Request when sending Inline Picture as a MS Team Bot I am receiving bad request when I including an attachment as an inline picture for the MS Teams Bot using the following code (the code works without attachments):
var message = Activity.CreateMessageActivity();
message.Text = "message here";
message.Attachments = new List<Attachment>();
var webClient = new WebClient();
byte[] imageBytes = webClient.DownloadData("https://img.icons8.com/windows/452/showing-small-size.png");
string url = "data:image/png;base64," + Convert.ToBase64String(imageBytes);

message.Attachments.Add(new Attachment
{
    ContentType = "image/png",
    ContentUrl = url
});

var conversationParameters = new ConversationParameters
{
  IsGroup = true,
  ChannelData = new TeamsChannelData
  {
      Channel = new ChannelInfo(outputChannelId),
  },
  Activity = (Activity)message
};

var response = await connectorClient.Conversations.CreateConversationAsync(conversationParameters);

I received the following error:
Microsoft.Bot.Schema.ErrorResponseException: Operation returned an invalid status code 'BadRequest'
   at Microsoft.Bot.Connector.Conversations.CreateConversationWithHttpMessagesAsync

Thanks in advance!

A: Rather than including the image as an attachment, consider instead sending an Adaptive Card and you can display the image directly to the user. See more on Adaptive Cards here.
As an alternative if you don't want to show the image but it's hosted somewhere, just include a link to it in the text message, using the markdown format that regular text message support in Teams (see more here).


text:
Q: How can I create a dynamic YTD anchor in Tableau? Does anyone know if it is possible to have a calculated field that would query YTD and dynamically set the anchor for the last day of the previous month?
My data is coming from Google Analytics, so this is just a very standard Date YTD field.
Image example: http://screencast.com/t/oRiYnr6ZDHK
Changing this anchor each month in dozens of places is very tedious.
My thanks in advance if anyone can help.

A: date(dateadd('day',-1,datetrunc('month',now())))
starting from the inside out:
-datetrunc('month',now()) - truncates the current datetime at the month level.
-dateadd('day',-1,... - subtract 1 day to get the last day of the previous month.
-date(... - convert final datetime to just a date.