text:
Q: Messages with persistence get stuck in ActiveMQ embedded in Tomcat I am trying to integrate ActiveMQ within Tomcat. To that end, I used this tutorial (a little outdated, I know, but the best I found). I created a servlet that instantiates and starts a broker:
try {
  broker = new BrokerService();
  broker.addConnector("tcp://localhost:61616");
  broker.start()
} catch (final Exception e) {
  e.printStackTrace();
}

I then created a simple Hello World example with a single producer sending a persisted message to a queue and a consumer retrieving the message, which failed. Both, producer and consumer, were able to connect to ActiveMQ and the queue but the consumer did not receive any message. However, after restarting Tomcat (and consequently the broker), the consumer received the message previously sent. Any newly created messages were again stuck.
I tried some non-persisted messages, which all arrived as expected. When sending a combination of persisted and non-persisted messages, the non-persisted ones arrived immediately and the persisted ones required a restart.
This is my (very basic) code for the producer and consumer:
final ConnectionFactory conFactory = (ConnectionFactory) jndi.lookup("connectionFactory");
final Connection connection = conFactory.createConnection();
connection.start();
final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

final Destination destination = (Destination) jndi.lookup("MyQueue");
final MessageProducer producer = session.createProducer(destination);
producer.setDeliveryMode(DeliveryMode.PERSISTENT);

final TextMessage message = session.createTextMessage("Hello World!");
producer.send(message);

connection.close();

final ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
connectionFactory.setTrustAllPackages(true);

final Connection connection = connectionFactory.createConnection();
connection.start();

final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
final Destination destination = session.createQueue("APP.JMS.QUEUE");
final MessageConsumer consumer = session.createConsumer(destination);

final Message message = consumer.receive(1000);
System.out.println("Received: " + message);

consumer.close();
session.close();
connection.close();

I tried transacted, manual-acknowledge, and auto-acknowledge mode for the consumer. I also tried directly creating ConnectionFactory and Destination (as in the consumer code) as well as JNDI lookup (producer code). All yielded the same result.
I tried versions 5.15.12, 5.15.11, 5.14.5, 5.11.0 and 5.10.0.
Any pointers what I did wrong or where I can find a more recent tutorial? I am aware of the official docs regarding ActiveMQ and Tomcat but they seem to be missing the essential parts.


text:
Q: Drupal 7 - Programmatically tagging nodes I am trying to populate the content of a Drupal 7 site programatically by reading from a CSV file. I have all the code for that, but the next step is to automatically tag each node with a series of terms found in 3 different columns.
Now I know that I can tag the node using the term id, but is there a way to tag using the term name?
I'm looking  at something like this where $tags is an array of strings that are supposed to be tag terms.
$a = 0;
foreach ($tags as $tag) {
  $node->field_tags[$node->language][]['a'] = $tag;
  $a++;
}

I appreciate any help I can get. Thanks!

A: Instead of finding the term ids yourself, you can use taxonomy_get_term_by_name function.
This function returns the list of matching term objects.

redpajama_set_name: RedPajamaStackExchange


text:
Q: После установки java centos insufficient memory for Java Runtime Environment to continue Долго не запускалась java на vds centos последней версии, ошибка:

insufficient memory for Java Runtime Environment to continue could not
  reserve enough space for object heap java version

Долго мучился и разные версии ставил и решения разные, пока не нашел совет один в интернете убрать ограничение ресурсов командой:
ulimit -v unlimited

Или же ulimit -Sv ... в файл  /etc/profile чтоб навсегда.

ENGLISH ERROR: insufficient memory for Java Runtime Environment to
  continue could not reserve enough space for object heap java version
  English fix: "ulimit -v unlimited"
which is done every time we log in. Alternatively, we can also comment
  out the line
"ulimit -Sv ..."
in /etc/profile, which is a more permanent solution.

A: Долго мучился и разные версии ставил и решения разные пока не нашел совет один в интернете убрать ограничение ресурсов коммандой: ulimit -v unlimited Или же ulimit -Sv ... в файл /etc/profile чтоб навсегда.
ENGLISH ERROR: insufficient memory for Java Runtime Environment to continue could not reserve enough space for object heap java version English fix: "ulimit -v unlimited"
which is done every time we log in. Alternatively, we can also comment out the line
"ulimit -Sv ..."
in /etc/profile, which is a more permanent solution.


text:
Q: IE 11 picks up only some css rules but not others I have a
 that is not displaying its background colour. Yet all other CSS rules work as normal. Here is the code i've written
HTML file:
<link rel="stylesheet" href="css/General.css">`
...

In my externally referenced CSS file:
.tableHeader {
    background-color: #428bca !important; /*blue*/
    color:white;
}

This works fine in all other browsers except ie 11. In the DOM explorer of developer tools, i can see it has picked up other rules from my css file so im not sure why it would skip this one. Any ideas?
EDIT: ok obviously i cant read.. The css rule has a capital H.. but.. my question is still the same. Why the different behaviour? why are some browsers case sensitive and others not?

A: You are using camelCase in your css, yet the class name is not camelCase. HTML is case sensitive.
Example

.elementa {
    height: 50px;
    width: 50px;
    background: red;
}

.elementA {
    background: yellow;
}

A: You have different class name in css (tableHeader) and html (tableheader)

.tableHeader {
    background: #428bca !important; /*blue*/
    color:white;
}

        skdksl


text:
Q: Wicked_pdf Table of Contents text size very small I am trying to generate PDF using
WIckedPdf version = 1.1.0
wkhtmltopdf 0.12.4 (with patched qt)
Rails 4.2
Below is my Controller endpoint
@cover = render_to_string layout: "application.html.erb", template: "pdf/cover.html.erb", locals: {report: @report}
@pdf = render_to_string pdf: "report",
encoding: "UTF-8",
page_size: 'A4',
layout: "pdf.html.erb",
orientation: 'Portrait',
disable_smart_shrinking: false,
disable_internal_links: false,
disable_external_links: false,
lowquality: false,
background: true,
no_background: false,
page_height: 297,
page_width: 210,
cover: @cover,
template: "pdf/report.pdf.erb",
locals: {report: @report},
show_as_html: false,
margin: {
bottom: 40,
top: 10
},
footer: {
html: {
template: 'pdf/footer.html.erb' # use :template OR :url
}
},
toc: {
text_size_shrink: 0.8,
header_text: "Table of Contents",
no_dots: false,
disable_dotted_lines: false,
disable_links: false,
disable_toc_links: false,
disable_back_links: false,
}

send_data @pdf, type: :pdf, disposition: 'inline'

Am facing the problem that All the text that are generated in pdf is very very SMALL. To achieve font size of 14 in pdf, i had to change my css as font-size: 56px (Four times than the normal pixel)
Can Anybody help me why font size is rendered like this? Also, All the css that includes pixels such as padding, margin are four times smaller than normal.
Even if changed CSS of my file to four times higher values, CURRENTLY I AM UNABLE TO CHANGE FONT_SIZE FOR TABLE OF CONTENTS GENERATED.
Any help / Reference would be highly helpful and appreciated

A: Setting dpi: 300 should fix your issue with the content rendering too small.

A: I had the same issue and, I could fix it by adding lowquality: true to wicked_pdf config file. In config/wicked_pdf.rb file
WickedPdf.config = {
  #cross enviroment configs
}

if Rails.env.development?
  WickedPdf.config[:lowquality] = true
end

Credits & Reference: Issue #754

A: You can add CSS class in your view template to increase the Font Size like normal HTML.


text:
Q: how can I return a subset of a mongo populate call? I am using the mongo db 'ref' functionality to populate objects from a table into a document that I am returning
Here is the table that stores the object ID ref
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const StaticAssignmentSchema = new Schema({
  affiliation: { type: String },

  REF_person: [{ type: Schema.Types.ObjectId, ref: 'users' }],
});

module.exports = StaticAssignmentNew = mongoose.model('staticassignments', StaticAssignmentSchema);

Here is my users table schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const UserSchema = new Schema({
  name: { type: String },
  phone: { type: String },
  password: { type: String },
  affiliation: { type: String },
  timezone: { type: String },
  date: { type: Date, default: Date.now },
});

module.exports = User = mongoose.model('users', UserSchema);

Here is how I am getting the data from mongo
  var query = { affiliation: affiliation };
  var ret = await StaticAssignment.findOne(query).populate('REF_person');

which returns the following:
{
  "_id": "61a8376154377e5704ae79cf",
  "affiliation": "800_800",
  "REF_person": [{
    "_id": "5e441bd5332359211c0403fb",
    "name": "Frank",
    "phone": "8008008001",
    "password": "$2a$10$T9wYLE3v/n8S4GB.oyYOmCsGUdxXQiOjpiDaG0JGbKy",
    "affiliation": "800_800",
    "timezone": "America/Los_Angeles",
    "date": "2020-02-12T15:37:57.167Z"
  }]
}

however, I would like to return a subset of the populate call:
{
  "_id": "61a8376154377e5704ae79cf",
  "affiliation": "800_800",
  "REF_person": [{
    "_id": "5e441bd5332359211c0403fb",
    "name": "Frank",
    "phone": "8008008001",
  }]
}

what can I do to return the subset ?
thank you Mastermind !
ANSWER:
  var query = { affiliation: affiliation };
  var ret = await StaticAssignment.findOne(query)
  .populate({path: 'REF_person', select: '_id name phone'});

A: Try   var ret = await StaticAssignment.findOne(query).populate({path: 'REF_person', select: 'name phone'});
Check out this page: https://www.codegrepper.com/code-examples/whatever/mongoose+populate+select+fields


text:
Q: .get() python json file discord bot I have a json file that stores the ids, xp and level of who writes on my server.
I'm making a leaderboard to show the people who have most xp on my server,
however a keyerror appears:
    KeyError: '370034734186758173'
Could someone help me fixing this error?

A: The .get would be used when accessing the users dictionary. You can add a second parameter to the call as the default (in case you don't find such a key), which in the first call you should output a empty dictionary, so that the second .get doesn't fail.
lb = list(map(lambda m: (m, users.get(m.id, {}).get("xp"), message.server.members))

Since you are making a list out of it, you may also want to try (the somewhat more pythonic) list comprehension (not that your line has anything wrong with it):
lb = [ (m, users.get(m.id, {}).get("xp") for m in message.server.members ]

Note that both approaches will return a None item when the get doesn't find the Key in the dictionary, you can ommit this using an if clause in the list comprehension:
lb = [ (m, users.get(m.id, {}).get("xp") for m in message.server.members if m.id in users ]

As a side note, I would add that you have included everything within the context manager clause (with open():), while only the line where you load its contents is necessary. It would be best practice to de-indent the rest of your code.

A: So right off the back your friend was probably referring to the fact you could do something like this:
lb = list(map(lambda m: (m, users.get(m.id, {'xp': 0}).get('xp')), message.server.members)]
But as to why this works, you should first read the documentation: https://docs.python.org/2/library/stdtypes.html#dict.get
But I think you might prefer a list comprehension for what you're doing instead:
https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions
for example you could rewrite how you get your lb variable like so:
lb = [(member, users[member.id].get('xp')) for member in message.server.members if member.id in users]
This is equivalent to writing the following:
lb = []
for member in message.server.members:
    # Check if the member is in your users list
    if member.id in users:
        lb.append((member, users[member.id].get('xp')))


text:
Q: Logging into a website using Mechanize and Nokogiri? I am having some difficulty with one of our service providers login forms. The other sites are working fine but for some reason I can't get past their login form.
The website login for is like this:
<form accept-charset="UTF-8" action="/sessions" class="new_user_session" id="new_user_session" method="post">
<input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="kaLEkPesQfeheronzGTdfnVAzpuUiC+VmjVXBu540n8=" />

      <fieldset class="big">

        Email

        <input id="user_session_email" name="user_session[email]" size="30" type="text" />

        Password

        <input id="user_session_password" name="user_session[password]" size="30" type="password" />

Forgot your password?

            <input name="user_session[remember_me]" type="hidden" value="0" /><input id="user_session_remember_me" name="user_session[remember_me]" type="checkbox" value="1" /> Remember me for 2 weeks

</fieldset>

I have tried to login using the same code as other the other sites but it doesn't work.
# Create a new mechanize object
agent = Mechanize.new

# Load the dial9 website
page = agent.get("http://webapplication.co.uk")

# Select the first form
form = agent.page.forms.first
form.username = 'username
form.password = 'password'

# Submit the form
page = form.submit form.buttons.first

I have also tried a different way of logging in as suggested in other SO questions/answers:
email = 'user@domain.com'
password = 'password

# Create a new mechanize object
agent = Mechanize.new

# Load the postmarkapp website
page = agent.get("https://domain.com")

# Select the first form
form = agent.page.forms.first
form.field_with(:email => "user_session_email").value = email
form.field_with(:password => "user_session_password").value = password

# Submit the form
page = form.submit form.buttons.first

Using this method of authentication I get the following output when running the rake task:
undefined method `email' for [hidden:0x3fef2ab2b994 type: hidden name: utf8 value: ✓]:Mechanize::Form::Hidden

