text:
Q: How to get uncompressed byte array from DirectShow? I am trying to use DirectShow https://learn.microsoft.com/en-us/windows/win32/directshow/directshow
in order to get uncompressed byte array from .mp3 stream. I have an implementation that can playback .mp3 byte stream
bool coAudioPlayer::LoadImp(SoundDataType dataType, std::string const & filename, unsigned char const * pData, int64_t dataLen, bool bOnlyIfFilenameChanged)
{
...
    m_pMemReader = new CMemReader(m_pMemStream, m_pMediaType, &hr);

    m_pMemReader->AddRef();

    hr = CoCreateInstance(CLSID_FilterGraph,
        NULL,
        CLSCTX_INPROC_SERVER,
        IID_IGraphBuilder,
        (void **)&this->m_pigb);

    hr = m_pigb->AddFilter(m_pMemReader, NULL);
    if (FAILED(hr))
    {
        return false;
    }

    m_pigb->QueryInterface(IID_IMediaControl, (void **)&m_pimc);
    m_pigb->QueryInterface(IID_IMediaEventEx, (void **)&m_pimex);
    m_pigb->QueryInterface(IID_IBasicAudio, (void**)&m_piba);
    m_pigb->QueryInterface(IID_IMediaSeeking, (void**)&m_pims);

    /*  Render our output pin */
    hr = m_pigb->Render(m_pMemReader->GetPin(0));
    if (!SUCCEEDED(hr))
    {
        return false;
    }

    HRESULT hr = m_pimc->Run();

    return m_bReady;
}

But I need to extend this functional and add approach to get uncompressed byte array (sound frames). As far as I understand under the hood DirectShow decodes it, but I don't see any way to retrieve this decoded array.
Is there a way to do it?

A: "uncompressed byte array" is quite a wrong definition of desired data. There is no such thing as media data in byte array format. MP3 audio would typically be decompressed by MP3 Decoder media object wrapper into DirectShow filter into audio of MEDIASUBTYPE_PCM format with certain properties (sampling rate, channel count, bits per sample). Specifically, selected bit depth (and this decoder does support multiple bit depth options!) defines directly the representation of audio data as byte array.
You don't need or want to access the data when you build a playback pipeline, such as in scenario with Render method you mention and do you don't have the data.
A typical way to access the content is to build a pipeline around Sample Grabber Filter. There is a huge amount of code and questions explaining the approach. The relevant keyword is SampleCB standing for ISampleGrabberCB::SampleCB method. For example: ffmpeg audio frame from directshow sampleCB imediasample.


text:
Q: Is there a C#(.net) equivalent of JSR 303/349 I am new to C# (.net) , i am trying to see if there is a standard way to validate the inputs for a REST API call.
Like in Java World we have JSR 303 / 349 Is there a C#(.net) equivalent of JSR 303/349 ?
Mostly all Java framework have some sort of similar framework Is there an implementation of JSR-303 (bean validation) available?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Understanding a Math "Meme"? I recently saw this "Math Meme":

Loosely speaking, I think I understand the humor - even though some functions may appear to look continuous on paper, they are not mathematically continuous as such.
As an example, I think the "Step Function" (https://en.wikipedia.org/wiki/Step_function) is an example, as I can draw this without lifting my pen/pencil, but is clearly not defined at certain points. Is this a valid example with regards to this math "meme"? If not, can someone please help me come up with one (e.g. perhaps "Absolute Value Function"?)
In general:

*

*Is there any particular relevance of the function that they have drawn in this picture (i.e. function plotted in red)?

Is this an example of a discontinuous function?

*

*In general, are functions like $$f(x) = x \cdot \sin{\left(\frac{1}{x}\right)}$$ considered discontinuous since at $x=0$ this function is "not defined" (i.e. infinity) - but nonetheless, I can still draw it without lifting my pen?

Thanks!
Note: R Simulation
# Define function
f <- function(x) x*sin(1/x)

# Plot function
plot(f, xlim = c(-5, 5), ylim = c(-5, 5), xlab = "x", ylab = "y")

# Add vertical lines at x = 0 and x = (2*k+1)*pi
abline(v = c(0, pi, -pi, 3*pi, -3*pi), lty = 2)

Warning message:
In sin(1/x) : NaNs produced

A: A bit of a philosophical answer, or a rant if you like.
I don't like the joke. The gist of it is that the real analysis is filled with cumbersome and confusing definitions of things that are clear and intuitive and obvious to pre-calculus students. Gets you to think - why study real analysis when all it does is muddle waters and make easy stuff hard? Thus the joke comes across as being derogatory towards the real analysis as a subject. (Well... probably the maker of the joke wasn't very good at real analysis in the first place! Or, at least they felt a bit too strongly for those people who were not.)
In fact, if the definition of continuity needed to involve such complicated entities as "I", " can", "draw", " pen" and "lifting", we would have to define those entities first, or give up with using logic in mathematics in the first place! E.g. who says that you can draw the same things as I can; maybe I don't have a pen (does it work with a pencil?) or I am six months old, or I cannot use a pen (if I am too ill), and nobody ever can prove one way or otherwise that $y=\arctan x$ is continuous around $x=10^{100}$. (You can't trick me, this is not $y=\arctan x$, it looks more like $y=\pi/2$ to me!)
So the main point is not in finding example which looks like a function is continuous while rigorously being not, or doesn't look continuous even though it is. The main point is that the pre-calculus definition which includes Earthly creatures (people) and their creations (pens) is not good enough for mathematical use. The "real analysis" definition, warts and all, removes that defficiency at the (small) cost that one needs to study a bit of real analysis to appreciate it.


text:
Q: ImageView in android not filling whole page using ViewPager I am facing problem while loading an Image in ViewPager. The image gets loaded with 5px gap at right and left side. Here is my code:
 @Override
    public Object instantiateItem(ViewGroup container, int position) {
        ImageView imageView = new ImageView(mContext);
        imageView.setImageResource(PoemActivity.mPoems[position]);
        container.addView(imageView);
        return imageView;
    }

Here is my xml file as asked by Hari.
    <android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/viewPager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />


text:
Q: Creating an application scoped bean in spring MVC Good day Everyone,
I want to explain my current legacy application before i ask my question.
I have a servlet in a Tomcat in which i load a non-changing database table into memory in the init() using Hibernate. Because this is defined in the init(), it is called only once and its available across all subsequent requests to the servlet, this is used because it improved application performance because of less round trips to the database.
I have recently started to use Spring 3 and i want to change this set up (servlet class is now a controller) to Spring but my challenge is how do i create the ArrayList of domain object (as i do in the init()) at Spring load time for efficiency and have it available across all calls to the controller class without accessing the database every time a request comes in. If this is not possible, then what options do i have?
Any help would be very appreciated.

A: Pop that static data into the RequestInterceptor
public class RequestInterceptor extends HandlerInterceptorAdapter {
 @Override
    public void postHandle(
        HttpServletRequest request,
        HttpServletResponse response,
        Object handler,
        ModelAndView modelAndView) throws Exception {

        ....
        modelAndView.addObject("variableName", dataIWantToHaveAvailableAllOverThePlace);
        ....
        super.postHandle(request, response, handler, modelAndView);

    }
}

A:
how do i create the ArrayList of domain object (as i do in the init()) at Spring load time for efficiency and have it available across all calls to the controller class without accessing the database every time a request comes in. If this is not possible, then what options do i have?

I would design this almost identically in your scenario as I would if the data was constantly changing and had to be read from the database on each request:

*

*The controller is wired up with an instance of the MyService interface which has operations for retrieving the data in question.

*

*Optionally, depending on if you separate your DAO layer from your service layer, the MyService implementation is wired up with a MyDAO bean.

*The MyService implementation is marked as InitializingBean, and in the afterPropertiesSet() method you retrieve the one-time-load data from the database.

With this design, your controller does not know where it's data is coming from, just that it asks a MyService implementation for the data. The data is loaded from the database when the MyService implementing bean is first created by the Spring container.
This allows you to easily change the design to load the data on each request (or to expire the data at certain times, etc) by swapping in a different implementation of MyService.


text:
Q: convert  code to @Bean I'm working on a project in Spring using SpringMVC, i'm using the xml element <bean/> and i want to convert my code to @Bean
spring-bean.xml
<bean id="myDao" class="com.my.dao.EmployeImplDB" init-method="init"></bean>

<bean class="com.my.service.EmployeImplMetier" id="myMetier">
    <property name="dao" ref="myDao"></property>
</bean>

how to convert xml to annotation @Bean?

A: You can write this way
@Repository
class EmployeImplDB{}

@Service
EmployeImplMetier{

@Autowired
EmployeImplDB myDao;

}

@Repository signifies that your bean is a DAO class
@Autowired injects dao class EmployeImplDB in the Service class

A: Like this:
@Bean(name = "myDao", initMethod = "init")
public EmployeDao myDao() {
    EmployeDao eidb = new EmployeImplDB();
    return eidb;
}

@Bean(name = "myMetier")
public Metier employeImplDB(EmployeDao myDao) {
    Metier metier= new EmployeImplMetier(myDao);
    return metier;
}

Note: Presuming that name of EmployeImplDB superclass (interface) is EmployeeDB.


text:
Q: Sulu: add a new locatlistation leads to permission error I wanted to give sulu a try and so far it looks nice. So installed a minimal version via composer, defined some page templates and everything worked so far. Then i added a new localization as described in http://docs.sulu.io/en/latest/book/webspaces.html and http://docs.sulu.io/en/latest/book/localization.html. Which is not working.
As described i simply added <localization language="de" default="false"/> to the list. But i cannot access the content of the new locale and moreover the starting page content.
The error i retrieve is a permission error:
Operation forbidden The available permissions are not sufficient for this operation

I've checked the permissions and every available permission is granted to the user. Now i am stuck.

A: That's because you don't have these permissions in the correct locale. The User Role only describes what the user is allowed to do, but it doesn't describe in which language. That's because we don't want to have uncontrolled of user roles. Imagine you have a big homepage, with english, german and french content, then you would have to create three roles: Content Manager EN, Content Manager DE and Content Manager FR. We have chosen a different way.
In a user role you don't describe in which language these permissions apply, you do that on the user instead. Go to Contacts, select the contact with your user, and choose the permissions tab.

In the permissions section on this page you see a table with all the roles, the one being assigned are checked. The dropdown on the right describes to which language this applies. You probably haven't assigned the language to your new user here.


text:
Q: dplyr: conditional column selection using select_if() A follow-up from a previous question...
How to select all columns based on a type, with the exception of one column based on a select helper function?
select_if(iris, is.numeric, vars(-contains("Width")))
Error: No tidyselect variables were registered

I have it within a nested dataframe, and am running it over a purrr::map() which slightly complicates the workflow options:
iris %>%
  group_by(Species) %>%
  nest %>%
  mutate(data = map(data, ~ .x %>% select_if(is.numeric) %>% mutate(count = sum(rowSums(.))))) %>%
  mutate(data = map(data, ~ .x %>% select_if(is.numeric) %>%
                      mutate_all(funs((. / count) * 100 )))) %>%

  unnest

A: The simplest and clearest way to do this is to pipe together 2 select functions:
iris %>%
    select_if(is.numeric) %>%       # Select all numeric columns
    select(-contains('Width')) %>%  # Then drop 'Width' column(s)
    head

  Sepal.Length Petal.Length
1          5.1          1.4
2          4.9          1.4
3          4.7          1.3
4          4.6          1.5
5          5.0          1.4
6          5.4          1.7

