text:
Q: Matplotlib animation in tkinter doesn't stop looping I'v got this matplotlib animation running in tkinter, it works fine but it just never stops looping, when i press 'X' the window closes but i have to force shut it with the task manager.
This is the example code of how i tried to set it up:
from matplotlib import pyplot as plt
from matplotlib import animation
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

import tkinter as tk
from tkinter import *

class Grapher(tk.Tk): # inherit Tk()
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        tk.Tk.wm_title(self, "Quarantined-Grapher")

        self.fig = plt.figure()
        ax = plt.axes(xlim=(0,2), ylim=(0, 100))

        N = 4 # amount of lines
        self.lines = [plt.plot([], [])[0] for _ in range(N)]

        # give the figure and the root(which is self) to the "canvas"
        self.canvas = FigureCanvasTkAgg(self.fig, self)
        self.canvas.show()
        self.canvas.get_tk_widget().pack()

        anim = animation.FuncAnimation(self.fig, self.animate, init_func=self.init,
                                        frames=100, interval=1000, blit=True)
    def init(self):
        for line in self.lines:
            line.set_data([], [])
        return self.lines

    def animate(self, i):
        for j,line in enumerate(self.lines):
            line.set_data([0, 2], [10 * j,i]) # some trick to animate fake data.
        return self.lines

app = Grapher()
app.mainloop()

My guess is it might be the animation loop that never stops running, because only tkinter knows to stop?..
Note: I made a graph work before, but i was using the tkinter after() method clearing and recreating data points, but it used up to much resources that i had to remake it. This way is so that i don't have to delete/create 10-50K data points every second.

A:
Answering the wrong question:
This is behaving as intended (looping indefinitely).  If you would like to only run once use the repeat kwarg (some what arcane docs):
anim = animation.FuncAnimation(self.fig, self.animate, init_func=self.init,
                               frames=100, interval=1000, blit=True,
                               repeat=False)


text:
Q: php mysql game map update automatically without refresh tab i want to ask..
this script show 8 images width (as Y) and 5 images heigh (as X).
 I also have character (Example Location Y: 5, X:4).
all from database. Map, character position.
And to move the character, simply by pressing button "North", "West", "East", "South" (Example if user press button "South" then will X+1. mean cordinate player from X:4, Y:5 become X:5, Y:5) <-- its good so far.
But, if player click button "South", the page is refresh.
My question is how to send data (form only button) without refresh page?
This's my form to move player's coordinate looks like this: (index.php)
<form action="index.php" method="post">
<input name="x+1" type="submit" value="North" />

<input name="y+1" type="submit" value="West" /><input name="y-1" type="submit" value="East" />

<input name="x-1" type="submit" value="South" />
</form>

and this is the process.. (index.php)
 $loca_x= $userrow["user_x"]; //x, up or down. From database user's x loc
   $loca_y= $userrow["user_y"]; //y , right or left. user's y locat.
    if (isset($_POST["x+1"])) { $loca_x--; if ($loca_x< 1) { $latitude = 1; $errormsg= "Edge of map!"; } }
    if (isset($_POST["x-1"])) { $loca_x++; if ($loca_x> 5) { $latitude = 5; $errormsg= "Edge of map!"; } }
    if (isset($_POST["y-1"])) { $loca++; if ($loca> 8) { $longitude = 8; $errormsg= "Edge of map!"; } }
    if (isset($_POST["y+1"])) { $loca--; if ($loca< 1) { $longitude = 1; $errormsg= "Edge of map!"; } }

Also i have second question too..
this script show grid map x, y from map.
for($x=1;$x<=5;$x++)
    {
        for($y=1;$y<=8;$y++)
        {
            $show_map_query = doquery("SELECT * FROM {{table}} WHERE x='$x' AND y ='$y'","explore");
        while($row_map = mysql_fetch_array($show_map_query)) {
                 if($userrow['user_x'] == $row_map['x'] && $userrow['user_y'] == $row_map['y']) {
            echo ' X:'.$row_map['x'].' - Y:'.$row_map['y'].')" style="float: left;margin: 0;padding:0;" height="90" width="90">';
                 } else {
        echo '';
                 }

        }
    }
    }

when execute, this is the result:
THIS IS THE IMAGE
But, its too heavy when browser load. how to show only 8 images. i mean like this:
[IMG][IMG][IMG]
[IMG][YOU][IMG]
[IMG][IMG][IMG]

and when player press button..all [img] change, but the character still in middle.
How to do this??
NB: Sorry for this noob 2 question long bad english written.

redpajama_set_name: RedPajamaStackExchange


text:
Q: I can't access textView in Kotlin I'm just a beginner at android development and Kotlin. I wrote some easy codes but it did not work much. Can u help me with it?
fun degistir(view: View) {
    textView.text = "Hello world"
}

I wrote this but I could not access textView. Note: My textView's id is textView too.

A: first you need to set an id for the TextView in your XML file
then in your onCreate function in your Activity or Fragment you will get the TextView in your XML and assign it to an Object like this and set the text after that
val textView: TextView = findViewById(R.id.myTextView)
textView.text = "Hello World"

For the Kotlin Extensions solution do the following
1- go to your app gradle file and add this plugin
apply plugin: 'kotlin-android-extensions'

2- and now once you write this
textView.text = "Hello World"

it will show you textView in underlined red and says it can import it, once you do, it will work.
this will bypass the findViewById and you will no longer need it.

A: Use ViewBinding
module-level build.gradle file.
    android {
    ...
    buildFeatures {
        viewBinding true
     }
   }

Usage For example, given a layout file called result_profile.xml:
<LinearLayout ... >
    <TextView android:id="@+id/name" />
    <ImageView android:cropToPadding="true" />
    <Button android:id="@+id/button"
        android:background="@drawable/rounded_button" />
</LinearLayout>

Sample OnCreate
To set up an instance of the binding class for use with an activity, perform the following steps in the activity's onCreate() method:
Call the static inflate() method included in the generated binding class. This creates an instance of the binding class for the activity to use.
Get a reference to the root view by either calling the getRoot() method or using Kotlin property syntax.
Pass the root view to setContentView() to make it the active view on the screen.
private lateinit var binding: ResultProfileBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ResultProfileBinding.inflate(layoutInflater)
    val view = binding.root
    setContentView(view)
}

binding.textViewId.text = "blablabla"