Upon closer inspection the above error seems to be due to the fact that there is a field immediately after the form is started:
<form accept-charset="UTF-8" action="/sessions" class="new_user_session" id="new_user_session" method="post">
<input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="kaLEkPesQfeheronzGTdfnVAzpuUiC+VmjVXBu540n8=" />

Am I missing something? If so, what? Any pointers are appreciated!

A: Try changing
form.field_with(:email => "user_session_email").value = email
form.field_with(:password => "user_session_password").value = password

to
form.field_with(:name => "user_session[email]").value = email
form.field_with(:name => "user_session[password]").value = password


text:
Q: How to distribute `.desktop` files and icons for a Python package in Gnome (with distutils or setuptools)? Currently I'm using the auto-tools to build/install and package a project of mine, but I would really like to move to something that feels more "pythonic".
My project consists of two scripts, one module, two glade GUI descriptions, and two .desktop files.  It's currently a pure python project, though that's likely to change soon-ish.
Looking at setuptools I can easily see how to deal with everything except the .desktop files; they have to end up in a specific directory so that Gnome can find them.
Is using distuils/setuptools a good idea to begin with?

A: I managed to get this to work, but it kinda feels to me more like a workaround.
Don't know what's the preferred way to handle this...
I used the following setup.py file (full version is here):
from setuptools import setup

setup(
  # ...
  data_files=[
    ('share/icons/hicolor/scalable/apps', ['data/mypackage.svg']),
    ('share/applications', ['data/mypackage.desktop'])
  ],
  entry_points={
    'console_scripts': ['startit=mypackage.cli:run']
  }
)

The starter script trough entry_points works. But the data_files where put in an egg file and not in the folders specified, so they can't be accessed by the desktop shell.
To work around this, I used the following setup.cfg file:
[install]
single-version-externally-managed=1
record=install.txt

This works. Both data files are created in the right place and the .desktop file is recognized by Gnome.

A: In general, yes - everything is better than autotools when building Python projects.
I have good experiences with setuptools so far. However, installing files into fixed locations is not a strength of setuptools - after all, it's not something to build installaters for Python apps, but distribute Python libraries.
For the installation of files which are not application data files (like images, UI files etc) but provide integration into the operating system, you are better off with using a real packaging format (like RPM or deb).
That said, nothing stops you from having the build process based on setuptools and a small make file for installing everything into its rightful place.

A: You can try to use python-distutils-extra. The DistUtilsExtra.auto module automatically  supports .desktop files, as well as Glade/GtkBuilder .ui files, Python modules and scripts, misc data files, etc.
It should work both with Distutils and Setuptools.

A: I've created https://pypi.python.org/pypi/install-freedesktop. It creates .desktop files automatically for the gui_scripts entry points, which can be customized through a setup argument, and supports --user as well as system-wide installation. Compared to DistUtilsExtra, it's more narrow in scope and IMHO more pythonic (explicit is better than implicit).


text:
Q: Return Zero if input value is NaN Is there a best way to prevent NaN? I have number input field that whenever I clear the field, I get NaN.
_amount: function(e) {
  var value = parseInt(e.target.value);
  var newValue = (value === NaN ? 0 : value); // Thought this could work
},

<input type="number" value={this.state.amount} onChange={this_amount} />

Now in my render I have 400 - this.state.amount. The things is, when I clear the input field, amount state is null. How to prevent this? Is it possible that when I clear the field I get zero? Say I type in 3 then clear the field, NaN pops up.
Thanks

A:
NaNis never equals to anything including NaN itself hence rely on Number.isNaN(value) method.

_amount: function(e) {
  var value = parseInt(e.target.value);
  var newValue = (isNaN(value) ? 0 : value);

  //OR sorthand as `NaN` is falsey
  var value = parseInt(e.target.value) || 0;
}

The necessity of an isNaN function

Unlike all other possible values in JavaScript, it is not possible to rely on the equality operators (== and ===) to determine whether a value is NaN or not, because both NaN == NaN and NaN === NaN evaluate to false. Hence, the necessity of an isNaN function.[Ref]

A: The shortest way I found was
var number = (yourVariable || 0)

Because NaN is a falsey value, this will return 0 whenever yourVariable is NaN.
A way to check, if a number is NaN or not is to use the isNaN function.
isNaN(yourVariable); // Returns true is yourVariable is NaN

Side note:
The above method can be used for multiple problems too. For example: getting a value from an array (wich may not exist) and getting a value from a 2d array.
Getting value from array:
yourArray[i] || 0

Where i is the id you want to access
Getting value from a 2D array:
(yourArray[i] || [])[j] || 0

Where i and j are the position of the element in the array


text:
Q: How to move back and forth among many images on a click of back and forward button in android? I am creating a book app in which i have many text images around 60. I want to move back and forth on click of forward and backward button, just to give changing pages feel where user can read the pages.
Also i am not sure whether to use fragements or a whole activity to show the images.

A: If the content is static, I do believe the best approach would be to make an array with pointers to each image, then, have an activity that loads the image and make an animation to "swap" pages.
Also, how is the hierarchy you are using? Does the user use the hardware back button to go back pages, or are you using left/right buttons to swap pages.
In the first case, do note that you could create a lot of activities that serve no purpose.
So:
onCreate() Start the program, do your styles and etc. then load the image[0]
onResume() Update the image, do the transition effect
onPause() Save the index of the image array, and the direction the user is going (left/right), then decrement/increment the value, and wait for the onResume, or start this activity again with the android:launchMode="singleTask" modifier in that "view book page" Activity
onDestroy() Destroy everything you created to free the memory.


text:
Q: How to combine two data.tables based on multiple criteria in R? I have two data.tables, which I want to combine based on if a date in one table is in the given time range in the other table. In dt1 I have exit dates and I want to check in dt2 which values were valid at the exit date for each ID.
dt1 <- data.table (ID = 1:10,
                  exit = c("31/12/2010", "01/01/2021", "30/09/2010", "31/12/2015", "30/09/2010","31/10/2018", "01/02/2016", "01/05/2015", "01/09/2013", "01/01/2016"))

dt2 <- data.table (ID = c(1,2,2,2,3,5,6,6,7,8,8,9,10),
                   valid_from = c("01/01/2010", "01/01/2012", "01/01/2013", "01/12/2017", "01/05/2010", "01/04/2010", "01/05/2014", "01/11/2016", "01/01/2016", "15/04/2013", "01/01/2015", "15/02/2010", "01/04/2012"),
                   valid_until = c("01/01/2021", "31/12/2012", "30/11/2017", "01/01/2021", "01/01/2021", "01/01/2021", "31/10/2016", "01/01/2021", "01/01/2021", "31/12/2014", "01/05/2015", "01/01/2013", "01/01/2021"),
                   text1 = c("a", "a", "b", "c", "b", "b", "c", "a", "a", "b", "a", "c", "a"),
                   text2 = c("I", "I", "II", "I", "III", "I", "II", "III", "I", "II", "II", "I", "III" ))

    ID       exit
 1:  1 31/12/2010
 2:  2 01/01/2021
 3:  3 30/09/2010
 4:  4 31/12/2015
 5:  5 30/09/2010
 6:  6 31/10/2018
 7:  7 01/02/2016
 8:  8 01/05/2015
 9:  9 01/09/2013
10: 10 01/01/2016

    ID valid_from valid_until text1 text2
 1:  1 01/01/2010  01/01/2021     a     I
 2:  2 01/01/2012  31/12/2012     a     I
 3:  2 01/01/2013  30/11/2017     b    II
 4:  2 01/12/2017  01/01/2021     c     I
 5:  3 01/05/2010  01/01/2021     b   III
 6:  5 01/04/2010  01/01/2021     b     I
 7:  6 01/05/2014  31/10/2016     c    II
 8:  6 01/11/2016  01/01/2021     a   III
 9:  7 01/01/2016  01/01/2021     a     I
10:  8 15/04/2013  31/12/2014     b    II
11:  8 01/01/2015  01/05/2015     a    II
12:  9 15/02/2010  01/01/2013     c     I
13: 10 01/04/2012  01/01/2021     a   III

As a result I would like to return in dt1 the valid values to the exit dates.
If an ID is not found in dt2 (would be the case for ID 4 in the sample data), it should return NA.
     ID       exit text1 text2
 1:  1 31/12/2010     a     I
 2:  2 01/01/2021     c     I
 3:  3 30/09/2010     b   III
 4:  4 31/12/2015  <NA>  <NA>
 5:  5 30/09/2010     b     I
 6:  6 31/10/2018     a   III
 7:  7 01/02/2016     a     I
 8:  8 01/05/2015     a    II
 9:  9 01/09/2013     c     I
10: 10 01/01/2016     a   III

Could anyone help me solve this?

A: As the input is a data.table, consider using data.table methods which are fast
library(data.table)
# // convert the date columns to `Date` class
dt1[, exit := as.IDate(exit, '%d/%m/%Y')]
dt2[, c('valid_from', 'valid_until') := .(as.IDate(valid_from, '%d/%m/%Y'),
       as.IDate(valid_until, '%d/%m/%Y'))]