This works even inside a map function:
iris %>%
    group_by(Species) %>%
    nest %>%
    mutate(data = map(data, ~ .x %>%
                          select_if(is.numeric) %>%
                          select(-contains('Width')) %>%
                          mutate(count = sum(rowSums(.))))) %>%
    mutate(data = map(data, ~ .x %>%
                          select_if(is.numeric) %>%
                          select(-contains('Width')) %>%
                          mutate_all(funs((. / count) * 100 )))) %>%

    unnest

# A tibble: 150 x 4
   Species Sepal.Length Petal.Length count
   <fct>          <dbl>        <dbl> <dbl>
 1 setosa          1.58        0.433   100
 2 setosa          1.52        0.433   100
 3 setosa          1.45        0.402   100
 4 setosa          1.42        0.464   100
 5 setosa          1.55        0.433   100
 6 setosa          1.67        0.526   100
 7 setosa          1.42        0.433   100
 8 setosa          1.55        0.464   100
 9 setosa          1.36        0.433   100
10 setosa          1.52        0.464   100
# ... with 140 more rows

A: select_if(iris[, !colnames(iris) %in% ("Sepal.Width")], is.numeric)
    Sepal.Length Petal.Length Petal.Width
1            5.1          1.4         0.2
2            4.9          1.4         0.2
3            4.7          1.3         0.2
4            4.6          1.5         0.2
5            5.0          1.4         0.2


text:
Q: jQuery calendar control I have a textbox that is wired up to a calendar control like so
 $('#txtPromoPrcStrt').datepick({
                    dateFormat: 'mm/dd/yyyy',
                    onSelect: function(selectedDate) { txtPromoPrcStrt_TextChanged(); }
 });

and inside of the txtPromoPrcStrt function I am triggering the change event so that I can postback to the server.  Everything works fine on the server, I can see the value of the date I selected in the TextBox.Text.  The problem is that when the page is rendered after the postback, I no longer see the value in the TextBox even though when I view the source I can see my date in the value="" of the INPUT tag.  Can anyone tell me what is taking place?

A: The datepicker is probably blanking the field when it loads initially. There's probably an option on that to default the field to the value of the datepicker, but otherwise you can do this:
 $('#myDatepicker').datepicker();
 $('#myDatepicker').val($('#myDatepicker.').attr('value'));

You set the value to what the attribute had.


text:
Q: Get element underneath another element? Just wondering the best way to tackle this.
Let's say I have a fixed navbar that sits exactly centered vertically.
As I'm scrolling, I want to find out the element behind the nav bar.
Lets say I have a nav like so:

And then sections like so:

If I give them all a fixed height of say 1000px so that we are able to scroll properly, how can I detect when the navbar is say over the 'services' section, so I can append an active class etc.
I was going to detect the scroll position from the top of the document, and compare that to the top positions of the sections which I'd be able to find out where the navbar is located from there, but is this the best way to tackle this?
Example: http://jsfiddle.net/c8jhajde/


text:
Q: Preventing descendants from overriding method In C++ (11/14/17, I don't care), I have a base class B which exposes method x as protected.
In class D1, which derives from B, I want to prevent further descendants (of D1) from calling x().  Now, if I were overriding x in D1, I would simply mark it as final.
But, what if D1 does not override x(), yet D1 still wants to hide it from descendants?  How can I do that?

A:
How can I do that?

By changing the program and overriding x in D1. You can just delegate to the base class version by calling it.


text:
Q: API 3.8: After dragging a marker, if marker.setMap(null) then it doesn't appear more Using version v3.8 I got this behaviour with dragged markers.
a) marker.setMap(map)   --> Marker on map
b) dragg the marker     --> It's a dragged marker
c) marker.setMap(null)  --> hiding the marker
d) marker.setMap(map)   --> The marker doesn't appear
If I force use v=3.7, everything works ok, in d) the marker appears in the map.
Greetings.

A: Following QAH's comment this does appear to be a bug in Version 3.8. See this bug report and add your star to it to help get it fixed.
A workaround is to use marker.setVisible(false) or an earlier version, as you found.


text:
Q: Why do entities need keys in Appengine datastore What is the usage of keys in the appengine datastore: I am new to Appengine, any info on it would be great.

A: Comparison
To keep things simple, let's assume MySQL stores all the rows of a table in a single file. That way, it can find all the rows by scanning that file.
App Engine's datastore (BigTable) does not have a concept of tables. Each entity (~row in MySQL) is stored separately. [It can also have a individual structure (~columns).] Because entities are not connected in any way, there is no "default" method to go through all of them. Each entity needs an ID and must be indexed.
Key Structure
A key consists of:

*

*App ID (the closest thing in MySQL is a database).

*Kind (the closest thing in MySQL is a table).

*ID or name (the closest thing in MySQL is a primary key).

*(Optionally) Parent key (all the above of another entity). (Details omitted for the sake of simplicity.)
Please note that what is meant by the closest thing is conceptual similarity. Technically, these things are not related. In MySQL, databases and tables represent actual storage structures. In BigTable they are just IDs, and the storage is actually flat, i.e. every entity is essentially a file.
In other words, identity-wise, a key is to an entity as the database + table + primary key are to a row in a MySQL table.
Key's Responsibilities
An entity's key:

*

*States what application the entity belongs to.

*What kind (class, table) it is of.

*By the means of the above and either a numeric key ID or a textual key name, identifies the entity uniquely.

*(Optionally) What the parent entity of the entity is. (Details omitted for the sake of simplicity.)
Usage
So that you can retrieve all entities of a kind, App Engine automatically builds indexes. That means App Engine maintains a list of all your entities. More specifically, it maintains a list of your entities' keys.
Complex indexes may be defined to run queries on multiple properties (~columns).
In contrast to MySQL, every BigTable query requires an index. Whenever a query is run, the corresponding index is scanned to find the entities that meet the query's conditions, and then the individual entities are retrieved by key.
A common high-level use is to identify an entity in a URL, as every key can be represented as a URL-safe string. When an entity's key is passed in the URL, the entity can be retrieved unambiguously, as the key identifies it uniquely.
Moreover, retrieving an entity by its key is strongly consistent, as opposed to queries on indexes, which means that when entity is retrieved by its key, it's guaranteed to be the latest version.
Tips

*

*Every entity stored in BigTable has a key. Such a key may be programmatically created in your application and given an arbitrary key name. If it's not, an numeric ID will be allocated transparently, as the entity is being stored.

*Once an entity is stored, its key may not be changed.

*The optional parent component might be used to define a hierarchy of entities, but what it's really important for is transactions and strong consistency.

*

*Entities that share a parent are said to belong to the same entity group.

*Queries within a group are strongly consistent.

*Just to reiterate, retrieving an entity by its key or querying an index by a parent key are strongly consistent. Retrieving entities in other ways (e.g. by a query on a property) is eventually consistent.

Glossary

*

*Entity - a single key-value document.

*Eventual consistency - retrieving an entity (often a number of them) without the guarantee that the replication has completed, which may result in some entities being an old version and some being missing, as they have not yet been brought from the server they were stored on.

*Key - an entity's ID.

*Kind - arbitrary textual name of a class of entities, such as User or Article.

*Key ID - a numeric identifier of a key. Usually automatically allocated.

*Key name - a textual identifier of a key.

*Strong consistency - retrieving an entity in such a way that its latest version is retrieved.