A: This procedure works for me : Go to build.gradle(Module: -> after dependencies { add these lines: apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' You can watch the video in this link : https://keley-blue-book.blogspot.com/2021/08/kotlin-how-to-get-and-set-text-to.html


text:
Q: Не работает $_SERVER['REQUEST_URI'] товарищи! Задача проста — скрывать два метатега на страницах, где они не нужны. Вот такая конструкция, почему-то не работает (задумывалось, что она будет выводить метатеги только на страницах, если их адрес совпадает с шаблоном /post/{id}):
<?php if ($_SERVER['REQUEST_URI'] === '/post/') : ?>
    <meta name="description" content="<?= $description ?>" />
    <meta name="keywords" content="<?= $keywords ?>" />
<?php endif; ?>

Так же, не работает иной код, который призван выводит разные блоки меню для сайта и админки. Он всё правильно делает, если адрес /admin, но если он, скажем, /admin/writePost, то, выводится стандартное меню. Вот такой код:
<?php if (isset($_SESSION['id'])) : ?>
    <?php if ($_SERVER['REQUEST_URI'] === '/admin') : ?>
         Admin
         <?php require_once('amenu.php'); ?>
    <?php else : ?>
         Главная
         <?php require_once('menu.php'); ?>
    <?php endif; ?>
<?php endif; ?>


text:
Q: Angular CLI and Stripe Is there a way to install Stripe checkout using Angular CLI? I tried installing as a 3rd party library but that didn't work

A: npm i angular-stripe-checkout

The angular CLI does not install packages.


text:
Q: OLAP/OLTP: What does "online" mean? Not sure this is where I should post this, but I found related questions on here, so I'm gonna give it a go:
I've been reading up on data warehousing, OLAP/OLTP etc. One thing I would like to know - and it might be a silly question - what does the "Online" stand for in OLAP/OLTP? I wasn't successful googling it because I only get an answer to the question "What is OLAP?", but the name is never fully explained, it's always about analytical vs transactional.
My own thought was maybe OLTP is "online" in the sense that it does what it does (storing/processing  transactional data etc) in real-time and then OLAP just modified that name when it was "invented", but that might be completely wrong.

A: As opposed to a local copy of data (e.g., a spreadsheet), both these data sources assume there's a remote server somewhere (not necessarily on the internet; could be on an internal network), and there's a communications channel connecting the server to the client.


text:
Q: Server 2008 - Search for Files and Delete.. very slow! Windows Server 2008 R2.  Old ish server (4 cores, 2GB RAM) fairly average disks running no raid.
I've used windows F, then searched for .svn files
Selected all, and deleting them.  631 files and 220MB.  It is going to take about 45mins to delete!!
Problem:  How to delete files quickly?
No antivirus or windows serach service running.  Out of the box install of 2008R2.  No other users on the system.  Using terminal services to admin onto the box as a development machine.
Cheers
Dave

A: Do you delete or shift-delete? If you delete to recycle bin it takes longer. Try shift-deleting. Plus: check whether recycle bin is full, if so it takes even longer deleting old files from bin while deleting the .svn folders.

A: A script might be a faster way to accomplish this, especially if you're going to do this multiple times.
for /f "tokens=* delims=" %%i in ('dir /s /b /a:d *.svn') do (
 del /q "%%i"
)


text:
Q: Strongly Connected Tournament I need to prove that every strongly connected tournament is Hamiltonian. My professor suggested proving a stronger result(A strongly connected tournament on $n$ vertices contains cycles of length $3, 4, ..., n$.
I am trying to prove by induction, but am stuck on concretely proving the base case even.

A: The base case holds. Take a king in the tournament. Because the graph is strongly connected, $|N^+(v)|,|N^-(v)| \neq \emptyset$. Therefore, both $|N^+(v)|$ and $|N^-(v)|$ have kings. Let the king of $|N^+(v)|$ be $k_+$. Clearly, it has to reach $v$ with a path of length $2$. Thus, we have a cycle of length three.
Now suppose that $G$ has a cycle $C$ of length $c$. There are two cases:
Easy case: There is some $v \in G -C$ s.t. $v$ loses to a $x \in C$ and beats a vertex $y \in C$. Then we splice $v$ into $C$ by $xvy$, creating a cycle of length $c+1$.
Hard case:
Suppose that no such $v$ exists. Then we split the vertices of $G - C$ into two disjoint sets: $S$, set of vertices that only lose to vertices in $C$, and $P$, the set of vertices that only beat vertices in $C$. Neither of these sets can be nonempty, or the graph is not strongly connected.
There exists $s \in S$ and $p \in P$ s.t. $s$ beats $p$, otherwise the graph cannot be strongly connected.
Take the vertices $c_1, c_2,c_3 \in C$ s.t. $c_3$ follows $c_2$, which follows $c_1$ in $C$. By definition, $c_1$ beats $s$, $s$ beats $p$, and $p$ beats $c_3$. Splice $s$ and $p$ into $C$ by $c_1spc_3$. By skipping $c_2$, we create a cycle of length $c+1$.
Therefore, we have shown by induction that any strongly connected tournament contains cycles of all lengths $3,...,n$, and thus must contain a Hamiltonian cycle.
For more information, you can check out the paper where this result was first published.


text:
Q: Какую библиотеку использовать для сравнения двух текстов? Есть два текстовых поля, в них будет текст. Нужно сделать так, чтобы при нажатии на кнопку, эти два текста проверялись и на экране показывались отличия. Какую библиотеку для этого использовать?

A: Вот хороший пример, думаю как раз то, что нужно
http://code.google.com/p/google-diff-match-patch/
http://neil.fraser.name/software/diff_match_patch/svn/trunk/demos/demo_diff.html


text:
Q: if run same stored procedure with same name on two different database with same logic but it returns different result for out parameter of procedure I have below test procedure :
DELIMITER $$
DROP PROCEDURE IF EXISTS `test`$$
CREATE DEFINER=`root`@`%` PROCEDURE `test`(
   IN  DBname VARCHAR(20),
  OUT flag INT
)
BEGIN
    SET flag=0;
    IF(DBname='testing')
     THEN
           SET flag=1;
     END IF;
END$$
DELIMITER ;

If I call above procedure using php code using one database db1
it returns out parameter flag as 1 if I pass 1 for calling stored procedure
But If I call same procedure with different database db2 then it returns null value of out parameter.
where is the problem, not getting.
above procedure works fine if I run through Mysqlyog on different database also.


text:
Q: Every unorientable 4-manifold has a $Pin^c$, $Pin^{\tilde c+}$ or $Pin^{\tilde c-}$ Structure The precise statement on J. W. Morgan's "The Seiberg-Witten Equations and Applications to the Topology of Smooth Four-Manifolds (MN-44)" that 4-manifold $X$ admits a Spinc structure (Lemma 3.1.2) seems to be that every 4-orientable manifold X admits a $Spin^c$ structure. This means that we impose the $w_1(X)=0$ for the 4-orientable manifold X.
However, for 4-unorientable manifold $M$, we may modify the statement to different structures.
In addition to,
$Spin^c=\frac{(Spin \times U(1))}{\mathbb{Z}/2\mathbb{Z}},$
we can have:
$$Pin^c=\frac{(Pin^+ \times U(1))}{\mathbb{Z}/2\mathbb{Z}}=\frac{(Pin^- \times U(1))}{\mathbb{Z}/2\mathbb{Z}},$$
$$Pin^{\tilde c+}=\frac{(Pin^+ \ltimes U(1))}{\mathbb{Z}/2\mathbb{Z}},$$
$$Pin^{\tilde c-}=\frac{(Pin^- \ltimes U(1))}{\mathbb{Z}/2\mathbb{Z}}.$$
See for example this Ref, Annals of Physics 394, 244-293 (2018) and References therein.
It seems that I can improve John Morgan's statement to show that

Every unorientable 4-manifold has either a $Pin^c$, $Pin^{\tilde c+}$ or $Pin^{\tilde c-}$  Structure.  (?)

e.g. My approach is based on improving the map
\begin{equation*}
H^1(X;Pin^c) \to H^1(X; O(n)) \oplus H^1(X;\mathbb{Z}) \xrightarrow{} H^2(X;\mathbb{Z}_2),
\end{equation*}
\begin{equation*}
H^1(X;Pin^{\tilde c+}) \to H^1(X; O(n)) \oplus H^1(X;\mathbb{Z}) \xrightarrow{} H^2(X;\mathbb{Z}_2),
\end{equation*}
\begin{equation*}
H^1(X;Pin^{\tilde c-}) \to H^1(X; O(n)) \oplus H^1(X;\mathbb{Z}) \xrightarrow{} H^2(X;\mathbb{Z}_2).
\end{equation*}
The last maps of all three need to have appropriate constraints between $c_1$ and $w_2(M)$, $w_1(M)$ and $w_1^2(M)$.

Question: I wonder whether there exists any math literature show the similar results like mine above? Or are my statements obviously true? (Or obviously wrong?)

A: $\newcommand{\RP}{\mathbb{RP}}\newcommand{\Z}{\mathbb Z}$
The conjecture is false: $\RP^4\amalg(\RP^2\times\RP^2)$ is an unorientable 4-manifold that has no
pin$c$, pin$\tilde c-$, or pin$\tilde c+$ structure.
It suffices to find three unorientable 4-manifolds $A$, $B$, and $C$, such that $A$ isn't pin$c$, $B$
isn't pin$\tilde c-$, and $C$ isn't pin$\tilde c+$. Then $A\amalg B\amalg C$ doesn't admit
any of the three structures: a $G$-structure is a reduction of the principal bundle of frames, so a $G$-structure
on a manifold induces a $G$-structure on each connected component.
First, $A = \RP^2\times\RP^2$ doesn't have a pin$c$ structure; this is discussed
here.
Then, $B = \RP^4$ has no pin$\tilde c-$-structure. Let $H^*(-; \Z_{w_1})$ denote integer cohomology
twisted by the orientation bundle.  From Shiozaki-Shapourian-Gomi-Ryu, Lemma
D.7, we learn that a manifold $M$ has a pin$\tilde c-$-structure iff $w_2 + w_1^2\in H^2(M;\Z/2)$ admits
a lift across the mod 2 reduction map
$$\tag{$*$} H^2(M;\Z_{w_1})\longrightarrow H^2(M; (\Z/2)_{w_1}) = H^2(M;\Z/2).$$
Twisted Poincaré duality tells us that if $M$ is a closed $n$-manifold, there are isomorphisms $H_k(M;\Z)\cong
H^{n-k}(M;\Z_{w_1})$, so $H^2(\RP^4;\Z_{w_1})\cong H_2(\RP^4;\Z) = 0$. A quick computation shows that if $x\in
H^1(\RP^4;\Z/2)$ is the generator, then $w_2(\RP^4) + w_1(\RP^4)^2 = x^2$; in particular, it's nonzero, so it can't
lift to $H^2(\RP^4;\Z_{w_1})$. Therefore $\RP^4$ admits no pin$\tilde c-$-structure.
Finally, $C = \RP^2\times\RP^2$ doesn't have a pin$\tilde c+$-structure. Lemma D.8 of the
Shiozaki-Shapourian-Gomi-Ryu paper tells us that a manifold $M$ has a pin$\tilde c+$-structure iff
$w_2\in H^2(M;\Z/2)$ admits a lift across ($*$).
Let $x$ denote the generator of $H^1(-;\Z/2)$ of the first $\RP^2$ and $y$ be that for the second $\RP^2$. Using
the usual CW structure on $\RP^2$ and the product CW strucure on $\RP^2\times\RP^2$, you can check that
$H_2(\RP^2\times\RP^2;\Z)\cong\Z/2$ and the reduction mod 2 map $H_2(\RP^2\times\RP^2;\Z)\to
H_2(\RP^2\times\RP^2;\Z/2)$ sends the nonzero element of $H_2(\RP^2\times\RP^2;\Z)$ to the Poincaré dual of $x+y$.
The Poincaré duality isomorphisms $H_2(\RP^2\times\RP^2;\Z)\cong H^2(\RP^2\times\RP^2;\Z_{w_1})$ and
$H_2(\RP^2\times\RP^2;\Z/2)\cong H^2(\RP^2\times\RP^2;\Z/2)$ are natural with respect to change-of-coefficients,
which means that the reduction mod 2 map ($*$) for $M = \RP^2$ sends the nonzero element of
$H^2(\RP^2\times\RP^2;\Z_{w_1})\cong\Z/2$ to $x+y$. However, $w_2(\RP^2\times\RP^2) = x^2+xy+y^2$, so it's not in
the image of ($*$), and therefore $\RP^2\times\RP^2$ has no pin$\tilde c+$-structure.


text:
Q: Vuejs 3 Parent child loop on same div In Vuejs 3, I have parent child json which gives output like below.

1

2

3

4

pbRow is parent and under its child.
Now what I want is, instead of Parent pbRow multiple time, I want it only once and all parent's child in same level like

1

2

3

4

That means I only need child elements, ignoring their parent.
Below is my code

Is there any way I can achieve what I have mentioned ? As I am not sure

A: If I understood you correctly you can prepare your data with computed property and then have one loop:

const app = Vue.createApp({
  data() {
    return {
      filteredNestedList: [{courses:[{id:1},{id:2}]},{courses: [{id:3}]}],
    };
  },
  computed: {
    list() {
      return this.filteredNestedList.map(l => l.courses).flat()
    }
  }
})
app.mount('#demo')

{{ coursePlatform.id }}


text:
Q: Enviar E-mails de um Formulário de Contato HTML alguém poderia me ajudar, estou criando um formulario de envio de email, porém nada acontece quando eu aperto no botao de enviar email, segue o codigo abaixo
insira o código aqui <form action="https://formsubmit.co/marques.bispo@hotmail.com" method="POST">

                <input type="text" class="form-control" placeholder="Nome">

                <input type="email" class="form-control" placeholder="Email">

                <input type="text" class="form-control" placeholder="Assunto">

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

              <button type="submit" class="btn">Enviar mensagem</button>
            </form>


text:
Q: Descriptive statistical analysis I have some data obtained from questionnaire. The question asks to perform a descriptive statistical analysis for the above data and hence interpret your results. What does it mean? Is it mean I have to find the mean median mode standard deviation variance?

A: Before starting to do numerical and graphical descriptions of data
for each question, it is important to determine whether the answers to the question are nominal, ordinal, or essentially numerical.
NUMERICAL (numbers, perhaps intervals): Perhaps age, income, or commute distance
to work. Modal intervals should be obvious. It might be possible to estimate medians and ranges.
Depending on allowed answers, perhaps even means and standard deviations. Graphical display might be a bar chart, showing
the relative frequency of each interval.
ORDINAL:  Answers like 'Strongly disagree/ disagree/ neutral/
agree/ strongly agree' or 'Never/ rarely/ occasionally/ often'.
You should be able to find mode and median. Bar chart (with
spaces separating bars) to make it clear you are not
representing a continuous scale.
NOMINAL: Answers like 'Male/Female' or 'Catholic/ Protestant/
Jewish/ Muslim/ Hindu/ Buddist/ Other'. Categories have no
natural order. Mode is the only valid measure of centrality.
Pie chart or bar chart.
Here is a summary of which measures of centrality you can
use of which data types.
 Valid Measures of Centrality for Various Data Types

           Nominal      Ordinal      Numerical
 Mean                  (See Note)       OK
 Median                    OK           OK
 Mode        OK            OK           OK

Computing the mean required addition and division, these arithmetic
procedures are only appropriate for numerical data. Finding the
median requires sorting and picking the 'middle' value. Ordinal
and numerical data can be sorted, Nominal cannot.
Note: Grades are inherently ordinal. Educational institutions
customarily assign arbitrary numerical values to these, such as A = 4, B = 3,
and so on. Then these numerical values are averaged to get a GPA
for each student. (Are two C's really the same as an A and an F?)
For large datasets the mean is a lot easier to find than the median.
This practice of grade points originated in an era when it was
feasible to compute GPAs, but not grade medians for large numbers
of students. It is relatively easy to find the median of a dozen numbers, but sorting a thousand as a prelude to finding the
median requires some computing power--power which is now routinely available. Even so, don't expect GPAs to disappear anytime soon.
'Likert' scaeles widely used in psychology and other social
sciences are another (often problematic) kind of attempt to treat
essentially ordinal data as numerical. (Can you meaningfully add
'Strongly opposed' and 'Favor'?)


text:
Q: How to minimize all open windows except my program? I want my program to be the only program showing, is there a way to do that?
I suppose by running something like
WindowState = ALL.Minimized;

Update
I made a Script like this
Set shell = wscript.CreateObject("Shell.Application")
Shell.MinimizeAll

Named it Mini.vbs
Then i used this code in Visual Studio
   {
InitializeComponent();
TopMost = true;
System.Diagnostics.Process.Start("c:/mini.vbs");
        }

It works, but its not the best solution .

A: You could simply  set the TopMost property to True on the creation of the form.
public Form1()
{
 InitializeComponent();
 this.TopMost = true;
}

Goodluck.


text:
Q: HTTPServer не полностью отдает файл при установке тайм аута в lxc контейнере Есть скрипт выступающий в роле простого http сервера.
В попытке устранить зависание скрипта при залипшем коннекте клиента к серверу, я решил установить тайм аут сокета (возможно ошибочное решение). Но возникла другая проблема, которая в свою очередь воспроизводится только в LXC контейнере. Скрипт отдает тело не более 83.5 КБ - файлы больше режутся до этого размера.
На хостовых Ubuntu Desktop 16.04 x64 и OpenSUSE Tumbleweed x64 скрипт отвечает на запрос как положено.
Пробовал на нескольких конфигурациях:

*

*Хост: Ubuntu server 16.04 x64 Контейнер: Ubuntu 16.04

*Хост: Proxmox VE 4.3 Контейнер: Debian 8

Пример:
import http.server as http
class HTTPRequestHandler(http.BaseHTTPRequestHandler):
    def __init__(self, reqest, cli_addr, server):
        self.timeout = 10.0
        super().__init__(reqest, cli_addr, server)

    def do_GET(self):
        if self.path == '/':
            self.send_response(200)
            self.send_header('Content-type', 'text/css')
            self.end_headers()
            with open("bootstrap.min.css", 'rb') as css:
                self.wfile.write(css.read())

http_server = http.HTTPServer(('', 8080), HTTPRequestHandler)

if __name__ == '__main__':
    http_server.serve_forever()


text:
Q: Can I deserialize a JSON array into properties of a class? I have a JSON file containing lines like this:
{"id":"0258","name":"Canterbury","coordinates":[1.07992,51.27904]}

The coordinates item is the geographic coordinates of the city. However it is stored as an array which always contains the [longitude, latitude].
I want to deserialize these entries into C# POCO classes that are defined like this:
    public sealed class City
        {
        [JsonPropertyName("name")]
        public string Name { get; set; }

        [JsonPropertyName("coordinates")]
        public GeographicLocation Location { get; set; }
        }

    public sealed class GeographicLocation
        {
        public GeographicLocation(double latitude, double longitude)
            {
            Latitude = latitude;
            Longitude = longitude;
            }

        public double Latitude { get; private set; }
        public double Longitude { get; private set; }
        }

I think you can see where I'm going with that.
Is there a way of annotating these classes so that the source JSON will deserialize correctly into my desired object graph?
I'm currently using System.Text.Json but would switch to Newtonsoft.Json in a heartbeat if it has a better solution.
Clarification
I know how to deserialize JSON to a class, where there's a correspondence between JSON elements and class properties. The essential problem here is that the source JSON file contains a 2-element array which I'd like to end up in properties of my deserialized class, rather than in a single array property. I don't know how to accomplish that.

A: As was mentioned above, you can use custom JsonConverter<>. A simple solution would look like this:
public class GeographicLocationJsonConverter : JsonConverter<GeographicLocation>
    {
        public override GeographicLocation ReadJson(JsonReader reader, Type objectType, [AllowNull] GeographicLocation existingValue, bool hasExistingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            var token = JArray.Load(reader);
            var values = token.ToObject<List<double>>();
            return new GeographicLocation(values[0], values[1]);
        }

        public override void WriteJson(JsonWriter writer, [AllowNull] GeographicLocation value, Newtonsoft.Json.JsonSerializer serializer)
        {
            var jArray = new JArray(new double[] { value.Latitude, value.Longitude });
            jArray.WriteTo(writer);
        }
    }

Usage:
        var city = new City()
        {
            Location = new GeographicLocation(1, 2),
            Name = "Zhytomyr"
        };

        var converter = new GeographicLocationJsonConverter();

        var json = JsonConvert.SerializeObject(city, converter);

        var deserializedCity = JsonConvert.DeserializeObject<City>(json, converter);


text:
Q: Get the value from listbox of template plugin in tinymce I want to add plugin to delete template in tinymce editor. For this I am using same form like template.
For deleting selected template I want the selected value from listbox which contains list of inserted templates. I have used various ways to get it but no luck.

*

*var selectedValue = win.find('#listbox')[0].value();

*getContent() is also not working.
I am getting null value or undefined value.
Any ideas for better solutions.


text:
Q: MS SQL Server - OpenXML - Multiple elements XML example:
<POLICY>
    <RISKS>
        <RISK>
            <DRV>1</DRV>
        </RISK>
        <RISK>
            <DRV>2</DRV>
        </RISK>
    </RISKS>
</POLICY>

I want to select both Risk elements with this query:
SELECT RISK
FROM OPENXML(@hDOC, 'POLICY/RISKS', 2)
WITH(
    RISK            XML     'RISK'
) AS Z

Expected:
1. <RISK><DRV>1</DRV></RISK>
2. <RISK><DRV>2</DRV></RISK>

Result:
1. <RISK><DRV>1</DRV></RISK>

(only first element was returned)
For comparison this query returns two rows as expected:
SELECT DRV
FROM OPENXML(@hDOC, 'POLICY/RISKS/RISK', 2)
WITH(
    DRV         XML     'DRV'
) AS Z

Result:
1. <DRV>1</DRV>
2. <DRV>2</DRV>

So the question is how can I get two Risk-rows?

A: Why are you not using the native XQuery support provided by SQL Server. OpenXML is old and having lot of issues.
You can write your query like following using XQuery Support
DECLARE @hDOC xml
SET @hDOC='<POLICY>
    <RISKS>
        <RISK>
            <DRV>1</DRV>
        </RISK>
        <RISK>
            <DRV>2</DRV>
        </RISK>
    </RISKS>
</POLICY>'
SELECT T.c.query('.') AS result
FROM   @hDOC.nodes('/POLICY/RISKS/RISK') T(c)
GO

You will get output as
1. <RISK><DRV>1</DRV></RISK>
2. <RISK><DRV>2</DRV></RISK>

Edit: If you still want to do with OpenXml, use query like following.
DECLARE @DocHandle int
DECLARE @hDOC VARCHAR(1000)
SET @hDOC=N'<POLICY>
    <RISKS>
        <RISK>
            <DRV>1</DRV>
        </RISK>
        <RISK>
            <DRV>2</DRV>
        </RISK>
    </RISKS>
</POLICY>'
EXEC sp_xml_preparedocument @DocHandle OUTPUT, @hDOC
SELECT RISK
FROM OPENXML(@DocHandle, 'POLICY/RISKS/RISK', 2)
WITH(
    RISK XML     '.'
) AS Z

EXEC sp_xml_removedocument @DocHandle

You will get the desired output.


text:
Q: POST multipart/form-data with ASIHTTPRequest I'm new to ASIHTTPRequest and I have a problem to implement a form.
At the moment I use the following code inside a UIWebForm and everything work fine.
    NSString *body = @"\
    <html> \
    <head> \
    <meta http-equiv=\"Content-Type\" content=\"text/html;
charset=iso-8859-1\"> \
        </head>   \
        <body>\
        <form name=\"my_form\" action=\"http://www.server.com/ar?
ca=11_s&id=22630957\" \
        method=\"POST\" enctype=\"multipart/form-data\"> \
        <input type=\"text\" name=\"name\"  value=\"myname\"> \
        <input type=\"text\" name=\"email\" value=\"mym...@gmail.com\"> \
    <textarea name=\"body\">My message</textarea> \
        <input type=checkbox name=\"sendercc\" value=\"0\"> \
    <input type=\"submit\" name=\"send\" value=\"Send\"> \
        </table> \
        </form> \
        </body>\
        </html>";

The (not working) code that should replace the form is the follow:
        ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:
[[[NSURL alloc] initWithString:@"http://www.server.com/ar?
ca=11_s&id=22630957"] autorelease]];
        [request setResponseEncoding:NSISOLatin1StringEncoding];
        [request setPostFormat:ASIMultipartFormDataPostFormat];
        [request setPostValue:@"myname" forKey:@"name"];
        [request setPostValue:@"mymail@gmail.com" forKey:@"email"];
        [request setPostValue:@"My message" forKey:@"body"];
        [request setPostValue:@"0" forKey:@"sendercc"];
        [request startSynchronous];

A: Could you explain more about how it doesn't work? Do you get an error back from the server if you check request.responseString?
You may need to add a value for the submit button, ie:
[request setPostValue:@"Sent" forKey:@"send"];

If that doesn't help, try using a proxy like CharlesProxy to capture both a working request from the browser and the non-working iphone request, and compare them looking for any differences.


text:
Q: Is it possible to write a Haskell function with type Int -> Float I can write
double :: Int -> Float
double i = 2.0

but that isn't in any way a function of its argument. Casting is apparently
forbidden, mixed-mode arithmetic isn't supported, so I can't do anything like
double :: Int -> Float
double i = 2.0 * i

I'm actually trying to figure out how to define
series :: (Int -> Float) -> Int -> [Float]

to return the infinite series [f(i), f(i+1), f(i+2),...]
but I'm stuck at computing f(i).
If this is really impossible, what type must I use?
Thanks!

A: I think you're looking for the fromIntegral function.

A: Michael Snoyman's answer is the practical one, but let me show you what you could do if fromIntegral didn't exist. First, the super-slow version:
intToFloat :: Int -> Float
intToFloat x
  | x > 0 = - itf (- x)
  | otherwise = itf x

-- Convert a negative Int to a Float
itf 0 = 0
itf x = itf (x + 1) - 1

This is slow, and may also use a lot of memory. But we can fix it through the power of division! Unfortunately, I can't write it up right now.


text:
Q: Sed - Remove digits from end of line/string I'm trying to remove digits from the end of each line within a text file, I've tried using:
sed 's/[0-9]\+$//' <input.txt >output.txt

but it doesn't work, however if I a echo input, ie
echo "Bla1Bla123" | sed 's/[0-9]\+$//'

it will work correctly and output as expected
Bla1Bla

removing " 123 " from the end.
however when I try using input.txt it fails to do that for each line..
example of input.txt is
heyexample1:123example123
h123h:i123i123

which should then output
heyexample1:123example
h123h:i123i

instead it makes no alterations

A: Your files are probably encoded with the \r\n line endings (since you are on Windows). Try 's/[0-9]\+\r$/\r/' replace command (preserving the \r intentionally).
There might be a way for sed to handle CRLF line endings, but I cannot find it after a brief search.


text:
Q: how to shorten function query? hello i have this function:
function mail_exists($email){
    global $db;
    $email = sanitize($email);
    $query = $db->query("SELECT Email FROM table1 WHERE Email= '$email' ");
    $check = $query->num_rows;
    $query2 = $db->query("SELECT Email FROM table2 WHERE Email= '$email' ");
    $check2 = $query->num_rows;
    return ($check > 0 || $check2 > 0) ? true : false;
}

first of all i would like to know how i can shorten it by using only one query and second thing is, why this does not work when using two queries? both tables have a different structure. in table1 the field email is no. 16 and on table2 it is field no.6.
thanks alot.

A: First of all you made a logic error *here in the last lines: $query->num_rows; should be: $query2->num_rows; and then resulting into:
function mail_exists($email){
    global $db;
    $email = sanitize($email);
    $query = $db->query("SELECT Email FROM table1 WHERE Email= '$email' ");
    $check = $query->num_rows;
    $query2 = $db->query("SELECT Email FROM table2 WHERE Email= '$email' ");
    $check2 = $query2->num_rows; // *here
    return ($check > 0 || $check2 > 0) ? true : false;
}

Second, you should be using two different queries if you are dealing with two completely different contexts. Don't join queries when you don't need to. If you are just counting rows you can easily do:
function mail_exists($email){
    global $db;
    $email = sanitize($email);
    $query = $db->query("SELECT COUNT(*) FROM table1 WHERE Email= '$email' ");
    $query2 = $db->query("SELECT COUNT(*) FROM table2 WHERE Email= '$email' ");
    $count1 = $query->fetch_row();
    $count2 = $query2->fetch_row();
    return ($count1[0] || $count2[0]);
}

The SQL COUNT() function is there to give you the most performant way to count rows.

A: Use can UNION ALL to return an overall count:
SELECT Email
FROM (
   SELECT Email FROM table1 WHERE Email= '$email'
   UNION ALL
   SELECT Email FROM table2 WHERE Email= '$email') t

Or you can use SELECT COUNT(Email) to return the count.

A: You might try:
SELECT t1.Email from table1 t1 inner join table2 t2 on t2.Email=t1.Email WHERE t1.Email = '$email'

and then:
return $query->num_rows > 0;

I'm not a PHP expert, so your mileage may vary.


text:
Q: error CS1519 (invalid token ";") and CS1001 (identifier expected). Vector 3 problem (Brakeys Multiplayer tutorial ep 2) The script in the video originally had a plethora of errors, and I've tried my best to fix the code and reduce the errors to as few as possible
The errors in my current script are:
Assets\PlayerMotor.cs(9,14): error CS1519: Invalid token '=' in class, struct, or interface member declaration
Assets\PlayerMotor.cs(9,32): error CS1001: Identifier expected
My script is:
using UnityEngine;

[RequireComponent(typeof(Rigidbody))]

public class PlayerMotor : MonoBehaviour
{

    private Vector3 velocity;
    velocity = new Vector3(zero);

    private Rigidbody rb;

    void Start()
    {

        rb = GetComponent<Rigidbody>();

    }

    //Gets a movement vector
    public void Move (Vector3 _velocity)
    {

        velocity = _velocity;

    }

    //Run every physics iteration
    void FixedUpdate ()
    {

        PerformMovement();

    }

    //Perfrom movement based on velocity variable
    void PerformMovement()
    {

        if (velocity != Vector3.zero){
            rb.MovePosition(rb.position + velocity * Time.fixedDeltaTime);
        }

    }
}

A: *

*You can't just write code inside class body like: velocity = new Vector3(zero);. What you can do, and what probably made you thought you could do that, is to initialize the variable at declaration: private Vector3 velocity = new Vector3(zero); Still, this has more issues.

*Vector3 doesn't have a constructor, that accepts only one parameter.

*Even if it did, you would have to declare Vector3 zero as a static variable.

*All in all, just use Vector3.zero where you need, there's no point in declaring it yourself.

A: private Vector3 velocity;
velocity = new Vector3(zero);

This does not work. You can either write it like this
private Vector3 velocity = Vector3.zero;

or assign the value in a method like Start:
private Vector3 velocity;

void Start()
{
    rb = GetComponent<Rigidbody>();
    velocity = Vector3.zero;
}

Also new Vector3(zero) does not work, because you never defined whatever zero is. It's probably a typo for Vector3.zero. An alternative would be new Vector3(0, 0, 0).


text:
Q: FPGA blocking assignments in always block not working properly In the following setup I have created a custom clock through switch on Spartan 3E FPGA to toggle the LED states one by one. I have connected 8 registers with 8 LEDs. By triggering the clock through switch, values of registers are toggled at the positive edge of clock. In each clock one register's value is toggled which is selected by the index variable.
Verilog Code
module IOCom(
    input wire dataInShiftCLK, dataOutShiftCLK,
    output wire dataOutEnb,
    output wire [7:0] LED
);

reg [7:0] temp;
integer index;
reg dataOutEnbReg, dataInShiftCLKReg;

initial begin
    temp <= 8'b00000000;
end

// blocking assignments used
always @ (posedge dataInShiftCLK) begin
    temp[index] = ~temp[index];
    index = index + 1;
    if(index == 8) begin
        dataOutEnbReg = 1;
        index = 0;
    end
end

assign dataOutEnb = dataOutEnbReg;

assign LED[0] = temp[0];
assign LED[1] = temp[1];
assign LED[2] = temp[2];
assign LED[3] = temp[3];
assign LED[4] = temp[4];
assign LED[5] = temp[5];
assign LED[6] = temp[6];
assign LED[7] = temp[7];

endmodule

UCF Code
# ==================
#     SPARTAN 3E
#   xc3s500e-4fg320
# ==================

NET "dataInShiftCLK" LOC = L13 | IOSTANDARD = "LVTTL";
NET "dataInShiftCLK" CLOCK_DEDICATED_ROUTE = FALSE;
NET "dataOutEnb" LOC = D7 | IOSTANDARD = "LVCMOS33";

NET LED<0> LOC=F12 | IOSTANDARD = LVCMOS33;
NET LED<1> LOC=E12 | IOSTANDARD = LVCMOS33;
NET LED<2> LOC=E11 | IOSTANDARD = LVCMOS33;
NET LED<3> LOC=F11 | IOSTANDARD = LVCMOS33;
NET LED<4> LOC=C11 | IOSTANDARD = LVCMOS33;
NET LED<5> LOC=D11 | IOSTANDARD = LVCMOS33;
NET LED<6> LOC=E9 | IOSTANDARD = LVCMOS33;
NET LED<7> LOC=F9 | IOSTANDARD = LVCMOS33;

I am facing the following issues

*

*I have used posedge but at negedge the toggling also happen sometime.

*The LEDs are very unstable and very few times toggling one by one. Some times all toggle at once and some times 3-4 LEDs toggle at once. I tried to fix the issue by using blocking assignment in always block but still not fixed.

Please suggest some solution to fix the issue. Thank you for your time.


text:
Q: use multiple Cognito Pool Client ids on the same Cognito Identity Pool for login I have a Cognito Identity Pool set up to use a Cognito user pool as a source of identity. Now, in my case the Cognito User Pool has 2 different client id, one for my mobile application and one for my website. In order to support login from both I need to add both client ids in the Authentication Providers settings but it seems that you can add only 1 client id at a time. Is there a way to configure Cognito Identity Pool to accept 2 different Cognito Pool client IDs?
I don't wanna use the same client id cause I need to do different user validations on user sign-up based on where the user came from (app or web) and the client id is the only parameter passed to my lambda that allows me to identify from where a user came from.

A: From the Identity Pool Cloudformation docs, it looks like you can provide a list of identity providers. A user pool identity provider is defined as the user pool ID plus the client ID. It seems like you should be able to specify two different ones with the same user pool ID and different client IDs. I don't know whether this is possible through the console.


text:
Q: Why does tcpdump not recognise piped input?

*

*I obtained a packet capture file:
$ sudo tcpdump -w file.pcap

*I can then analyse that file:
$ tcpdump -r file.pcap

I can even use file redirection to read from standard input:
$ tcpdump -r - < file.pcap

*However, I cannot use a pipe to read from standard input:
$ cat file.pcap | tcpdump -r -
tcpdump: unknown file format

This should work.  What's going on?
OS X Yosemite 10.10
tcpdump version 4.3.0 -- Apple version 59
libpcap version 1.5.3 - Apple version 47

I'm actually trying to sudo tcpdump -w - | tee file.pcap | tcpdump -r -, which gives rise to the same problem—however it appears to arise with any form of piped input.

A: This is still an issue with OS X Mojave 10.14.2 (libpcap 1.0.1 Apple 79.200.4, tcpdump 4.9.2 Apple 83.200.2). It's ultimately a bug in Apple's patches to libpcap and tcpdump.
In addition to using upstream tcpdump (which is available in Homebrew), you could also:

*

*Use tshark (part of Wireshark), which works similarly to tcpdump.

*Write the packets to a temporary file.

*Prefix the stream with 4 null bytes:
sudo tcpdump -i en0 -w - | cat <(printf "\0\0\0\0") - | tcpdump -nvr -
Cause (and why inserting nulls works)
Apple has patched their tcpdump such that it tries to read files as PCAP-NG format first:
#else /* __APPLE__ */
        pd = pcap_ng_open_offline(RFileName, ebuf);

They also added a -P option to emit packets in pcapng format.
pcap_ng_open_offline ends up in pcap_fopen_offline_internal(..., isng=1).  This flow calls pcap_ng_check_header early (see if (isng) in pcap_fopen_offline_internal), and on failure, jumps into the bad: label.
That bad: label attempts to fseeko to seek the file back to the start:
 bad:
    fseeko(fp, offset, SEEK_SET);
    if (p != NULL)
        free(p);
    return (NULL);

But you can't seek a FIFO, so we're still reading from the same spot!  fseeko would return an error, but this error is ignored.
On pcap_ng_open_offline returning an error, Apple's patch then calls pcap_open_offline, which follows a similar control flow to normal pcap. However, because the file pointer on the FIFO is still forward by 4 bytes, the next set of headers have the fifo's magics, and so tcpdump gives up.
You can work around this by inserting 4 extra NULL bytes at the start of your pipe, with a little shell-script trickery:
tcpdump -i en0 -w - | cat <(printf "\0\0\0\0") - | tcpdump -nvr -

This means that when fseeko fails, you'll be in the correct spot in the FIFO for the "actual" magic.
However, there are still some limitations:

*

*tcpdump -P (Apple-specific pcapng flag) still doesn't work.

*These files are no longer valid pcap files. If you wanted to read it with another tool (or even a non-Apple tcpdump), you'll need to tee the output before cat.

This also works with tshark (which can output pcapng, and doesn't work as a source without this work-around):
tshark -F pcapng -w - | cat <(printf "\0\0\0\0") - | tcpdump -nvr -

However, I wouldn't suggest putting this work-around in anything long term.
It will break once Apple fixes this bug, or if your users have a non-Apple tcpdump on OSX (such as with Homebrew).

A: I have the same problem on Mavericks (10.9.5).  It's probably not the best answer but I downloaded the open source version of tcpdump (tcpdump-4.6.2) and put it in my path before the system version and it works with pipes.  Of course, you lose the extra Apple-specific functionality.


text:
Q: Get drive letters of USB 3.0 devices (Java under Windows) My Java program needs to get a list of the drive letters of connected USB devices, but only those that support USB 3.0 (both the device and the USB port it is plugged into, so that it works with high speed).
Currently I try to use WMI through a PowerShell command my Java programm executes.
I already found this: Powershell: Grab USB Drive letter. But it would also list USB 2.0 devices.
Regarding version detection I found this: How to check the version of the available USB ports? - The PowerShell command I tried is Get-WmiObject Win32_USBHub. This brings up several problems. First: It lists far more stuff than only USB drives (I think also all the USB hubs of my PC). Second: Even though there is a field USBVersion for all items in the list it is always empty.
Update
The essence of my research over the last days is, that there are 2 realms of information I need to connect.

*

*Drives / Logical Drives

*

*Drive Letter

*BusType (is equal to "USB" for my matter)

*USB devices

*

*Vendor ID and Product ID (VID&PID)

*bcdUSB (value within the usb device descriptor, indicating USB Version)

For a given drive letter I need to find the bcdUSB value. But I haven't found a way to get the drive corresponding to a USB device.
What I tried so far
WMI over PowerShell
Relevant commands I found are
Get-Disk               // Get BusType
gwmi Win32_LogicalDisk // Get drive letter
// Those make the connection between disk and logical disk
gwmi Win32_LogicalDiskToPartition
gwmi Win32_LogicalDiskToPartition

Even though I get the BusType I couldn't make a connection to bcdUSB
usb4java (Link)
I only get information from the USB device realm here. I can load devices and see ther VID&PID and the bcdUSB value, but no way to map this to drives and drive letters.
lsusb via Cygwin
According to this post the linux command is easier to handle than WMI. So I tried to use it under Windows. But I like usb4java I only got VID&PID + bcdUSB, not the mount point (drive letter).
Searching the Windows Registry
I did a few string searchs in the Windows registry. No success.
Reading Windows Event log
I thought about ovserving Windows events to detect what Drive and what USB device connect at the same time. I didn't even find events when plugging in a USB stick.

A: Maybe this is what you are looking for:
Find Windows Drive Letter of a removable disk from USB VID/PID
At least someone marked the answer as working... :-)

A: Since the suggested Link solves this problem for C# not Java and leaves out one step, I'll post my final code here.
Summary
In Java

*

*Use USB4Java to find all connected USB devices with bcdUSB=0x0300

*Get Vendor ID and Product ID (VID&PID) for that devices

Via Powershell (with jPowerShell)

*

*Get PnPEntity for given VID&PID

*Get related USB Controller

*Find associator of that USB Controller that is associated with a disk drive

*Get that Disk drive

*Get related disk partition

*Get related logical disk -> LogicalDisk.DeviceID = Drive Letter

Code
Java class:
class UsbDetector {

  private PowerShell shell;

  @PostConstruct
  private void init() {
    shell = com.profesorfalken.jpowershell.PowerShell.openSession();
  }

  @OnDestroy
  private void onShutdownHook() {
    shell.close();
  }

  /**
   * Get drive letters of USB 3.0 devices.
   */
  public List<String> getDriveLettersForUsb3Devices() throws IOException, UsbException {
    List<UsbDevice> devicesUSB3 = getAllUsb3Devices();

    ImmutableList.Builder<String> driveLetterList = ImmutableList.builder();
    for (UsbDevice device : devicesUSB3) {
      String vidAndPid = getVidAndPid(device);

      String powerShellScript = buildScript(vidAndPid);

      String driveLetter = executeOnPowerShell(powerShellScript);
      driveLetterList.add(driveLetter);
    }

    return driveLetterList.build();
  }

  private String executeOnPowerShell(String powerShellScript) {
    InputStream psScriptStream = new ByteArrayInputStream(powerShellScript.getBytes());
    BufferedReader psScriptReader = new BufferedReader(new InputStreamReader(psScriptStream));

    PowerShellResponse response = shell.executeScript(psScriptReader);

    return response.getCommandOutput();
  }

  private String buildScript(String vidAndPid) throws IOException {
    InputStream psScriptStream =
        getClass().getClassLoader().getResourceAsStream("GetUsbDrives.ps1");

    String psScript = IOUtil.toString(psScriptStream);

    psScript = String.format("$input=\"%s\"", vidAndPid) + "\n" + psScript;
    return psScript;
  }

  /**
   * The Vendor ID and Product ID are necessary to find the device via WMI.
   */
  private String getVidAndPid(UsbDevice device) {
    short vendorId = device.getUsbDeviceDescriptor().idVendor();
    short productId = device.getUsbDeviceDescriptor().idProduct();

    String vendorIdHexString = String.format("%04x", vendorId).toUpperCase();
    String productIdHexString = String.format("%04x", productId).toUpperCase();

    String vidAndPid = String.format("VID_%s&PID_%s", vendorIdHexString, productIdHexString);
    return vidAndPid;
  }

  /**
   * From all Usb devices find those with USB 3.0. The value bcdUsb is a hexadecimal coded number
   * telling us the USB version.
   */
  private List<UsbDevice> getAllUsb3Devices() throws UsbException {
    List<UsbDevice> devicesUSB3 = Lists.newArrayList();
    UsbServices services = new org.usb4java.javax.Services();

    UsbHub hub = services.getRootUsbHub();
    List<UsbDevice> devices = getAllUsbDevices(hub);
    for (UsbDevice device : devices) {
      UsbDeviceDescriptor descriptor = device.getUsbDeviceDescriptor();
      short bcdUsb = descriptor.bcdUSB();
      String bcdDecoded = DescriptorUtils.decodeBCD(bcdUsb);

      if (Objects.equal(bcdDecoded, "3.00")) {
        devicesUSB3.add(device);
      }
    }
    return devicesUSB3;
  }

  /**
   * UsbHubs can either mount UsbDevices or further UsbHubs. This method searches through the tree
   * of UsbHubs for UsbDevices and returns them as list.
   */
  private List<UsbDevice> getAllUsbDevices(UsbHub hub) {
    List<UsbDevice> devices = Lists.newArrayList();

    List<UsbDevice> attachedDevices = hub.getAttachedUsbDevices();
    for (UsbDevice device : attachedDevices) {
      if (device instanceof UsbHub) {
        List<UsbDevice> subdevices = getAllUsbDevices((UsbHub) device);
        devices.addAll(subdevices);
      } else {
        devices.add(device);
      }
    }
    return devices;
  }

}

PowerShell script:
# $input = "VID_XXXX&PID_XXXX (this line is added in Java Code)

# For given VID and PID of a USB device we search for
# the corresponding logical disk to get the drive letter.

# The chain of objects is:
# PnPEntity (PnP = Plug and Play)
# -> USBController
# -> Some associator of USBController that has a related disk drive
# -> diskDrive
# -> diskPartition
# -> logicalDisk

# Find PnPEntity for given VID and PID
$usbPnPEntity = (gwmi Win32_PnPEntity | where DeviceID -match $input)

# Get USB Controller related to PnP Entity
$usbController = $usbPnPEntity.getRelated("Win32_USBController")
$usbControllerID = $usbController.DeviceID

# Find objects associated with the USB Controller
$query = "ASSOCIATORS OF {Win32_USBController.DeviceID='$usbControllerID'}"
$associators = ([wmisearcher]$query).get()

# Search through associators
foreach ($associator in $associators) {
    # Find associator that is related to a disk Drive
    $assoDeviceID = $associator.DeviceID
    $diskDrive = (gwmi win32_diskdrive | where PNPDeviceID -eq $assoDeviceID)

    if($diskDrive){
        # Get logical Disk related to the disk drive
        $logicalDisk = $diskDrive.getRelated("Win32_DiskPartition").getRelated("Win32_LogicalDisk")

        # Print device ID which is the drive letter (e.g. "C:")
        $logicalDisk.DeviceID
        break
    }

}

Maven dependencies:
    <dependency>
        <groupId>org.usb4java</groupId>
        <artifactId>usb4java-javax</artifactId>
        <version>1.3.0</version>
    </dependency>
    <dependency>
        <groupId>com.profesorfalken</groupId>
        <artifactId>jPowerShell</artifactId>
        <version>3.1.1</version>
    </dependency>


text:
Q: Is AWS s3 "Put Object - copy" performed async? Suppose I have a huge file in Amazon S3 (1 GiB, for example). If I call the put object - copy operation to create a copy in another bucket, will Amazon S3 respond the HTTP request only after the actual copy is finished (holding my TCP connection), or will it just respond with a "OK, your object will be copied" (releasing my TCP connection)?
I couldn't find the answer in the operation description.
The proposal document of the operation seems to mention something about my question, but it's not clear enough (actually a bit confusing):

Since we want to mitigate the possibility for time outs during long copy operations, the response to a copy is slightly different than other operations in Amazon S3—once Amazon S3 initiates the actual copy, it will respond with a 200 response. To determine whether the copy was successful, check the returned body for a CopyObjectResult body, which will contain the LastModified date and ETag of the uploaded object. If the copy fails, Amazon S3 might respond with a non-200 error as it does today.
The returned data is an XML document. After the XML declaration, there are a number of whitespace characters that you must read, after which there will be either a CopyObjectResult element or a standard error document. The number of whitespace characters sent to you will be determined by the time required for Amazon S3 to perform the copy operation.

A: I found it in another AWS Doc, it may clear your confusion:

A copy request might return an error when Amazon S3 receives the copy
  request or while Amazon S3 is copying the files. If the error occurs
  before the copy operation starts, you receive a standard Amazon S3
  error. If the error occurs during the copy operation, the error
  response is embedded in the 200 OK response. This means that a 200 OK
  response can contain either a success or an error. Design your
  application to parse the contents of the response and handle it
  appropriately.
  If the copy is successful, you receive a response with information about the copied object.

AWS Put Object - Copy
Although, it doesn't say anything about copy being a async. In general, put object for large files is usually multipart requests.

A: In PHP SDK (not sure others, but it may be similar) there have different methods to copy.
Document is in here.
1. CopyObject
This works sync, which means it will wait until finish the job.
$client->copyObject($args)
$args is key-value array, detail is in the document.
2. CopyObjectAsync
This works async, which means server will not wait the job.
$client->copyObjectAsync($args)

A: There is a CopyObjectAsync method in various APIs (Jave, .net, ruby, etc.), and a CopyObjectRequest class, and, as usual, AWS' documentation is really terrible to search.


text:
Q: Rotate big size image gives error in php When I am rotating small images by rotateImage() function then its working fine.But in case large file (5500 X 3000px) it gives error. How we handle large images in php.
// Content type
header('Content-type: image/jpeg');
// Load
$source = imagecreatefromjpeg($filename);
// Rotate
$rotate = imagerotate($source, $degrees, 0);
imagejpeg($rotate,'new.jpg');

When we rotate image its memory size and dimensions increased gives and it gives out of memory error.I want to rotate image similar photo-shop rotate operation every thing is same as original image.

A: My guess is that you are running out of memory if it works on small images but not large ones.   If this is the case you can increase the memory limit in php.ini with memory_limit .
You should also run through your script and make sure you are not copying things unnecessarily. Try to do in-place modification.


text:
Q: iphone cbc encryption returning null I have the following code inside the NSData+AES256 class. I am trying AES CBC encryption to a NSString with the following code. I have a key and a iv. But getting null in result. Can not find out what's wrong. This is what I tried-
NSString *initV= @"somekey*********";
NSData *input= [initV dataUsingEncoding:NSUTF8StringEncoding];

size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCModeCBC,
                                      keyPtr, kCCKeySizeAES256,
                                      [input bytes] /* initialization vector (optional) */,
                                      [self bytes], dataLength, /* input */
                                      buffer, bufferSize, /* output */
                                      &numBytesEncrypted);

A: This is the code that worked for me finally-
-(NSData *)AES256EncryptWithKey:(NSString *)key {
NSUInteger dataLength = [self length];
NSData *keyGiven= [key dataUsingEncoding:NSUTF8StringEncoding];

size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);

NSString *initV= @"***************";
NSData *input= [initV dataUsingEncoding:NSUTF8StringEncoding];

size_t numBytesEncrypted = 0;

CCCryptorRef ccRef;
CCCryptorCreate(kCCEncrypt, kCCAlgorithmAES128, 0, (const void *)[keyGiven bytes], kCCKeySizeAES256, (const void *)[input bytes], &ccRef);
CCCryptorStatus cryptStatus = CCCryptorUpdate(ccRef, [self bytes], dataLength, buffer, bufferSize, &numBytesEncrypted);
CCCryptorRelease(ccRef);

if (cryptStatus == kCCSuccess) {
    return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer); //free the buffer;
return nil;
}

I am converting an NSString to NSData and passing it for encryption. The NSString must be of 16 characters. If it is of less than 16 characters I make it 16 by appending spaces.
I don't know if this is going to help anybody. But I just thought I should share. Thanks.


text:
Q: jQuery: Convert TextArea content to html string and vice versa what I'm trying to do is converting a TextArea content into a valid html code. Suppose you type inside the TextArea and then you press a button that shows the typed text inside a element. If you typed something like inside the TextArea:

Hi folks!
  Do you like jQuery?
  I do!

The resulting string you have to put inside the '' element is:
Hi folks!
Do you like jQuery?
I do!

That's because the newline inside the TextArea must be converted to the
 tag!
The same thing should happend if you want to take the html of the  element and put it inside the TextArea input field, for example:
Hi folks!
Do you like jQuery?
I do!

should be converted to:

Hi folks!
  Do you like jQuery?
  I do!

So, is there a way to convert a string to html-string (and vice versa) or should I write a function by myself?
Thanks in advance!

A: With the appropriate styling on the element, you shouldn't need to convert anything.  Using the CSS white-space property with a value set to pre, any white-space in the element should appear exactly as it does in the textarea:
#myElement { white-space: pre; }

Example:  http://jsfiddle.net/TkpSu/

A: Consider looking into a markdown editor.  Stack overflow uses a modified version of this one: http://wmd-editor.com/

A: Well, it's not very difficult:
$('#element').html($('textarea').html().replace(/\n/g, "
"));


text:
Q: How to get the key value pair from a json array string I called someone web api method that return a list:
"[{"departmentNumber":"1","departmentName":"food"},{"departmentNumber":"2","departmentName":"beverage"},{"departmentNumber":"3","departmentName":"apparel"}]"

My Department class:
public class Department
{
    private int _departmentID;
    private string _departmentName;

    public Department(int DepartmentID, string DepartmentName)
    {
        this._departmentID = DepartmentID;
        this._departmentName = DepartmentName;
    }

    public int DepartmentID
    {
        get { return _departmentID; }
        set { _departmentID = value; }
    }

    public string DepartmentName
    {
        get { return _departmentName; }
        set { _departmentName = value; }
    }
}

The problem is that my when I try to deserialize the json string back into a List, only the DepartmentName data was able to bind but departmentNumber was not because my class have have the property as DepartmentID.  How can I know about fixing this without having to change my class?

A: Using Json.Net
public class Department {
    [JsonProperty("departmentNumber ")]
    public int DepartmentNumber {get;set;}
    [JsonProperty("departmentName ")]
    public string DepartmentName {get;set;}
}

List<Department> departments = JsonConvert.DeserializeObject<List<Department>>(jsonString);

A: You can do something like this.
const departments = [{"departmentNumber":"1","departmentName":"food"},{"departmentNumber":"2","departmentName":"beverage"},{"departmentNumber":"3","departmentName":"apparel"}];

departments.forEach(value => {
  console.log(value.departmentName)
  console.log(value.departmentNumber)
})


text:
Q: Highlight Wordpress parent menu item when submenu link active I have a simple menu in Wordpress.
I need to highlight the ACTIVE PARENT MENU ITEM when a submenu item is selected.
The problem is, whenever I do that via current-page-parent/current-page-ancestor - ALL menu items in the dropdown are have the active style applied to them as well as the parent.
Any ideas how I can do this without touching the submenu item styles?

Parent Menu Item

Sub-menu Item

A: WordPress automatically add some classes to the ancestor of the current item, that you can use to highlight the parent item. You can see in your code, how WordPress added the classes current-page-ancestor and current-menu-ancestor.
I recommend you to use .current-menu-ancestor because it will work with all the object types.


text:
Q: Что быстрее? CREATE TABLE IF NOT EXISTS `categorys` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `parent_id` int(10) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=cp1251 AUTO_INCREMENT=139 ;

-- --------------------------------------------------------
CREATE TABLE IF NOT EXISTS `category_product` (
  `id_product` int(10) unsigned NOT NULL,
  `id_category` int(10) unsigned NOT NULL,
  KEY `id_product` (`id_product`),
  KEY `id_category` (`id_category`)
) ENGINE=MyISAM DEFAULT CHARSET=cp1251;

*

*
SELECT * FROM
`categorys`,`category_product` WHERE
`id`=`id_category` AND `id_product`=23

*
SELECT * FROM `categorys` INNER JOIN
`category_product` ON
`id`=`id_category` WHERE
`id_product`=23

*
SELECT * FROM `categorys` WHERE `id`
IN (SELECT `id_category` FROM
`category_product` WHERE
`id_product`=23)

A: На меленьких таблицах мерить бесполезно, результаты будут <5-7ms.
Код на SQLFIddle
По EXPLAIN запросы 1,2 одинаковые, в запросе 3 надо перебирать всю таблицу, вообщем, я бы 3-й не стал использовать.
A: Посмею предположить, что 2 вариант. Но время выполнения запроса не мерял =)
Только мне кажется правильнее будет так:
SELECT * FROM categorys INNER JOIN category_product ON categorys.id=category_product.id_category WHERE id_product=23


text:
Q: Getting data with UTF-8 charset from MSSQL server using PHP FreeTDS extension I can't seem to get data from MSSQL encoded as UTF-8 using FreeTDS extension.
Connecting:
ini_set('mssql.charset', 'UTF-8');
$this->_resource = mssql_connect($config['servername'], $config['username'], $config['password']);

I have no ability to use any other extension.
I've tried creating ~/.freetds.conf
[global]
client charset = UTF-8

I've tried passing parameters to php:
php -d mssql.charset="UTF-8" index.php

Data is still not in UTF-8.
php -i
mssql

MSSQL Support => enabled
Active Persistent Links => 0
Active Links => 0
Library version => FreeTDS

Directive => Local Value => Master Value
mssql.allow_persistent => On => On
mssql.batchsize => 0 => 0
mssql.charset => no value => no value
mssql.compatability_mode => Off => Off
mssql.connect_timeout => 5 => 5
mssql.datetimeconvert => On => On
mssql.max_links => Unlimited => Unlimited
mssql.max_persistent => Unlimited => Unlimited

Ideas?

A: I had a similar problem and tried all settings i could find on the web - in vain.
In my case the problem was the configuration of FreeTDS itself. On Linux the file is /etc/freetds/freetds.conf
I had to change the Version to 7.0 (maybe other numbers work, too. i just tried 7.0)
[global]
    # TDS protocol version
    tds version = 7.0

After this, the driver seemed to accept changes of the charset like.
ini_set('mssql.charset', 'UTF-8');

Btw: the change immediately is in effect, no need to restart anything afterwards

A: It seem version 7.0 or great is required. iconv() also seems to work well, but is tedious.
$query = $this->db->query($sql);
$result = $query->fetchAll(PDO::FETCH_OBJ);
foreach ($result as $row) {
    foreach (get_object_vars($row) as $key => $value) {
    $row->$key = (mb_detect_encoding($value, mb_detect_order(), true) === 'UTF-8')
            ? $value : iconv('iso-8859-1', 'utf-8', $value);
    }
    $results[] = $row;
}

A: I had this problem and it solved by adding this line to my php script before connecting to MSSQL Server:
ini_set('mssql.charset', 'UTF-8');

A: MSSQL and UTF-8 are quite a pain in the ... sometimes. I had to convert it manually.
The problem: MSSQL doesn't actually know and support UTF-8.
Convert from database value to UTF-8:
mb_detect_encoding($value, mb_detect_order(), true) === 'UTF-8' ? $value : mb_convert_encoding($value, 'UTF-8');

Converting from UTF-8 to database value:
mb_convert_encoding($value, 'UCS-2LE', mb_detect_encoding($value, mb_detect_order(), true));

Fortunately I was using Doctrine so all I had was to create a custom StringType implementation.

A: If you use freeTDS, you should change below lines on /etc/freetds/freetds.conf:
[global]
# TDS protocol version
tds version = 4.2

To this:
[global]
# TDS protocol version
tds version = 8.0
;tds version = 4.2

and finally add this line:
# set charset
client charset = UTF-8

** clinet charset is in global [scope]
In your queries, you should use N character. like this:
$query = "INSERT INTO dbo.SMSOutbox (StationID, Dest, Text) VALUES ";
   $query .= '(';
   $query .= "'" . $this->stationId . "', ";
   $query .= "'" . $this->destination . "', ";
   $query .= "N'" . $this->text . "'";
   $query .= ')';

A: You can also solve this issue by adding CharacterSet UTF-8 in the $connectionInfo before connecting to the DB.
$serverName = "MyServer";
$connectionInfo = array( "Database"=>"AdventureWorks", "CharacterSet" => "UTF-8");
$conn = sqlsrv_connect( $serverName, $connectionInfo);

Worked fine NO additional encoding needed.

A: You should change your TDS version based on what version of SQL server your using.
Check out the installation guide for details.
http://www.freetds.org/userguide/choosingtdsprotocol.htm

A: I used same as above but windows 1250, so:
$query = $this->db->query($sql);
$result = $query->fetchAll(PDO::FETCH_OBJ);
foreach ($result as $row) {
    foreach (get_object_vars($row) as $key => $value) {
    $row->$key = (mb_detect_encoding($value, mb_detect_order(), true) === 'UTF-8')
            ? $value : iconv('windows-1250', 'utf-8', $value);
    }
    $results[] = $row;
}

And then it worked, but I use polish characters


text: Q: Can I use Google Wallet's send/request money feature with my app? Google's Android Pay API seems to be about receiving payments from clients. But I was wondering if I could direct users from my app to Google Wallet so they could send money to or request money from their friends. Like, ideally I could create an intent and set the recipient's e-mail, the amount of money, and whether they are sending or requesting as extras, and then it would open the Google Wallet app with that information already filled in.


text:
Q: css popup doesn't work on the last rows of table HI guys!
So I've a table in html. And one of the columns has a popup in the cell to show some information. the table is also quite large so I've added an horizontal scrollbar on the top and bottom of the page with jquery, with the help of @Stanley, see question.
The popup always stays at the bottom of the cell. But the scrollbar hides the last ones.
So what I would like is the popup to stay above the scrollbar.
I tried put
z-index: 999; #popup hover
z-index: 1; #scrollbar

but that doesn't work.
Anyone has any idea?
If any code is needed, just ask.
Thank you all!

A: use firefox firebug and position it using
 css  top:100px,left:100px.

can you increase width of table?
 actually i had a similar issue .
 i put an empty table with height of popup below the first table (you show popup on clicking of this tables columns).
So the popup will not hide, or go inside the scroll.

on click or mouse over show popup

on click or mouse over show popup

on click or mouse over show popup

as this the last td popup was going inside the scroll so i put table below

If this not at all your situation. pardon me  . :)

A: In the template, at the bottom:

Javascript file:
function make_tooltip () {
   var tooltip = $(this);
   var flyer = $("#popup-flyer");
   flyer.css('position', 'absolute');
   flyer.css('left', tooltip.position().left + 30);
   flyer.css('top', tooltip.position().top);
   flyer.append(tooltip.children('span').clone());
   flyer.show(1);
};

function hide_tooltip () {
   var tooltip = $(this);
   var flyer = $("#popup-flyer");
   flyer.hide(1);
   flyer.children('span').remove();
};

$(document).ready( function () {
$(".tooltip").hover(make_tooltip, hide_tooltip);
});

the css:
a class='tooltip'>

                     lalalakalsjsjhfksajhfdsh
                           text here....


text:
Q: Unable to get block cookie value in Internet Explorer 11 Hi Anyone please help me:
var cookieBlockedUrl = ""<%URL%>"";
var cookieName = ""cmdTestCookie"";
xDeleteCookie(cookieName); // don't get false positive
document.cookie = cookieName + ""=test; path=/"";
var cookieString = document.cookie || """";
var cookies = cookieString.split(/\s*;\s*/);
var cookieFound = 0;
for (var i in cookies) {
var cookie = cookies[i];
var dough = cookie.split(/\s*=\s*/);
if (dough[0] == cookieName) {
cookieFound = 1; break;
}
}
xDeleteCookie(cookieName);
if (cookieFound != 1) {
window.location = cookieBlockedUrl
}
function xDeleteCookie(name) {
var oldDate = new Date(1970, 1, 1);
document.cookie = cookieName + ""=0; expires="" + oldDate.toGMTString();
}"

Above code is for redirecting to a specific page if the cookies are blocked from the browser the page is redirecting in every browser but not only in Internet Explorer 11


text:
Q: Can't use PLOS rticles template with bookdown Following this post, I'm trying to put @YihuiXie 's answer in practice with the PLOS template of rticles but it doesn't work. Any help would be very appreciated!
Below in a minimal example:
---
title: Title of submission to PLOS journal
author:
  - name: Me
    affiliation: Here

# output: rticles::plos_article
output:
  bookdown::pdf_document2:
    base_format: rticles::plos_article
---

# Introduction

Some text \@ref(fig:fig1)

# References {#references .unnumbered}

The error message reads
Error in pdf_book(..., base_format = rmarkdown::pdf_document) :    formal argument "base_format" matched by multiple actual arguments
Calls: <Anonymous> -> create_output_format -> do.call -> <Anonymous>
Execution halted

A: You cannot change the base_format for bookdown::pdf_document2. You can do so for bookdown::pdf_book, though:
---
title: Title of submission to PLOS journal
author:
  - name: Me
    affiliation: Here

#output: rticles::plos_article
output:
  bookdown::pdf_book:
    base_format: rticles::plos_article
---

# Introduction

Some text \@ref(fig:fig1)

# References {#references .unnumbered}

Note to other readers: Make sure that .../rticles/rmarkdown/templates/plos_article/skeleton/PLOS-submission.eps is present in that directory.


text:
Q: how to make apache hosted website url requests case insensitive I have my page1.php file located inside
/public_html/mypages/page1.php
if user requests www.myurl.com/Mypages/Page1.php  is returning file not found
how can I ensure that each each request is handled irrespective of the case
I am using godaddy linux server
from their support page
https://support.godaddy.com/help/article/899/how-do-i-use-mod_rewrite
I came to know that it can be done from .htaccess
so I added a .htaccess to /public_html/mypages/
http://www.chrisabernethy.com/force-lower-case-urls-with-mod_rewrite/
here is the content of my .htaccess file
RewriteEngine On
RewriteMap  lc int:tolower
RewriteCond %{REQUEST_URI} [A-Z]
RewriteRule (.*) ${lc:$1} [R=301,L]

after this when I try to access  any file www.myurl.com/Mypages/Page1.php its giving internal server error. Please help me resolve this issue .
I also tried adding
<IfModule mod_speling.c>
CheckSpelling On
CheckCaseOnly On
</IfModule>

and now I am not getting internal server error ,but I am getting

"file not found error"

www.myurl.com/mypages/page1.php  -->working fine.
 but
www.myurl.com/mypages/Page1.php  --> "file not found error"

A: If you can load the mod_speling module. use this:
RewriteEngine On
AllowOverride All
CheckSpelling on

Otherwise; if you can't (you don't have control of it) force lowercase URLs with mod_rewrite (like you wrote on your question)
RewriteEngine On
RewriteMap  lc int:tolower
RewriteCond %{REQUEST_URI} [A-Z]
RewriteRule (.*) ${lc:$1} [R=301,L]

Since your .htaccess was inside a folder and now is in the document root (public_html) try to add your rewrite. Maybe it was just an issue because, it wasn't in the document root.

A: To solve this issue ,I changed all my file names to lowercase ,and added the following to .htaccess . (as suggested here )
RewriteCond %{REQUEST_URI} !([A-Z]+)
RewriteRule .* - [S=27]
RewriteRule ^(.*)A(.*)$ http://%{HTTP_HOST}/$1a$2 [R=301,L]
RewriteRule ^(.*)B(.*)$ http://%{HTTP_HOST}/$1b$2 [R=301,L]
RewriteRule ^(.*)C(.*)$ http://%{HTTP_HOST}/$1c$2 [R=301,L]
RewriteRule ^(.*)D(.*)$ http://%{HTTP_HOST}/$1d$2 [R=301,L]
RewriteRule ^(.*)E(.*)$ http://%{HTTP_HOST}/$1e$2 [R=301,L]
RewriteRule ^(.*)F(.*)$ http://%{HTTP_HOST}/$1f$2 [R=301,L]
RewriteRule ^(.*)G(.*)$ http://%{HTTP_HOST}/$1g$2 [R=301,L]
RewriteRule ^(.*)H(.*)$ http://%{HTTP_HOST}/$1h$2 [R=301,L]
RewriteRule ^(.*)I(.*)$ http://%{HTTP_HOST}/$1i$2 [R=301,L]
RewriteRule ^(.*)J(.*)$ http://%{HTTP_HOST}/$1j$2 [R=301,L]
RewriteRule ^(.*)K(.*)$ http://%{HTTP_HOST}/$1k$2 [R=301,L]
RewriteRule ^(.*)L(.*)$ http://%{HTTP_HOST}/$1l$2 [R=301,L]
RewriteRule ^(.*)M(.*)$ http://%{HTTP_HOST}/$1m$2 [R=301,L]
RewriteRule ^(.*)N(.*)$ http://%{HTTP_HOST}/$1n$2 [R=301,L]
RewriteRule ^(.*)O(.*)$ http://%{HTTP_HOST}/$1o$2 [R=301,L]
RewriteRule ^(.*)P(.*)$ http://%{HTTP_HOST}/$1p$2 [R=301,L]
RewriteRule ^(.*)Q(.*)$ http://%{HTTP_HOST}/$1q$2 [R=301,L]
RewriteRule ^(.*)R(.*)$ http://%{HTTP_HOST}/$1r$2 [R=301,L]
RewriteRule ^(.*)S(.*)$ http://%{HTTP_HOST}/$1s$2 [R=301,L]
RewriteRule ^(.*)T(.*)$ http://%{HTTP_HOST}/$1t$2 [R=301,L]
RewriteRule ^(.*)U(.*)$ http://%{HTTP_HOST}/$1u$2 [R=301,L]
RewriteRule ^(.*)V(.*)$ http://%{HTTP_HOST}/$1v$2 [R=301,L]
RewriteRule ^(.*)W(.*)$ http://%{HTTP_HOST}/$1w$2 [R=301,L]
RewriteRule ^(.*)X(.*)$ http://%{HTTP_HOST}/$1x$2 [R=301,L]
RewriteRule ^(.*)Y(.*)$ http://%{HTTP_HOST}/$1y$2 [R=301,L]
RewriteRule ^(.*)Z(.*)$ http://%{HTTP_HOST}/$1z$2 [R=301,L]
RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1 [R=301,L]

Now I don't see any errors and it accepts the requests irrespective of the case.


text:
Q: how to isolate yellow part of the picture and make black other parts? This is the image:

I want to turn all the colours to black except yellow and tried this code but showing an error can anyone please help?
import cv2 as cv
import numpy as np
img = cv.imread('Screenshot 2022-04-10 at 10.02.19 AM.png',1)
if(img.any() == [255, 255, 0]):
   cv.imshow('image',img);

else:
   ret , thresh1 = cv.threshold(img,500,255,cv.THRESH_BINARY);
cv.imshow("Timg",thresh1);
cv.waitKey(0)
cv.destroyAllWindows()

The error is showing for the if conditional statement.
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

A: Steps:  TLDR;

*

*Convert image to LAB color space

*Otsu Threshold over b-component

*Mask the result over the original image in BGR color space

Code
# read the image in BGR
img = cv2.imread("image_path", 1)

# convert image to LAB color space
lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)

# store b-component
b_component = lab[:,:,2]

# perform Otsu threshold
ret,th = cv2.threshold(b_component, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)

# mask over original image
result = cv2.bitwise_and(img, img, mask = th)

Details
Why did I do this?
The LAB color space contains 3 channels:

*

*L-component: highlights brightness value

*a-component: represents color values between green and magenta

*b-component: represents color values between blue and yellow

Since your image comprised of blue, magenta and yellow, I opted for LAB color space.  And specifically the b-component because it highlights yellow color


text:
Q: How to create a DataSet from RDD using Case Class with composed columns Hi guys i using Spark/Scala 2.4.4 and have an RDD[Map(String, String)] with Persons... the rows are like this:
rdd = Map(
(FirstName -> "Michael")
(SecondName -> "Jackson")
)

I created a case class like this:
case class Person(FirstName: String, SecondName: String) {
    val FullName = FirstName + SecondName
}

how can i convert this RDD to a Dataset[Person], and it's possible to generate FullName column when the class are instantiated or i need to run withcolumn?
Thanks!

A: You need to expand the map into two columns and cast the rows as Person.
val rdd = sc.parallelize(Seq(Map(
    ("FirstName" -> "Michael"),
    ("SecondName" -> "Jackson")
)))

val df = rdd.toDF("person").select("person.FirstName", "person.SecondName").as[Person]

Then you can get the FullName using map, for example:
df.map(r => r.FullName).show
+--------------+
|         value|
+--------------+
|MichaelJackson|
+--------------+


text:
Q: Assign variable sized array to fixed sized array c I have a buffer of chars defined as char *buffer.  When I send my XBEE packet data, there is a fixed size requirement (84 bytes).  My problem is I don't know how to convert the buffer into 84 byte chunks as I iterate.  Here is what I get:
warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]
     packet = (buffer + i);
            ^

And my code:
int sendSerialBuffer(char *buffer, int length)
{
  int i = 0;
  int result = 0;
  char (* packet)[84];

  // Iterate through all the bytes in the buffer
  for (i = 0; i < length; i = i + 84)
  {
    packet = (buffer + i);
    result = sendPacket(packet)
  }
  return 0;
}

Edit:
I have also tried declaring packet like char packet[84]; and get:
error: assignment to expression with array type
     packet = (buffer + i);
            ^

Also, sendPacket is defined as:sendPacket(char packet[84]);

A: int i = 0;
int result = 0;

// Iterate through all the bytes in the buffer
for (i = 0; i < length; i = i + 84)
{
  char packet[84];
  memcpy(packet, buffer[i],84);
  result = sendPacket(packet);
}

return 0;

note this does not deal with the case where buffer is not exact multiple of 84
life would be easier if sendPAcket expected char * rather that char [84]. Then code would read
int i = 0;
int result = 0;

// Iterate through all the bytes in the buffer
for (i = 0; i < length; i = i + 84)
{
  char packet[84];
  memcpy(packet, buffer[i],84);
  result = sendPacket(buffer[i]);
}

return 0;

A: This doesn't work:
packet = (buffer + i);

Because the types are not the same.  packet has type char (*)[84] (i.e. a pointer to an array of 84 char) while buffer has type char *.  You actually don't need this extra type.
Given that sendPacket is defined as:
int sendPacket(char packet[84])

The parameter packet actually has type char *, since arrays as function parameters decay into a pointer to the first element.
You can then call this function as follows:
result = sendPacket(buffer + i)

The expression buffer + i evaluates to the address of element i in the buffer.  Assuming sendPacket reads 84 bytes from this address, it will grab the next 84 bytes in the buffer.


text: Q: Change file association to the file with the same name but different path I made file association to file path1/example.bat. After double-click to associated file in windows explorer was opened related batch file. Later I used open with in windows context menu to change association to path2/example.bat. Problem is, that after double-click in File explorer was path1/example.bat opened. I did try also an .exe file, with the same result. So problem should not be in my batch. PC restart does not help. There is value in Computer\HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FileExts\..., but is somehow hashed, I can not see path to batch file. Renaming to example2.bat helps, but this is not, what I want. Is this windows issue? Or what did I miss?


text:
Q: Issue in saving contacts to android - code attached I am trying to save the contact details to the android contacts through my application. I do not want to have the default contact application to do this job, instead I need to do this from my code directly. Here is the code which I use. After the button onclick, I would require to have the contact detail stored to the cntact in android, which, unfortunately is not happening.
Can someone please guide me where I am going wrong in this code and what need to be done in order to resolve the issue.
Any help in this regard is well appreciated.
Regards,
Rony
            ContentValues values = new ContentValues();
            values.put(Phone.NUMBER, "456456");
            values.put(Phone.TYPE, Phone.TYPE_WORK);
            Uri uri = getContentResolver().insert(Phone.CONTENT_URI, values);

A: I look for a solution for this problem and I found this.
http://developer.android.com/reference/android/provider/ContactsContract.Data.html
There are examples there for any kind of operations. This is the insert example.
 ContentValues values = new ContentValues();
 values.put(Data.RAW_CONTACT_ID, rawContactId);
 values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
 values.put(Phone.NUMBER, "1-800-GOOG-411");
 values.put(Phone.TYPE, Phone.TYPE_CUSTOM);
 values.put(Phone.LABEL, "free directory assistance");
 Uri dataUri = getContentResolver().insert(Data.CONTENT_URI, values);

I hope it helps you.


text:
Q: How to ensure that certain ID shows up only once in core data? So far, this is what I tried:
+(NSManagedObject *) getObjectWithStringOfValue:(NSString *) Value fromTable:(NSString*) table withAttribut:(NSString *) AttributName
{
    NSManagedObject * buffer=nil;
    @synchronized(self)
    {
        buffer=[self LookUpObjectWithAttributeValue:Value fromTable:table WithAttribut:AttributName];
        if (buffer == nil)
        {
            //CLog( @"gk boleh create");
            buffer=[self CreateNewObjectFromTable:table];
            [buffer setValue:Value forKey:AttributName];
            [BGMDCRManagedObjectContextThreadHandler commit];
            NSAssert([self LookUpObjectWithAttributeValue:Value fromTable:table WithAttribut:AttributName], @"Object must exist and must only be one");
        }
        else
        {
            //assert(!(buffer.isFault));
        }
    }

    return buffer;
}

Basically the @synchronized is necessary. It is possible that one thread see that there is no object create and another thread do the same thing and they both commit 2 objects instead.
However, this often cause deadlock.
In my implementation, every thread has their own moc. So [BGMDCRManagedObjectContextThreadHandler managedobjectcontext] will give moc to that thread. Every moc has the same parent, a main managedobject context created on the main thread.
The lock happen when executeFetchRequest inside LookUpObjectWithAttributeValue halt. On the other hand, the main thread also halt on @synchronized(self).
I wonder how to fix this?
Should I ensure that the main managedObjectContext not to be associated with main thread?

A: I rarely access core data directly. So there is only one line of code in the whole program that do excecuteFetchRequest, for example.
I do performBlockAndWait every time what a child do indirectly access the parent
[moc performBlockAndWait:^{
    saveSuccesfully = [moc save:&error];
    if (!saveSuccesfully) {
        CLog(@"Error in Saving %@", error);
    }
    else{
    }
}];

[moc performBlockAndWait:^{
    fetchedObjects = [moc executeFetchRequest:request error:&error];
}];

    [moc performBlock:^{
        if (![moc save:&error])
        {
            CLog(@"Error in Saving %@", error);// handle error
        }
    }];

No deadlock again since then.


text:
Q: Finding the indexes of values from a list to a different list Using Python 3, I want to iterate over the items in a first list in ascending order, and find the item's index in a second list to store it into a third result list.
Below is a working example:
list1 = [53, 65, 67, 37, 14, 98, 122, 124, 183]
list2 = [0, 14, 37, 53, 65, 67, 98, 122, 124, 183, 199]

wanted_output = getWantedOutput(list1, list2)

print(wanted_output)

>>> [3, 4, 5, 2, 1, 6, 7, 8, 9]

A: This approach is less readable than the other given answer, but it is faster if your list is long.
wanted_output = []
for item in list1:
    try:
        wanted_output.append(list2.index(item))
    except ValueError: # item not in list2
        continue

A: list1 = [53, 65, 67, 37, 14, 98, 122, 124, 183]
list2 = [0, 14, 37, 53, 65, 67, 98, 122, 124, 183, 199]

[list2.index(x) for x in list1 if x in list2]

Output:
[3, 4, 5, 2, 1, 6, 7, 8, 9]

A: The most efficient solution for long lists is to preprocess the second list and convert it into a dictionary where list items are keys and their positions are values. Then look up the elements from the first list in that dictionary:
positions = {item: pos for pos, item in enumerate(list2)}
[positions[item] for item in list1]
#[3, 4, 5, 2, 1, 6, 7, 8, 9]


text:
Q: Stripe Secret and Publishable key validation Is there any validation like length of key or any else for secret key and publishable key in Stripe account.
I want in Php, jQuery, javascript.

A: Stripe secret API keys start with either sk_live_ (for live keys) or sk_test_ (for test keys).
Similarly, Stripe publishable API keys start with pk_live_ or pk_test_.


text:
Q: Intersection Point of Two Lists JAVA Question: Given head nodes of two linked lists that may or may not intersect, find out if they intersect and return the point of intersection; return null otherwise.
Solution time:o(m+n),space o(1):

*

*Find lengths of both linked lists: L1 and L2

*Calculate difference in length of both linked lists: d = |L1 - L2|

*Move head pointer of longer list 'd' steps forward

*Now traverse both lists, comparing nodes until we find a match or
reach the end of lists

Here's the code:
public static LinkedListNode intersect(
    LinkedListNode head1,
    LinkedListNode head2) {

    LinkedListNode list1node = null;
    int list1length = get_length(head1);
    LinkedListNode list2node = null;
    int list2length = get_length(head2);

    int length_difference = 0;
    if(list1length >= list2length) {
      length_difference = list1length - list2length;
      list1node = head1;
      list2node = head2;
    } else {
      length_difference = list2length - list1length;
      list1node = head2;
      list2node = head1;
    }

    while(length_difference > 0) {
      list1node = list1node.next;
      length_difference--;
    }

    while(list1node != null) {
      if(list1node == list2node) {
        return list1node;
      }

      list1node = list1node.next;
      list2node = list2node.next;
    }
    return null;
}

However, I'm thinking is there a possible that the Intersection Point just appear at the position before d steps in the longer list? Like:

I'm confused, please help me clear my mind, thank you!

A: A node can only has one successor. While in the second picture, the intersection node get two successors, which is impossible.

A: No. That is not possible. Because after the intersection point, the rest of both lists should be the same which means that they should have

*

*the same length after that point

*each element after that point is the same.

So it is not possible before d steps since that will not satisfy point 1.

A: Your algorithm is correct. However, after the intersection point, its no longer two lists, its just one list.
So whatever difference d you have in no. of nodes, it is before the intersection point.

A: First thing, you cannot create singly linked list with your given input.
 A node can point only to single next node. In your  input, node points to two next nodes. You need to find the intersection point where the two lists converge. Your algorithm will find the intersection point immediately after 'd' nodes which is the expected output


text:
Q: Can't use two SPI devices at the same time I can use the MFRC522 using the following code:
#include <SPI.h>
#include <MFRC522.h>

MFRC522 mfrc522(10, 9);

void setup() {
    SPI.begin();
    mfrc522.PCD_Init();
}

void loop() {
    if (  mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial() ) {
         // Do stuff
    }
}

And it works great. I can also use the dot-matrix (8x8) using the following code:
#include "LedControl.h"

LedControl lc = LedControl(12,11,8,1);

void setup() {
    lc.shutdown(0,false);
    lc.setIntensity(0,3);
    lc.clearDisplay(0);

    lc.setLed(0,2,5,true);
    lc.setLed(0,5,5,true);

    lc.setLed(0,2,2,true);
    lc.setLed(0,3,1,true);
    lc.setLed(0,4,1,true);
    lc.setLed(0,5,2,true);
}

void loop() {
}

And it works just fine as well. However, when I try to use both of them using the following code:
#include <SPI.h>
#include <MFRC522.h>
#include "LedControl.h"

LedControl lc = LedControl(12,11,8,1);
MFRC522 mfrc522(10, 9);

void setup() {
    SPI.begin();
    mfrc522.PCD_Init();

    lc.shutdown(0,false);
    lc.setIntensity(0,3);
    lc.clearDisplay(0);

    lc.setLed(0,2,5,true);
    lc.setLed(0,5,5,true);

    lc.setLed(0,2,2,true);
    lc.setLed(0,3,1,true);
    lc.setLed(0,4,1,true);
    lc.setLed(0,5,2,true);
}

void loop() {
    if (  mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial() ) {
         // Do stuff
    }
}

In that case only one of them works (the MFRC522). I know that since they are connected in SPI mode they need to have different SS pins, so I used pin 10 for MFRC522 and pin 8 for dot-matrix. So, what's wrong? Why dot-matrix doesn't work at the same code with MFRC522??

A: Without the datasheets at hand, I'd first suspect that the two SPI devices have clock rates that are incompatible.  You need to find the clock rates for each one and either clock them off two different timers, or switch timing on a single timer to provide the correct clock rate for the currently selected device.  Incompatible clock rates has been the only problem I've ever had with SPI devices.


text:
Q: Concatenate signs, find text in Word doc and Range.MoveEndUntil Cset:= paragraph sign & "2" & ". " I have this macro that is run from Excel VBA editor and it searches strings in Word document, copies that string and pastes it into a cell in .Activesheet.Range("E27")
So I have this code and I'm already so close to making it work, but I need to concatenate four characters to make it work, paragraph sign (¶), & "2" & ". "
Sub AdjusFindFirstName()
    Sub AdjFindFirstName()
    'Variables declaration
    Dim WordApp As Word.Application
    Dim WordDoc As Word.Document
    Dim ExcelApp As Excel.Application
    Dim Rng As Word.Range

    Dim ws As Worksheet
    Dim TextToFind As String
    Dim ApartmentPrice As String
    Dim StartPos As Long
    Dim EndPos As Long
    Dim FullName As String
    Application.ScreenUpdating = False

    'Assigning object variables
    Set WordApp = GetObject(, "Word.Application")
    Set WordDoc = WordApp.ActiveDocument
    Set Rng = WordApp.ActiveDocument.Content
    'Searching
    With Rng.Find
    '.Text = TextToFind
    .Text = "REGON 364061169, NIP 951-24-09-783,"
    .Execute    '?Rng = REGON 364061169, NIP 951-24-09-783,
        If .Found = True Then
            Rng.MoveEndUntil Cset:="2" & ". "  'expands Rng variable until first "2. "
            Rng.MoveEnd wdWord, 3          'expands Rng variable wdWord, 3 further
                                           'wdParagraph, wdLine, wdSentence, wdScreen
            If Rng.Words.Last.Next.Text = "-" Then    'I want the text of the word following the last word in my range
               Rng.MoveEnd wdWord, 2    'expands Rng variable wdWord, 2 further
            End If
            StartPos = InStr(1, Rng.Text, "2. ")
            FullName = Mid(Rng.Text, StartPos + 3)
        End If
    End With
    Debug.Print FullName
End Sub

In fact I cannot even execute Range.MoveEndUntil Cset:= "2. "
I even tried Range.MoveEndUntil Cset:= "2" & ". "
These lines are not expanding my Rng variable by any word or character.
But what I really need  is finding/MovingEndUntill Cset:= "¶" & "2" & ". "
Here is the printscreen, where I've selected the string I need to .MoveEndUntil

Maybe you could tell me how to expand my Rng variable until the end of the current paragraph?

A: Careful reading of the Help topic for MoveEndUntil reveals that it looks only at individual characters, not character combinations:

Moves the end position of the specified range until any of the specified characters are found in the document.

There is no "Move" method that works in that manner. Word's Find feature, however, can locate character combinations. Adding an additional Find that runs from the first "found" term locates the information specified in the question. For example
Dim WordDoc As Word.Document
Dim rngStart As Word.Range, rngEnd As Word.Range

Set WordDoc = WordApp.ActiveDocument
Set rngStart = WordDoc.Content
'Searching
With rngStart.Find
'.Text = TextToFind
    .Text = "REGON 364061169, NIP 951-24-09-783,"
    .Execute    '?Rng = REGON 364061169, NIP 951-24-09-783,
    If .found = True Then
        'Instantiate a Range for the next search, starting with the first "found"
        Set rngEnd = rngStart.Duplicate
        'Extend that range to the end of the document
        rngEnd.End = WordDoc.Content.End
        With rngEnd.Find
            .Text = vbCr & "2. "
            .Forward = True
            .Execute
            If .found Then
                rngEnd.MoveEnd wdWord, 3
                If rngEnd.Words.Last.Next.Text = "-" Then    'I want the text of the word following the last word in my range
                    rng.MoveEnd wdWord, 2    'expands Rng variable wdWord, 2 further
                End If
            End If
        End With

        startPos = InStr(1, rngEnd.Text, "2. ")
        FullName = Mid(rngEnd.Text, startPos + 3)
    End If
End With


text:
Q: Visual Studio Code debug python script with ampersand in file path I am using VS Code and debugging a python script.  I'm in a conda environment.  I start debugging, and at each line of execution, I get an error like this:
Unable to open 'filename.py': File not found (file:///s:/path/word&morewords/etcetc/filename.py).

To be clear, this file that VS cannot find is the very same .py file that I have open in VS and am debugging.
It appears that where the ampersand occurs, it looks for "&" instead of just "&".  But the debugger works, insofar as it evaluates lines and gives results.  But at each line step, the error pops open again.  Changing the file path isn't really an option.
The actual path is:
s:/path/word&morewords/etcetc/filename.py

How can I make this error not happen?
Also, the line that is being executed is not highlighted when I am running the debugger.  So, I have no idea where I am unless I keep track.  Perhaps these issues are related, but I am not sure.

A: This has been verified as a bug.


text:
Q: why memcpy alters the string array? I have code which goes like this. Could you tell me why it is not behaving as I would expect it to be?
/*
 * test.cpp
 *
 *  Created on: Dec 6, 2012
 *      Author: sandeep
 */

#include<iostream>
#include<string.h>
using namespace std;

int main()
{
    int i=0;
    string s="hello A B:bye A B";
    char *input;
    input=new char(s.size());
    for(i=0;i<=s.size();i++)
        input[i]=s[i];
    char *tokenized1[2],*tokenized2[3];
    tokenized1[0]=strtok(input,":");
    tokenized1[1]=strtok(NULL,":");
    i=0;
    char *lstring;
    while(i<2)
    {
        lstring=new char(strlen(tokenized1[i]));
        memcpy(lstring,tokenized1[i],strlen(tokenized1[i])+1);
        cout<<tokenized1[0]<<"  "<<tokenized1[1]<<endl;
        tokenized2[0]=strtok(lstring," ");
        tokenized2[1]=strtok(NULL," ");
        tokenized2[2]=strtok(NULL," ");
        char c=tokenized2[0][0];
        cout<<c<<endl;
        cout<<tokenized2[0]<<"  "<<tokenized2[1]<<"  "<<tokenized2[2]<<endl;
        i++;
    }

}

and the output is this.
hello A B  by
h
hello  A  B
hello A B  by
b
by

There are some junk values at the end of 1st, 4th and 6th line of output.
Why tokenized1[1] got altered when I I did memcopy of tokenized1[0]? and how to solve this?

A: There's a couple of bugs in the following new call. You need to use square brackets; also, the argument is off by one.
lstring=new char[strlen(tokenized1[i]) + 1];

Without the square brackets, your are allocating space for one character. As a result, the memcpy() writes past the allocated memory.
edit: I just noticed the other new, which will also need to be fixed:
input=new char[s.size() + 1];

Finally, s[i] reads past the end of the string in:
for(i=0;i<=s.size();i++)
    input[i]=s[i];

There could well be other bugs, not to mention memory leaks...

A: You don't appear to be zero terminating 'input'

A: In addition to what NPE said, there's a couple of other small things:
char *input;
input=new char(s.size());

This might have something to do with it - you are allocating a single character. You then write that one character, and overwrite other memory that is used for who-knows-what. Try this instead:
char *input = new char[s.size() + 1];

Another issue is your loop, immediately below that:
for(i=0;i<=s.size();i++)
        input[i]=s[i];

At least on my system, using std::string::operator[] with an offset equal to s.size() fails; I don't know about your particular implementation, but I'm pretty it fails as well. Be safe, rather than sorry, and recode your loop thusly:
for(i = 0; i < s.size(); i++)
    input[i] = s[i];

input[i] = 0;

I hope this helps.