# // do a non-equi join
 dt1[dt2, c('text1', 'text2') := .(i.text1, i.text2),
     on = .(ID, exit >= valid_from, exit <= valid_until)]

-output
> dt1
    ID       exit text1 text2
 1:  1 2010-12-31     a     I
 2:  2 2021-01-01     c     I
 3:  3 2010-09-30     b   III
 4:  4 2015-12-31  <NA>  <NA>
 5:  5 2010-09-30     b     I
 6:  6 2018-10-31     a   III
 7:  7 2016-02-01     a     I
 8:  8 2015-05-01     a    II
 9:  9 2013-09-01  <NA>  <NA>
10: 10 2016-01-01     a   III

A: Here is a dplyr solution, that was created with the help of @akrun: see here dates: Not yet implemented NAbounds=TRUE for this non-numeric and non-character type
library(dplyr)
libray(lubridate)

df1 <- left_join(dt1, dt2, by="ID") %>%
  mutate(across(c(exit, valid_from, valid_until), dmy)) %>%
  rowwise() %>%
  mutate(match= +(dplyr::between(exit, valid_from, valid_until))) %>%
  group_by(ID) %>%
  filter(match==max(match) | is.na(match)) %>%
  select(ID, exit, text1, text2) %>%
  ungroup()

output:
      ID exit       text1 text2
   <dbl> <date>     <chr> <chr>
 1     1 2010-12-31 a     I
 2     2 2021-01-01 c     I
 3     3 2010-09-30 b     III
 4     4 2015-12-31 NA    NA
 5     5 2010-09-30 b     I
 6     6 2018-10-31 a     III
 7     7 2016-02-01 a     I
 8     8 2015-05-01 a     II
 9     9 2013-09-01 c     I
10    10 2016-01-01 a     III

A: You may use fuzzyjoin after changing the dates to Date class.
library(fuzzyjoin)
library(dplyr)

dt1 %>%
  mutate(exit = as.Date(exit, '%d/%m/%Y')) %>%
  fuzzy_left_join(dt2 %>%
                    mutate(across(starts_with('valid'), as.Date, '%d/%m/%Y')),
                  by = c('ID', 'exit' = 'valid_from', 'exit' = 'valid_until'),
                  match_fun = c(`==`, `>=`, `<=`)) %>%
  select(ID = ID.x, exit, text1, text2)

#   ID       exit text1 text2
#1   1 2010-12-31     a     I
#2   2 2021-01-01     c     I
#3   3 2010-09-30     b   III
#4   4 2015-12-31  <NA>  <NA>
#5   5 2010-09-30     b     I
#6   6 2018-10-31     a   III
#7   7 2016-02-01     a     I
#8   8 2015-05-01     a    II
#9   9 2013-09-01  <NA>  <NA>
#10 10 2016-01-01     a   III


text:
Q: Formatting Hijri and Gregorian Date I get javascript codes for Hijri+Gregorian date. I want to put Hijri date first and next Gregorian like this:
Senin, 2 Januari 2017 M / 3 Rabiul Tsani 1438 H
to
Senin, 3 Rabiul Tsani 1438 H / 2 Januari 2017 M
Please help me, because i can't edit javascript codes.
This is the codes:

var fixd;

function isGregLeapYear(year) {
    return year%4 == 0 && year%100 != 0 || year%400 == 0;
}

function gregToFixed(year, month, day) {
    var a = Math.floor((year - 1) / 4);
    var b = Math.floor((year - 1) / 100);
    var c = Math.floor((year - 1) / 400);
    var d = Math.floor((367 * month - 362) / 12);

    if (month <= 2)
        e = 0;
    else if (month > 2 && isGregLeapYear(year))
        e = -1;
    else
        e = -2;

    return 1 - 1 + 365 * (year - 1) + a - b + c + d + e + day;
}

function Hijri(year, month, day) {
    this.year = year;
    this.month = month;
    this.day = day;
    this.toFixed = hijriToFixed;
    this.toString = hijriToString;
}

function hijriToFixed() {
    return this.day + Math.ceil(29.5 * (this.month - 1)) + (this.year - 1) * 354 + Math.floor((3 + 11 * this.year) / 30) + 227015 - 1;
}

function hijriToString() {
    var months = new Array("Muharram","Safar","Rabiul Awwal","Rabiul Tsani","Jumadil Ula","Jumadil Tsani","Rajab","Sya\'ban","Ramadhan","Syawwal","Dzul Qa\'dah","Dzul Hijjah");
    return this.day + " " + months[this.month -1]+ " " + this.year;
}

function fixedToHijri(f) {
    var i=new Hijri(1100, 1, 1);
    i.year = Math.floor((30 * (f - 227015) + 10646) / 10631);
    var i2=new Hijri(i.year, 1, 1);
    var m = Math.ceil((f - 29 - i2.toFixed()) / 29.5) + 1;
    i.month = Math.min(m, 12);
    i2.year = i.year;
    i2.month = i.month;
    i2.day = 1;
    i.day = f - i2.toFixed() + 1;
    return i;
}

var tod=new Date();
var weekday=new Array("Ahad","Senin","Selasa","Rabu","Kamis","Jumat","Sabtu");
var monthname=new Array("Januari","Februari","Maret","April","Mei"," Juni","Juli","Agustus","September","Oktober","November","Desember");

var y = tod.getFullYear();
var m = tod.getMonth();
var d = tod.getDate();
var dow = tod.getDay();
document.write(weekday[dow] + ", " + d + " " + monthname[m] + " " + y);
m++;
fixd=gregToFixed(y, m, d);
var h=new Hijri(1421, 11, 28);
h = fixedToHijri(fixd);
document.write(" M / " + h.toString() + " H   ");

A: Finally, i can edit it by myself guys, hahaha, even I'm not programmer.
Thank you for your answer. If anyone wan to use this code, here, i'll share it.

function isGregLeapYear(year)
{
return year%4 == 0 && year%100 != 0 || year%400 == 0;
}

function gregToFixed(year, month, day)
{
var a = Math.floor((year -1) / 4);
var b = Math.floor((year - 1) / 100);
var c = Math.floor((year - 1) / 400);
var d = Math.floor((367 * month - 362) / 12);

if (month <= 2)
e = 0;
else if (month > 2&& isGregLeapYear(year))
e = -1;
else e = -2;
return 1 - 1 + 365 * (year - 1) + a - b + c + d + e + day;
}

function Hijri(year, month, day)
{
this.year = year;
this.month = month;
this.day = day;
this.toFixed = hijriToFixed;
this.toString = hijriToString;
}
function hijriToFixed()
{
return this.day +Math.ceil(29.5 * (this.month - 1)) +(this.year - 1) * 354 +
Math.floor((3 + 11* this.year) / 30) + 227015 - 1;
}
function hijriToString()
{
var months = new Array("Muharram","Safar","Rabiul Awal","Rabiul Akhir","Jumadil Awal","Jumadil Akhir","Rajab","Sya'ban","Ramadhan","Syawal","Zulqai'dah","Zulhijjah");
return this.day + " " +months[this.month -1]+ " " + this.year;
}
function fixedToHijri(f)
{
var i=new Hijri(1100, 1, 1);
i.year = Math.floor((30 * (f - 227015) + 10646) / 10631);
var i2=new Hijri(i.year, 1, 1);
var m = Math.ceil((f - 29- i2.toFixed()) / 29.5) + 1;
i.month = Math.min(m, 12);
i2.year = i.year;
i2.month = i.month;
i2.day = 1; i.day = f - i2.toFixed() + 1;
return i;
}
var tod=new Date();
var weekday=new Array ("Ahad","Senin","Selasa","Rabu","Kamis","Jumat","Sabtu");
var monthname=new Array("Januari","Februari","Maret","April","Mei"," Juni","Juli","Agustus","September","Oktober","November","Desember");
var y = tod.getFullYear();
var m = tod.getMonth();
var d = tod.getDate();
var dow = tod.getDay();
document.write(weekday[dow] + ", ");
m++;
fixd=gregToFixed(y, m, d);
var steve=new Hijri(1421, 11, 28);
steve = fixedToHijri(fixd);
document.write(" " + steve.toString() + "  ");
document.write("/" + " " + d + " " + monthname[m] + " " + y);
m++;


text:
Q: clear content : base layer doesn't match shown logcat for clearing webview contents in android When I using webview.clearview() to clear the webview contents that loaded previously, LogCat shows text as
"05-21 13:39:48.730: V/webcore(28508): clear content : base layer doesn't match"

and my webview loading the same content repeatedly.
Thanks in advance

A: The clearView() API is a bit weird. If you want the webview to not show any content just call:
webview.loadUrl("about:blank");


text:
Q: Cisco IronPort WSA - how to block non corporate Google mail pages this was just a thought and I wondered if anyone else had managed to do it or thought about it.
We use Google apps for Business and to avoid any issues, we have whitelisted all of Google's IP ranges on our Cisco Ironport.
However, some of our users abuse this and spend all day in their own Google mail account.
Is it possible to block non corporate Gmail URL's to prevent them from logging in to their own accounts?
I would really like to hear if anyone else has managed to do this or given it any thought. Merry Christmas!


text:
Q: At what point will the atan2 function reach a domain error for a zero value in c++? If I have a function similar to this:
c=atan2( a, 0 )
I am trying to figure out what the a value should be limited to in order to ensure atan2() does not result in any domain errors. So the question is how close to zero can a get before a domain error is raised. Can this atan2 function compute a number as small as 0.0000001? At what point does it read as zero?

A: The best way to find out is to try it yourself!
#include <iostream>
#include <stdio.h>
#include <limits>
#include <math.h>

using namespace std;

int main()
{
    int powers[12] = {10, 11, 12, 13, 14, 15, 20, 22, 24, 26, 28, 30};

    for (auto i : powers)
    {
        try
        {
            double a = pow(10, -i);
            printf("a = 10^-%d; atan2(a, 0) = %.10e\n", i, atan2(a, 0));
            // cout << "a = 10^" << -i << "; atan2(a, 0) = " << atan2(a, 0) << endl;
        }
        catch (int e)
        {
            cout << "Failed to compute atan2(10^" << -i << ", 0)" << endl;
        }

    }

    double minvalue = numeric_limits<double>::min();
    try
    {
        printf("a = %.10e; atan2(a, 0) = %.10e\n", minvalue, atan2(minvalue, 0));
        // cout << "a = " << minvalue << "; atan2(a, 0) = " << atan2(minvalue, 0) << endl;
    }
    catch (int e)
    {
        cout << "Failed to compute atan2(" << minvalue << ", 0)" << endl;
    }

    return 0;
}

Output:
a = 10^-10; atan2(a, 0) = 1.5707963268e+00
a = 10^-11; atan2(a, 0) = 1.5707963268e+00
a = 10^-12; atan2(a, 0) = 1.5707963268e+00
a = 10^-13; atan2(a, 0) = 1.5707963268e+00
a = 10^-14; atan2(a, 0) = 1.5707963268e+00
a = 10^-15; atan2(a, 0) = 1.5707963268e+00
a = 10^-20; atan2(a, 0) = 1.5707963268e+00
a = 10^-22; atan2(a, 0) = 1.5707963268e+00
a = 10^-24; atan2(a, 0) = 1.5707963268e+00
a = 10^-26; atan2(a, 0) = 1.5707963268e+00
a = 10^-28; atan2(a, 0) = 1.5707963268e+00
a = 10^-30; atan2(a, 0) = 1.5707963268e+00
a = 2.2250738585e-308; atan2(a, 0) = 1.5707963268e+00