(I intentionally used MySQL in the examples, as I'm much more familiar with it than with any other relational database.)

A: Please read https://developers.google.com/appengine/docs/java/datastore/#Java_Entities ... you may want to delete your question and ask again after you have studied this documentation section.
(This is meant to help you, not complain.)


text:
Q: pyDEA running as a python script I am attempting to run pyDEA. The main_gui approach does not work from wha appears to be the
ValueError: cannot use LOCALE flag with a str pattern
issue with the latest version of Python (I am running Python 3.8.5, Anaconda on MacOS).
Has anyone run it directly in a script? If so, do they have any sample code to show what they needed to import and call to run the DEA analysis?


text:
Q: MySQL update query not using indexed columns I tried the following SQL query to update the table INDEXED_MERCHANT where I have 10000 records in the table. I indexed both "Name" and "A" as Indexed keys to improve the update query performance.  By executing the command SHOW CREATE TABLE INDEXED_MERCHANT; I'll get an output result as follows:
 INDEXED_MERCHANT | CREATE TABLE `INDEXED_MERCHANT` (
  `ID` varchar(50) NOT NULL,
  `NAME` varchar(200) DEFAULT NULL,
  `ONLINE_STATUS` varchar(10) NOT NULL,
  `A` varchar(100) DEFAULT NULL,
  `B` varchar(200) DEFAULT NULL,
  PRIMARY KEY (`ID`),
  KEY `NAME` (`NAME`,`A`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |

Here this means both my keys are recognized as indexed keys. When I execute the following command, the "Extra" column result says the query doesn't using the index keys. How should I achieve my goal ?
Executed query : EXPLAIN EXTENDED UPDATE INDEXED_MERCHANT SET ONLINE_STATUS = '0' WHERE NAME = 'A 205' AND A = 'P 205';
Result:
+----+-------------+------------------+-------+---------------+------+---------+-------------+------+----------+-------------+
| id | select_type | table            | type  | possible_keys | key  | key_len | ref         | rows | filtered | **Extra**       |
+----+-------------+------------------+-------+---------------+------+---------+-------------+------+----------+-------------+
|  1 | SIMPLE      | INDEXED_MERCHANT | range | NAME          | NAME | 906     | const,const |    1 |   100.00 | **Using where** |
+----+-------------+------------------+-------+---------------+------+---------+-------------+------+----------+-------------+

A: Your query is hitting "NAME" index as evident in explain output column "key".
Here is the explanation of key and extra columns from mysql documentation

key

The key column indicates the key (index) that MySQL actually decided to use. If MySQL decides to use one of the possible_keys indexes to look up rows, that index is listed as the key value.

Using where

A WHERE clause is used to restrict which rows to match against the next table or send to the client. Unless you specifically intend to fetch or examine all rows from the table, you may have something wrong in your query if the Extra value is not Using where and the table join type is ALL or index. Even if you are using an index for all parts of a WHERE clause, you may see Using where if the column can be NULL.


text:
Q: I can't figure out how to get this sequence to converge to 0 I'm trying to prove this sequence converges to $0$ (or maybe I'm wrong..):
$$k\in\mathbb N,1<q,\lim_{n\rightarrow\infty}\frac{n^k}{q^n}$$
I'd be happy to get some help with this! thank you!

A: Let $a_n=\frac{n^k}{q^n}$.
$$\lim_{n\to\infty}\frac{a_{n+1}}{a_n}=\lim_{n\to\infty} \frac{(n+1)^k}{q^{n+1}}/\frac{n^k}{q^n}=\frac{1}{q}\lim_{n\to\infty}\left(\frac{n+1}{n}\right)^k=\frac{1}{q}\left(1+\lim_{n\to\infty}\frac{1}{n}\right)^k=\frac{1}{q}$$
Hence there will be a $K$ after which the ratio is less than $b<1$ whenever $n\ge K$, so after that point it decreases exponentially. This is the same idea as in the proof of the ratio test, which further shows that your sequence, when summed, is also convergent (this also implies that the terms of the series go to 0).
Details
$\exists K\in\mathbb{N}$ s.t. $\forall n\ge K,\quad\frac{a_{n+1}}{a_n}<b$ where $b\in(\frac{1}{q},1)$.
$\forall n>K,\quad 0\le a_n=\frac{a_n}{a_{n-1}}a_{n-1}\le ba_{n-1}\le \dots\le b^{n-K}a_K\to 0$ as $n\to\infty$.
By squeeze theorem, $a_n\to 0$.

A: Hint. You are right. You may write, as $n$ is great:
$$
\log \left(\frac{n^k}{q^n}\right)=k \log n - n\log q=-n \left(\log q - k\frac{\log n}{n} \right)\sim -n \log q \longrightarrow -\infty
$$ thus your initial sequence is tending to $0^+$:
$$
\frac{n^k}{q^n}=e^{\log \left(\frac{n^k}{q^n}\right)} \longrightarrow e^{-\infty}=0
$$

A: $\frac{a_{n+1}}{a_n}=(\frac{n+1}{n})^k*\frac{1}{q}$.
We have $q>1$ and $\lim_{n\to\infty}(\frac{n+1}{n})^k=1$.
Using the epsilon-delta definition, we have $N$ such that $(\frac{n+1}{n})^k<q\ \forall n>N$
Without loss of generality, assume it is so for all $n\in\mathbb{N}$. Thus, the sequence is decreasing, and we also have that it is bounded below by $0$. Thus, it is converging.
Denote the limit by $x$.$\lim_{n\to\infty}a_n=\lim_{n\to\infty}a_{n+1}$
$x=\frac{1}{q}x$ and thus $x=0$

A: So after long discussions about this problem I got a solution which doesn't use any of the suggested methods (such as limit of exponential's, logarithmic's, etc)
so my calculus course will accept it.
We find an $\alpha$ such that: (1) $\alpha^n>n^k$ $\land$ (2) $ 1\lt\alpha\lt q$
(1)
from the dense order of $\mathbb R$ and because $q>1$ then $\exists 1 \lt\alpha\lt q$
(2)
$\alpha^n>n^k \iff \alpha> \sqrt[n]{n}^k$ though $\lim\limits_{n \to \infty} \sqrt[n]{n}^k = 1^k = 1 \implies \exists N_0 \forall n>N_0 \,\mid\sqrt[n]{n}^k-1\,\mid<\frac{q-1}{2}$
from here
we choose $1<\frac{q-1}{2}<\alpha<q$ and we get $\frac{n^k}{q^n}<\frac{\alpha^n}{q^n}=(\frac{\alpha}{q})^n$ for $n>N_0$ though we know that
$\lim\limits_{n \to \infty} (\frac{\alpha}{q})^n = 0 \implies \lim\limits_{n \to \infty} \frac{n^k}{q^n} = 0$ from the squeeze theorem.
Wow! this is the first time I wrote something this long  here, thanks for the help!


text:
Q: Groovy script too long for string I would like to execute a script from a JavaScript file but due the same origin policy measure, I can't.
I tried to execute put the script in a string and pass it to the function.
js.exec()

However I cannot execute this script due the fact that the string is too long.
This is how I pass the script.
class TheClass extend GebReportingSpec {
....
and:'I execute the script'
      js.exec('''
        $.getScript("http://localhost/jscript/html2canvas.js", function() {
        var height = Math.round($("#TopImageContainer").height());
        var width =  Math.round($("#TopImageContainer").height());
        // function() {
        html2canvas($("#TopImageContainer"), {
            onrendered: function (canvas) {
                 var tempcanvas = document.createElement("canvas");
                 tempcanvas.width = width;
                 tempcanvas.height = height;
                 var context = tempcanvas.getContext("2d");
                context.drawImage(canvas,0,0,width,height,0,0,width,height);
                 var link = document.createElement("a");
                 link.href = tempcanvas.toDataURL("image/png");
                 link.download = "myElement.png";
               link.click();
          }
    });

     });''')
    }

I am getting the following error:

The given string is 126694 Unicode code units long, but only a maximum of 65535 is allowed.

What can I do?


text:
Q: remote flink job with query to Hive on yarn-cluster error:NoClassDefFoundError: org/apache/hadoop/mapred/JobConf env: HDP: 3.1.5(hadoop: 3.1.1, hive: 3.1.0), Flink: 1.12.2
Java code:
public static void main(String[] args) {
    EnvironmentSettings settings = EnvironmentSettings.newInstance().useBlinkPlanner().build();
    TableEnvironment tblEnv=TableEnvironment.create(settings);

    String name = "myhive";
    String defaultDatabase = "default";
    String hiveConfDir = "/etc/hive/conf";
    HiveCatalog hive = new HiveCatalog(name, defaultDatabase, hiveConfDir);
    tblEnv.registerCatalog("myhive", hive);
    tblEnv.useCatalog("myhive");

    //tblEnv.getConfig().setSqlDialect(SqlDialect.HIVE);
    tblEnv.sqlQuery("SELECT * FROM users").execute().print();
}

Dependency:
<dependency>
  <groupId>org.apache.flink</groupId>
  <artifactId>flink-table-api-java-bridge_2.12</artifactId>
  <version>${flink.version}</version>
</dependency>

<dependency>
  <groupId>org.apache.flink</groupId>
  <artifactId>flink-connector-hive_2.12</artifactId>
  <version>${flink.version}</version>
</dependency>

error 1:
org.apache.flink.util.FlinkException: JobMaster for job 35afe414e1dd861c86130ddd031312f2 failed.
    at org.apache.flink.runtime.dispatcher.Dispatcher.jobMasterFailed(Dispatcher.java:887) ~[flink-dist_2.12-1.12.2.jar:1.12.2]
    at org.apache.flink.runtime.dispatcher.Dispatcher.dispatcherJobFailed(Dispatcher.java:465) ~[flink-dist_2.12-1.12.2.jar:1.12.2]
    at org.apache.flink.runtime.dispatcher.Dispatcher.handleDispatcherJobResult(Dispatcher.java:444) ~[flink-dist_2.12-1.12.2.jar:1.12.2]
    ...
Caused by: org.apache.flink.runtime.client.JobInitializationException: Could not instantiate JobManager.
    at org.apache.flink.runtime.dispatcher.Dispatcher.lambda$createJobManagerRunner$5(Dispatcher.java:494) ~[flink-dist_2.12-1.12.2.jar:1.12.2]
    at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1604) ~[?:1.8.0_292]
    ...
Caused by: org.apache.flink.runtime.JobException: Cannot instantiate the coordinator for operator Source: HiveSource-zjdev_xiangliang.users -> SinkConversionToTuple2
    at org.apache.flink.runtime.executiongraph.ExecutionJobVertex.<init>(ExecutionJobVertex.java:231) ~[flink-dist_2.12-1.12.2.jar:1.12.2]
    at org.apache.flink.runtime.executiongraph.ExecutionGraph.attachJobGraph(ExecutionGraph.java:866) ~[flink-dist_2.12-1.12.2.jar:1.12.2]
    ...
Caused by: java.lang.NoClassDefFoundError: Lorg/apache/hadoop/mapred/JobConf;
    at java.lang.Class.getDeclaredFields0(Native Method) ~[?:1.8.0_292]
    at java.lang.Class.privateGetDeclaredFields(Class.java:2583) ~[?:1.8.0_292]
    at java.lang.Class.getDeclaredField(Class.java:2068) ~[?:1.8.0_292]
    at java.io.ObjectStreamClass.getDeclaredSUID(ObjectStreamClass.java:1871) ~[?:1.8.0_292]
    ...
Caused by: java.lang.ClassNotFoundException: org.apache.hadoop.mapred.JobConf
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382) ~[?:1.8.0_292]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418) ~[?:1.8.0_292]
    ...

try add dependency
    <dependency>
      <groupId>org.apache.hadoop</groupId>
      <artifactId>hadoop-mapreduce-client-core</artifactId>
      <version>${hadoop.version}</version>
      <scope>provided</scope>
    </dependency>

get another error
Exception in thread "main" java.lang.NoSuchMethodError: org.apache.commons.cli.Option.builder(Ljava/lang/String;)Lorg/apache/commons/cli/Option$Builder;
    at org.apache.flink.runtime.entrypoint.parser.CommandLineOptions.<clinit>(CommandLineOptions.java:27)
    at org.apache.flink.runtime.entrypoint.DynamicParametersConfigurationParserFactory.options(DynamicParametersConfigurationParserFactory.java:43)
    at org.apache.flink.runtime.entrypoint.DynamicParametersConfigurationParserFactory.getOptions(DynamicParametersConfigurationParserFactory.java:50)
    at org.apache.flink.runtime.entrypoint.parser.CommandLineParser.parse(CommandLineParser.java:42)
    at org.apache.flink.runtime.entrypoint.ClusterEntrypointUtils.parseParametersOrExit(ClusterEntrypointUtils.java:63)
    at org.apache.flink.yarn.entrypoint.YarnJobClusterEntrypoint.main(YarnJobClusterEntrypoint.java:89)

try to fix conflict about commons-cli:1.3.1 with 1.2:
choose 1.3.1 then error 1;
choose 1.2 then error 2;
add dependency commons-cli 1.4, then error 1.

A: 1、commons-cli choose 1.3.1 or 1.4
2、add $hadoop_home/../hadoop_mapreduce/* to yarn.application.classpath

A: i got this error too , when i think i maybe a version conflict ,because i used
hive 3.1.2 version is to high than hadoop 2.7.6 version. i always got error such as guava version conflict and so on
so when i used flink-1.15.0 and link hive with jar flink-sql-connector-hive-3.1.2_2.12-1.15.0.jar  i got  Caused by: java.lang.ClassNotFoundException: org.apache.hadoop.mapred.JobConf
resolve: this error it because not found jars please move your hadoop jars
hadoop-mapreduce-client-core.,hadoop-common,hadoop-mapreduce-client-common
,hadoop-mapreduce-client-jobclient and hive-exec-3.1.2.jar to flink lib path


text:
Q: Will changing the CPU show up in system or device manager? I recently bought a new computer, and was told that the CPU had been swapped out for a better (Core i7 7700) processor, however this does not show up in system or the device manager.
I have uninstalled all CPUs from the device manager and rebooted the computer, to no avail.
This may be a noob question so any help is appreciated.
Also, if possible I would like to find out without taking apart the computer.
I have Windows 10.

A:
Will changing the CPU show up in system or device manager?

Yes!
Whatever CPU is currently installed in your system will be shown in the System control panel app. It's not necessary to uninstall the CPU from Device Manager for the new CPU to be detected; Windows will detect it automatically.
If you want an extra sense of assurance that the CPU reported by Windows is what's actually installed on your computer (without opening it), then access your system's BIOS/UEFI and note the CPU information reported there.

A: Just to clarify, your computer will definitely show up the model of your CPU within the system.
If you have been told that your computer's processor has been swapped out for a better one, then there should be some indication of this in the System tab.
Go to Control Panel, System and Security, then System. You should see something akin to the image below.
If your claimed processor is not listed in this view, then I am sorry to say that you have probably been conned by the person who sold you the processor upgrade.
I have never, ever, ever heard of a case where the processor is incorrectly reporting its model name to the system.


text:
Q: site can't reached when running from docker container I am new to Docker community, when I run the sample MVC/API application which I created on .net core 3.1 using Microsoft Visual Studio Community 2019 Version 16.5.3 on windows 10 pro. I am getting couple of issues:
 It was not possible to find any compatible framework version
 The framework 'Microsoft.AspNetCore.App', version '3.1.0' was not found.
 - The following frameworks were found:
3.1.0-preview3.19555.2 at [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
You can resolve the problem by installing the specified framework and/or SDK.
The specified framework can be found at:
- https://aka.ms/dotnet-core-applaunch?
framework=Microsoft.AspNetCore.App&framework_version=3.1.0&arch=x64&rid=win10-x64

second, When I run the application on chrome browser I am getting "This site can't be reached". I did several things to resolve the issue but no luck.
docker ps command will give me the following data:

I am using docker for windows (Docker Desktop ver 2.2.0.5) and my docker file as follows:
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-nanoserver-1803 AS base
WORKDIR /app
EXPOSE 80

FROM mcr.microsoft.com/dotnet/core/sdk:3.1-nanoserver-1803 AS build
WORKDIR /src
COPY ["Demo_3_1/Demo_3_1.csproj", "Demo_3_1/"]
RUN dotnet restore "Demo_3_1/Demo_3_1.csproj"
COPY . .
WORKDIR "/src/Demo_3_1"
RUN dotnet build "Demo_3_1.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "Demo_3_1.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "Demo_3_1.dll"]

I have no idea what I am doing wrong here.


text:
Q: Sorting posts ordered by custom field value I have a series of posts (using a wp-zoom theme). I would like to create a custom field called order and sort by that field.
Here is part of my homepage code:
<?php
$z = count($wpzoom_exclude_cats_home);
if ($z > 0) {
    $x = 0;
    $que = "";
    while ($x < $z) {
        $que .= "-".$wpzoom_exclude_cats_home[$x];
        $x++;
        if ($x < $z) {
            $que .= ",";
        }
    }
}
query_posts( $query_string . "&cat=$que" );
if (have_posts()) :
?>

A: You can use the "orderby" parameter of query_posts.
You must specify your custom field and you must give it a numeric value.
Short example:
query_posts($query_string . "&cat=$que&orderby=meta_value_num&meta_key=your_custom_field")


text:
Q: Refactoring duplicated code in Angular typescript I need to refactor duplicated code but I don't know how I would do it.
I have two methods that basically call the same service (I need to call the same request because of pagination) but now it looks ugly because of duplicated code. How can I make this better?
    getStockData(id: string): Observable<{
    searchResult: IStockResult[];
    searchCount: number;
}> {
    return this.service
        .search(
            id,
            this.service.getSearchMetaDefaults()
        )
        .pipe(
            map(response => {
                return {
                    searchResult: response,
                    searchCount: response.meta.totalResourceCount
                };
            })
        );

A: There are possibly multiple elegant solutions to the question. I could propose the following quick changes

*

*Define types for the objects used (eg. using TS interface)

export interface ISearch {
  searchResult: IStockResult[];
  searchCount: number;
}

export interface IMeta {
  pagination: {
    size: number;
    index: number;
  },
  sorting: {
    order: string;
    attribute: string;
  }
}

*Define optional parameters using ?: and send the argument as object using the types defined.

getData(id: string, meta?: IMeta): Observable<ISearch>

So the previous calls would change to
getStockData('some id') -> getData('some id')

paginate(1, 3, 'some id', 'some order', 'some attr') ->

const meta: IMeta = {
  pagination: {
    size: 3,
    index: 1
  },
  sorting: {
    order: 'some order',
    attribute: StockMapper.getDataForSorting('some attr')
  }
};

getData('some id', meta);

*Check if the optional argument is defined using nullish coalescing operator (??) before using it.

const meta = meta ?? this.service.getSearchMetaDefaults();

Combining everything
getData(id: string, meta?: IMeta): Observable<ISearch> {
  const meta = meta ?? this.service.getSearchMetaDefaults();

  return this.service.search(id, meta).pipe(
    map(response => ({
      searchResult: StockMapper.fromStockResource(response),
      searchCount: response.meta.totalResourceCount
    } as ISearch))
  );
}


text:
Q: Как правильно обновить более 100000 записей в базе данных? У меня есть json файл, из которого я считываю данные Code и Employees. Есть и базы данных, в которых есть те же столбцы. Мне нужно обновить базу, заменить Employees из файла по Code.
while ($reader->read()) {
   $employees_no = $crm_conn->query("
          UPDATE accounts_cstm
             INNER JOIN accounts ON accounts_cstm.id_c = accounts.id
             SET accounts_cstm.Employees = '{$Employees}'
             WHERE accounts.Code = '{$Code}'");
}

Записей получается 100000+, и такой цикл длится оооочень долго. Возможно ли быстрее?
EDIT
По совету в комментариях сделал временную таблицу, и пробую обьеденить данные одним запросом. Все равно получается долго. Может надо как то лучше переписать запрос?
UPDATE accounts_cstm
INNER JOIN accounts ON accounts_cstm.id_c = accounts.id
INNER JOIN temp_employees ON (accounts.sic_code = temp_employees.sic_code)
SET accounts_cstm.employees_no_c=temp_employees.employees
WHERE accounts.sic_code = temp_employees.sic_code

EDIT
Я создал index key для sic_code в обеих таблицах в которых оно находится.
Теперь 100000 записей обновляется за несколько секунд! Может кто нибудь может в кратце обьяснить сие чудо? В гугл очень сложные обяснения нахожу...


text:
Q: Made a mistake installing RVM with sudo. How to reverse? I am new to Rails and Linux and have installed RVM with sudo.

sudo bash -s stable < <(curl -s
  https://raw.github/wayneeseguin/rvm/master/binscripts/rvm-installer)

Now I have to run most commands (like spork) with 'rvmsudo'. It is redundant, and the way I learned, when something is redundand it is often wrong. How to get rid of this nuance? Is the only way to reinstall RVM? If so, how to properly reinstall?

A: Use rvm implode to uninstall rvm. Check that there are no environment variables left over in /etc/profile, /etc/bash_profile or whatever shell you're using. Once you do that, then re-install using the single user guide found here.
You'll have to execute the implode command using sudo since you installed it as root.

A: 1)remove in home directory:
rm -rf .rvm*

2)remove from your bash file:
[[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm"

3)  remove from /etc/rvmrc file
sudo rm -rf /etc/rvm*

4)Delete everything else
sudo groupdel rvm

A: I couldn't find a complete/concise step-by-step to 100% remove rvm when it was run as root. Here's what I came up with, and I've tested it three times successfully:
sudo su -
rvm implode
groupdel rvm
rm /etc/rvmrc
rm /etc/profile.d/rvm.sh

You'll also want to double check that you don't have ~/.rvm or ~/.rvmrc or any rvm whatnot in your .bashrc (possibly .bash_profile on OSx), as you've likely been trying to install rvm several ways by this point!
Next, you'll need to reboot, as the global environment variables set in /etc/profile.d/rvm.sh will keep getting populated in new shells until you do. After rebooting, open a terminal and try this command to test:
echo $rvm_path

If it's empty, that means you've succeeded! If not, it'll most likely be set to /usr/local/rvm.


text:
Q: Setting data of one class from within another class I am trying to set the attendance of students based on user input. Where I run it to the problem is trying to take that input and assign it to my data on each student.
All the data I have is read from a file in to a singly linked list. The struct for this data type is declared in my node.h.
So what I'm asking is how would I modify the values that originate from the Node class, within my menu class?
Menu.cpp
   void Menu::chooseMenu(ifstream *input, List L1)
{
    data temp;
    //data plswork[12];
    char holder[30];
    char junk[30];
    int i=1,j=1;

    do{
    system("cls");
    cout<<"1. Import"<<endl;
    cout<<"2. Load Master"<<endl;
    cout<<"3. Store Master"<<endl;
    cout<<"4. Mark Absence"<<endl;
    cout<<"5. Generate Report"<<endl;
    cout<<"6. Exit"<<endl;
    cout<<""<<endl;
    cin>>selection;

    if(selection == 1)//import
    {
        while(!input->eof())
        {
            memset(holder,0,30);

            if(i==3 && j != 1)
            {
                input->getline(holder,30,'"');
                input->getline(holder,30,'"');
                input->getline(junk,30,',');
            }
            else
            {
                input->getline(holder,30,',');
            }

            if(i==1)
            {
                strcpy(temp.record, holder);
                //cout<<temp.record<<endl;
                i++;
            }
            else if(i==2)
            {
                strcpy(temp.ID, holder);
                //cout<<temp.ID<<endl;
                i++;
            }
            else if(i==3)
            {
                strcpy(temp.name, holder);//read between quotes
                //cout<<temp.name<<endl;
                i++;
                j=2;
            }
            else if(i==4)
            {
                strcpy(temp.email, holder);
                //cout<<temp.email<<endl;
                i++;
            }
            else if(i==5)
            {
                strcpy(temp.units, holder);
                //cout<<temp.units<<endl;
                i++;
            }
            else if(i==6)
            {
                strcpy(temp.major, holder);
                //cout<<temp.major<<endl;
                i++;
            }
            else if(i==7)
            {
                strcpy(temp.grade, holder);

                //cout<<temp.grade<<endl;
                L1.insertOrder(temp);
                i=1;
            }

        }
    }

    else if(selection == 2)//load master
    {

    }

    else if(selection == 3)//store master
    {

    }

    else if(selection == 4)//mark absence
    {
        while(L1.nextPtr() != NULL)
        {
        char name;
            cout<<"Bruce :"<<L1.getDataL().absent<<endl;
            cout<<"Is "<<L1.getDataL().name<<" present? (Y/N)"<<endl;
            cin>>name;
            if(name == 'y' || name == 'Y')
            {
                L1.setAtt(L1.getDataL(),1); // This is where I try to set attendance to 0 or 1.
                cout<<L1.getDataL().absent<<endl;
            }
            else
            {
                L1.setAtt(L1.getDataL(),0);
            }

            L1.nextPtr();
            system("pause");
        }
    }

    else if(selection == 5)//gen report
    {

    }

    }while(selection != 6);

}

Node.cpp
#include "Node.h"

ListNode::ListNode (ListNode &copyObject)
{
    this->mData = copyObject.mData;
    this->mpNext = copyObject.mpNext;
}

ListNode::~ListNode ()
{
    // does nothing
    cout << "exiting listnode object - going out of scope" << endl;
}

ListNode * ListNode::getNextPtr () const
{
    return mpNext;
}

data ListNode::getData() const
{
    return mData;
}

ListNode::ListNode(data newData)
{
    mData = newData;
    this->mpNext = NULL;
}

List.h
#include "Node.h"

#ifndef LinkedList_H
#define LinkedList_H
using std::ostream;

class List
{
    friend ostream & operator << (ostream &lhs, List &rhs);
    friend ListNode;

    public:
        List ();
        List (List &copyObject);
        ~List ();

        List & operator = (List &rhs);

        ListNode *makeNode (data newNode);
        bool insertOrder (data Node);
        bool deleteNode (data Node);
        data getDataL();
        ListNode *nextPtr();
        void setAtt(int atten);

    private:
        ListNode *pHead;
};
#endif

ListNode.h
#ifndef ListNode_H
#define ListNode_H

#include <iostream>
#include <string>

using std::cin;
using std::cout;
using std::endl;
using std::string;

struct data
    {
        char record[8];
        char ID[12];
        char name[30];
        char email[30];
        char units[6];
        char major[8];
        char grade[14];
        int absent;
        char dateabsent[32];
    };

class List;

class ListNode
{
    friend class List;
    friend struct data;
    public:
        ListNode();
        ListNode(data newData);
        //ListNode(char newrecord[], string newID, string newname, string newemail, string newunits, string newmajor, string newgrade);
        ListNode(ListNode &copyObject);
        ~ListNode();

        data getData() const;
        ListNode *getNextPtr() const;

        ListNode & operator = (ListNode &rhs);

    private:
        data mData;
        ListNode *mpNext;
};
#endif

A: Ok, so, you're going to have a real tough time getting any good answers with that code because your data structure is not very well constructed, you only need one class, maybe two, to do this.  Bellow is the two class declaration:
struct data
{
    char record[8];
    char ID[12];
    char name[30];
    char email[30];
    char units[6];
    char major[8];
    char grade[14];
    int absent;
    char dateabsent[32];
};
class listNode
{
    listNode* next;
    data data;

public:
    listNode(data& d);    //Will copy d into data, you will need to define
    listNode();           //Will initialize a blank data, you will need to define
    ~listNode();          //Definitely need a destructor

    data& getMutableData();
    const data& getImutableData() const;

    void insert(listNode* n);
    bool delete(listNode* n);
    listNode* next();

};

The wrapper class you have is really unnecessary for a linked list, and you want to pass large data structures either as pointers or by reference, you should never return "data", only "data*" and "data&".  "data" should be reserved for the creation of new objects only.  The implementation of a few important functions here:
void listNode::insert(listNode* n)
{
    if(next!=NULL)
        next->insert(n);
    else
        next = n;
}
bool listNode::delete(listNode* n)
{
    if(next==NULL)
        return false;
    if(next == n)
    {
        listNode* temp = next;
        next = next->next();
        delete temp;
        return true;
    }
    return next->delete(n);
}

The reason you're having trouble is basically that your data structures are very poorly implemented, they need a redesign.  What I have above is by no means the only or even the best implementation (notably, there is little encapsulation or data protection), but it appears to be close to the singly-linked list functionality you are looking for.

A: I have no idea how your setAtt method on List is supposed to work. So without using setAtt, one solution is to make getDataL return data * (a pointer to the data struct). Now your main holds a pointer to some data in the linked list, and can modify it as needed.


text:
Q: How to resize pixmap in Qt? I am trying to use a custom icon in a QtMessageBox, but can't resize the icon at all. The box shows up fine, but the icon is too large.
I've tried code from a similar question, but it didn't work.
QPixmap p(80,80);
p.scaled(80,80); //this doesn't seem to change anything
p.load("checkmark.png");

box->setIconPixmap(p);

How do I do this?

A: It is pointless to scale the pixmap before loading it, scale it afterwards.
QPixmap p("checkmark.png");
auto newPixmap = p.scaled(80, 80);
box->setIconPixmap(newPixmap);


text:
Q: Reassign array inside another array inside a collection In VBA I have an collection with items defined as this:
MyCollection.Add Array("Key", Array()), "Key"
So I can refer to the value or key by the index of the "Item" array.
MyCollection.Item(1)(1) gives empty array
MyCollection.Item(1)(0) gives "Key"
However when I assign my empty array to a populated array it won't change.
MyCollection.Item(1)(1) = Array("New", "New1")
Refering to the Item value it will still give an empty array instead of
the new.


text:
Q: Error id accion Este es mi problema.
Tengo un proyecto trabajándolo bajo el modelo MVC (Modelo, vista, controlador) y jsp con conexión a una base de datos sql y sus correspondiente código por java.
Tengo un formulario que muestra las personas y había logrado que un botón me llevara a un formulario para actualizar el usuario seleccionado, escribirle un estado de habilitado o deshabilitado en la base de datos (Básicamente un update) y eliminarlo.
Todo esto me funcionaba correctamente pero ahora tengo un problema, que es que solo me funciona el update y el eliminar con el ultimo id de los usuarios.
Por ejemplo tengo tres usuarios, con id 3,4,5 correspondientemente, pero al habilitar, deshabilitar o eliminar sin importar cual elija, siempre hará la respectiva acción con el ultimo id y no con el deseado.
Lo extraño es que esto me funcionaba perfectamente, en la escuela después de unas horas ocurrió este error y en casa a pesar de que trabajar con un proyecto y base de datos mas viejo pero que aun así funcionaban, ya no sirven.
La única forma de hacerlo funcionar bien es cuando en la barra de la dirección web escrita pongo el controlador con el id que quiero, ejemplo:
http://localhost:50091/student_follow_upultimo/Controlador?accion=Deshabilitar&idPersona=21

Adjunto segmentos de código correspondientes, espero haberme hecho explicar y disculpen la longitud del post.
Pagina:
Número de Identidad
                                                Nombres
                                                Apellidos
                                                Fecha de Nacimiento
                                                Edad
                                                Dirección
                                                Teléfono
                                                Correo Electrónico
                                                Nombre de Usuario

                                                Numero de Rol
                                                Numero de Tipo de Documento
                                                Estado
                                                Actualizar Usuario
                                                Habilitar Usuario
                                                Deshabilitar Usuario
                                                Eliminar Usuario

                                        <%
                                        PersonaDAO dao=new PersonaDAO();
                                        List<Persona>list=dao.listar();
                                        Iterator<Persona>iter=list.iterator();
                                        Persona per=null;
                                        while(iter.hasNext()){
                                        per=iter.next();

                                        %>

                                                <%= per.getdni()%>
                                                <%= per.getnombres()%>
                                                <%= per.getapellidos()%>
                                                <%= per.getfechaNacimiento()%>
                                                <%= per.getedad()%>
                                                <%= per.getdireccion()%>
                                                <%= per.gettelefono()%>
                                                <%= per.getcorreoElectronico()%>
                                                <%= per.getnombreUsuario()%>

                                                <%= per.getrol_idRol()%>
                                                <%= per.gettipodoc_idTipoDoc()%>
                                                <%= per.getestado()%>
                                                <a href="Controlador?accion=Editar&idPersona=<%= per.getidPersona()%>"><button href="Controlador?accion=Editar&idPersona=<%= per.getidPersona()%>" type="submit" class="btn btn-warning" data-toggle="tooltip" data-placement="top" title="Actualizar los datos de un usuario"></button>
                                                <button class="btn btn-primary" data-toggle="tooltip" data-placement="top" title="Habilitar a un usuario su ingreso" onClick="mensaje2()"></button>
                                                <button class="btn btn-secondary" onClick="mensaje1()" data-toggle="tooltip" data-placement="top" title="Deshabilitar a un usuario su ingreso"></button>
                                                <button class="btn btn-danger" onClick="mensaje()" data-toggle="tooltip" data-placement="top" title="Eliminar un usuario"></button>

Controlador/Servlet:
else if(action.equalsIgnoreCase("Eliminar")){
            idPersona=Integer.parseInt(request.getParameter("idPersona"));
            p.setidPersona(idPersona);
            dao.delete(idPersona);
            acceso=dele;
        }
        else if(action.equalsIgnoreCase("Deshabilitar")){
            idPersona=Integer.parseInt(request.getParameter("idPersona"));
            p.setidPersona(idPersona);
            dao.deshabilitar(p);
            acceso=des;
        }
        else if(action.equalsIgnoreCase("Habilitar")){
            idPersona=Integer.parseInt(request.getParameter("idPersona"));
            p.setidPersona(idPersona);
            dao.habilitar(p);
            acceso=hab;
        }

DAO:
@Override
    public boolean delete(int idPersona) {
        String sql="delete from persona where idPersona="+idPersona;
        try {
            con=cn.getConnection();
            ps=con.prepareStatement(sql);
            ps.executeUpdate();
        } catch (Exception e) {
        }
        return false;
    }

    @Override
    public boolean habilitar(Persona per) {
        String sql="update persona set estado='Habilitado'where idPersona="+per.getidPersona();
        try {
            con=cn.getConnection();
            ps=con.prepareStatement(sql);
            ps.executeUpdate();
        } catch (Exception e) {
        }
        return false;
    }

    @Override
    public boolean deshabilitar(Persona per) {
        String sql="update persona set estado='Deshabilitado'where idPersona="+per.getidPersona();
        try {
            con=cn.getConnection();
            ps=con.prepareStatement(sql);
            ps.executeUpdate();
        } catch (Exception e) {
        }
        return false;
    }

```[![introducir la descripción de la imagen aquí][1]][1]

  [1]: https://i.stack.imgur.com/4PUr4.png

A: Soy nuevo en Stackoverflow así que no se si es la manera correcta de responderte. Pero lo que pasa es que primero recorres tu array de personas armas tu tabla pero siempre queda la última persona del array en el objeto per. Entonces cuando llamas a tu function le estas diciendo que <% per(en este caso la ultima persona) %>, cuando lo correcto sería que guardes solo el id.
Espero que se entienda. Saludos

function mensaje2(id) {
    window.location.href = "Controlador?accion=Habilitar&idPersona="+id;
}
<button class="btn btn-primary" data-toggle="tooltip" data-placement="top" title="Habilitar a un usuario su ingreso" onClick="mensaje2(<% out.print("+per.getidPersona()+") %>)"></button>


text:
Q: What is index do I need create? I have query which sometimes really slow, how can I speed it up?
SELECT PRODUCTS.ID,
    SPECIALPRODUCTGROUPS."id" AS "isProductGroup",
    PRODUCTS."OEM",
    PRODUCTS.NAME,
    MAIN."stockBalance" AS STOCKBALANCE,
    PRODUCTS."minShippingRate",
    PRODUCTS."externalId",
    ARTICLE,
    "categoryId",
    BRAND,
    PRICES."price" AS "price"
FROM PUBLIC."Products" AS PRODUCTS
INNER JOIN PUBLIC."Prices" AS PRICES ON PRODUCTS.ID = PRICES."productId"
AND PRICES."accountId" = 13576
AND PRICES."price" >= 0
AND PRICES."price" <= 337802
INNER JOIN PUBLIC."RegionalWarehouseStockBalances" AS MAIN ON PRODUCTS.ID = MAIN."productId"
AND MAIN."warehouseId" = 1
AND MAIN."stockBalance" > 0
LEFT JOIN PUBLIC."SpecialProductGroups" AS SPECIALPRODUCTGROUPS ON PRODUCTS."productGroupId" = SPECIALPRODUCTGROUPS."productGroupId"
AND SPECIALPRODUCTGROUPS."accountId" = 13576
AND NOW() < SPECIALPRODUCTGROUPS."finishedAt"
WHERE PRODUCTS."active" = TRUE
ORDER BY BRAND ASC
LIMIT 50

There is explain of this query
Explain
I can't add explain in text because stackoverflow complains about the amount of code
Added explain https://explain.depesz.com/s/4UAg
I tried to create indexes on RegionalWarehouseStockBalances, but all my variants doesn't help me
I am using PostgreSQL 12

A: You need to run
VACUUM prices;

so that the index-only scan has few "heap fetches". That will make all the difference.
Reduce autovacuum_vacuum_scale_factor for that table so that the system vacuums the table frequently.


text:
Q: Certificates, Identifiers & Profiles Now Available, but the account is empty Today I was happy to receive this email from Apple. I'm a member of 3 teams but one of them was totally wiped out:

*

*no more devices

*no more certificates

*no more provisioning profiles

*no appIDs

I'm not worried about cert and devices, but I'm warried about the appID, yesterday I've submitted an app to the appstore, with an appID that doesn't exist anymore!!!!!!
Am I the only one with that problem? Does someone know if there could be a problem in the review and releasing process?

A: About 10 hours ago, I received an e-mail message titled 'Certificates, Identifiers & Profiles Now Available' for both Mac OS developer account and iOS developer account.  I waited for 8 long days so that I could submit two OS X software titles.  Finally, I was able to create app identifiers.  Then I learnt that iTunes Connect did not read new app ID additions.  I was as furious as an atomic bomb.  What I did was clicked on contact us and told them about the problem I faced.  After waiting for a couple of hours, the problem was fixed, and I was able to submit applications to iTunes Connect.
What I'm telling is not exactly a fix.  And I don't know if the problem was a propagation issue, or they actually fixed something upon my message.  But if you haven't, I would click on that 'contact us' contact them.  Also, I wrote to them through iTunes Connect's Contact us.


text:
Q: country, state and city database structure for laravel 5.1 with mongo database I'm using laravel 5.1 and mongo db. I need to create country, state and city in form. I checked that there is no normalization in mongo database so please guide me how to create database table structure for populating country, state and city. Please help. Thanks

A: Well you can still "reference" one collection to another, you  should read more about modeling in mongoDB, basically the structure of your models will vary depending on which operation you perform more often and what's the use case for you.
For example, if you write a lot more than you are reading then having separated collections could be a good practice and if you read more than you write then having a structure with embedded objects may be fine for you.
for me I'd create a mix of both since you may have a lot of cities by state, so it would be good to have a separate collection. (but again that will depend on your use case)
this collection holds countries and states
{
    _id: ObjectId<>,
    countryName:"Spain",
    countryCode:"es",
    states[{
        _id: ObjectId<>,
        stateName:"Barcelona"
    }]
}

and then the other collection to fetch cities when is convenient.
{
 _id:ObjectId<>,
 _stateId:ObjectId<>, //Reference to you stateId
 cityName:"SomeCity or province"

}

that's a simple approach, that depends on your use case and how you are going to read your data but, in a simple scenario when you select a country and then a state and at last a city, that would work just fine.

A: You can add reference using the objectid created by the system. In mongodb there is no join queries. All you can do is application level joins if needed. Try to design your collections based on the data needs.


text:
Q: Can you explain this solution to find Isource (Thevenin Norton)
I know it is current division method but how is it applied ?

A: I can see you are struggling and, when this happens, it makes a lot of sense to redraw the circuit: -

Notice how much simpler it is; just one current source and three resistors. So, to move forward, what resistance (\$R_X\$) connects across the 15 amp current source?
Once you have calculated that resistance you can calculate the voltage across the 8 Ω resistor by multiplying the 15 amps by \$R_X\$.
Once you have that voltage (\$15\cdot R_X\$) you can calculate the current that flows through the short between "a" and "b".

A: You can get rid of the 12 Ohm resistor in the parallel arm. After this, it's simple.


text:
Q: Insert image in resources folder Java I have a database WAMP in which, despite other fields, I can insert the name followed by the extension of an image, for instance, "imagen1.jpg".
The program I am doing is written in Java and SQL for the sentences and I'm using the IDE of Netbeans to do it.
I have a type called "Imagenes.java" in which I pick the route of an image to, in this way, insert it in my Jpanel or Jlabel.
public class Imagenes extends javax.swing.JPanel {
    String path;
    ImageIcon imag;

    public Imagenes(int width,int height,String path)
    {
        this.path=path;
        this.setSize(width,height);
    }

    @Override
    public void paint(Graphics graph)
    {
        Dimension tam = getSize();
        if (imag!=null)
        graph.drawImage(imag.getImage(),0,0,tam.width, tam.height, null);
        else
        {
            ImageIcon imagenFondo = new ImageIcon(getClass().getResource(path));
            graph.drawImage(imagenFondo.getImage(),0,0,tam.width, tam.height, null);
        }
        setOpaque(false);
        super.paintComponent(graph);
    }

}

All the images I've inserted are already saved in a folder called "resources".
Therefore, I want to add to the "resources" folder, images from the computer I pick from a "fileChooser".
I've tried it in a thousand ways, putting the complete route and there is no way for the folder to being recognized. However, it
copies the images in the source folder.
I've tried type of routes like '\\resources\\imagen1.jpg', Java specific, but It doesn't pick it properly. But If I do
a print of the string of the route, this is correct.
What I'm doing wrong?

A: If you used ImageIcon(path) instead of ImageIcon(getClass().getResource(path)). You may want to try "src/resources/imagen1.jpg". Netbeans will search from the ProjectRoot. So just typing "resources/imagen1.jpg", it wont be found. You need to add the src
ProjectRootDir
            src
               resources
                      imagen1.jpg

When you useImageIcon(getClass().getResource(path)); The program will try and locate the Image from the classes dir in the build dir. If you place the resources dir in the classes dir, using ImageIcon(getClass().getResource(path)) should work
ProjectRootDir
            build
                classes
                     resources
                             imagen1.jpg

In the above scenario, your path would be "resources/imagen.jpg"

A: How could I use this to save in resources folder?
    // declare JFileChooser
JFileChooser fileChooser = new JFileChooser();

// let the user choose the destination file
if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
    // indicates whether the user still wants to export the settings
    boolean doExport = true;

    // indicates whether to override an already existing file
    boolean overrideExistingFile = false;

    // get destination file
    File destinationFile = new File(fileChooser.getSelectedFile().getAbsolutePath());

    // check if file already exists
    while (doExport && destinationFile.exists() && !overrideExistingFile) {
        // let the user decide whether to override the existing file
        overrideExistingFile = (JOptionPane.showConfirmDialog(this, "Replace file?", "Export Settings", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION);

        // let the user choose another file if the existing file shall not be overridden
        if (!overrideExistingFile) {
            if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
                // get new destination file
                destinationFile = new File(fileChooser.getSelectedFile().getAbsolutePath());
            } else {
                // seems like the user does not want to export the settings any longer
                doExport = false;
            }
        }
    }

    // perform the actual export
    if (doExport) {
        // the code to write the file goes here...
    }


text:
Q: PHP '@' syntax?
Possible Duplicate:
Reference - What does this symbol mean in PHP?

Found an image upload script on the net and I'm just modifying it to my needs. It contains lines like the one below that begins with an @ symbol. I'm more of a javascript/jQuery guy so can someone explain what this '@' syntax is all about please?
@move_uploaded_file($_FILES[$fieldname]['tmp_name'], $uploadFilename)
    or error('receiving directory insuffiecient permission', $uploadForm);

Please note I'm not asking what the above lines do, just about the functionality of the @ symbol

A: It stops error messages, see here:
http://us3.php.net/manual/en/language.operators.errorcontrol.php

A: It suppresses PHP errors, generally it'll be used by lazy developers as a substitute to isset()


text:
Q: How to change div style on the places of loading web? I just started creating these Loading bar by me:

The white bar is increasing from left to right , so on the end of web page i put these JS - so it makes end of loading bar and change display property o whole loading div :
$(window).load(function() {
         document.getElementById("myn").style.width = "640px";
         setTimeout(function(){$('#loading').fadeOut()}, 2700);
     })

But I need to change the div width of that bar on the most place (for example after loading 10 picture change with to 100px and after loading another 10 pics change with to 200px ect ) on the web to create progress change of loading bar when the page will loading.
How can I change that div width on the most places of web to create continuously move of loading bar on loading web page.
And : I dont want to use Progressbar, I like to make things by myself :-)
Thanks for your help

A: The following code snippet wil do, as far as I understand, what you want. On a press of a button (or when some images are loaded), the width will increase by 16 pixels. This could be any variable and jQuery can be used to animate it as well. This is just an example to illustrate the principle.

$('#button').click(function() {
  var width = $('.progress').width();

  if (width < 256) {
    width = width + 16;
    $('.progress').width(width)
  }

});
div.progress-bar {
  width: 256px;
  height: 32px;
  border: 1px solid black;
}
div.progress {
  width: 0px;
  height: 100%;
  background-color: #e0e0e0;
}
button#button {
  margin-top: 32px;
}

<button id="button">MORE PROGRESS!</button>

A: Finally i Use this code to change div width on the place of loading web :
//First is width 20 in the css
#myBtn {width:20px;height:30px;background-color:white;transition: all 0.5s ease 0s;}

**The HTML :**

// width 62.5% after load div#2013
$('#2013').load("load" , function() {
         $('#myBtn').css('width', '62.5%');
});

some images

//last 100% after load div#2010 with images and with fadeout
$('#2010').load("load" , function() {
         $('#myBtn').css('width', '100%');
         setTimeout(function(){$('#loading').fadeOut()}, 2700);
});


text:
Q: How to combine all values of a single column into single string variable using python? I have dataframe with column name "Column Name"
column Name
ab
cd
ef
gh
ij
kl

I have an 18K rows in single column. And I want to convert like this using python..
Expected Output: abcdefghijkl

A: one_string = ''.join(df['Column Name'].tolist())

A: If you use Pandas:
import pandas as pd
print(df['column Name'].sum())

Output:
abcdefghijkl


text:
Q: I'm getting the error: "Type doesn't conform to protocol 'Comparable'" when trying to compile a Swift code from manual I tried the example below from the Swift - Protocols manual page, but I am getting the compiler error:
error: type 'SkillLevel' does not conform to protocol 'Comparable':
enum SkillLevel: Comparable {
    case beginner
    case intermediate
    case expert(stars: Int)
}
var levels = [SkillLevel.intermediate, SkillLevel.beginner,
              SkillLevel.expert(stars: 5), SkillLevel.expert(stars: 3)]
for level in levels.sorted() {
    print(level)
}

Xcode suggests to add the function below to make it to conform to Comparable:
static func < (lhs: SkillLevel, rhs: SkillLevel) -> Bool {
    <#code#>
}

From the manual:

Swift provides a synthesized implementation of Comparable for enumerations that don't have a raw value. If the enumeration has associated types, they must all conform to the Comparable protocol. To receive a synthesized implementation of <, declare conformance to Comparable in the file that contains the original enumeration declaration, without implementing a < operator yourself. The Comparable protocol's default implementation of <=, >, and >= provides the remaining comparison operators.

I'm not sure if the enumeration in the code above has a raw value, but if it doesn't, shouldn't the code had compiled without the implementation of the function "<"?

A: Automatically generating the < operator works if you have something similar to a plain C enum; just the cases and nothing else. But here one of the cases has an associated type, so the compiler doesn't want to guess how you want values ordered.


text:
Q: Variational forms of non-convex functions I am trying to understand what kind of variational forms exist for non-convex functions. Alternatively, are there conjugate forms which attain strong duality? For a non-convex function $f$, I am interested in finding an $f^*$ which satisfy the following relation
$$\min\limits_u f(u)=\min\limits_u\sup\limits_v~~(u\cdot v)-f^*(v)$$
Are there results stating under what conditions does the strong duality hold for the Fenchel biconjugate of non-convex functions? $u$ here need not be a finite dimensional vector.
Thanks!


text:
Q: Insert new record - add end date to old record Have 2 tables - tblEmployee which is our main employee table that's imported from an HR system and a table thats been created called tblEmployeeDeptByDay. The data is as -
DROP TABLE IF EXISTS #tblEmployee
DROP TABLE IF EXISTS #tblEmployeeDeptByDay
--tblEmployee
SELECT '123456' AS ID
        , 'John Smith' AS EmpName
        , 99999 AS DeptID --UPDATED TODAY TO A NEW DEPT ID
        , DATEADD(D, DATEDIFF(d, 0, getdate()), 0) AS StartDate
        , 'blah@blah.com' Email
        , 'X4' ShiftPattern
        , 'Tom Jones' AS Manager
        , 'W33321' AS Ext
INTO #tblEmployee
--tblEmployeeByDay
SELECT *
INTO #tblEmployeeDeptByDay
FROM (
SELECT
     '123456' AS ID
    , 548758 AS DeptID
    , DATEADD(YY, DATEDIFF(YY,0,GETDATE()), 0) AS StartDate
    , DATEADD(D, DATEDIFF(d, 0, getdate())-1, 0) AS EndDate
UNION ALL
SELECT
     '123456' AS ID
    , 548758 AS DeptID
    , DATEADD(D, DATEDIFF(d, 0, getdate()), 0) AS StartDate
    , NULL AS EndDate
    ) AS a

SELECT * FROM #tblEmployee

SELECT * FROM #tblEmployeeDeptByDay

When HR moves an employee to another department currently I manually update tblEmployeeDeptByDay with the end date of the old department - and the details of the new (based off of an alert I generate). I want to automate this, inserting the new record is easy but I cant work how to update the previous record with an end date.
So the final output would be as the #tblEmployeeDeptByDay data above after HR has changed the date in #tblEmployee.
I've attempted various CTE's configuration and using LEAD but cant get it to do the final update.
Output expected as above

A: UPDATE tblEmployeeDeptByDay SET StartDate = DATEADD(YY,DATEDIFF(YY,0,GETDATE()), 0) , EndDate= DATEADD(D, DATEDIFF(d, 0,getdate())-1, 0)
WHERE EID=("Your selection");

I think it will be something like this from what I understood.


text:
Q: How to solve the "Invalid regular expression: /?/: Nothing to repeat" problem I want to replace every occurence of a question mark, point, comma etc. in a string called TextToSimplify but I keep getting the error as said in the title. What can I do about it
ToSimplifyText = ToSimplifyText.replace(/,/g, "");
ToSimplifyText = ToSimplifyText.replace(/./g, "");
ToSimplifyText = ToSimplifyText.replace(/!/g, "");
ToSimplifyText = ToSimplifyText.replace(/?/g, "");
ToSimplifyText = ToSimplifyText.replace(/'/g, "");

A: You can do all that stuff on one single replace, like this:

ToSimplifyText = "Hello. Dude! Aren't you ok?"
console.log(ToSimplifyText.replace(/[,.'?!]/g, ""));

Note, that if you want to replace a special character, you will have to escape it with \. Note also, this is not necessary when using a set of characters with [...], like in the previous example:

ToSimplifyText = "Hello. Dude! Aren't you ok?"
console.log(ToSimplifyText.replace(/\?/g, ""));


text:
Q: How to show django messages based on queryset filter? I want to show message based on my filter.
CHOICES = (

        ('0', 'published',),

        ('1', 'pending',),

        ('2', 'rejected',),

        )

Here I tried this code for showing message based on filter but it's only showing the published message.
def get_context_data(self, **kwargs):

            data = super().get_context_data(**kwargs)

            published = BlogComment.objects.filter(is_published="0")

            pending = BlogComment.objects.filter(is_published="1")

            if published:

                 messages.add_message(self.request, messages.INFO, 'Comment status published Sucessfully')

            elif pending:

               messages.add_message(self.request, messages.INFO, 'Comment status pending Sucessfully')

            return data

why I am only getting the published message?
I also tried if statement instead of elif. After using if statement I am getting three message at time while changing status of any object.
        if published:
             messages.add_message(self.request, messages.INFO, 'Comment Published Sucessfully')
        if pending:
             messages.add_message(self.request, messages.INFO, 'Comment Status Pending')
        if rejected:
             messages.add_message(self.request, messages.INFO, 'Comment Status

A: Are you trying to display the status update of a single object? If so then you can simply update your view logic where view is inherited from from django.views.generic import UpdateView.
from django.views.generic import UpdateView
from django.contrib import messages

class YourUpdateView(UpdateView):
    # other part of view

    def form_valid(self, form):
        self.object = form.save()
        status = self.object.status
        messages.success(self.request, f"Status updated to {status}")
        return super().form_valid(form)

If I'm mistaken please explain in detail in the comment.


text: Q: Error importing 'CoreData/CoreData.h' I just finished my first successful CoreData store and fetch which worked fine in the simulator, but wouldn't run on my device (I got dozens of errors). Most of the errors were link errors and I was able to fix them by deleting all the links to the CoreData framework and then re-linking it in the build phases tab. This solved most of the errors when building for my device, but introduced 2 errors when building for the simulator. The errors are all the same thing "CoreData/CoreData.h file not found" although I checked the file directory and it seems to be fine. I also have another app from a tutorial that uses CoreData and it runs fine and has the same file directory. Specifically, the errors are in my NSManagedObject classes, fresh out of the .xcdatamodel and obviously occur on the line where I import .


text:
Q: What would be the simplest system to send sms from linux server? What would be the simplest system to send sms from linux server? It`s a Debian system. There would be not much SMSes. What hardware and software to use? Maybe use some SMS sending service?

A: If you like to to do it yourself and utilize your old mobile phone, try this recipe :-)
There is a real advantage in this approach over using some email SMS service: computer network problems don't affect local hardware. It's especially important if you use SMSes for monitoring your server.

A: Each cell phone company offers email addresses to send sms messages to phones. For example verizon uses something like 55512345678@vtext.com to send messages. All you need to do is find a list of each provider's email domain and then find out the service your user subscribes. After that just send the sms like a regular email. This is how most software does it.

A: Since you are probably looking for a lithuanian service (judging from your name), look into www.gsms.lt.

A: Yeah, I think the simplest way would be getting a serial GSM modem, or a GSM phone with a serial connection, and a SIM card. Some USB ones can work, but is better getting a serial one and staying on the safe side.
Serial modems don't need any drivers, you just need to connect via the serial port (/dev/tty...) and dump there the commmands...
Also, if you want it easier, you can install the SMS Tools available on Linux. They are packaged with the easy name 'smstools' in Ubuntu, Debian, and other Distros.
Last version is number 3, and you can get some info on this site:
http://smstools3.kekekasvi.com/

A: Maybe this Question helps you. Otherwise take a look at Kannel.

A: There is another option perl independent exec. Download and Run directly.
No Moderm required. Global sms supported and free try.
you can refer http://www.sms4mail.com/smsmail/smscmd.htm

A: the simplest way is to use a GPRS modem or a pool of modems. More advance - buy gateway service in cell network operator.

A: Use a modem connected to a serial port. And use gnokii.


text:
Q: MySQL How do I join and select visible records from one table? I'm trying to fix some data by adding a new field.
I have a backup from a few months ago and I have restored this database to my server.
I'm looking at table called pads, its primary key is PadID and the field of importance is called RemoveMeDate.  In my restored (older) database there is less records with an actual date set in RemoveMeDate. My control date is 2001-01-01 00:00:00 meaning that the record is not hidden aka visible.
What I need to do is select all the records from the older database / table with the control date and join with those from the newer db /table where the control date is not set.
I hope I've explained that correctly.
I'll try again, with numbers.  I have 80,000 visible records in the older table (with control date set) and 30,000 in the newer db/table. I need to select the 50,000 from the old database, to perform an update query.
Heres my query, which I'd can't get to work as I'd like.  jules-fix-reasons is the old database, jules is the newer one.
select p.padid
from `jules-fix-reasons`.`pads` p
JOIN `jules`.`pads` ON p.padid = `jules`.`pads`.`PadID`
where p.RemoveMeDate <> '2001-01-01 00:00:00' AND
`jules`.`pads`.RemoveMeDate =     '2001-01-01 00:00:00'

EDIT - Perhaps I can provide an example, instead of a 10,000 records I'll show 1 example.
p.pads (old table)
PadID=1 RemoveMeDate=2010-12-01 09:00:00
PadID=2 RemoveMeDate=2001-01-01 00:00:00
PadID=3 RemoveMeDate=2001-01-01 00:00:00
PadID=4 RemoveMeDate=2001-01-01 00:00:00
PadID=5 RemoveMeDate=2001-01-01 00:00:00
PadID=6 RemoveMeDate=2001-01-01 00:00:00
PadID=7 RemoveMeDate=2001-01-01 00:00:00
PadID=8 RemoveMeDate=2001-01-01 00:00:00
PadID=9 RemoveMeDate=2001-01-01 00:00:00
PadID=10 RemoveMeDate=2009-01-05 00:10:00

So theres 8 (aks=a 80,000 in the real table) records visible.
Jules.pads
PadID=1 RemoveMeDate=2010-12-01 09:00:00
PadID=2 RemoveMeDate=2010-12-01 08:00:00
PadID=3 RemoveMeDate=2010-12-01 07:00:00
PadID=4 RemoveMeDate=2010-12-01 06:00:00
PadID=5 RemoveMeDate=2001-01-01 00:00:00
PadID=6 RemoveMeDate=2001-01-01 00:00:00
PadID=7 RemoveMeDate=2001-01-01 00:00:00
PadID=8 RemoveMeDate=2001-01-01 00:00:00
PadID=9 RemoveMeDate=2001-01-01 00:00:00
PadID=10 RemoveMeDate=2009-01-05 00:10:00

So theres 5 (aks=a 50,000 in the real table) records visible.
So the SQL query I want would return records 2,3,4 from table P
Edit ajreal - working query (FYI)
SELECT old_table.padid
FROM `jules-fix-reasons`.`pads` AS old_table
JOIN `jules`.`pads` AS new_table ON old_table.padid = new_table.`PadID`
WHERE new_table.RemoveMeDate <> '2001-01-01 00:00:00'
AND old_table.RemoveMeDate = '2001-01-01 00:00:00'

A:
What I need to do is select all the records from the older database / table with the control date and join with those from the newer db /table where the control date is not set.

you just need to flip the condition
select old_table.padId, new_table.padId
from `jules-fix-reasons`.`pads` as old_table
JOIN `jules`.`pads` as new_table
ON old_table.padid = `jules`.`pads`.`PadID`
where new_table.RemoveMeDate<>'2001-01-01 00:00:00' AND
old_table.RemoveMeDate='2001-01-01 00:00:00'

PS: is time to learn how to give a good name for your table alias


text:
Q: Why does ImagesService always return urls with ip 0.0.0.0 in development? Does anybody know why ImagesService.getServingUrl() from Google App engine SDK (1.6.0) always returns 0.0.0.0 in url in development enviroment ? How can I change it ? Initially I thought it depends on binding IP for DevServer which I pass in "--address" parameters but it turns out it's not the case.
This is problem for me because I can't fetch image from http://0.0.0.0/ on Windows 7 machine. But I know it works on Mac.
Plus I'd like to be able to test my GWT app from another machine in the network therefore I'd like to bind to IP other than localhost.
Because of it I have to string.replace() "0.0.0.0" with my real ip which kinda lame :)
Thanks!

A: It is a bit annoying, and I think that a lot of people have that same string-replace in their code.  I suspect that the GAE team have it as a low priority (rightly), because of its low impact and easy workaround.  Anyway, there is at least one open issue on their issue tracker:  http://code.google.com/p/googleappengine/issues/detail?id=4402
Here's another related issue:  http://code.google.com/p/googleappengine/issues/detail?id=5871
You might want to double-check that you aren't specifying (even accidentally) the ip address when starting up the development server.

A: i solved it by going  Edit->Application Settings and then remove all values from "External Command line flags"


text:
Q: Unity TileMap has no tiles I have created a tilemap containing several tiles using the Tile Palette Gamobject brush in Unity. The tilemap is correctly rendered when I run my game.
TileMap created
However when I try to access the tiles from code no tiles can be accessed. I used the following script
Tilemap tileMap = GetComponent<Tilemap>();
    List<Vector3> availablePlaces = new List<Vector3>();
    Debug.Log(tileMap.name+" Tiles are " + tileMap.size.x+", "+ tileMap.size.y + ", "+ tileMap.size.z);
    Debug.Log("Cell bounds: " + tileMap.cellBounds.x + ", " + tileMap.cellBounds.y + ", " + tileMap.cellBounds.z);
    for (int n = tileMap.cellBounds.xMin; n < tileMap.cellBounds.xMax; n++)
    {
        for (int p = tileMap.cellBounds.yMin; p < tileMap.cellBounds.yMax; p++)
        {
            Vector3Int localPlace = (new Vector3Int(n, p, (int)tileMap.transform.position.y));
            Vector3 place = tileMap.CellToWorld(localPlace);
            if (tileMap.HasTile(localPlace))
            {
                //Tile at "place"
                availablePlaces.Add(place);
            }
            else
            {
                //No tile at "place"
            }
        }
    }

The values x, y, z of tileMap.size are 0,0,1
The values x, y, z of tileMap.cellBounds are 0,0,0
Does anyone know what am I doing wrong? Thank you.

A: When you use the GameObject brush no tiles are instantiated. Instead, this brush what does is to instantiate a new clone of that GameObject aligned to the Grid of the Tilemap.

A: I know this is old, but I just had the same issue.  T
he work around I am using for now is to not use the GameObject brush and instead create the levels programmatically. For example to create a simple rectangle you could so something like this:

 // draw initial walls
        Vector3Int borderOrigin = new Vector3Int(0, 0, 0);

        for(int h = 0; h <= height; h++)
        {
            for (int w = 0; w <= width; w++)
            {

                Vector3Int newPos = borderOrigin + new Vector3Int(w, h, 0);

                if(h == 0 | w == 0 | h == height | w == width)
                {
                    Debug.Log(newPos.ToString());
                    Tile wallTile1 = ScriptableObject.CreateInstance<Tile>();
                    wallTile1.gameObject = wallPrefabBorder;

                    myTileMap.SetTile(newPos, wallTile1);
                }
            }

        }

I'm sure there are much more efficient means of plotting out a rectangle, but since I only need to do it once this sloppiness worked.


text:
Q: Getting error CS0031: Constant value `65535' cannot be converted to a `short' I'm getting the above error on this line:
Int16 maskBits = 0xFFFF;

I am doing this because I am working with the Box2D library, written in C++.
It says here that:

"The default values are 0x0001 for categoryBits and 0xFFFF for maskBits"

I thought 0xFFFF or 65535 was the maximum value for an Int16?
Edit: Should be a UInt16  duuh!! thanks people!

A: 0xFFFF is for UInt16. For Int16 the max value is 32767.

A: 0xFFFF is certainly not a 16 bit signed literal, it is at least (depending on your language: you've tagged a couple) 32 bits with a value 65535. Conversion to a signed 16 bit signed number will fail as the largest value is 32767.

A: the max value of int16 is 32767 which is 0x7FFF

A: The maximum value for a int16 would be 32767 as it's signed (the minimum would be -32768)
You want a uint16 type (as it's unsigned). This would give you a maximum value of 65535 (ie 0xFFFF) and a minimum value of 0.


text:
Q: Creating a zebra effect using listings
This question led to a new package:
lstlinebgrd (lstaddons bundle)

Friends, consider the following example using the listings package:
\documentclass{article}

\usepackage[T1]{fontenc}
\usepackage{beramono}
\usepackage{listings}
\begin{document}

\begin{lstlisting}[language=C,basicstyle=\ttfamily]
/**
* Prints Hello World.
**/
#include <stdio.h>

int main(void) {
   printf("Hello World!");
   return 0;
}
\end{lstlisting}

\end{document}

The output is as we expect:

I was wondering if we could add something I know as zebra effect (pardon my possible misinterpretation of this term). I know this as a common style used in tables, where rows alternate colors, hence the name zebra. The previous example should look something like this:

Does anyone have any ideas?

A: The following code is giving a zebra effect. See below for a description.
\documentclass{article}

\usepackage[T1]{fontenc}
\usepackage{beramono}
\usepackage{listings}
\usepackage{xcolor}

\newcommand\realnumberstyle[1]{}

\makeatletter
\newcommand{\zebra}[3]{%
    {\realnumberstyle{#3}}%
    \begingroup
    \lst@basicstyle
    \ifodd\value{lstnumber}%
        \color{#1}%
    \else
        \color{#2}%
    \fi
        \rlap{\hspace*{\lst@numbersep}%
        \color@block{\linewidth}{\ht\strutbox}{\dp\strutbox}%
        }%
    \endgroup
}
\makeatother

\begin{document}

\begin{lstlisting}[language=C,basicstyle=\ttfamily,numberstyle=\zebra{green!35}{yellow!35},numbers=left]
/**
* Prints Hello World.
**/
#include <stdio.h>

int main(void) {
   printf("Hello World!");
   return 0;
}
\end{lstlisting}

\bigskip

% If you want to make the bars shorter you need to use a `minipage` or similar environment:
\noindent
\begin{minipage}{.45\textwidth}
\begin{lstlisting}[language=C,basicstyle=\ttfamily,numberstyle=\zebra{green!25}{white},numbers=left]
/**
* Prints Hello World.
**/
#include <stdio.h>

int main(void) {
   printf("Hello World!");
   return 0;
}
\end{lstlisting}
\end{minipage}

\end{document}

My first idea was to use backgroundcolor with a conditional depending on the line number, but it seem only be used for boxing the whole listing. After studying the source code of listings a while to learn how to hack the line processing I came to the idea to (mis-)use the numberstyle for this. It is called with the line number register as argument and is typeset inside a \llap in a distance of numbersep. I just put a low-level command of \colorbox (xcolor package) called \color@block inside a \rlap to place the colored bars. This requires numbers=left. If you don't want lines numbers keep \realnumberstyle how it is, or redefine it otherwise.
If you only want one color you can use the following definition and numberstyle=\zebra{<color>}.
\newcommand{\zebra}[2]{%
    {\realnumberstyle{#2}}%
    \begingroup
    \lst@basicstyle
    \ifodd\value{lstnumber}%
        \color{#1}%
        \rlap{\hspace*{\lst@numbersep}%
        \color@block{\linewidth}{\ht\strutbox}{\dp\strutbox}%
        }%
    \fi
    \endgroup
}

In the meantime I had a second look on the listings source code, this time to the numbers key. The following package hacks this key to inserts its own handler without interfering with the numbering like the code above. It then provides a set of new listings keys/options called linebackground..., to the set background color but also the height, depth, width, separation or even the drawing command.
You can set the color using linebackgroundcolor=<some color code> which can hold a conditional. The default background color is -., i.e. the opposite (-) of the current foreground color (aliased as . by xcolor). The box drawing code follows after color code inside braces, so if not background is wanted (not even a white one) than the color code can simply gobble the box drawing code as an argument.
% lstlinebgrd.sty
\RequirePackage{listings}
\RequirePackage{xcolor}

% Patch line number key to call line background macro
\lst@Key{numbers}{none}{%
    \def\lst@PlaceNumber{\lst@linebgrd}%
    \lstKV@SwitchCases{#1}%
    {none&\\%
     left&\def\lst@PlaceNumber{\llap{\normalfont
                \lst@numberstyle{\thelstnumber}\kern\lst@numbersep}\lst@linebgrd}\\%
     right&\def\lst@PlaceNumber{\rlap{\normalfont
                \kern\linewidth \kern\lst@numbersep
                \lst@numberstyle{\thelstnumber}}\lst@linebgrd}%
    }{\PackageError{Listings}{Numbers #1 unknown}\@ehc}}

% New keys
\lst@Key{linebackgroundcolor}{}{%
    \def\lst@linebgrdcolor{#1}%
}
\lst@Key{linebackgroundsep}{0pt}{%
    \def\lst@linebgrdsep{#1}%
}
\lst@Key{linebackgroundwidth}{\linewidth}{%
    \def\lst@linebgrdwidth{#1}%
}
\lst@Key{linebackgroundheight}{\ht\strutbox}{%
    \def\lst@linebgrdheight{#1}%
}
\lst@Key{linebackgrounddepth}{\dp\strutbox}{%
    \def\lst@linebgrddepth{#1}%
}
\lst@Key{linebackgroundcmd}{\color@block}{%
    \def\lst@linebgrdcmd{#1}%
}

% Line Background macro
\newcommand{\lst@linebgrd}{%
    \ifx\lst@linebgrdcolor\empty\else
    \rlap{%
        \lst@basicstyle
        \color{-.}% By default use the opposite (`-`) of the current color (`.`) as background
        \lst@linebgrdcolor{%
        \kern-\dimexpr\lst@linebgrdsep\relax%
        \lst@linebgrdcmd{\lst@linebgrdwidth}{\lst@linebgrdheight}{\lst@linebgrddepth}%
        }%
    }%
    \fi
}

Usage:
\documentclass{article}

\usepackage{lstlinebgrd}

\begin{document}

\begin{lstlisting}[language=C,basicstyle=\ttfamily,linebackgroundcolor={\ifodd\value{lstnumber}\color{green}\fi}]
/**
* Prints Hello World.
**/
#include <stdio.h>

int main(void) {
   printf("Hello World!");
   return 0;
}
\end{lstlisting}

\begin{lstlisting}[language=C,basicstyle=\ttfamily\Large,linebackgroundcolor={\ifodd\value{lstnumber}\color{green}\else\color{yellow}\fi},linebackgroundsep=1em,linebackgroundwidth=18em]
/**
* Prints Hello World.
**/
#include <stdio.h>

int main(void) {
   printf("Hello World!");
   return 0;
}
\end{lstlisting}

\begin{lstlisting}[language=C,basicstyle=\ttfamily\tiny,linebackgroundcolor={\color{blue!\the\numexpr 5*\value{lstnumber}\relax}},linebackgroundheight=1.7ex,linebackgrounddepth=.4ex]
/**
* Prints Hello World.
**/
#include <stdio.h>

int main(void) {
   printf("Hello World!");
   return 0;
}
/**
* Prints Hello World.
**/
#include <stdio.h>

int main(void) {
   printf("Hello World!");
   return 0;
}
\end{lstlisting}

\end{document}


text:
Q: The argument of -i should be 2 readable file I am currently using argparse like this:
from argparse import ArgumentParser

def is_valid_file(parser, arg):
    if not os.path.exists(arg):
        parser.error("File %s khong ton tai!" % arg)
    else:
        return open(arg, 'rb')   # return an open file handle

def readinput():
    parser = ArgumentParser(description="ikjMatrix multiplication")
    parser.add_argument("-i", dest="filename", required=True,
                        help="File need predict", metavar="FILE",
                        type=lambda x: is_valid_file(parser, x))
    args = parser.parse_args()
    return args.filename.read()

I want to run  python3 demo.py -i text1.txt text2.txt.
I would like to get 2 readable file. How can I do that?
thank you for your help!

A: import argparse

parser = argparse.ArgumentParser(description="Testfile")
parser.add_argument("-f", "--files", help="The files", nargs=2)
args = parser.parse_args()
print(args.files)

Usage:
python .\test.py -f 1.txt 2.txt
['1.txt', '2.txt']

python .\test.py -f 1.txt
usage: test.py [-h] [-f FILES FILES]
test.py: error: argument -f/--files: expected 2 arguments


text:
Q: AngularJs routing white screen while loading page A have a web application (AngularJS 1.5.6) that changes the screen content every x seconds. The screen is white for 1-2 seconds after the change, because there is a lot of data processing behind, Http get calls, etc.
The app is using ui.router to change the page content. The Controller is pretty big and is using a lot of other services and directive components.
I tried to move the content from a app.factory component (the main factor that produces this delay) to a app.provider and use it in $stateProvider.resolve block but i'm getting a lot of errors.
Is there another option to this problem?
If not, how should I refactor my code? Do you have an example?
Thank You!


text:
Q: Rename column in DB2 I am trying to rename a column in one table where data already exists.
But below is the error it is throwing.Please advice.
Syntax I tried
ALTER TABLE TPR.PRODUCT_FEATURE RENAME COLUMN PRODUCT_ID TO SERVICE_ID

Error:

[Error] Script lines: 23-23 ------------------------
   DROP, ALTER, TRANSFER OWNERSHIP, REVOKE, or CREATE OR REPLACE on object type "COLUMN" cannot be processed because there is an object "PRODUCT_FEATURE_X01", of type "PRIMARY KEY", which depends on it.. SQLCODE=-478, SQLSTATE=42893, DRIVER=3.67.28

Looks me to, I need to drop and recreate is the only option. Please advice.

A: Drop the constraint:
ALTER TABLE TPR.PRODUCT_FEATURE
    DROP CONSTRAINT PRODUCT_FEATURE_X01

Then alter your table:
ALTER TABLE TPR.PRODUCT_FEATURE RENAME COLUMN PRODUCT_ID TO SERVICE_ID

Then add new constraint:
ALTER TABLE TPR.PRODUCT_FEATURE
      ADD CONSTRAINT PRODUCT_FEATURE_X01
      PRIMARY KEY (insert,columns,here)