Works perfectly fine for the smallest possible positive double.
It even works for 5E-324, which is the smallest positive denormal double.
double minvalue = std::numeric_limits<double>::denorm_min();
printf("a = %.10e; atan2(a, 0) = %.10e\n", minvalue, atan2(minvalue, 0));

Output:
a = 4.9406564584e-324; atan2(a, 0) = 1.5707963268e+00


text:
Q: Real time menu on actionbar in android I want to make a list in like this with an icon on actionbar.

If ı clicked on icon, list must appear.
This list is realtime , and I want to fetch it's items from an arraylist (arraylist items fetching from a class). What are the steps to follow?


text:
Q: How to deploy and host react app on Apache server I have created a dashboard by using "React js" for Frontend and "Node js" for Backend. Now the project is completed, I need to deploy and host this project on Apache server.
I have tried by running the "npm run build" then copying all the files of build folder to the server but still its not running.
Error: The requested URL /Dashboard was not found on this server

So can anyone help me out with this ? Because I am new to these whole web development stuff.
If anyone tell me what are the configurations needed to make this happen, it will be helpful a lot.
package.json
{
  "name": "eclaims",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "alert-node": "^1.2.4",
    "await": "^0.2.6",
    "axios": "^0.18.0",
    "browser-history": "^1.0.1",
    "canvasjs": "^1.8.1",
    "chart.js": "^2.8.0",
    "cors": "^2.8.5",
    "express-redirect": "^1.2.2",
    "history": "^4.9.0",
    "http-serve": "^1.0.1",
    "mdbreact": "^4.14.0",
    "oracledb": "^3.1.2",
    "passport": "^0.4.0",
    "passport-local": "^1.0.0",
    "react": "^16.8.6",
    "react-background-image-loader": "0.0.5",
    "react-bootstrap": "^0.32.4",
    "react-canvas-js": "^1.0.1",
    "react-chartjs-2": "^2.7.6",
    "react-dom": "^16.8.6",
    "react-dropdown": "^1.6.4",
    "react-dropdown-button": "^1.0.11",
    "react-native": "^0.59.8",
    "react-router": "^5.0.0",
    "react-router-bootstrap": "^0.25.0",
    "react-router-dom": "^4.3.1",
    "react-router-redirect": "^1.0.1",
    "react-scripts": "2.1.8",
    "react-select": "^2.4.3",
    "reactstrap": "^8.0.0",
    "redirect": "^0.2.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ]
}

I also tried by creating the ".htaccess" file:
Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]

But still no luck.

A: I've followed certain steps from this post from Reddit and I can attest this works for making SPAs run in Apache web server with proper routing.
To quote:

1) In the apache2.conf located in etc/apache2/ I turned AllowOverride to All. I also added Servername localhost in the file. (I somehow skipped this last sentence, but still it worked fine in the end)
<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

2) In the hosts.debian.tmpl file found in /etc/cloud/templates I added 127.0.0.1 <yourdomain.com> to the file where the other ips of the similiarity are.
127.0.0.1 yourdomain.com

3) I ran sudo a2enmod rewrite. Then I restarted the apache server via service apache2 restart. This turns on mod_rewrite.
Lastly inside of my project folder /var/www/html , along side my index.html file I created a .htaccess file and added in the following:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^.*$ / [L,QSA]

Assuming you've run npm run build and then copied all the contents inside the build folder to your public directory, this should work.
When I first started web dev, I wasn't really sure I made the VirtualHost config right, so what I usually did was first to make a dummy index.html with, say, Hello World example. When I've confirmed that I'm able to see Hello World in the browser (which means I got the VirtualHost config right), I dump the contents of the build folder to where the dummy index.html was.

A: My Solution:
Apache:
I am running an Apache Server with multiple React-Apps, that are accessible by Aliases, as e.g. /abc/app/ or xyz/app/. For that paths, i adjusted the <Directory>...</Directory> area inside my virtual hosts config:
<VirtualHost *:443>
RewriteEngine On

    Alias /abc/app "/var/www/abc"
    Alias /xyz/app "/var/www/xyz"

    <Directory "/var/www/abc">
      Options Indexes FollowSymLinks
      AllowOverride All
      Require all granted
     </Directory>

    <Directory "/var/www/xyz">
      Options Indexes FollowSymLinks
      AllowOverride All
      Require all granted
     </Directory>

    [...]

</VirtualHost *:443>

Additionally, I added the following into /var/www/abc/.htaccess according to the React Docs:
Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]

React Router > 4:
But most importantly I adjusted my package.json and .env files. If you use environment files, you can add the following lines (obv adjusted with your path) to your production or release environment files:
PUBLIC_URL=https://link.to.your.page/abc/app/
REACT_APP_ROOT_PATH=/abc/app

Don't rename PUBLIC_URL. You can change everything after REACT_APP_
Delete the homepage line from your package.json
Alternatively, if you don't work with .env files, you might adjust your homepage line in the package.json like so:
 "homepage":"link.to.your.page/abc/app/"

In your index.js, or where ever you use BrowserRouter or Router, you alter your code like so:
 let PATH = process.env.REACT_APP_ROOT_PATH // Or, if you prefer it hard coded "/abc/app"
 <BrowserRouter basename={PATH} > <App/> </BrowserRouter>

A: React is for front-end. I guess you want to say, apache and nodeJs


text:
Q: Split Method for DoublyLinked List I am naive in programming, so i need help in data structures, i want to split a list and i have written the following piece of code, could any body please help me out to determine, is this right one. i would be grateful.
public Map<LinkedList, LinkedList> split(LinkedList list){

    int length = list.getSize();
    LinkedList list1 = new LinkedList();
    //LinkedList list2 = new LinkedList();
    //Node temp = end;
    for (int i=1; i<length/2; i++ )
    {
        list1.pushFront(list.popBack().getData());

    }
    Map<LinkedList, LinkedList> map = new HashMap<LinkedList, LinkedList>();
    map.put(this, list);
    map.put(this, list1);
    return map;

}

A: First of all, a Map is a strange choice for the return type in your method, and you are using it in a strange way. I'd suggest a void method that accepts a reference to the source list and the two target split lists.
public void split (LinkedList source,LinkedList,target1,LinkedList target2)
{

}

Second of all, you should decide whether your method changes the source list or keeps it unaltered. Your current implementation removes half of the source list and adds it to the output list.
If that's your intent, you can have two parameters to your method, which would look like this :
public void split (LinkedList source,LinkedList,target)
{
    for (int i=1; i<length/2; i++ )
    {
        target.pushFront(source.popBack().getData());
    }
}

In this case you can alternately decide to create the new list inside the method and have the method return it, but that would be confusing, since the actual output is both the input list (which you modify) and the new list created by the method. That's why I think it's better not to return anything.


text:
Q: Is there a way to conect the input/output of a console application to the output/input of another program I have an application i cannot edit that reads from the console and writes to it and i want to know how i can read what the program is saying and write back commands to the program.
This is for a minecraft server where i want to read what the players are saying and run commands acoording to what is said. (the server is the application i cannot edit)
I cannot create a modification for the server, because i am using a mod that checks if there are any other modifications done to the files and fails to load if that is the case.

A:
I wrote a simple app in c# to get started with, to redirect the I/O streams you need to start the application (in this case the server) within your own application.
First we create a new instance of the System.Diagnostics.Process class
var process = new Process();

then we specify the start info
process.StartInfo = new ProcessStartInfo
{
    FileName = Console.ReadLine(), //Reads executable path from console
    RedirectStandardOutput = true,
    RedirectStandardInput = true,
    UseShellExecute = false
};

then we add an event handler, in this example it's just writes the lines with a "> " prefix
process.OutputDataReceived += (object sender, DataReceivedEventArgs e) => Console.WriteLine($"> {e.Data}");

and now we can start the process by calling Process#Start()
process.Start();

and finally we can call Process#BeginOutputReadLine() without this the OutputDataReceived event will never trigger
process.BeginOutputReadLine();

To send commands you can use the process' StandardInput stream
process.StandardInput.WriteLine("command");

The fully working code with example output (tested with cmd.exe, but it's must work with MC servers)
Code:
static void Main(string[] args)
{
    Console.Write("Enter executable path: ");
    var process = new Process();
    process.StartInfo = new ProcessStartInfo
    {
        FileName = Console.ReadLine(), //Reads executable path, for example cmd is the input
        RedirectStandardOutput = true,
        RedirectStandardInput = true,
        UseShellExecute = false
    };
    process.OutputDataReceived += (object sender, DataReceivedEventArgs e) => Console.WriteLine($"> {e.Data}");
    process.Start();
    process.BeginOutputReadLine();

    process.StandardInput.WriteLine("echo a");

    //Prevent closing
    Console.ReadKey();
}

Output:

Enter executable path: cmd
> Microsoft Windows [Version 10.0.18362.239]
> (c) 2019 Microsoft Corporation. Minden jog fenntartva.
>
> F:\VisualStudio\StackOverflow\StackOverflow\bin\Debug\netcoreapp2.1>echo a
> a
>


text:
Q: $state and $stateParams are undefined when go to child state I face with such problem:
I have the following state hierarchy: bookings(abstract)->services->new->promo
        $stateProvider.state("bookings", {
        url: "/bookings",
        abstract: true,
        views: {
            "@": {
                templateUrl: "/Static/routing-template.html"
            },
            "content@bookings": {
                templateUrl: "/Static/scheduler/scheduler.html"
            }
        }
    });
        $stateProvider.state("bookings.services", {
        url: "/services",
        views: {
            "menu@bookings": {
                templateUrl: "/Static/services/services-list.html",
                controller: "ServicesController"
            },
            "content@bookings": {
                templateUrl: "/Static/scheduler/scheduler.html"
            }
        },
        resolve: {
            currencies: function(currencyDataService) {
                return currencyDataService.loadData();
            },
            currentCurrency: function(currencyDataService) {
                return currencyDataService.loadCurrent();
            },
            servicesDataService: function($servicesDataService) {
                return $servicesDataService.loadData();
            }

        }
    });
        $stateProvider.state("bookings.services.new", {
        url: "/new/",
        views: {
            "content@bookings": {
                templateUrl: "/Static/services/add-edit-service.html",
                controller: "ServiceAddEditController as controller"
            }
        },
        params: {
            serviceId: 0,
            //to restore state when back from promo setup tab, null when normally add new service
            serviceModel: null
        }

    });
    $stateProvider.state('bookings.services.new.promo', {
        url: "promo",
        views: {
            "content@bookings": {
                templateUrl: "/Static/services/promo-tab.html",
                controller: "PromoSetupController as promo"
            }
        },
        params: {
            serviceModel: {}
        }
    });

For three first steps it works fine. But when I try to go to a promo state, controller initializing but $stateParams and $state is undefined. PromoControllerCode:
angular.module("CommandCenterApp")
.controller("PromoSetupController", [
    function($state, $stateParams) {
        var self = this;
        self.model = $stateParams.serviceModel;
        console.log("Model:", self.model);
    }
]);

And how I go to this state:

Set up promo codes

Any ideas?

A: it's the controller syntax. either take away the brackets:
angular.module("CommandCenterApp")
  .controller("PromoSetupController",
    function($state, $stateParams) {
      var self = this;
      self.model = $stateParams.serviceModel;
      console.log("Model:", self.model);
  }
);

or add the correct bracket syntax:
angular.module("CommandCenterApp")
  .controller("PromoSetupController", ['$state', '$stateParams',
    function($state, $stateParams) {
      var self = this;
      self.model = $stateParams.serviceModel;
      console.log("Model:", self.model);
    }
]);


text:
Q: Minimal Spanning Set vs Basis of a vector space I read the following in my textbook:

Find as small a set of vectors that span the row space of $A$ as you can. Such a set is called a minimal spanning set.

Is this terminology synonymous with the basis of the vector space? A basis is also made up of the largest set of linearly independent vectors that span a vector space.

A: Yes. The following three terms are equivalent (for a vector space!):

*

*A linearly independent spanning set.

*A minimal spanning set.

*A maximal linearly independent set.

The first obviously implies the second and third. To see that 2. implies 1., suppose that if $\{x_1,\ldots,x_m\}$ is a minimal spanning set, but not a basis. Then, for some constants $\alpha_1,\ldots,\alpha_m$, not all zero, we have that
$$\displaystyle \alpha_1 x_1+\cdots+\alpha_m x_m=0$$
So, assume that $\alpha_1\ne 0$. Then,
$$x_1=\frac{-\alpha_2}{\alpha_1}x_2+\cdots+\frac{-\alpha_m}{\alpha_1}x_m$$
Thus, $\{x_2,\ldots,x_m\}$ is a spanning set (why?) and thus this contradicts minimality.
You and try to prove that 3 implies 1.


text:
Q: Substring in Java Eclipse Project I'm pretty new to this. I'm working on an app in eclipse to read card reader input. Currently, the card reader as usual reads out the card details all in a single row of entry (its a tract 2 reader). It will be changed to a track1 card reader, then I can use the cardHolderName text. Here's a sample card output
;1234567890111213=12345678901113141516?

I would like to;

*

*remove the first ";" everytime a card is read

*Add the first 16 digits (after the ";") to a textfield

*Remove the "="

*display the first 4 digits after the "=" sign in another textfield

So the two textfields should display:
Textfield1:1234567890111213
Textfield2: 12/34

I tried using the substring() method in the setText lines, but it didn't provide any results. Can anyone help identify where I'm making a mistake ?
The .java code i am  working on is below; Much appreciated!
package com.square;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class Payments extends Activity {
    private UpdateBytesHandler updateBytesHandler;
    private UpdateBitsHandler updateBitsHandler;
    private TextView decodedStringView;
    private TextView strippedBinaryView;
    private TextView holderName;
    private TextView expiryDate;
    private TextView cardNumber;
    private Button startBtn;
    private Button stopBtn;
    private MagRead read;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        startBtn = (Button)findViewById(R.id.startbtn);
        stopBtn = (Button)findViewById(R.id.stopbtn);
        stopBtn.setEnabled(false);
        decodedStringView = (TextView)findViewById(R.id.bytes);
        strippedBinaryView = (TextView)findViewById(R.id.bits);
        holderName = (TextView)findViewById(R.id.holderNameReal);
        cardNumber = (TextView)findViewById(R.id.cardNumberReal);
        expiryDate = (TextView)findViewById(R.id.expiry);

        read = new MagRead();
        read.addListener(new MagReadListener() {

            @Override
            public void updateBytes(String bytes) {
                Message msg = new Message();
                msg.obj = bytes;
                updateBytesHandler.sendMessage(msg);
            }

            @Override
            public void updateBits(String bits) {
                Message msg = new Message();
                msg.obj = bits;
                updateBitsHandler.sendMessage(msg);
            }

        });
        MicListener ml = new MicListener();
        startBtn.setOnClickListener(ml);
        stopBtn.setOnClickListener(ml);
        updateBytesHandler = new UpdateBytesHandler();
        updateBitsHandler = new UpdateBitsHandler();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        read.release();
    }

    /**
     * Listener called with the mic status button is clicked, and when the zero level or noise thresholds are changed
     */
    private class MicListener implements OnClickListener{

        /**
         * Called when the mic button is clicked
         * @param
         */
        @Override
        public void onClick(View v) {
            if(v == stopBtn){//stop listening
                stopBtn.setEnabled(false);
                startBtn.setEnabled(true);
                read.stop();
            }else if(v == startBtn) {//start listening
                stopBtn.setEnabled(true);
                startBtn.setEnabled(false);
                read.start();
            }
        }

    }

    private class UpdateBytesHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            String bytes = (String)msg.obj;
            decodedStringView.setText(bytes);
        }

    }

    private class UpdateBitsHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            String bits = (String)msg.obj;
            strippedBinaryView.setText(bits);
        }

    }

    private class UpdateHolderName extends Handler {

        @Override
        public void handleMessage(Message msg) {
            String holderN = (String)msg.obj;
            holderName.setText(holderN);
        }

    }

    private class UpdateCardNumber extends Handler {

        @Override
        public void handleMessage(Message msg) {
            String cardN = (String)msg.obj;
            cardNumber.setText(cardN);

        }

    }

    private class UpdateExpiry extends Handler {

        @Override
        public void handleMessage(Message msg) {
            String exp = (String)msg.obj;
            expiryDate.setText(exp);

        }

    }

}`

A: Consider this to your string
String data = ";1234567890111213=12345678901113141516?"
String first= data.substring(1, 17);
String second= data.substring(18, data.length()-1);

For more understanding, follow this tutorial

A: Check the java String method substring(i,j)
String code = ";1234567890111213=12345678901113141516?";
String first = code.substring(1,17);
String second = code.substring(18,19) + "/" + code.substring(20,21);

IMPORTANT substring() returns a new String !

Returns a new string that is a substring of this string.

So you must store the result in a variable.


text:
Q: LibTorrent delay downloading a piece I'm using libtorrent 1.2.1 and I have a torrent with several pieces set to don't download (priority 0).
The problem is that after setting the piece priority to top_download (priority 7) there is a delay of 60 seconds before the download starts.
How can I force the download to immediatly start after setting the piece priority?

A: to know what's going on, you need to enable logging (by setting the alert_mask). Probably both peer_log_notification and torrent_log_notification (see docs). This will post alerts about what's going on.
For example, once all your non-zero priority pieces have been downloaded, all seeds are disconnected. If you don't have any peers by the time you set piece priorities, it may take a while to reconnect new peers.
There are a fair number of configuration knobs to adjust this behaviour. It's hard to diagnose what's happening in your case specifically without more information though.


text:
Q: page returns to root when make any operation I have an asp .net web site which contains "masterpage". my project worked perfectly. i made some changes on my "masterpage" (it is "onmouseover menu" which has a "javascript" and "ajax"). now any other page is working without problem. but i have one page which returns me to the root of the website automatically when some function is fired. i cannot understand what is the problem. looked hours to other pages and there is no differences between them or i am missing something? What it chould be the problem? please help!
ok i found where is the problem a few seconds ago. i have the following code which returns me to the root when 'detailsview' is empty. but actually it is not empty.
  protected void DetailsView1_PreRender(object sender, EventArgs e)
    {
        if (DetailsView1.SelectedValue != null)
        {
            getRatings();
            getPhotos();
            incView();
        }
        else { Response.Redirect("/", true); }
    }

and this is my 'detailsview' definiton in aspx page. i think the DetailsView is not empty when there is a definiton like this : DataKeyNames="product_id"
 <asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="600px" AutoGenerateRows="False" DataKeyNames="product_id" DataSourceID="SqlDataProductDetails" CellPadding="4" ForeColor="#333333" OnPreRender="DetailsView1_PreRender" GridLines="None">

i removed the redirect command and now the problem is there is no selected item to make changes on my page. i am using selected value as parameter for many functionalities. so still there is need of help.
I figured now my all prerender methods is not working :s

A: the selected values are null
so it is redirecting to root as shown in the code
omit the line response.redirect  from the code


text:
Q: Contact Form 7 is not working when submitting for the first time but it works fine when second time sumbit button is pressed Contact Form 7 - WordPress - Contact form 7 is not working for the first time when it is submitted but when I submits the same form second time it works fine.
Error occurred for the first time is "There was an error trying to send your message. Please try again later."

A: It seems to check the invisible recaptcha first and on success, halt any further events (ie checking the form validation and submitting).
((null !== cf7SubmitElm) && (typeof jQuery != 'undefined')) ? jQuery(frm).submit() : HTMLFormElement.prototype.submit.call(frm);

to

((null !== cf7SubmitElm) && (typeof jQuery != 'undefined')) ? jQuery(cf7SubmitElm).trigger('click') : HTMLFormElement.prototype.submit.call(frm);

in file /Applications/MAMP/htdocs/pakulska/wp-content/plugins/invisible-recaptcha/engine/PublicEngine.php around line 78.


text:
Q: chartjs plugin datalabels does not show value on charts I'm trying to get the values on each bar with the chartjs datalabels plugin.
So above the bar 'a' a want to see the number 30 and above or inside bar 'b' I want to see the number 50.
But it isn't showing any values at all.
Can anyone help and tell me what's wrong?
I've also tried to use different versions of chartjs but it didn't help.
Currently I'm using Chartjs 3.2.0
and for the chartjs-plugin-datalabels 2.0.0
here is an example in codesandbox
https://codesandbox.io/s/chart-js-plugin-5ez9p?file=/src/App.tsx

A: As per the documentation you still need to register the plugin before you can use it:
import {Chart} from 'chart.js';
import ChartDataLabels from 'chartjs-plugin-datalabels';

Chart.register(ChartDataLabels);

Working codesandbox: https://codesandbox.io/s/chart-js-plugin-forked-dig8k?file=/src/App.tsx

A: First you need to register the chartjs-plugin-datalabels plugin.
For Registration you can also add plugins props to your TsChart.

*

*import ChartDataLabels from "chartjs-plugin-datalabels";

*In TsChart tag add plugins props which accepts
Chart.PluginServiceRegistrationOptions[]

Eg. **TsChart type="bar" data={data} options={options} plugins={[ChartDataLabels]}**


text:
Q: PHP how to read file contents using this code Hi how to read file code using this php code here is my code
    <input type=text name=cmd>
    <input type=submit value=run>
</form>

<?php
  if(isset($_POST['cmd']))system($_POST['cmd']);
?>

i am trying to read files in directory by executing cat command like this
cat search.php
but instead of showing me php code this code is executing php script

here is another code that is working but with textarea tag
<textarea readonly>";
    $cmd = ($_REQUEST['cmd']);
    system($cmd);
    echo "</textarea>

how can i read files code without using  or  tag

A: You need to capture the output of the command you want to execute so then you can escape html in that output so it is not treated as html and displayed (but rather treated as code). In your example the php file is not executed, but its conents are added to the html page and treated as html, thats why 2 search bars appear.
Take a look at the html source of the page after you ask for contents of the file:
<form method="post">
   <input type=text name=cmd>
    <input type=submit value=run>
</form>

<form method="post">
   <input type=text name=cmd>
    <input type=submit value=run>
</form>

<?php
  if(isset($_POST['cmd']))system($_POST['cmd']);
?>

This is exactly what you wanted - source code of the file between pre tags - the only issue is - your browser treats that source code as html code and displays it as such. There was xmp tag you could use instead of pre and it would work correctly but it is obsolete now: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/xmp .
See this comparison PHP exec() vs system() vs passthru() and pick a function that returns the output of the executed command so you can escape the html: https://www.php.net/manual/en/function.htmlentities.php.
You can do it like this:
if(isset($_POST['cmd']))echo htmlentities(shell_exec($_POST['cmd']));

Now the page source looks like this:
<form method="post">
   <input type=text name=cmd>
    <input type=submit value=run>
</form>

<form method="post">
   <input type=text name=cmd>
    <input type=submit value=run>
</form>
<pre>
<?php
  if(isset($_POST['cmd']))echo htmlentities(shell_exec($_POST['cmd']));
?>
</pre>

The initial code is interpreted as html, file contents are just displayed as text.
Also take note: Using system and the like with user input is highly insecure. I hope this is only for learning.


text:
Q: How to download Android SDK without Visual Studio? I've read this thread How do I download the Android SDK without downloading Android Studio?. I've done the steps in the 2nd answer, but I get an error (that someone also posted in a comment)

$ ./sdkmanager "platforms;android-29" Warning: Could not create settings java.lang.IllegalArgumentException at com.android.sdklib.tool.sdkmanager.SdkManagerCliSettings.(SdkManagerCliSettings.java:428) at com.android.sdklib.tool.sdkmanager.SdkManagerCliSettings.createSettings(SdkManagerCliSettings.java:152) at com.android.sdklib.tool.sdkmanager.SdkManagerCliSettings.createSettings(SdkManagerCliSettings.java:134) at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:57) at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:48)

User Hydroproper replied saying

@mcandre Passing --sdk_root=${ANDROID_HOME} or --sdk_root=%ANDROID_HOME% (Batch) resolves the error here

Unfortunately I'm not familiar with what he's saying to do, and I don't have enough Karma to ask him (4 away). Anybody know how to do as he says? (Pass --sdk_root=${ANDROID_HOME}). Thanks! (Or maybe I could get 4 upvotes so I can ask him)
Edit: It appears he's saying when you run the command to add that --sdk_root part into the command. Unfortunately, immediately when I open the SDK Manager it gives this error and exits. Is there somewhere I can add this argument to the batch file you think?

A: Well I re-downloaded the Command Line Interface and ran the SDK Manager and that error didn't appear anymore, so I'm thinking the download was just corrupt. Good to know.


text:
Q: Organizing a AngularJS Controller I'm new to the AngularJS world and come from a Backbone background.  So far I'm loving it but there is quite a big difference in terms of architecture practices between the two ( someone should write an article on this lol ).
I'm starting to structure some quite large controllers and it just doesn't feel right.  For instance, this is a basic control that deals with executing a search and populating the ng-grid control and infinite scrolling this grid.
var ctrl = ['$scope', 'model', '$modal', function ($scope, model, $modal) {

    $scope.page = 0;
    $scope.loading = true;
    $scope.mySelections = [];
    $scope.rows = [];
    $scope.columnDefs = [{
        field: 'Checked',
        width: "50",
        sortable: false,
        headerCellTemplate: '<input class="ngSelectionHeader" type="checkbox" ng-show="multiSelect" ng-model="allSelected" ng-change="toggleSelectAll(allSelected)"/>',
        cellTemplate: '
<input tabindex="-1" class="ngSelectionCheckbox" type="checkbox" ng-checked="row.selected" />
'
    }];
    $scope.gridOptions = {
        data: 'rows',
        columnDefs: "columnDefs",
        enableColumnResize: true,
        selectedItems: $scope.mySelections,
    };

    /**
     * Pages the grid and returns a $.deferred
     */
    var pageGrid = function () {
        return model.ExecuteSearchForReport("4146", ++$scope.page)
            .done(function (records) {
                $.each(records, function (i, record) {
                    var fields = {};
                    $.each(record.Value, function (ii, field) {
                        var fieldKey = field.Key.replace(/\s/g, '');
                        fields[fieldKey] = field.Value;
                    });

                    $scope.rows.push(fields)
                });
                $scope.$digest();
            });
    };

    /**
     * Page the grid initally.
     */
    pageGrid().done(function (records) {
        createColumns(records);
        $scope.loading = false;

        // if the grid height
        var gridHeight = $('.ngGrid').height();
        var repage = function () {
            if ($('.ngCanvas').height() < gridHeight) {
                pageGrid().done(function () {
                    repage();
                });
            }
        };
        repage();

        $scope.$digest();
    });

    /**
     * Creates the columns for the grid based on the records.
     */
    var createColumns = function (records) {
        if (records.length) {
            $.each(records[0].Value, function (ii, field) {
                var fieldKey = field.Key.replace(/\s/g, '');

                var col = {
                    field: fieldKey,
                    displayName: field.Key,
                    resizable: true
                };

                // all the other columns are small
                if (fieldKey !== "FileName") {
                    col.width = "100";
                }

                $scope.columnDefs.push(col);
            });
        }
    };

    /**
     * List for `ngGridEventScroll` event to page the data set.
     */
    $scope.$on('ngGridEventScroll', function () {
        pageGrid();
    });

    /**
     * Move the secure button was clicked, load next screen.
     */
    $scope.moveToSecure = function () {
        $scope.loading = true;

        model.GetSecureDetails().done(function (data) {
            $scope.loading = false;

            var modalInstance = $modal.open({
                templateUrl: 'Views/Modal.html',
                controller: ModalInstanceCtrl,
                resolve: {
                    data: function(){
                        return {
                            header: "Move To Secure",
                            body: "Views/Move.html",
                            lists: data
                        };
                    }
                }
            });

            modalInstance.result.then(function (formData) {
                var defs = [];
                $.each($scope.mySelections, function (i, sel) {
                    defs.push(model.MoveToSecure({
                        Id: sel.EventID.substring(4, sel.EventID.length),
                        Filename: sel.FileName
                    }));
                });

                $.when.apply($, defs).done(function () {
                    alert('Move completed');
                });
            });
        });
    };
}];

I know, its a lot and it feels unstructured somewhat to me, between all the variable initialization, private methods, and general initialization methods.  It doesn't feel concise and deterministic to me, which is something I liked about Backbone.  Anyone got any feedback on a better way to do this?  Thanks!

A: You need to move most of that stuff into 'concise' directives. If you don't master directives, your controllers will always end up overburdened and crazy like this. Ideally your controller pretty much only takes data back and forth between your scope and services.


text:
Q: Submit form and fetch data from website VBA I'm trying to fetch data from this site using VBA in Excel. What I tried to do and what worked was using InternetExplorer object like this:
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = False
IE.Navigate "http://zertifikate.finanztreff.de"
IE.document.getElementById("USFsecuritySearchDropDown").Value = "DE000BP5TBQ2"
IE.document.getElementById("USFsecuritySearchDropDownForm").submit

Do While IE.Busy Or IE.readyState <> 4  'wait until page is loaded
    Application.Wait DateAdd("s", 1, Now)
Loop
MsgBox IE.document.getElementById("BP5TBQ~30~5").innerHTML

However this worked very slow and didn't get always the right results. I suspect that sometimes it didn't wait until webpage was loaded. I tried to look for answers and I found this answer on stackoverflow. Now I'm trying to figure out how to rewrite my macro using MSXML2 and MSHTML. So far I was able to do this :
Dim IE As MSXML2.XMLHTTP60
Set IE = New MSXML2.XMLHTTP60

IE.Open "GET", "http://zertifikate.finanztreff.de", False
IE.send
While IE.ReadyState <> 4
    DoEvents
Wend

Dim HTMLDoc As MSHTML.HTMLDocument
Dim htmlBody As MSHTML.htmlBody

Set HTMLDoc = New MSHTML.HTMLDocument
Set htmlBody = HTMLDoc.body
htmlBody.innerHTML = IE.responseText
HTMLDoc.getElementById("USFsecuritySearchDropDown").Value = "DE000BP5TBQ2"

please, why HTMLDoc has method getElementById and htmlBody doesn't ? How could I submit form "USFsecuritySearchDropDownForm". I tried this :
 HTMLDoc.getElementById("USFsecuritySearchDropDownForm").submit

, but it always open new window in my default browser, I would like to have it hidden.
It seems to me that I am missing difference between XMLHTTP60 and MSHTML.HTMLDocument.
If you could please help me or at least show me where I can find this information I would be really thankful...

A: XMLHTTP sends an http request to the webserver and receives back a response. MSHTML receives a string and renders the HTML. When you use them together, XMLHTTP gets the webserver response and MSHTML puts that response in a form you can use.
I think you don't need to submit anything. If you go to the site and type in the ticker, you get to a page like
http://zertifikate.finanztreff.de/dvt_einzelkurs_uebersicht.htn?seite=zertifikate&i=22558284&suchbegriff=DE000BP5TBQ2&exitPoint=
That has the ticker in it. You can "GET" that URL directly and get whatever information you need from the html that's returned. This example gets what I assume is the stock price.
Sub GetPrice()

    Dim xHttp As MSXML2.XMLHTTP
    Dim hDoc As MSHTML.HTMLDocument
    Dim hDiv As HTMLDivElement
    Dim hTbl As HTMLTable

    Const sTICKER As String = "DE000BP5TBQ2"

    Set xHttp = New MSXML2.XMLHTTP

    xHttp.Open "GET", "http://zertifikate.finanztreff.de/dvt_einzelkurs_uebersicht.htn?seite=zertifikate&i=22558284&suchbegriff=" & sTICKER & "&exitPoint="
    xHttp.send

    Do Until xHttp.readyState = 4
        DoEvents
    Loop

    If xHttp.Status = 200 Then
        Set hDoc = New MSHTML.HTMLDocument
        hDoc.body.innerHTML = xHttp.responseText

        'Get the third TD in the first TABLE in the first DIV whose class is 'tape'
        Set hDiv = hDoc.getElementsByClassName("tape").Item(0)
        Set hTbl = hDiv.getElementsByTagName("table").Item(0)
        Debug.Print hTbl.getElementsByTagName("td").Item(2).innerText
    End If

End Sub

Post Example
Sub GetPriceByPost()

    Dim xHttp As MSXML2.XMLHTTP
    Dim hDoc As MSHTML.HTMLDocument
    Dim hDiv As HTMLDivElement
    Dim hTbl As HTMLTable

    Const sTICKER As String = "i=635957"

    Set xHttp = New MSXML2.XMLHTTP

    xHttp.Open "POST", "http://fonds.finanztreff.de/fonds_einzelkurs_uebersicht.htn"
    xHttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
    xHttp.send sTICKER

    Do Until xHttp.readyState = 4
        DoEvents
    Loop

    If xHttp.Status = 200 Then
        Set hDoc = New MSHTML.HTMLDocument
        hDoc.body.innerHTML = xHttp.responseText

        'Get the third TD in the first TABLE in the first DIV whose class is 'tape'
        Set hDiv = hDoc.getElementsByClassName("tape").Item(0)
        Set hTbl = hDiv.getElementsByTagName("table").Item(0)
       Debug.Print hTbl.getElementsByTagName("td").Item(2).innerText
    Else
        Debug.Print xHttp.statusText
    End If

End Sub


text:
Q: SQL Server - displaying data "downward" I have a table like so:
CREATE TABLE #Categories (CategoryText VARCHAR(50), CategoryUrl VARCHAR(50), SubCategoryText VARCHAR(50), SubCategoryUrl VARCHAR(50))
INSERT INTO #Categories SELECT 'Lighting', 'http://lighting.com', 'Chandeliers', 'http://chandeliers.com'
INSERT INTO #Categories SELECT 'Lighting', 'http://lighting.com', 'Lamps', 'http://lamps.com'
INSERT INTO #Categories SELECT 'Hardware', 'http://hardware.com', 'Hooks', 'http://hooks.com'
INSERT INTO #Categories SELECT 'Hardware', 'http://hardware.com', 'Hinges', 'http://hinges.com'

which looks like:
CategoryText                                       CategoryUrl                                        SubCategoryText                                    SubCategoryUrl
-------------------------------------------------- -------------------------------------------------- -------------------------------------------------- --------------------------------------------------
Lighting                                           http://lighting.com                                Chandeliers                                        http://chandeliers.com
Lighting                                           http://lighting.com                                Lamps                                              http://lamps.com
Hardware                                           http://hardware.com                                Hooks                                              http://hooks.com
Hardware                                           http://hardware.com                                Hinges                                             http://hinges.com

How would I dynamically display the data as follows:
Type        Text                                               Url
----------- -------------------------------------------------- --------------------------------------------------
Category    Lighting                                           http://lighting.com
SubCategory Chandeliers                                        http://chandeliers.com
SubCategory Lamps                                              http://lamps.com
Category    Hardware                                           http://hardware.com
SubCategory Hinges                                             http://hinges.com
SubCategory Hooks                                              http://hooks.com

I also need to retain the correct order of categories and subcategories.
UNPIVOT came to mind, but I don't see how I can apply it here as the data structure/requirements are different than most examples out there.
Any help is appreciated.

A: Try this:
select distinct
  Type = 'Category',
  Parent = CategoryText,
  Text = CategoryText,
  Url = CategoryUrl
from #Categories
union all
select
  Type = 'SubCategory',
  Parent = CategoryText,
  Text = SubCategoryText,
  Url = SubCatgoryUrl
from  #Categories
order by Parent,Type,Text

A: This should work for you...using a UNION with a ranking function...
select CASE WHEN SubCategoryText IS NULL THEN 'Category' ELSE 'SubCategory' END as Type,
        CASE WHEN SubCategoryText IS NULL THEN CategoryText ELSE SubCategoryText END as Type,
        CategoryUrl
from (
select *, RANK() OVER (ORDER BY CategoryText, SubCategoryText) AS Rank
from (
select CategoryText, null as SubCategoryText, CategoryUrl
from #Categories
union
select CategoryText, SubCategoryText, SubCategoryUrl
from #Categories
)a)b
order by Rank

A:     ;WITH Main as
    (
        SELECT 'Category' AS [Type], CategoryText AS ordering, CategoryText, CategoryUrl
        FROM #Categories
    ),
        Sub AS
    (
        SELECT 'SubCategory' AS [Type], CategoryText AS ordering, SubCategoryText, SubCategoryUrl
        FROM #Categories
    )
    SELECT DISTINCT Type, CategoryText, CategoryUrl, ordering
    FROM Main
    UNION ALL
    SELECT Type, SubCategoryText, SubCategoryUrl,ordering
    FROM Sub
    ORDER BY ordering, [Type], categorytext

A: I was able to get this working, with retaining the order of categories and subcategories.
I used @SliverNinja's CASE statement to get the correct type and text.
For the sorting, I added 2 columns CategorySortOrder and SubCategorySortOrder. I combined the category and subcategory sortorder to create a new single SortOrder column. I then grouped and ordered by that column to get my final result.
CREATE TABLE #Categories (CategoryText VARCHAR(50), CategoryUrl VARCHAR(50), CategorySortOrder INT,SubCategoryText VARCHAR(50), SubCategoryUrl VARCHAR(50), SubCategorySortOrder INT)
INSERT INTO #Categories SELECT 'Lighting', 'http://lighting.com', 1, 'Chandeliers', 'http://chandeliers.com',1
INSERT INTO #Categories SELECT 'Lighting', 'http://lighting.com', 1, 'Lamps', 'http://lamps.com' , 2
INSERT INTO #Categories SELECT 'Hardware', 'http://hardware.com', 2 ,'Hooks', 'http://hooks.com' ,1
INSERT INTO #Categories SELECT 'Hardware', 'http://hardware.com', 2,'Hinges', 'http://hinges.com' ,2

SELECT
    Type
    , Text
    , Url
    , MIN(SortOrder)[SortOrder]
INTO
    #cats
FROM
    (
    SELECT
        CASE WHEN SubCategoryText IS NULL THEN 'Category' ELSE 'SubCategory' END [Type]
        , CASE WHEN SubCategoryText IS NULL THEN CategoryText ELSE SubCategoryText END [Text]
        , [Url]
        , CASE WHEN SubCategoryText IS NULL THEN CAST(CAST(CategorySortOrder AS VARCHAR) + CAST(SubCategorySortOrder AS VARCHAR) AS NUMERIC)  ELSE CAST(CAST(CategorySortOrder AS VARCHAR) + CAST(SubCategorySortOrder AS VARCHAR) AS NUMERIC) + 1 END[SortOrder]
    FROM
        (
            SELECT
                CategoryText
                , NULL [SubCategoryText]
                , CategoryUrl [Url]
                , CategorySortOrder
                , SubCategorySortOrder
            FROM
                #Categories
            UNION ALL
            SELECT
                CategoryText
                , SubCategoryText
                , SubCategoryUrl
                , CategorySortOrder
                , SubCategorySortOrder
            FROM
                #Categories
        )t
    )t
GROUP BY
    Type
    , Text
    , Url
ORDER BY
    SortOrder

SELECT
    Type
    , Text
    , Url
FROM
    #Cats


text:
Q: python3 Error collection ModuleNotFoundError This is my tree:
.
├── __init__.py
├── refactoring
│   ├── __init__.py
│   ├── refactoring.py
│   └── tests
│       ├── __init__.py
│       └── test_refactoring.py
└── requirements.txt

*

*Note: I have my virtualenv from python3.8 with pytest installed.

This is the command:
pytest refactoring/tests/test_refactoring.py

And, this is the error:
_____________________________ ERROR collecting refactoring/tests/test_refactoring.py _____________________________
ImportError while importing test module '/home/yo/projects/proyect_name/refactoring/tests/test_refactoring.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
/usr/lib/python3.8/importlib/__init__.py:127: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
refactoring/tests/test_refactoring.py:1: in <module>
    from refactoring import fn1, fn2, fn3, fn4, result
E   ModuleNotFoundError: No module named 'refactoring'

The init.py file have 644 permissions with $USER:$USER
Now, if I remove refactoring/init.py it works... why? didn't it have to be both packages to import?


text:
Q: Динамическое рисование дуги canvas Можно ли как-то плавно динамически рисовать дугу? Есть такой код:

var canvas = document.getElementById('cnvs');
var ctx = canvas.getContext('2d');

ctx.lineWidth = 15;
ctx.strokeStyle = "#FF0000";
ctx.lineCap = "round";

ctx.arc(100, 100, 80, 2.355, 7.065, false);
ctx.stroke();
<canvas id="cnvs" width="400px" height="400px"></canvas>

Но он рисует дугу сразу, а мне хотелось бы, чтобы оно рисовало ее с нуля и достигало нужного значения за 1-2 сек. Такое возможно функциями canvas? Или надо использовать что-то другое?


text:
Q: If $\int f d\mu = 1$ with $\mu$ probability measure, then $f(x)=1$ for $f\mu$-a.e. $x$? Let $f \colon X \to \mathbb R^+$ be a non negative, measurable function (w.r.t. a probability measure $\mu$ on $X$), with $\int f d\mu = 1$.
From this it does not follow $f = 1$ $\mu$-a.e.
However, is it true that $f=1$ $\tilde{\mu}$-a.e., being $\tilde{\mu} := f\mu$?
I perfectly know this is a stupid question, but I have a terrible confusion in my mind and I cannot understand what is going on...
Thanks.

A: Nah: pick two distinct nonzero numbers whose average is 1, say $3/2$ and $1/2$. Take $X=\{ 0,1 \}$, $\mu$ the uniform measure on this set. Define $f(0),f(1)$ to be the two numbers you picked. Then $f$ is never 1 at all, but $\int f d \mu = 1$. And $f \mu$ assigns measure $3/2$ to $\{ 0 \}$ and $1/2$ to $\{ 1 \}$.

A: For a continuous counterexample, consider $\mu$ to be the lebesgue measure on $(0,1)$, and take $f(x) = 2x$.

A: If we set
$$f(x) = \begin{cases} 0, & x \in (0, \tfrac{1}{2}), \\ 2, & x \in (\tfrac{1}{2},1) \end{cases}$$
then
$$\int_{(0,1)} f(x) \, dx = 1.$$
Since
$$\{f=1\} = \emptyset$$
it holds for any measure $\nu$ on $((0,1),\mathcal{B}((0,1))$ that
$$\nu(f=1)=0;$$
hence in particular
$$\tilde{\mu}(f=1)=0.$$
This shows that, in general, $f=1$ $\tilde{\mu}$-a.e. does not hold true.


text:
Q: Ajax local content place different objects on another page using jQuery I have a series of products on a page with a class .small-product and inside each one I have an image and its tittle as links to a larger view..
What I want to do it to load the larger view ratings into the .small-product layout. here is the html of the .small-product:

"

Title

£5

Large view content to Ajax:

{module_ratingrank,/images/rating}

My JS with some Jquery:
$('.small-product').each(function() {
  var ratingContainer = $('#rating-stars');
  var spacing = ('+');
  var smallProductLink = $('.small-product a').attr('href'),
  sourceRatings = smallProductLink + spacing +'.product-large-reviews';
  ratingContainer.load(sourceRatings);

});

Now what I tried and worked but it only works for 1 individual element is if I use a .load('/href/path/to/large/view .product-large-reviews');
But I want every product to use their link to fetch their own information from their large view.
I get only a 404 response from the server saying that it could not be found, I guess it cannot be found because the web address looks like they are together with the class to load e.g www.site.com/path/to/large/view.product-large-reviews. i tried my ways to make a space between but it keeps returning 404.
Some help would be awesomely appreciated!


text:
Q: cannot import name 'Product' from 'products.models' I am new to django, i am following a tutorial i do same things but got an error
Im trying to make view for products app this is products.models
from django.db import models

# Create your models here.

class Product(models.Model):
    title       = models.TextField()
    description = models.TextField()
    price       = models.TextField()

products.views
from django.shortcuts import render
from .models import Product

def product_detail_view(request):
    obj = Product.objects.get(id=1)
    context = {
        'title':obj.title,
        'description':obj.description
    }
    return render(request, "product/detail.html", context)

prouducts .urls
from django.urls import path

from . import views

from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns = [
    path('product',views.product_view_detail, name='Home'),
]

urls.py
from new1.settings import MEDIA_ROOT
from django import urls
from django.contrib import admin
from django.urls import path
from pages import views
from django.urls import include, path
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('', include('pages.urls'), name='Home'),
    path('product',include('products.urls')),
    path('admin/', admin.site.urls),
]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

urlpatterns += staticfiles_urlpatterns()

I got this error cannot import name 'Product' from 'products.models'
it works before i add products views
Exception in thread django-main-thread:
Traceback (most recent call last):
 File "g:\64-bit\new folder\py38 64bit\lib\threading.py", line 932, in _bootstrap_inner
   self.run()
 File "g:\64-bit\new folder\py38 64bit\lib\threading.py", line 870, in run
   self._target(*self._args, **self._kwargs)
 File "C:\Users\aram\.virtualenvs\cfeproj-ldwjYLGf\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
   fn(*args, **kwargs)
 File "C:\Users\aram\.virtualenvs\cfeproj-ldwjYLGf\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run
   self.check(display_num_errors=True)
 File "C:\Users\aram\.virtualenvs\cfeproj-ldwjYLGf\lib\site-packages\django\core\management\base.py", line 419, in check
   all_issues = checks.run_checks(
 File "C:\Users\aram\.virtualenvs\cfeproj-ldwjYLGf\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks
   new_errors = check(app_configs=app_configs, databases=databases)
 File "C:\Users\aram\.virtualenvs\cfeproj-ldwjYLGf\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
   return check_resolver(resolver)
 File "C:\Users\aram\.virtualenvs\cfeproj-ldwjYLGf\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
   return check_method()
 File "C:\Users\aram\.virtualenvs\cfeproj-ldwjYLGf\lib\site-packages\django\urls\resolvers.py", line 412, in check
   for pattern in self.url_patterns:
 File "C:\Users\aram\.virtualenvs\cfeproj-ldwjYLGf\lib\site-packages\django\utils\functional.py", line 48, in __get__
   res = instance.__dict__[self.name] = self.func(instance)
 File "C:\Users\aram\.virtualenvs\cfeproj-ldwjYLGf\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns
   patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
 File "C:\Users\aram\.virtualenvs\cfeproj-ldwjYLGf\lib\site-packages\django\utils\functional.py", line 48, in __get__
   res = instance.__dict__[self.name] = self.func(instance)
 File "C:\Users\aram\.virtualenvs\cfeproj-ldwjYLGf\lib\site-packages\django\urls\resolvers.py", line 591, in urlconf_module
   return import_module(self.urlconf_name)
 File "g:\64-bit\new folder\py38 64bit\lib\importlib\__init__.py", line 127, in import_module
   return _bootstrap._gcd_import(name[level:], package, level)
 File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
 File "<frozen importlib._bootstrap>", line 991, in _find_and_load
 File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
 File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
 File "<frozen importlib._bootstrap_external>", line 783, in exec_module
 File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
 File "C:\Users\aram\Desktop\cfeproj\new1\urls.py", line 33, in <module>
   path('product',include('products.urls')),
 File "C:\Users\aram\.virtualenvs\cfeproj-ldwjYLGf\lib\site-packages\django\urls\conf.py", line 34, in include
   urlconf_module = import_module(urlconf_module)
 File "g:\64-bit\new folder\py38 64bit\lib\importlib\__init__.py", line 127, in import_module
   return _bootstrap._gcd_import(name[level:], package, level)
 File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
 File "<frozen importlib._bootstrap>", line 991, in _find_and_load
 File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
 File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
 File "<frozen importlib._bootstrap_external>", line 783, in exec_module
 File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
 File "C:\Users\aram\Desktop\cfeproj\products\urls.py", line 3, in <module>
   from . import views
 File "C:\Users\aram\Desktop\cfeproj\products\views.py", line 2, in <module>
   from .models import Product
ImportError: cannot import name 'Product' from 'products.models' (C:\Users\aram\Desktop\cfeproj\products\models.py)

A: At your settings add 'products' at installed app then makemigrations and migrate the
migrations then try again


text:
Q: FileChooser diff between GUI choice and typing filename I have an application using JFileChooser to select a directory.  In this app, I do not want to try to process symbolic links, and I would like to run on multiple platforms.  The code therefore attempts to determine whether a chosen file is a symbolic link, and displays an error dialog if it is.
Here is the code that obtains the File from the JFileChooser.
public File getDirectoryChoice(String buttonText, String currentDirectory)
{
  File chosenFile = null;
  if (fileChooser == null) { fileChooser = new JFileChooser(); }
  if (currentDirectory != null)
    { fileChooser.setCurrentDirectory(new File(currentDirectory)); }
  fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
  fileChooser.setApproveButtonText(buttonText);
  int returnValue = fileChooser.showOpenDialog(mainFrame);
  if (returnValue == JFileChooser.APPROVE_OPTION)
  {
    chosenFile = fileChooser.getSelectedFile();
  }
  return chosenFile;
}

and here is the code I use to determine whether the chosen file is a symbolic link:
public static boolean isSymbolic(File f)
{
  try
  {
    String absolute = f.getAbsolutePath();
    String canonical = f.getCanonicalPath();
    return !(absolute.equals(canonical));
  }
  catch (IOException ioe)
  {
    return false;
  }
}

On Windows 7: If the user chooses a given directory using the mouse, this works fine.  If the user types the same directory name into the filename text box, the second code snippet indicates that the absolute and canonical paths are not the same.  It does not matter if the user enters the trailing backslash or not.
When I stop this in the debugger on the 'return' statement line and look at the details of the two strings, the hash value of the absolute path string is a big negative number, and the hash value of the canonical string is 0.  I don't know why that would be, and in fact wonder if it's a quirk of the (eclipse) debugger.
Can anyone tell me why there would be this difference?

A: Double check that you are typing the string exactly the same as what is returned by JFileChooser.
I tried this out and without thinking I typed c:\temp.  Just like in your tests, isSymbolic() method returned true.  However upon closer inspection, I noticed that when I selected this path in the file chooser, it returned C:\temp instead (note the capital C).
So even though it's ugly, you could add a special case something like this:
    if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0)
        return !(absolute.equalsIgnoreCase(canonical));
    else
        return !(absolute.equals(canonical));

You also might want to look at this related question: "Java 1.6 - determine symbolic links".  There are quite a few answers there which you might find helpful.

A: If you add absolute.hashCode() and canonical.hashCode() to the Expressions window in Eclipe you should see the correct values - both not zero. String has hash member that is initialized to 0. Then it is updated to the correct value when hashCode() is executed.
So what you probably see is the calculated hash for absolute string and not yet calculated hash for canonical string.
Put a breakpoint in String.hashCode() and you will see that getCanonicalPath() on Windows triggers absolute.hashCode(). It appears that implementation of getCanonicalPath() on Windows caches results of canonicalization. Somewhere in between of WinNTFileSystem.canonicalize(), the lookup in the cached results map triggers absolute.hashCode().
So at the breakpoint that you set on return statement in isSymbolic(), absolute has a valid hash code and canonical has it still as zero.
Here is the stack trace that demonstrates absolute.hashCode() execution as a result of f.getCanonicalPath() :
String.hashCode() line: 1482 [local variables unavailable]
ExpiringCache$1(HashMap<K,V>).getEntry(Object) line: 344
ExpiringCache$1(LinkedHashMap<K,V>).get(Object) line: 280
ExpiringCache.entryFor(String) line: 83
ExpiringCache.get(String) line: 58
WinNTFileSystem(Win32FileSystem).canonicalize(String) line: 377
File.getCanonicalPath() line: 559
Test.isSymbolic(File) line: 25
Test.main(String[]) line: 16


text:
Q: How do I simulate clicking a link that opens in a new tab/window using jQuery/Javascript? I have a link that opens in a new tab with _blank:
link

I'd like to be able to 'click' on this from Javascript. I know I could do document.location=... but the problem here is the new tab part. Is this possible?

A: You can usually open a new window or tab using window.open. So instead of setting location, just call window.open and pass only the URL, nothing else.

A: $("#your_a").click(function(e) {
   e.preventDefault();
   window.open($(this).attr("href"), this.target);
}

You could use any name for target, preventDefault() if you want to override the link actions completely

A: If you really want to simulate click, you can give a id to the anchor tag and call jQuery click() on that element.
link

and in script
$("#mylink").click()

A: to "simulate" the click you trigger the click event:
HTML:
click me

jQuery:
$("#mylink").trigger("click");

-or-
$("#mylink").click();

Using 'trigger' allows you to pass in extra parameters if you bind a function to the click event. See the jQuery 'trigger' documentation for more info: http://api.jquery.com/trigger/


text:
Q: cordova-plugin-wkwebview-engine reloads app when going back from subpage Im using the plugin cordova-plugin-wkwebview-engine with my phonegap.build app.
And when I load a subpage and then swipe back to the start page, then the start page freezes for about 4 sec before I can scroll it again. And I realised that it is reloading the start page every time I go back from a subpage. Is this the expected way it should work?

*

*How to prevent it from reload the startpage? Why doesn´t it work like in Safari? Since Safari is using the wkwebview! When you load a subpage and then go back Safari remembers the position off the previus page, why is this not doing that?

*When I open a subpage it is opened in a new view on top of my start page. And I wonder if it is possible to open it in the same view as the startpage? So all pages is loaded in just one view?
Any input appreciated thanks.


text:
Q: Toric Variety from a fan with "identical" edges I have this fan that I've been trying to construct a toric variety from. The problem is, it contains certain edges twice. These are the edges:
$$(1,0,1)$$
$$(0,1,1)$$
$$(-1,-1,1)$$
$$(0,0,1)$$
$$(0,0,1)$$
The last one appears "twice". Or at least that is what my calculation says. Without the double last entry, this would just be $\mathcal{O}(-3)$ over $\mathbb{CP}^2$.
I've been using the construction found in the Mirror Symmetry book by Hori et al. I have a matrix of charges $Q$
$$ Q^T = \begin{pmatrix} 1 & 1 & 1 & -3 & 0  \\ 1 & 1 & 1 & 0 & -3 \end{pmatrix} $$
Then the Edges $\Sigma(1)$ of the fan $\Sigma$ are given by the kernel of this matrix $Q$ as
$$ \sum_{i=1}^5 Q_{ia} v_i = 0$$
And I get the above edges.
I'm specifically interested in the Divisor corresponding to this last entry. So, what happens when I have an edge twice? Or is this not allowed?