text:
Q: Second order approximation of $\log \det X$ I'm trying to follow the derivation of second order approximation of $\log \det X$ from page 658 of Boyd & Vandenberghe's Convex Optimization. How is the last step derived? I.e., where does the trace expression come from?

A: Short answer: The trace gives the scalar product on the space of matrices: $\langle X,Y \rangle = \mathrm{tr}(X^\top Y)$. Since you're working with symmetric matrices, you can forget the transposition: $\langle X,Y \rangle = \mathrm{tr}(XY)$.
Long answer, with all the gory details: Given a function $f:\mathrm S_n^{++}\to\mathbf R$, the link between the gradient $\nabla_Xf$ of the function $f$ at $X$ (which is a vector) and its differential $d_Xf$ at $X$ (which is a linear form) is that for any $U\in V$,
$$ d_Xf(U) = \langle \nabla_Xf,U \rangle. $$
For your function $f$, since you know the gradient, you can write the differential:
$$ d_Xf(U) = \langle X^{-1},U \rangle = \mathrm{tr}(X^{-1}U). $$
What about the second order differential? Well, it's the differential of the differential. Let's take it slow. The differential of $f$ is the function $df:\mathrm S_n^{++}\to\mathrm L(\mathrm M_n,\mathbf R)$, defined by $df(X) = V\mapsto \mathrm{tr}(X^{-1}V)$. To find the differential of $df$ at $X$, we look at $df(X+\Delta X)$, and take the part that varies linearly in $\Delta X$. Since $df(X+\Delta X)$ is a function $\mathrm M_n\to\mathbf R$, if we hope to ever understand anything we should apply it to some matrix $V$:
$$ df(X+\Delta X)(V) = \mathrm{tr}\left[ (X+\Delta X)^{-1} V \right] $$
and use the approximation from the passage you cited:
\begin{align*}
df(X+\Delta X)(V)
&\simeq \mathrm{tr}\left[ \left(X^{-1} - X^{-1}(\Delta X)X^{-1}\right) V \right]\\
&= \mathrm{tr}(X^{-1}V) - \mathrm{tr}(X^{-1}(\Delta X)X^{-1}V)\\
&= df(X)(V) - \mathrm{tr}(X^{-1}(\Delta X)X^{-1}V).
\end{align*}
And we just see that the part that varies linearly in $\Delta X$ is the $-\mathrm{tr}(\cdots)$. So the differential of $df$ at $X$ is the function $d^2_Xf:\mathrm S_n^{++}\to\mathrm L(\mathrm M_n, \mathrm L(\mathrm M_n,\mathbf R))$ defined by
$$ d^2_Xf(U)(V) = -\mathrm{tr}(X^{-1}UX^{-1}V). $$


text:
Q: Python how to initialize thread with unknown number of arguments? I'm having trouble using the starred expressions in combination with fixed argument lists when attempting to create threads.
Consider the following code:
the_queue = Queue()

def do_something(arg1, arg2, queue):
    # Do some stuff...
    result = arg1 + arg2

    queue.put(result)

def init_thread(*arguments):
    t = Thread(target=do_something, args=(arguments, the_queue))
    t.start()
    t.join()

init_thread(3,6)

This throws the exception:
TypeError: do_something() takes exactly 3 arguments (2 given)

In other words, the "arguments" tuple is evaluated as one tuple object (i.e. it's not unpacked), and the_queue is regarded as the second argument.
The code needs to be able to initalize threads calling different methods with an unknown number of arguments, but that always will have a "queue" parameter at the end.
Is there any way to achieve this? In that case, how? And if not -- what am I doing wrong?
Thanks.
EDIT: I should add that calling the "init_thread()" method with the queue as an argument is not an option, since I don't want the rest of my code to be "aware" of how the thread handler works internally...

A: You need to make a new tuple.
t = Thread(target = do_something, args = arguments + (the_queue, ))

A: You can also unpack the packed-up *arguments tuple, like so:
>>> def Print(*args):
...     print('I am prepended to every message!', *args)
...
>>> Print('This', 'has', 'four', 'arguments')
I am prepended to every message! This has four arguments
>>> def Print(*args):
...     print('I am prepended to every message!', args)
...
>>> Print('This', 'has', 'four', 'arguments')
I am prepended to every message! ('This', 'has', 'four', 'arguments')

So you see, referring to *agruments, as opposed to arguments, will unpack the tuple.
Thus your code might be:
def init_thread(*arguments):
    t = Thread(target=do_something, args=(*arguments, the_queue))
    t.start()
    t.join()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Text Parsing Design Let's say I have a paragraph of text like so:

Snails can be found in a very wide
  range of environments including
  ditches, deserts, and the abyssal
  depths of the sea. Numerous kinds of snail can
  also be found in fresh waters. (source)

I have 10,000 regex rules to match text, which can overlap. For example, the regex /Snails? can/i will find two matches (italicized in the text). The regex /can( also)? be/i has two matches (bolded).
After iterating through my regexes and finding matches, what is the best data structure to use, that given some place in the text, it returns all regexes that mached it? For example, if I want the matches for line 1, character 8 (0-based, which is the a in can), I would get a match for both regexes previously described.
I can create a hashmap: (key: character location, value: set of all matching regexes). Is this optimal? Is there a better way to parse the text with thousands of regexes (to not loop through each one)?
Thanks!

A: I'm assuming that your regex does not cross between multiple sentences. In that case you could
1) break your text into array of sentences
2) for each sentence simply record which (id) regex have matched.
3) when you would like to see the match - run the regex again.

"Store less / compute more" solution.

A: Storing all of the matches in a dictionary will work, but will it means you'll have to store all of the matches in memory at the same time. If your data is small enough to easily fit into memory, don't worry about it. Just do what works and move on.
If you do need to reduce memory usage of increase speed it really depends on how you are using the data. For example, if you process positions starting at the beginning and going to the end, you could use re.finditer to iteratively process all of the regexes and not maintain extra matches in memory longer then needed.


text:
Q: How can I add a custom allure report with jbhave I am trying to use allure report with jbehave on Java using maven. So there is a package that has a java class that we can use to create the allure report.
I only imported that class and I added the class as a reportBuilder for the configuration of Jbehave, just like the code below.
...
import io.qameta.allure.jbehave.AllureJbehave
...

public class RunStories extends JUnitStories {

 private AllureJbehave allureJBehave;
 ...
 ...

 @Override
 public Configuration configuration() {

  // set path of results
  System.setProperty("allure.results.directory", "build/allure-results")

  // create AllureJbehave instance
  allureJBehave = new AllureJbehave();
  StoryReporterBuilder reporterBuilder = new StoryReporterBuilder()
   .withReporters(allureJBehave)
   .withCodeLocation(codeLocationFromClass(this.getClass()));

  // create and return configuration instance
  Configuration jBehaveConfiguration = new MostUsefulConfiguration();
   jBehaveConfiguration
     .useStoryReporterBuilder(reporterBuilder);

   return jBehaveConfiguration;
 }

}

But I am not getting the information for trends graphs, how can I add those values or add more information to the allure report ?

A: You might want to check the plugin file (allure.yml) you are using for Allure. in case there is none, you can add your own with the list of plugins you are interested to use and add it to your configuration.
You can also check the read access of your files. If you are using Jenkins (for example), sometimes there is some access rights that are inherited and that can cause some issues when read.


text:
Q: SQL-Server SQLEXPRESS slower then real SQL 2008 Server? I got my first bigger project with around 150 users at every day since a week.
For my smaller projects like a company homepage with 100 visits each day, I installed the free sqlexpress.
Now it all semms a bit slow and I really try to find out why.
My idea was and my question is: Is the SQLServer Express slower then the SQL Server 2008 full install ?

A: Note that the limitations of the EXPRESS editions include CPU and memory limitations which might influence performance characteristics.
With the SQL Server EXPRESS 2012 being "[...]limited to lesser of 1 Socket or 4 cores" and the SQL Server 2008 EXPRESS being limited to a single CPU with any number of cores, the Express editions cannot benefit from multithreading as much as editions without this limit. Also, all versions of EXPRESS editions are limited to a maximum of 1 GB of RAM, meaning that more disk seeks are necessary as soon as the 1 GB is not sufficient to cache the working data set (usually at least all index pages).
Especially the memory limitations surely would make it "slower then the full install" for many applications.

A: It's probably worth pointing out that its not how many visitors your site gets a week but rather how many visits happen at once and what the load each user generates on the system looks like.
There's a huge difference in the database load generated by 150 users spread out over the course of a week (so 21 or 22 visits a day on a 7 day week) who log in, get given a cookie to say they've logged in, and read a new blog post, for example, and 150 users who all hit the site at 9am every single day when work starts, with each one of them needing to run different but complex queries on a massive dataset every hour to track sales or something.
SQL Server Express is only likely to be your problem if you're actually hitting the limits built into SQL Server Express in the same way that a small amount of memory is only a problem on a system if you're doing things that actually require more memory than the system has.


text:
Q: Inverting a key/value pair I've written the following code:
from collections import Counter

shopping_list = input().split()
a = Counter(shopping_list)

print('\n'.join("{} {}".format(k, v) for k, v in a.items()))

If the input is carrots carrots bread tomatoes onions apples tomatoes carrots tomatoes onions onions onions bread milk bread apples
The code outputs:
carrots 3
bread 3
tomatoes 3
onions 4
apples 2
milk 1

The code works fine, but any pairs that are inserted in the input have to be printed with the counter before the items themselves. (The test environment will insert different inputs each time)
So how do I make it output like this?
3 carrots
3 bread
3 tomatoes
4 onions
2 apples
1 milk

Thanks in advance

A: Thanks to @oskros
Final code with the modification proposed:
from collections import Counter

shopping_list = input().split()
a = Counter(shopping_list)

print('\n'.join("{} {}".format(v, k) for k, v in a.items()))


text:
Q: Unix-Echo -n is not working for(( i=0;i<=5;i++))
do
    for ((j=1;j<=i;j++))
    do
        echo -n "$j"
    done
    echo " "
done

Outputs:
-n 1

-n 1
-n 2

-n 1
-n 2
-n 3

-n 1
-n 2
-n 3
-n 4

-n 1
-n 2
-n 3
-n 4
-n 5

My OS: SunOS sun4v sparc sun4v
I want the output to be:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

A: According to the manual, the -n option to echo is not portable. On a Solaris system -n is supported by the BSD emulation of echo in /usr/ucb/echo, but not by the default echo. As a result:

ksh88's and ksh's echo does not have an -n option. csh's echo and /usr/ucb/echo, on the other hand, have an -n option, but do not understand the back-slashed escape characters. sh and ksh88 determine whether /usr/ucb/echo is found first in the PATH and, if so, they adapt the behavior of the echo builtin to match /usr/ucb/echo.

To fix the problem, you have several options:

*

*Switch to printf %s "$j" to portably print a string without newline. (I would recommend doing this.)

*Switch to \c escapes, i.e. replace echo -n "$j" with echo "$j\c". (Not recommended if the script needs to remain portable to BSD systems.)

*Download a well-tested free shell such as bash that implements echo -n, and use it to run the shell scripts you care about.

*Prepend /usr/ucb to the PATH. This will cause echo to switch to BSD-compliant behavior, but will also introduce other BSD commands, potentially breaking unrelated parts of the script. (Not recommended.)

A: If -n option is not working for you, you can try using -e option which enables the use of backslash characters and then you can use \c in your echo statement.
Here is the code sample:
    for(( i=0;i<=5;i++))
    do
        for ((j=1;j<=i;j++))
           do
               echo -e "$j \c"
          done
        echo " "
   done


text:
Q: How do you hide specific content if $page = name How do you hide specific content if $page = name
For example:
<?php
if ($page=='special'){
    echo "
hello
";
}
?>

The above example will show the div if the $page = special. How do I do the opposite of this, hide a specific div if the $page = something?
Edit:
To be more specific I would like to hide my main navigation  when on the $clients page.
Do I wrap the  with PHP or is it possible to hide a specific div if I give it a name, for example.  the PHP would be: if $clients then hide the id named clients.
I should also mention that the content in question has <?php echo $url; ?> and the likes contained within it.
This is the exact content I would like to hide on $clients pages.

<a <?php if ($page=="work") echo "class=\"current\"" ?> href="<?php echo $url; ?>" title="Work">Work

<a <?php if ($page=="profile") echo "class=\"current\"" ?> href="<?php echo $url; ?>profile/" title="Profile">Profile

<a <?php if ($page=="approach") echo "class=\"current\"" ?> href="<?php echo $url; ?>approach/" title="Approach">Approach

<a <?php if ($page=="contact") echo "class=\"current\"" ?> href="<?php echo $url; ?>contact/" title="Contact">Contact

A:
hide a specific div if the $page = something?

if ($page !='special'){
    echo "
hello
";
}

You just echo it if $page is different from something.
If you want, you can also echo it anyway but as 'hidden' if that's what you're trying to achieve.
if ($page =='special'){
     echo "
hello
";
} else {
     echo "
hello
";
}

This way, the div will be in the DOM anyway and you can show it later on without reloading the page using JavaScript.

A: If you want it on every other page that is not special
<?php
if ($page!='special'){
    echo "
hello
";
}
?>


text:
Q: ruby with gem devise autofill in field fullname My code is :
users_controller.rb
**class UsersController < ApplicationController
  def show
    @user = User.find(params[:id])
  end
  def create
       @user.create(user_params)
      if @user.save
          @user.fullname = @user.firstname + ' ' + @user.lastname
      end
  end
end**

user.rb code :
**class User < ApplicationRecord

  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  validates :lname, presence:true, length: {maximum: 40}
  validates :fname, presence:true, length: {maximum: 40}
  validates :fullname, presence:true, length: {maximum: 80}
  has_attached_file :avatar, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/assets/default_image.jpeg"
  validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\z/
  has_many :rooms
end**

And
new.html.erb code :
**
<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= render 'shared/devise_errors' %>

                <%= f.text_field :lname, autofocus: true, class: "form-control", placeholder: "Prénom" %>

                  <%= f.text_field :fname, autofocus: true, class: "form-control", placeholder: "Nom de famille" %>

    <%= f.text_field :fullname, autofocus: true,  class: "form-control", placeholder: "Nom complet ( Prénom + Nom)" %>

**

I would like that when user fill in lname and fname fields, fullname will be automatically fill in with lname + ' ' +fname.
Thanks for your help

A: in the form, just let user fill firstname and lastname, delete the fullname text_field. auto generate and save fullname in the backend.
class UsersController < ApplicationController
  def create
    user_params[:fullname] = "#{user_params[:firstname]} #{user_params[:lastname]}"
    @user.create(user_params)
  end
end


text:
Q: PHP excel Maatwebsite giving me random character file name \Excel::create("test", function ($excel) use ($logs) {
    $excel->sheet('AllProjectLogHours', function ($sheet) use ($logs) {
        $sheet->loadView('template',
            array('log' => $logs));
    });
})->export('xlsx');

I am using Maatwebsite to generate excel.
It returns me excel file named d45e9cfc-ed62-4422-918a-2d3ecb980131. I check create and export function in Maatwebsite  in vendor directory as well.
File name variable set correctly but still it is giving me random character file name
Anyone solved or encounter this problem ?


text:
Q: How can I back up my iPhone without Wi-Fi? I assume there is something wrong with the battery in my iPhone 4, because it will not stay on unless it's plugged into the charger.
I have about 1,000 pictures on my phone, and when my phone is plugged in, I can look at them, and still use my phone somewhat normally but my phone will not connect to Wi-Fi.
Is there any way I can keep my phones pictures if I have to get a new phone, without doing an iCloud backup?

A: You can back up to iTunes on your Mac or PC desktop or laptop directly over USB.
Connect the device over USB to iTunes, select your device in the toolbar and click Back Up Now.

A: In addition to the other answer which allows you to do a general backup of your phone which may include your photos, you can also download your photos directly to your computer with software such as Picasa (from Google) or Apple software like Image Capture (in Utilities) or iPhoto (which may also be known as Photos). These methods will also preserve the full resolutions of your photos. Obviously, you will need to have a computer on hand and have your phone plugged into it.
You may also want to check in iPhoto to see if there is a photo stream that already has all of your photos online.
Another option, if you still have cellular data, is to download Google's Photos app (or Google+ if you have an old enough version of that app) and you can choose the option to back up all of your photos, optionally over cellular, but that would use up a lot of data.


text:
Q: Trying to make script only send a message to teams if specific value returned I can login, get the API token from the server, and return the values I'm looking for. What I haven't been able to do is make the script write to the host only if the value returned is NOT "Primary".
I'm not quite to sending an alert to MS Teams yet as I'm building this modular as I go.
Right now, the code always writes "fail" to the host regardless of the value I set. I had originally put a simple If -not match statement within the CAStatus function, but I don't want to build my alert function within the function I'm using to retrieve server status
#Use login token to pull CA system status
Function CAStatus {
#URL and logon token in header
$system_summary_uri ="https://website.com"
$header_parameters = @{"Authorization" = CALogon}

#Get Summary info from primary CA server and only return its role
(Primary or DR)
$summary_query = Invoke-RestMethod -Uri $system_summary_uri -Method Get -
Headers $header_parameters -ContentType "application/json"
$summary_result = $summary_query.Vaults.Role[0]
return $summary_result
}

#Report if primary server fails
Function Notify {
if (CAStatus -eq "dr") {
    Write-Host "fail"
}
}

castatus

I expect output of "fail" only when the value returned by the API call to CAStatus is "DR". Otherwise I want it to do nothing.
Right now, when I run CAStatus, I get the value "Primary" returned, which is correct since the server is currently in the primary role. There should be nothing output to the host since CAStatus does not equal "dr", but it is outputting "fail" anyway.


text:
Q: in a gnuplot script how to go access the range I call a function in a gnuplot session, and would like to know the ranges and also if a logscale is used inside this function. How to do that ?
Thank you
gnuplot> load 'myfunction.gnu'

the file myfunction.gnu:
if "logscale" {do this};else {do that}

A: Partial solution could be as follows. Let's say that the main script looks like:
set logscale x
set xr [10:100]

load 'my_function.gpl'

Then in my_function.gpl, you could do:
set terminal push
set terminal unknown
plot 1
isLogScale = (GPVAL_X_LOG > 0)?1:0
xMin = GPVAL_X_MIN
xMax = GPVAL_X_MAX
set terminal pop

if(isLogScale){
    print "logscale"
}else{
    print "..."
}

The idea is to:

*

*save the current terminal with set terminal push

*set a "fake" terminal with set terminal unknown

*generate a plot into this terminal (nothing is plotted) in order to force Gnuplot to initialize its internal variables used in the lines below

*check the log scaling using GPVAL_X_LOG (equal to zero if logscale hasn't been set) and ranges with GPVAL_X_MIN, GPVAL_X_MAX.

*revert the terminal settings with set terminal pop

*perform some action using this information

However, the catch is that although set logscale x sets GPVAL_X_LOG by default to 10, unset logscale does not revert it back to zero, so if one used set logscale x;unset logscale, the code snippet above would not handle this correctly...
In my opinion, a better solution would be to introduce a custom variable in the main script as:
useLogScale = 1

if(useLogScale){
    set logscale x
}

set xr [10:100]

load 'my_function.gpl'

then the variable useLogScale is also directly available in my_function.gpl.


text:
Q: KhepinYamlFixturesBundle gives fatal error: call to undefined method Symfony\Bundle\DoctrineBundle\Registry::getManager() I've installed [KhepinYamlFixturesBundle][1] Symfony 2.0.16 to load fixtures but when I run
php app/console khepin:yamlfixtures:load

I get this error:

Fatal error: Call to undefined method Symfony\Bundle\DoctrineBundle\Registry::getManager() in D:\public_html\s2\trunk\src\Khepin\YamlFixturesBundle\Loader\YamlLoader.php on line 138

Is there a workaround for this?
EDIT:
I also tried with Symfony 2.1. After successfully installing Symfony 2.1 and doctrine-fixtures-bundle, I run:
php composer.phar update khepin/yaml-fixtures-bundle
It says:
Updating dependencies
Your requirements could not be resolved to an installable set of packages.
Problem 1
- Installation request for khepin/yaml-fixtures-bundle dev-master -> satisfiable by khepin/yaml-fixtures-bundle dev-master.

- Conclusion: don't install doctrine/doctrine-fixtures-bundle v2.1.0-ALPHA

- Conclusion: remove doctrine/doctrine-fixtures-bundle dev-master

- khepin/yaml-fixtures-bundle dev-master requires doctrine/doctrine-fixtures-bundle 2.* -> satisfiable by
  doctrine/doctrine-fixtures-bundle v2.0.0, doctrine/doctrine-fixtures-bundle v2.0.1,
  doctrine/doctrine-fixtures-bundle v2.1.0-ALPHA, doctrine/doctrine-fixtures-bundle 2.0.x-dev.

- Can only install one of: doctrine/doctrine-fixtures-bundle dev-master, doctrine/doctrine-fixtures-bundle v2.0.0.

- Can only install one of: doctrine/doctrine-fixtures-bundle dev-master, doctrine/doctrine-fixtures-bundle v2.0.1.

- Can only install one of: doctrine/doctrine-fixtures-bundle dev-master, doctrine/doctrine-fixtures-bundle 2.0.x-dev.

- Installation request for doctrine/doctrine-fixtures-bundle dev-master -> satisfiable by doctrine/doctrine-fixtures-bundle dev-master.

`

A: For 2.1, the bundle requires the fixtures bundle with version "2.". Since composer switched the "minimum-stability" to "stable" recently, 2. and dev-master are no longer equivalent.
If you really need "dev-master", you can use:
require: {
    "khepin/yaml-fixtures-bundle": "dev-master as 2.1.0"
    ...
}

for example.
UPDATE:
I pushed the code and this should be fixed with older versions of Doctrine now.

A: It's a known bug: https://github.com/khepin/KhepinYamlFixturesBundle/issues/14
You should try with Symfony 2.1 if you can.

A: I was using "dev-master" for doctrine-fixtures-bundle with Symfony 2.1:
     `"doctrine/doctrine-fixtures-bundle": "dev-master"`

KhepinYamlFixturesBundle does not support it.
Once I changed it to "doctrine/doctrine-fixtures-bundle": "v2.1.0-ALPHA" in my composer.json file, it installed fine


text:
Q: Storing boolean datas and textview datas in android I want to store a boolean variable and textview text on the device the app is running, so that even after clearing in recent apps i can use the recent booleab states to make changes remain the same. Or is there any way to get the last state even after clearing the app from the recent apps or onDestroy

A: You should check out Shared Preferences in Android.
Write to Shared Preferences:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();

Read from Shared Preferences:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);

A: @apelsoczi's answer is essentially correct, but here is a more detailed example which also includes boolean values, and String values, as asked in your question.
First get a reference to your apps Shared Preferences like this:
SharedPreferences prefs = getActivity().getPreferences(Context.MODE_PRIVATE);
Then save your string and your boolean like this:
SharedPreferences.Editor editor = prefs.edit();
    editor.putBoolean(YOUR BOOLEAN KEY, YOUR BOOLEAN);
    editor.putString(YOUR STRING KEY, YOUR TEXT VIEW STRING);
    editor.commit(); // if commit is not called then data not saved!

To retrieve the values do this:
boolean b = prefs.getBoolean(YOUR BOOLEAN KEY, OPTIONAL DEFAULT VALUE IF ITS NOT FOUND);
String s = prefs.getString(YOUR STRING KEY, OPTIONAL DEFAULT VALUE IF ITS NOT FOUND);

Shared Preferences is a way to store simple key value pairs of data - very useful for settings. For example say you have a value false for your boolean, and you want to save it, so what you do is you pass in a name for it (passing a name is important because you need that name to retrieve the value) and the actual value to save. When you want to retrieve it, you again pass in the name you had assigned it when saving it.


text:
Q: Unable to find any jvms matching version 1.7 while starting neo4j I am using Mac OS X Yosemite and I had Java8 JRE installed

but, when I start neo4j, it is unable to find any JVM's matching version 1.7

A: You've installed java 8 while neo4j is searching for java 7. So install java 7 and set it as your default jvm/jre and it should execute correctly.

A: Neo4J startup script looks for JAVA_HOME and if it is not set defaults to setting it to Java v1.7. So, set your JAVA_HOME in your .bash_profile file.
export JAVA_HOME=$(/usr/libexec/java_home)

Then, either restart your Terminal or do
$ source .bash_profile

Now, if you restart Neo4J you shouldn't see the error message.


text:
Q: Проблема с разбитием строки Вроде бы изначально казалось что простое задание, но почему-то не получается добиться оптимального результата.
"Программа ждет ввода строки неограниченной длины.
Затем программа ждет ввода символа.
После чего она должна разбить первую строку в другие подстроки, используя второй параметр в виде разделителя и вывести на экран."
Могу скинуть свой кривой код:
std::string str;
std::cout << "Введите строку: ";
std::getline(std::cin, str);

char symb;
std::cout << "Введите разделяющий символ: ";
std::cin >> symb;

int check = 0;
std::vector<std::string> arr;

for (size_t i = 0; i < str.size(); i++)
{
    std::string temp = "";

    if (str[i] == symb && check == 0) { temp = str.substr(0, i); arr.emplace_back(temp); check=i; }

    if (str[i] == symb && check != i)
    {
        int index = i;
        for (size_t j = i+1; j < str.size(); j++)
        {
            if (str[j] == symb)
            {
                temp = str.substr(index + 1, j);
                arr.emplace_back(temp);
                break;
            }
            index++;
        }
    }
}

for (auto &el : arr)
{
    std::cout << el << std::endl;
}

Пожалуйста, помогите разобраться.

A: Получилось так:
int main(int argc, char** argv)
{
    std::string str = "Test string";
//  std::cout << "Введите строку: ";
//  std::getline(std::cin, str);

    char symb = 's';
//  std::cout << "Введите разделяющий символ: ";
//  std::cin >> symb;

    std::vector<std::string> arr;
    size_t last_index = 0;

    // Разбиваем по символу разделителю
    for (size_t i = 0; i < str.size(); i++)
    {
        if (str[i] == symb)
        {
            // В массив складываем подстроки и запоминаем индекс символа-разделителя, если найден
            arr.emplace_back(str.substr(last_index, i - last_index));
            last_index = i /*+ 1*/; // +1, если символ-разделитель не должен попадать в подстроки
        }
    }

    // Всё что осталось в строке - последний элемент, тоже закидываем в вектор
    arr.emplace_back(str.substr(last_index, str.size() - last_index));

    for (auto &el : arr)
    {
        std::cout << "[" << el << "]" << std::endl;
    }

    system("pause");
}

Вывод:
[Te]
[st ]
[string]

Или так:
[Te]
[t ]
[tring]


text:
Q: Error db.sqlite3 locked when deploying Django using option Continuous deployment in Azure App Service When i'm deploying a Django project (tried two of them) in Azure App Services (Linux), i always get the error SQLite3 database locked: OperationalError: database is locked,when trying to log in. Has someone  an idea or workaround to resolve the problem without changing to another database? I changed the default timeout as mentioned by the official django documentation: https://docs.djangoproject.com/en/2.2/ref/databases/#sqlite-notes, but the problem remain. I want to keep using sqlite database!
Thanks for your help.

A: App Service locks the db.sqlite3 file, preventing both reads and writes. This behavior doesn't affect an external database:
https://learn.microsoft.com/en-us/azure/devops/pipelines/languages/python-webapp?view=azure-devops#considerations-for-django
https://vscode-eastus.azurewebsites.net/docs/python/tutorial-deploy-app-service-on-linux
Test App: https://github.com/itsimplified/slick-crud-app
However, you should be able to use the following way to make the WebApp work by moving the SQLite to Azure Storage.
Please follow the below steps in order to achieve this:
Mount your Azure Storage to the WebApp:
Example:

Make necessary changes to the path of the DB file in the application:
Example:

You should also be able to see the DB file in the Storage:


text:
Q: Custom control events I've written a custom control which has a combo on there.
The combo has a SelectedIndexChanged event which has also been made visible to the application using the control.
So within the application I subscribe to the SelectedIndexChanged event too.
Within the application I change the combo value and the 2 events fire (I've tested this using message boxes).
All is great at this point, here is my problem: I have another control on my custom control which fires the SelectedIndexChanged event of the combo but the one within the application doesn't fire. How can I make this happen?
I hope that all makes sense?!
I'm using C# 4.0
Thanks in advance.

A: Have you tried to make a public function in your control that you can call from your application that fires the selectedIndexChanged event


text:
Q: How to make the connections to the 1 channel optocoupler relay module? I want to light a bulb connected to the socket by using an 1 Channel Optocoupler Relay Module which accepts an input of 5V.
From my understanding, when the modul receives DC current (5V), it's going to turn on the other circuit and turn on the bulb.
I'm not sure how to connect the module in this context.
It looks like this:
    +----------------------+
    | 10A 250VAC 10 125VAC |
DC+ – 10A  30VDC 10  28VAC – NC
DC- –                      – COM
IN  –                      – NO
    | SRD-05VDC-SL-C       |
    +----------------------+

It didn't came with any documentation, so I'm not sure what these notations mean.
I assumed I have to connect the positive wire from the 5V circuit to DC+ and the negative/ground to the DC-. I'm not sure if this is correct.
However, I don't understand how to connect the wires at the other end.
I have no ideas what IN, NC, COM and NO mean.

Is there any place where I can find the documentation for this kind of relay or are these universal notations? What do they mean?
How should I make the connections?
The module looks like this:

So, I connected the bulb wires to COM and NC and the bulb is turned on when I connect it to the socket. Then I tried connecting a battery to the DC+ and DC- and the power led of the relay component is turned on, but the bulb is not turned off.

A: The signals on the left are the input side and the signals on the right are the output side.
Ok so now it is clear that you have a module rather than just a relay. The module has additional circuitry on it for driving the relay. Based on this the input pins are as I put in my original answer:

*

*DC+ - Positive logic supply voltage

*DC- - Negative logic supply voltage (a.k.a ground)

*IN - Input control signal - the thing that tells the relay whether to be on or off.

On the output side a bog standard switch naming is used:

*

*NC  - Normally Closed (Connected to COM when relay coil off)

*NO  - Normally Open (Connected to COM when relay coil on)

*COM - Common pin of switch

Your relay operates as a DPST switch as shown in the diagram below.

You need to apply power to the DC+/DC- pins (such as a battery), and then use the IN pin to control whether the relay is on or off. Connecting the IN pin to DC+ will turn the relay on (connect NO and COM), and connecting the IN pin to DC- will turn the relay off (connect NC to COM).
You may need to add a resistor in series with the IN pin - i.e. don't connect it directly to DC+ or DC-. A 1k resistor will suffice. It is not clear from the description whether or not this is actually necessary as the information on the listing is a very bad translation.

A: Did you bother to scroll down on that page where you bought it...

That the last two lines mean is gibberish to me. Try it and see. I'd guess it means you can drive it either with a high or a low signal depending on that jumper.
In a nutshell, DC+ and DC- is the power the coil will need, IN drives an opto-coupler to deliver that DC to the coil somehow.
What High is, it does not say though, but since it's feeding an opto-coupler, do not exceed the 5mA.

A: Your relay module has a relay plus some interfacing electronics in it.
You have to supply the 5V from your batteries to the relay through the DC+ DC- pins. The IN signal is the input control signal. You can connect this pin to an output pin from a microcontroller like an Arduino, or to a mechanical switch connected to the 5V supply.
As a plus, you also have a jumper to select whether your control signal is active LOW (i.e., a logic ZERO makes the relay switch) or active HIGH (i.e., a logic ONE makes the relay switch).
The relay internally connects the COM (common) pin to the NC (normally closed) pin when the IN signal is driven LOW (or when it's driven HIGH, if you set your jumper to "active LOW").
Then, when you drive the IN signal HIGH (or when it's driven LOW, if you set your jumper to "active LOW") the relay switches and internally connects the COM (common) pin to the NO (normally open) pin.

A: NC is Normally Closed, and NO is Normally Open. COM is COMmon.
What this means is that, when no signal is applied to the coil, there is a short circuit between NC and COM, and an open circuit between NO and COM. When you energize the relay coil, there will be an open circuit between NC and COM, and a short circuit between NO and COM.
I'm not sure what IN is. You're right on the DC+/- terminals, I believe.


text:
Q: How to generate set array of object in post request in Swagger with Laravel? I am trying to generate array of object in Laravel-5.5 Swagger using body request in Laravel Model.
How should i achieve desired output ??
[
  {
    "user_name": "string",
    "education": [
      {
        "degree": [
          {
            "year": "string",
            "name": "string"
          },
          {
            "year": "string",
            "name": "string"
          }
        ],
        "hobby": [
          {
            "type": "string",
            "description": "string"
          },
          {
            "type": "string",
            "description": "string"
          }
        ]
      }
    ]
  }
]

can anyone please help me ?
Thanks.

A: In "User" model you just need to put this below code.
/**
 *  @SWG\Definition(
 *      definition="User",
 *      type="array",
 *      @SWG\Items(
 *          type="object",
 *          @SWG\Property(type="string", property="user_name", description="User name"),
 *          @SWG\Property(type="array", property="education", description="Education",
 *              @SWG\Items(
 *                  @SWG\Property(property="degree", type="object",
 *                      type="array",
 *                      @SWG\Items(
 *                          @SWG\Property(property="year", type="string"),
 *                          @SWG\Property(property="name", type="string"),
 *                      ),
 *                  ),
 *                  @SWG\Property(property="hobby", type="object",
 *                      type="array",
 *                      @SWG\Items(
 *                          @SWG\Property(property="type", type="string"),
 *                          @SWG\Property(property="description", type="string"),
 *                      ),
 *                  ),
 *              ),
 *          ),
 *      ),
 * ),
 */
class User extends Model
{
   //
}

In above code while you send request that time you just need to edit.
  After copy paste after immidiate degree object with ",". Then you can
  pass multiple object in array.
Thanks,


text:
Q: FlipTileData reflection stopped working with Win8 I want to create one universal method to create tile in WP7.8 and WP8.
When I'm using reflection (like Microsoft suggest):
// Get the new FlipTileData type.
Type flipTileDataType = Type.GetType("Microsoft.Phone.Shell.FlipTileData, Microsoft.Phone");
var UpdateTileData = flipTileDataType.GetConstructor(new Type[] { }).Invoke(null);

It's working on WP7.8.
But after upgrade my project to Win8 flipTileDataType is null.
But then constructor
 Microsoft.Phone.Shell.FlipTileData UpdateTileData = new Microsoft.Phone.Shell.FlipTileData();

is working.
So, how can I build one universal version for both systems?

A: Do not upgrade project to Windows Phone 8. Develop it as Windows Phone 7.8 app. The tile will work correctly on WP8 devices. I found the  same problem before and it looks like there is no solution.


text:
Q: How do I centralize code shared by multiple Web API controllers? I have close to 10 controllers that currently share the same code. The code is pretty simple, it just checks if a set of data is null and checks if the current user has permission to access the data.
If there is an issue, I throw an HttpResponseException.
The code works when it is sitting in each controller. I have also managed to centralize the code but I think the way I have done it is wrong. I've created a new class which inherits ApiController and then I have the controllers inheriting my new class. This is the only way I could get the HttpResponseExceptions working. Code is as follows:
//New centralized class:

public class AuthorizationClass : ApiController
{
    private DataModel db = new DataModel();

    public async Task checkUserisValid(int user_id)
    {
        user_list user_list = await db.user_list.FindAsync(user_id);

        if (user_list == null)
        {
            throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest,"This user does not exist"));
        }

        int businessID = user_list.business_id;

        var result = checkAccess(User.Identity.Name, businessID);

        if (result.Count <= 0)
        {
            throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "You do not have access to modify this business"));
        }
    }

    public static List<user_details> checkAccess(string userName, int id)
    {
        //code which checks if the user is in the right tables
            return checkAccess.ToList();
    }
}

Then in the controller class, I have:
    public class MyController : AuthorizationClass
{
        public async Task<IHttpActionResult> Postnew_table(int id, new_table new_table)
        {
            await checkUserisValid(id);

        //rest of controller
            }
}

I tried to do it in different ways but this is the only way I could get it working with HttpResponseException. Is there a better way to do this without inheriting classes or is this the only way to do what I am after?
Thanks.

A: You could just move these 2 methods to some static helper class in a common assembly, you mention that Request is an instance variable on the controller, just pass it to the method.
public static class SomeHelper
{
    public static async Task checkUserisValid(int user_id, DataModel db, Request request, User user)
    {
       user_list user_list = await db.user_list.FindAsync(user_id);

       if (user_list == null)
       {
          throw new   HttpResponseException(request.CreateErrorResponse(HttpStatusCode.BadRequest,"This user does not exist"));
        }

        int businessID = user_list.business_id;

        var result = checkAccess(user.Identity.Name, businessID);

        if (result.Count <= 0)
        {
          throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "You do not have access to modify this business"));
        }
   }

  public static List<user_details> checkAccess(string userName, int id)
  {
      //code which checks if the user is in the right tables
          return checkAccess.ToList();
   }

}


text:
Q: Differential Equations Recipes I have many questions I'd like to ask today. I'm currently studying for my A-levels which is a qualification mainly based in England. I'm taking A-level Further Maths, which involves the study of First and Second Order Differential Equations. It seems we are just being taught to apply recipes to these types of equations and are given no intuition as to why these things even work? This isn't just for teaching in England, I've watched many American lectures and lecture notes and the same thing is done.
Let's take a look at Non-Linear Separable First Order Differential Equations.
We have defined these equations to take the form $$ N(y)\frac{dy}{dx} = M(x)$$
We are taught to solve these equations by multiplying $\ dx $ to both sides and then integrate by their respective variables.  Like so:
$$ \int N(y)\ dy = \int M(x) \ dx $$
I have just accepted this for some time, but I'd like to get to the bottom of wtf is going on. We are taught from Year 12/Calculus 1 days that $\frac{dy}{dx} $ is not a ratio but can be treated like one in many cases. Ok... then could you explain really what we just did when solving the above differential equation? I can accept the fact that we can treat $\frac{dy}{dx}$ as a ratio but it's not really a ratio. So, can we be told what we are really doing? Is it some kind of hidden secret? I just want to know why we multiplied both sides by $\ dx$, what are we actually doing?
I can assume that the reason we are not told is because it involves higher level math, that someone taking Calculus would not understand. But will actual reasoning behind why these recipes work be exposed to us during University math courses?


text:
Q: How to make "assign places to people" editor as usable as possible So we have places and we have people. the added complexity is additional metadata attached to each link between each pair. Like date range when a person spent at a particular place.
I know. Lots of data and many possibilities.
One way of doing this is by having a list of people and when you click on one, a modal dialog opens, where a list of places is displayed. When you select a place, you also have to enter a date range.
From a usability perspective and quick relation editor this is almost definitely not the optimal solution. User focus changes several times and that slows things down + makes users tired since they have to be very concentrated and focused = higher rate of human error.
I would like to avoid dialogs. Do you maybe know of a website where a similar thing is done = two entities need to be related with additional metadata.
The main requirements of this page are:

*

*simplicity

*avoid modal dialogs if possible

What I'm trying to do: many-to-many editor with additional metadata data on each pair.
Questions

*

*What would you suggest? Provide any ideas (even dumn ones).

*Do you know of a public site (so it can be checked) that has this kind of scenario implemented?

A: doesn't this come down to two operations select and connect. you'd select some group of people or places via a number of different paths string search, time, space, or such and then you'd connect them by creating some record
note that useful relations aren't just between one person and another or one place and a person or just one place and another although when storing these they can all be reduced to a->b tuples but this can be ignored if the relations you have only have one person place and time
this sort of reminds me of Entity Workspace but in that case they were dealing with data collection in the domain of crime investigation so they had names addresses phone numbers dates and such as base types which in their setup were drag and drop on to cards
so if you took that you could have a center file and a list of people after some filtering to add that one to this set you'd drag it from the list and like wise from the places you'd have another list to drag from
commonly referenced ones might be shown in another place and this would work a bit like putting the toppings on a pizza and when your done you put it in the oven or commit it if you want to later undo this it would keep the set together so you can remove it later if you didn't want it or you can add something
and this wouldn't have any of the dialogs you suggest and as such it could be called mode-less


text:
Q: Java server that can get POST requests from JS client Basically I'm just trying to create a simple HTML page that can send a string of text to the server. The server runs on some port on the localhost and receives that string.
I've found code for a simple server that can handle POST requests:
public static void main(String args[]) throws Exception
{
    ServerSocket s = new ServerSocket(8080);

    while (true) {
        Socket remote = s.accept();
        System.out.println("Connected");
        BufferedReader in = new BufferedReader(new InputStreamReader(remote.getInputStream()));
        PrintWriter out = new PrintWriter(remote.getOutputStream());

        String str = ".";

        while (!str.equals("")) {
            str = in.readLine();
            if (str.contains("GET")) {
                break;
            }
        }

        System.out.println(str);

        out.println("HTTP/1.0 200 OK");
        out.println("Content-Type: text/html");
        out.println("Access-Control-Allow-Origin: null");
        out.println("");
        out.flush();
    }
}

But I don't know what should I do further. I've learned that I need to use a XMLHttpRequest that can send asynchronous requests:
function sendData(data) {
    var XHR = new XMLHttpRequest();
    var urlEncodedData = "message";
    var urlEncodedDataPairs = [];
    var name;
    for (name in data) {
        urlEncodedDataPairs.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]));
    }
    urlEncodedData = urlEncodedDataPairs.join('&').replace(/%20/g, '+');
    XHR.open('POST', 'http://localhost:8080', true);
    XHR.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    XHR.send(urlEncodedData);
}

So, I'm starting my server, opening the .html file with JS script, and the script connects to the server. How then can I handle the message that the script sends? How can I decode and print it? And, eventually, do I write the message sender in a right way?

A: If you're simply trying to hit the endpoint you created for testing & continuing to build, try using Postman. You should be able to write a custom body for your POST request.


text:
Q: Why would we use bitwise operators between 2 numbers? I don't understand, given the information below, why you would ever want to evaluate, for example, 2 hex integers with the & operator. I understand the inversion pattern explained below, and I can calculate it myself, but it's hard to deduce why (from posts I see on the internet). What is the real world scenario that might give me insight here?
  0xff00 & 0xf0f0 is 0xf000
  0xff00 ^ 0xf0f0 is 0x0ff0
  0xff00 | 0xf0f0 is 0xfff0
For &, the result value is the bitwise AND of the operand values.
For ^, the result value is the bitwise exclusive OR of the operand values.
For |, the result value is the bitwise inclusive OR of the operand values.

In my own head, I currently think of it like this:
if ( 65280 & 61680 )  // evaluates to 61440, not boolean?

A: I think that if you need to implement a small array of boolean, it could be a good idea to represent it as an int or long, with each bit representing one array element:

*

*if there is a huge number of those arrays, so that memory usage is a concern; or

*if you are doing a huge number of calculations.

In that case, you'd use the shift operators and &, |, &=, |=, or ^= to test, clear, set, or flip elements of the array.  (Note also that this can be used on multiple elements of array in parallel.)
It's rare that this case comes up.  For readability, it's much better to use a regular array or ArrayList.  However, I've had both use cases come up at least once.  One was writing a Sudoku solver using a brute-force backtracking algorithm; I don't remember the details, but I think I used 9 bits of an int to represent whether the cells in a row, column, or square were occupied.  If I recall correctly, some of my code tested multiple cells simultaneously, which I could do with one & operator.  Since solving by backtracking can involve a huge number of combinations, I believe that using this mechanism made a noticeable difference in the running time.  The other case involved a table of items that kept information on whether items had certain properties.  The number of properties was relatively small (between 10 and 20), but the number of items could run into the tens of millions.  A Set would have been the natural choice for representing the set of properties, but with the huge number of HashSets I'd need to keep, memory was a concern.
I wouldn't recommend this unless there is a big difference in memory or time.  It smacks of "trickiness", and I prefer straightforward code that expresses what you're trying to accomplish.

A: These kinds of operators are used for lots of things, but these days in higher level languages they are most commonly used with flags. It's a holdover from lower level languages like C, in which memory allocation and deallocation is not always trivial, and which was developed at a time where hardware resources were scarce.
Let's say there are 3 possible flags for some operation, and they can be provided in any given combination.  A quick, easy, and efficient way to supply a flag is to assign each flag to a bit in an integer.
public static final int FLAG_1 = 1;       // 00000001
public static final int FLAG_2 = 1 << 1;  // 00000010
public static final int FLAG_3 = 1 << 2;  // 00000100

Then to send multiple flags, I can use the bitwise or "|" operator.
someFunc(FLAG_1 | FLAG_3).

To read the flags that are passed, I can use the bitwise & operator.
public void someFunc(int flags) {
    if ((flags & FLAG_1) == FLAG_1 /*Or (flags & FLAG_1) != 0 */) {
      // Passed in flag 1.
    }
}

There are other ways that this can be done, but this is very efficient, easy to read, and results in zero object allocations on the heap. If you think of other ways you'd accomplish this in Java, let's say with an array or collection of enums/ints, or with each flag being a separate method parameter, it's clear why this pattern is used instead.

A: For a very basic example in an if-statement :
if ( (65280 & 1) == 0 ){
  // 65280 is even!
}

*

*x & 1 is 0 if x is even

*x & 1 is 1 if x is odd

A: I'm looking at some source code written in Java (it was originally ported from C):
int dest = y * width + (x & 0xfffc);

Took me a while to realize what it means:
0xfffc is 65532 or 1111111111111100
dest is the offset in an array of size 65536.
So what does the expression above actually say?
I think it says:
int dest = y * width + (x<=65532?x:65532);


text:
Q: Get data from array base on a value in this array I have this type of array:
$fruits = array(
    array(
        'fruit'       => "Banana",
        'color'       => "Yellow",
        'latinName'   => "Banana",
        'origin'      => "Africa"
    ),
);

How can I get the color if I have the fruit value for example ?
I'm using this structure as I would like to use this array, by giving the fruit name, the color or the latinName to get other informations.
Thanks.

A: Not sure if that's the best way, but it works for sure (maybe there's some function too, but idk sorry):
$fruits = array(
    array(
        "fruit"         => "Banana",
        "color"         => "Yellow",
        "latinName"     => "Banana",
        "origin"        => "Africa"
    ),
    array(
        "fruit"         => "Apple",
        "color"         => "Red",
        "latinName"     => "Dunno1",
        "origin"        => "Dunno2"
    ),
    array(
        "fruit"         => "Orange",
        "color"         => "Orange",
        "latinName"     => "Dunno3",
        "origin"        => "Dunno4"
    ),
);

for($i=0; $i<count($fruits); $i++){
    if($fruits[$i]["fruit"]=="Banana"){
        echo $fruits[$i]["color"];
    }
}

A: Take a look at array_flip in the PHP docs. While I would agree that your data structure makes this rather awkward, this function might alleviate some of the issues.

A: Seems a pretty trivial foreach statement unless I missed something rather glaringly obvious:
<?php

    $input='Banana';
    $fruits = array(
        array(
        'fruit'         => "Banana",
        'color'         => "Yellow",
        'latinName'     => "Banana",
        'origin'        => "Africa"
        ),
    );

    foreach($fruits as $val)
    {
        if($val['fruit']==$input)
        {
            echo $val['color'];
        }
    }

?>

Edit: On the structure of your array, there is nothing wrong with this simple 2d array. If anything, I would consider using a key naming structure for your outer array which might make it easier to use for you:
$fruits = array(
    "Banana" =>
            array(
            'color'         => "Yellow",
            'latinName'     => "Banana",
            'origin'        => "Africa"
    )
);

This way you can then use the common name to access the right inner array - and you get to use all the inbuilt PHP functions for finding/accessing keys as needed.


text:
Q: Comprehensive list of command line flags/options for Burn/bootstrapper in WiX I can't seem to find a comprehensive list of commands, flags, and things I can do from the command line.

A: WiX installers will take the standard Windows Installer commandline switches, as documented in Command-Line Options.
Any additional parameters that are added to the commandline will be passed on to your installer if you're using a custom Burn installer.
This was confirmed by the primary WiX maintainer on the WiX mailing list: http://windows-installer-xml-wix-toolset.687559.n2.nabble.com/Running-Burn-driven-installer-in-quiet-mode-command-line-parameters-tp5913001p5913628.html

*

*Yes, absolutely. Burn supports parsing the "standard package switches"  and will pass extra switches on the Bootstrapper
Application so it can apply  additional behavior.

*The complete list is dependent on the Bootstrapper Application you pick.  The wixstdba supports only the "standard package switches":

 -q, -quiet, -s, -silent = silent install
 -passive = progress bar only install
 -norestart = suppress any restarts
 -forcerestart = restart no matter what (I don't know why this is still  around)
 -promptrestart = prompt if a restart is required (default)
 -layout = create a local image of the bootstrapper (i.e. download files so  they can be burned to DVD)
 -l, -log = log to a specific file (default is controled by bundle developer)
 -uninstall = uninstall
 -repair = repair (or install if not installed)
 -package,-update = install (default if no -uninstall or -repair)

*Yes, as noted above extra command-line parameters are passed to the >  BootstrapperApplication and it can set Variables to flow into Chained  Packages (ExePackage XxxCommand attributes or
MsiPackage/MsiProperty  element).

You may want to also be familiar with the standard installer command line parameters: Microsoft Standard Installer Command-Line Options


text:
Q: unable to hide logout button after signout using ng-show in angularjs I have the logout button like this:

            Change Password

            Change Profile Picture

            Logout

And in the controller:
$scope.logIn = function (user) {
    $scope.myPromise = AuthService.login({
        'uid': user.email,
        'password': user.password,
    }).then(function (response) {
        $localStorage.userName = response.userName;
        $scope.userName = $localStorage.userName;
    }, function (error) {
        $scope.authError = true;
    });
};

Sign out controller:
$scope.userName = "";
delete $localStorage.userName;
$rootScope.userName = "";

Doesn't matter I use ng-if or ng-show it is still showing the logout button and the dropdown.

A: Try with the below code.
Logout

A: This should do

    Logout


text:
Q: Sorting ArrayList of model that is connected with a hashmap I have an arraylist of model and a hashmap. The model class contains variable such as id(int), name, address, etc. The hashmap, contains id(int) and distance (double). I have tried using Collection to sort a list of model before, but the problem here is, I have to sort the hashmap by it's distance value, and then adjust the arraylist according to how the hashmap sorted. The hashmap's id and the model class' id here act as a "foreign key". Anyone have any idea how to do this?
Here is the hashmap:
HashMap<Integer, String> listDistance = new HashMap<Integer, String>();
listDistance.put(1, 3.22);
listDistance.put(2, 2.57);
listDistance.put(3, 6.32);
listDistance.put(4, 8.82);
listDistance.put(5, 1.32);

Here is the arraylist:
ArrayList<Listing> listings = new ArrayList<Listing>();
listing.add(1, "asd", 123);
listing.add(2, "ghf", 3434);
listing.add(3, "ert", 876);
listing.add(4, "tyi", 1267);
listing.add(5, "ohg", 1345);

Here is the model class:
public class Listing {

int id, count;
String name;

public Listing(int id, String name, int count) {
    this.id = id;
    this.count = count;
    this.name = name;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public int getCount() {
    return count;
}

public void setCount(int count) {
    this.count = count;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}
}

The result of what I want should sort the listings to become like this:

*

*listing.add(5, "ohg", 1345);

*listing.add(2, "ghf", 3434);

*listing.add(1, "asd", 123);

*listing.add(3, "ert", 876);

*listing.add(4, "tyi", 1267);

I actually haven't tried anything to make this works except thinking the logical flow because I am quite out of idea as to how to do this.

A: You can sort the list like this:
Collections.sort(listing, (a,b) -> Double.compare(listDistance.get(a.getId()),
                                                  listDistance.get(b.getId())));

See running code at IDEONE.


text:
Q: Change the page number of slides in notes when using | handout: command I have some slides where I will print out as different pages for the handouts. I am using the command \onslide<1 | handout:1> {} and so on. Is it possible to show on the handout as 5(a) , 5(b) and 5(c) where a, b, c represents the handout page for that particular slide.
I will put the same minimal code from my previous question: How to handle only overlays while printing a latex beamer notes
%\documentclass[mathserif]{beamer}

\documentclass[arial,handout]{beamer}

\usepackage{pgf,pgfpages}
\usepackage{graphicx}
%\usepackage{units}
%\usepackage[utf8]{inputenc}
\usepackage{mathtools}
%\usepackage{amsmath}
\usepackage{animate}

\usepackage{booktabs}
\usepackage{tikz}
\usetikzlibrary{arrows,shapes}

 \tikzset{
    invisible/.style={opacity=0},
    visible on/.style={alt=#1{}{invisible}},
    alt/.code args={<#1>#2#3}{%
      \alt<#1>{\pgfkeysalso{#2}}{\pgfkeysalso{#3}} % \pgfkeysalso doesn't change the path
    },
  }

\mode<presentation>
{
  \usetheme{ift}
  \setbeamertemplate{items}[square]
}

\usefonttheme[onlymath]{serif}
\setbeamerfont{frametitle}{size=\LARGE,series=\bfseries}

\definecolor{uibred}{RGB}{170, 0, 0}
\definecolor{uibblue}{RGB}{0, 84, 115}
\definecolor{uibgreen}{RGB}{119, 175, 0}
%\definecolor{uibgreen}{RGB}{50, 105, 0}
\definecolor{uiborange}{RGB}{217, 89, 0}

%% Create a new command called redub for underbraces
\newcommand\redub[2]{%
    \colorlet{currentcolor}{.}%
    \color{red}%
    \underbrace{\color{currentcolor}#1}_{\color{red}#2}%
    \color{currentcolor}%
}

%Beamer block template
\setbeamertemplate{blocks}[rounded][shadow=true]

\setbeamercolor{block title}{bg=uibblue,fg=white}
\setbeamercolor{item projected}{fg=white,bg=green}

\beamertemplatenavigationsymbolsempty

%\include{macros}

%\includeonlyframes{current}

\defbeamertemplate{enumerate item}{mycircle}
{
  %\usebeamerfont*{item projected}%
  %\usebeamercolor[bg]{item projected}%
  \begin{pgfpicture}{0ex}{0ex}{1.5ex}{0ex}
    %\pgfcircle[fill]{\pgfpoint{0pt}{.75ex}}{1.25ex}
    \pgfbox[center,base]{\color{uibblue}\insertenumlabel.}
  \end{pgfpicture}%
}
[action]
{\setbeamerfont{item projected}{size=\scriptsize}}
\setbeamertemplate{enumerate item}[mycircle]

\begin{document}

%\setbeamertemplate{background}
% {\includegraphics[width=\paperwidth,height=\paperheight]{slide_bg1}}
%\setbeamertemplate{footline}[ifttheme]

\mode<presentation>

\begin{frame}
    \frametitle{Eulerian Salt Flux Decomposition}

    \only<1-2 | handout:1>{\begin{itemize}
        \item Subtidal Volume discharge rate $Q_f$: through a cross=section A  \\
        $Q_f = \langle\int u.dA \rangle$
        \item Salt transport rate $F_s$ through a cross-section A \\
        $F_s = \langle \int uS.dA \rangle$
    \end{itemize}}
        \onslide<2->Sub-tidal salt flux decomposed into three parts

    \onslide<2->\begin{align*}
        F  & = \langle \int(u_0+u_E+U_T)(s_0+s_E+s_T)dA \rangle \\
            & \approx \langle \int(u_0s_0+u_Es_E+u_Ts_T)dA \rangle \\
            & = \redub{Q_fs_0}{\mathclap{\text{     River flow     }}} +
             \redub{F_E}{\substack{\text{Exchange}\\\text{shear dispersion}}} +
             \redub{F_T}{\substack{\text{tidal osciallatory}\\\text{salt transport}}}
    \end{align*}

    \onslide<3- | handout:2>\begin{itemize}
        \item $u_0$ and $s_0$ tidally and cross-sectionally averaged
        \item $u_E$ and $s_E$ tidally averaged and cross-sectionally varying
        \item $u_T$ and $s_T$ tidally and cross-sectionally varying
    \end{itemize}

\end{frame}

\begin{frame}
\frametitle{Age of Water under dye from all Rivers}

    \only<1-3>{\begin{tikzpicture}
    \centering
        \node [](0,0)(start){ hello2};
%       \draw [step=0.5cm,thin,dotted] (-5,-4) grid(5,4);
%       \node [circle]at (-4.5,0){0};
%       \node [circle,radius=0.9cm,fill=red!30,] at (-4.5,0)(a){};
        \draw [red,fill=red!30](-4.3,-0.2)circle(0.1cm);
        \draw [red,fill=red!30](-3.3,0)circle(0.1cm);
        \draw [red,fill=red!30](-2.5,-0.7)circle(0.1cm);
        \draw [red,fill=red!30](-4.,-0.8)circle(0.1cm);
        \draw [red,fill=red!30](-4.,-1.2)circle(0.1cm);
        \draw [red,fill=red!30](4.3,1.6)circle(0.1cm);
        \draw [red,fill=red!30](3.3,2.7)circle(0.1cm);
        \draw [red,fill=red!30](1.6,3.5)circle(0.1cm);
        \draw [red,fill=red!30](1.3,3.5)circle(0.1cm);
        \node [rectangle,text width=4cm,red] at (5.5,3) (return) {$Q_2 = 169 A^{0.616}$     \linebreak Mason et. al. 1998};
        \node [rectangle,text width=4cm,red,visible on =<2->] at (5,0) (return) {Smaller near the source     \linebreak Increases away from the source};
        \draw [red,visible on =<3->](-3.3,-1.5) circle(0.7cm);%wolf bay small age
    \end{tikzpicture}}

        \only<4-5>{\begin{tikzpicture}
        \node [](0,0)(start){hello1};
%   \draw [step=0.5,dotted](-5,-4) grid (5,4);
     \node [rectangle,text width=4cm,red] at (5,0) (return) {Scale different from    \linebreak 2 year inflows};
     \node [rectangle, text width =4cm, red,visible on =<5->] at (5,-2) {Maximum age of 120 days};
     \draw [red] (1.5,-1) ellipse(1cm and 0.6cm);
     \node [rectangle, text width=4cm, red] at (5,3) {Minimum 7 day flow over 10 yr. interval};
    \end{tikzpicture}}

        %
        \only<6-7>{\begin{tikzpicture}
        \node [](0,0)(start){hello};
        \node [rectangle, text width=4cm, red, visible on =<7->] at (5,3) {Mean inflows over 10 yr. interval};
        \end{tikzpicture}}
\end{frame}

\end{document}

Added the output

IFT THEME ADDED
The beamer ift theme can be found on the following location:
https://www.dropbox.com/sh/ewkklsys1zp9xhs/J4msUp2Wbe

A: As mentioned in an answer to a related question, the number of the current slide within a frame is stored in \beamer@slideinframe. Following Martin Scharrer's comment, we can create a LaTeX counter named slideinframe with
\makeatletter
\def\c@slideinframe{\beamer@slideinframe}
\makeatother

Then to change the pagination of a given frame, you can define a new different footline template, say frame renumbering, and apply that locally to the frame in question. Since I don't have the ift theme you used in your MWE, I'll illustrate with the Madrid theme in the following example.
Outstanding Issue
An outstanding problem that I can't seem to figure out: the frame numbering is correct in the body, but wrong in the footline...
\documentclass[handout]{beamer}
\usetheme{Madrid}

% Define counter "slideinframe"
\makeatletter
\def\c@slideinframe{\beamer@slideinframe}
\makeatother

% Define new template style "frame renumbering"
\defbeamertemplate*{footline}{frame renumbering}
{
  \leavevmode%
  \hbox{%
   \begin{beamercolorbox}[wd=.333333\paperwidth,ht=2.25ex,dp=1ex,center]{author in head/foot}%
     \usebeamerfont{author in head/foot}\insertshortauthor~~(\insertshortinstitute)
   \end{beamercolorbox}%
   \begin{beamercolorbox}[wd=.333333\paperwidth,ht=2.25ex,dp=1ex,center]{title in head/foot}%
     \usebeamerfont{title in head/foot}\insertshorttitle
   \end{beamercolorbox}%
  \begin{beamercolorbox}[wd=.333333\paperwidth,ht=2.25ex,dp=1ex,right]{date in head/foot}%
    \usebeamerfont{date in head/foot}\insertshortdate{}\hspace*{2em}
    \insertframenumber(\alph{slideinframe}) / \inserttotalframenumber\hspace*{2ex}
  \end{beamercolorbox}}%
  \vskip0pt%
}

% This is the usual footline template used in Madrid theme
\setbeamertemplate{footline}[infolines theme]

\begin{document}

{
% Enclose the frame to which you want to apply the template "frame renumbering" with {...}
\setbeamertemplate{footline}[frame renumbering]
\begin{frame}{Frame 1}
This is frame \insertframenumber, slide (\alph{slideinframe})
\begin{itemize}
  \item<1| handout:1> Handout 1
  \item<2| handout:2> Handout 2
  \item<3| handout:1-3> Handout 1-3
\end{itemize}
\end{frame}
}

\begin{frame}{Frame 2}
This is frame \insertframenumber, slide (\alph{slideinframe}), with usual pagination.
\end{frame}

\end{document}

Update
A work-around is to use Matthew Leingang's answer in the above mentioned question. It defines a new counter, and calculates the current slide in frame by using the current page minus the page where the current frame starts and plus one.
The problem with this approach is that the counter defined in this way does not show the correct value in the body text.
\documentclass[handout]{beamer}
\usetheme{Madrid}

% Define counter "slideinframe"
\newcounter{slideinframe}

% Define new template style "frame renumbering"
\defbeamertemplate*{footline}{frame renumbering}
{
  % Set counter to correct value
  \setcounter{slideinframe}{\insertpagenumber}%
  \addtocounter{slideinframe}{-\insertframestartpage}%
  \addtocounter{slideinframe}{1}%

  % Redefine footline format
  \leavevmode%
  \hbox{%
   \begin{beamercolorbox}[wd=.333333\paperwidth,ht=2.25ex,dp=1ex,center]{author in head/foot}%
     \usebeamerfont{author in head/foot}\insertshortauthor~~(\insertshortinstitute)
   \end{beamercolorbox}%
   \begin{beamercolorbox}[wd=.333333\paperwidth,ht=2.25ex,dp=1ex,center]{title in head/foot}%
     \usebeamerfont{title in head/foot}\insertshorttitle
   \end{beamercolorbox}%
  \begin{beamercolorbox}[wd=.333333\paperwidth,ht=2.25ex,dp=1ex,right]{date in head/foot}%
    \usebeamerfont{date in head/foot}\insertshortdate{}\hspace*{2em}
    \insertframenumber(\alph{slideinframe}) / \inserttotalframenumber\hspace*{2ex}
  \end{beamercolorbox}}%
  \vskip0pt%
}

% This is the usual footline template used in Madrid theme
\setbeamertemplate{footline}[infolines theme]

\begin{document}
  % same as above
\end{document}


text:
Q: How to group by dynamic key value of an object of arrays(Month and year) This question is an extention of this question here. Underscore js group by each month on each year in single level
The code which i am using is here.
        const months = [
            'January','February','March','April','May','June','July','August','September','October','November','December'
        ]
        const result = flashMessage.reduce((res:any, item:any) => {
            const date = new Date(item.created_at)
            const year = date.getFullYear();
            const month = months[date.getMonth()];
            const existingYear=res[`${month} ${year}`] ||[];
            const updated  = [...(existingYear[month] || []), item]
            const returnItem = {
                title:item.title,
                user_message:item.user_message,
                created_at:item.created_at
            };
            res[`${month} ${year}`] = [...existingYear,returnItem]
            return res
        }, {});

The above code is producing expected result but it is in out of order here is the result of the above code.
[![enter image description here][1]][1]
I want the result is in order. The order which i wanted is shown below.

March 2022

February 2022

January 2022

March 2021

February 2021

January 2021

So on how can  i do that?
[1]: https://i.stack.imgur.com/BS9ZS.png

A: This may be one possible solution to achieve the desired objective.
// 'sortedKeys' will hold only the keys of the 'res' object
// but these will be in a sorted-order (based on prop 'created_at')
const sortedKeys = [
    ...Object.keys(result)
  ].sort(
    (a, b) => (
      result[a][0]['created_at'] > result[b][0]['created_at']
      ? -1
      : 1
    )
);

// to render in the sorted order, use 'sortedKeys' like this
sortedKeys.forEach(k => {
  console.log('key: ', k, ' value: ', result[k])
});

Approach

*

*First obtain the keys from result object

*Next, spread them and then apply .sort()

*Sorted array is stored in sortedKeys array

*The .sort employs the result object's created_at prop corresponding to the value of each key.

*To validate the sort, iterate over the sortedKeys array using .forEach and display the key k and the corresponding value from result object.

Code Snippet
The below provides a working-example of the sortedKeys generated

const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const flashMessage = [
  {
    created_at: '2021-03-11T06:40:46.790Z',
    title: 'Announcement 02',
    user_message: 'see more test',
  }, {
    created_at: '2021-01-11T06:40:46.790Z',
    title: 'Announcement 25',
    user_message: 'see more test',
  }, {
    created_at: '2021-02-11T06:40:46.790Z',
    title: 'This is a push notification to all',
    user_message: 'A push notification to all'
  }, {
    created_at: '2022-01-11T06:40:46.790Z',
    title: 'title for jan 2021',
    user_message: 'message for jan 2021'
  }, {
    created_at: '2022-03-11T06:40:46.790Z',
    title: 'title for mar 2021',
    user_message: 'message for mar 2021'
  }, {
    created_at: '2022-02-11T06:40:46.790Z',
    title: 'title for feb 2021',
    user_message: 'message for feb 2021'
  }
];

const result = flashMessage.reduce((res, item) => {
  const date = new Date(item.created_at)
  const year = date.getFullYear();
  const month = months[date.getMonth()];
  const existingYear = res[`${month} ${year}`] || [];
  const updated = [...(existingYear[month] || []), item]
  const returnItem = {
    title: item.title,
    user_message: item.user_message,
    created_at: item.created_at
  };
  res[`${month} ${year}`] = [...existingYear, returnItem]
  return res
}, {});

const sortedKeys = [
  ...Object.keys(result)
].sort(
  (a, b) => (
    result[a][0]['created_at'] > result[b][0]['created_at']
    ? -1
    : 1
  )
);

console.log('keys of result object sorted: ', sortedKeys);

sortedKeys.forEach(k => {
  console.log('key: ', k, ' value: ', result[k])
});


text:
Q: How to send ARP replies using pcap_sendpacket I am trying to use pcap library for packet sniffing. Till now I have been able to capture IP and ARP packets from my local network traffic. Now, I want to send an ARP request to the default gateway server. I am not sure, but I think I will have to use pcap_sendpacket function. I am not getting how to build the arp request, because when I checked the arphdr structure defined in net/if_arp.h, it is something like this:
struct arphdr
  {
    unsigned short int ar_hrd;      /* Format of hardware address.  */
    unsigned short int ar_pro;      /* Format of protocol address.  */
    unsigned char ar_hln;       /* Length of hardware address.  */
    unsigned char ar_pln;       /* Length of protocol address.  */
    unsigned short int ar_op;       /* ARP opcode (command).  */
#if 0
    /* Ethernet looks like this : This bit is variable sized
       however...  */
    unsigned char __ar_sha[ETH_ALEN];   /* Sender hardware address.  */
    unsigned char __ar_sip[4];      /* Sender IP address.  */
    unsigned char __ar_tha[ETH_ALEN];   /* Target hardware address.  */
    unsigned char __ar_tip[4];      /* Target IP address.  */
#endif
  };

As it can be seen, the hardware address art is in #if 0..#endif block, which means, effectively commented out. I am not understanding why is it done in that way. In order to send an ARP request, I have to fill those fields. Can someone give any suggestion on how to send one ARP request using pcap_sendpacket and fill those fields in arphdr?


text:
Q: MySQL2 Library NodeJS - Update Fails without error & RowsAffected on async call The way to get AffectedRows when non-Async is shown here: https://github.com/mysqljs/mysql/issues/363
My Code below - none of the console.logs after the update display in the console, certain columns are not being updated in the database, and no error or try catch is encountered. If there's an error, why don't I see it, otherwise, why don't I see the AffectedRows?
This is being called from another async function.
async function UpdatePassword(connection, rowID) {
  ... some code omitted here...
  try
  {
    var [errQuery,results] = await
  connection.query(sqlUpdate);
    if (errQuery) throw errQuery;
    console.log("Back from update");
    console.log("AffectedRows=" + results.affectedRows);
  } catch (err)
  {
    console.log("*** Catch Error:")
    console.log(err.stack);
  }
}

I think I have improved the code, but same issue. Non error, no console.log statements after the connection.query show up.
console.log("SQL Update=" + sqlUpdate);
try
{
    var [rows, fields, errQuery] = await connection.query(sqlUpdate);
    if (errQuery) throw errQuery;
    console.log("Back from update");
    console.log("AffectedRows=" + rows.affectedRows);
} catch (err2)
{
  console.log("*** Catch Error:")
  console.log(err2.stack);
}
console.log ("end function");

A: Got the answer here: https://github.com/sidorares/node-mysql2/issues/999.
The call from the first async routine to the second one needed an await.
for (let r=0; r < rows.length; ++r) {
  await UpdatePassword(connection, rows[r].ID);
}

He recommended a for loop, instead of answer I got earlier here.  If using .each or .map, you create another "inner" function, which is not async, and you can't call use the "await" keyword in that kind of logic.


text:
Q: Deploying React app with npm run build not finding files I currently have a directory myproject/
In myproject I have these
/src
/public
package.json

etc.
Normal stuff you'd see in a react app.
I pushed this to a server aws lightsail nodejs
I then run npm install.
After I do all this I go and run npm run build
I get this output:
> react-scripts build

Creating an optimized production build...
Failed to compile.

./src/index.js

Cannot find module: 'layouts/Admin.jsx'. Make sure this package is installed.

You can install this package by running: npm install layouts/Admin.jsx.

The files it's calling for are in the directory.
Here is package.json
{
  "name": "argon-dashboard-react",
  "version": "1.0.0",
  "description": "React version of Argon Dashboard by Creative Tim",
  "main": "index.js",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/creativetimofficial/argon-dashboard-react.git"
  },
  "keywords": [
    "react",
    "reactjs",
    "argon",
    "argon-react",
    "dashboard",
    "dashboard-react",
    "argon-dashboard",
    "argon-dashboard-react"
  ],
  "author": "Creative Tim",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/creativetimofficial/argon-dashboard-react/issues"
  },
  "homepage": "https://demos.creative-tim.com/argon-dashboard-react/",
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "install:clean": "rm -rf node_modules/ && rm -rf package-lock.json && npm install && npm start",
    "compile-sass": "node-sass src/assets/scss/argon-dashboard-react.scss src/assets/css/argon-dashboard-react.css",
    "minify-sass": "node-sass src/assets/scss/argon-dashboard-react.scss src/assets/css/argon-dashboard-react.min.css --output-style compressed",
    "map-sass": "node-sass src/assets/scss/argon-dashboard-react.scss src/assets/css/argon-dashboard-react.css --source-map true"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ],
  "dependencies": {
    "@material-ui/core": "^4.6.1",
    "@material-ui/icons": "^4.5.1",
    "chart.js": "2.7.3",
    "classnames": "2.2.6",
    "firebase": "^6.6.2",
    "firebase-admin": "^8.8.0",
    "http2": "^3.3.7",
    "moment": "2.24.0",
    "node-sass": "4.11.0",
    "nouislider": "13.1.1",
    "react": "16.9.0",
    "react-bootstrap-table-next": "^3.2.1",
    "react-chartjs-2": "2.7.4",
    "react-copy-to-clipboard": "5.0.1",
    "react-data-table-component": "4.0.1",
    "react-datepicker": "^2.9.6",
    "react-datetime": "2.16.3",
    "react-dom": "16.9.0",
    "react-google-maps": "9.4.5",
    "react-loading-screen": "0.0.17",
    "react-router-dom": "4.3.1",
    "react-scripts": "2.1.8",
    "reactstrap": "7.1.0",
    "recompose": "^0.30.0",
    "styled-components": "^4.4.1",
    "sweetalert2": "^9.5.4",
    "sweetalert2-react-content": "^2.0.2"
  },
  "devDependencies": {
    "@types/googlemaps": "3.30.18",
    "@types/markerclustererplus": "2.1.33",
    "@types/react": "16.8.7",
    "typescript": "3.3.3333"
  }
}

Any idea what's going on with this?

A: The problem was related to the way I was using my import paths for components.
In example, currently I have:
import UserHeader from "components/Headers/UserHeader.jsx";

The correct way to have set them was:
import UserHeader from "../../components/Headers/UserHeader.jsx";

What was throwing me off was that locally it worked.


text:
Q: C# Entity Framework Core write raw SQL without model First of all, I have seen this post: Raw SQL Query without DbSet - Entity Framework Core but I feel like it does not answer my question.
I have an ASP.NET Core MVC project with Entity Framework Core (newest at this date).
What I need to do is:
public IActionResult MyView(string NameOfTable)
{
    // send model that is same as NameOfTable
    // or
    // send something like List<string> that has properties and names of columns
    return View();
}

What I want to do is call a function and send the name of a table in database. It will find the table in the database and return the properties of table (column names, types of columns[int/ varchar..]).
What I think will work: either write raw SQL to database.
What I think is good answer: some snippet of how to write raw SQL to query the database without knowing a model. Or some way of overcoming this problem.
Thanks for everything. Sorry if this is dumb question.

A: Sorry for bothering you all. I have found solution. Here it is:
public class AA
{
    public string One { get; set; }
    public string Two { get; set; }
}

private async Task pokus()
{
    List<AA> groups = new List<AA>();
    var conn = _db.Database.GetDbConnection();
    try
    {
        await conn.OpenAsync();
        using (var command = conn.CreateCommand())
        {
            string query = "SELECT * FROM TABLE";
            command.CommandText = query;
            DbDataReader reader = await command.ExecuteReaderAsync();

            if (reader.HasRows)
            {
                while (await reader.ReadAsync())
                {
                    try
                    {
                        var row = new AA { One = reader.GetString(1), Two = reader.GetString(2) };
                        groups.Add(row);
                    }
                    catch { }
                }
            }
            else
            {
                Console.WriteLine("Dont have rows");
            }
            reader.Dispose();
        }
    }
    finally
    {
        conn.Close();
    }
    foreach(AA s in groups)
    {
        Console.WriteLine(s.One);
        Console.WriteLine(s.Two);
    }
}

I hope it will help somebody.


text:
Q: Passing an ID through a hidden form field I tried to do something similar to this in a form, but get this error:
Started POST "/opinions" for 127.0.0.1 at 2019-01-03 17:11:12 -0800
Processing by OpinionsController#create as JS
  Parameters: {"utf8"=>"✓", "opinion"=>{"content"=>"This is an opinion"}, "type_of"=>"pro", "topicId"=>"{:value=>2}", "commit"=>"Create Opinion"}
  User Load (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
  Topic Load (0.0ms)  SELECT  "topics".* FROM "topics" WHERE "topics"."id" = ? LIMIT ?  [["id", nil], ["LIMIT", 1]]
Completed 404 Not Found in 3ms (ActiveRecord: 0.0ms)

ActiveRecord::RecordNotFound (Couldn't find Topic with 'id'=):

app/controllers/opinions_controller.rb:6:in `create'

opinions_form.html.erb:
<%= form_for(opinion, :html=> {class:"form-horizontal", role:"form"}, remote: true) do |f| %>

      <%= f.text_area :content, rows:4, class: "form-control", placeholder: "Opinion" %>

  <%= hidden_field_tag 'type_of', typeOf %>
  <%= hidden_field_tag :topicId, :value => @topic.id %>
  <% puts "ID: " + @topic.id.to_s %>

      <%= f.submit %>

<% end %>

Relevant code in controller:
def create
  @opinion = Opinion.new(opinion_params)

  @opinion.user = current_user
  @opinion.topic = Topic.find(params[:opinion][:topicId])
  if @opinion.save
    flash[:success] = 'Opinion Added'
  else
    puts @opinion.errors.full_messages
    flash[:danger] = 'Opinion not Added'
  end
end

private

def opinion_params
  params.require(:opinion).permit(:content, :type_of)
end

and finally, relevant code in the topic show page:

  <%= render 'opinions/form', opinion: Opinion.new, typeOf: "pro", :topic => @topic %>

  <%= render 'opinions/form', opinion: Opinion.new, typeOf: "con", :topic => @topic %>

A: As you can see in the request parameters:
Parameters: {"utf8"=>"✓", "opinion"=>{"content"=>"This is an opinion"}, "type_of"=>"pro", "topicId"=>"{:value=>2}", "commit"=>"Create Opinion"}

The topicId parameter is not nested under opinion, so you need to change your finder to:
@opinion.topic = Topic.find(params[:topicId][:value])

You can also remove the superfluous value key in your view:
<%= hidden_field_tag :topicId, @topic.id %>

Which would further simplify your finder:
@opinion.topic = Topic.find(params[:topicId])

As an aside. Note that idiomatic ruby calls for snake_case in all identifiers. This won't change how your code works, but it will help other Ruby developers read your code.


text:
Q: ¿Cómo situar el footer siempre abajo? Estoy haciendo una página web y realmente no sé mucho de css ni de html.
¿Cómo hago para mantener el footer siempre al final de la página? Me queda un espacio entre el footer y el final de la página.
Agradezco su ayuda.

/*-----------General-----------*/

#pagina {
  width: 100%;
  margin: 0 auto;
  position: relative;
}

/* -----fuente y color del menu ----- */

.menu {
  color: #b40404;
  font-weight: normal;
  font-family: 'Roboto', sans-serif;
  font-size: 17px;
  line-height: 16px;
}

/* ----- Color del link (titulo) del menu ----- */

.menu a {
  color: #b40404;
}

/* ----- Color del título del menú al pasar el ratón por encima----- */

.menu a:hover {
  color: #354f83;
}

/* ----------color, fuente tamaño del texto body------------*/

body {
  color: #5e5e5e;
  font-weight: normal;
  font-family: 'Arial', sans-serif;
  font-size: 13px;
  line-height: 18px;
  text-align: left;
  /*------------reemplazar imagen cuando este en el servidor----------------*/
  background: #e5e2db url("http://dynamic.websimages.com/s/themes/savvy/v1.72/images/simple/bg.png") repeat fixed center 0;
  z-index: 1;
}

/* ---------------------------------- Color de los link en body ------------------------------------------*/

body a {
  color: #3f5b87;
}

/* -------------------------- Color de los link al pasar el ratón en body ----------------------------------*/

body a:hover {
  color: #000000;
}

/* ------------------------------------------ general ----------------------------------------------- */

a {
  text-decoration: underline;
  outline: none;
}

a:hover {
  text-decoration: none;
}

p {
  padding: 0 0 20px;
}

.interno {
  width: 950px;
  margin: 0 auto;
  background: #ffffff none repeat fixed center 0;
  -moz-box-shadow: 0 0 5px #555555;
  -webkit-box-shadow: 0 0 5px #555555;
  box-shadow: 0 0 5px #555555;
  -moz-border-radius: 4px;
  -webkit-border-radius: 4px;
  border-radius: 4px;
  position: relative;
  top: 8px;
  height: auto;
}

.externo {
  width: 966px;
  margin: 0 auto;
  -moz-border-radius: 4px;
  -webkit-border-radius: 4px;
  border-radius: 4px;
  background: #c5beaf;
  background: rgba(154, 143, 115, 0.15);
}

/* ---------------------------------- Header ----------------------------------------------*/

header.header {
  width: 100%;
  /*height: 130px;*/
  position: relative;
}

/*.header-area {
  width: 950px;
  height: 130px;
  margin: 0 auto;
  z-index: 1;
  overflow: visible;
 }
.w-header-area {
  min-height: 130px;
 }*/

/* ---------------------------------- Nav y menu ------------------------------------------*/

.cabecera-menu {
  height: 90px;
  position: relative;
  margin: 0 auto 10px;
  width: 966px;
}

.cabecera-menu {
  width: 966px;
}

.interno-cabecera-menu {
  width: 920px;
  height: 74px;
  position: relative;
  margin: 0 auto;
  top: 8px;
  padding: 0 15px;
}

#caja-nav>ul {
  list-style: none;
  position: relative;
  top: 0;
  z-index: 20;
}

#caja-nav>ul>li {
  float: left;
  padding: 15px 15px;
  margin-top: 14px;
  position: relative;
  /* -- Este es el espacio entre dos items del menu -- */
  margin-left: -5px;
}

#caja-nav>ul>li>a {
  display: block;
  text-decoration: none;
}

#caja-nav>ul>li.active,
#caja-nav>ul>li.child-active {
  color: #FFFFFF;
  display: block;
  outline: medium none;
  border: 1px solid #161616;
  -moz-border-radius: 6px;
  -webkit-border-radius: 6px;
  border-radius: 6px;
  background-color: #4d71b7;
  background-image: -moz-linear-gradient(top, #4d71b7, #354f83);
  background-image: -o-linear-gradient(top, #4d71b7, #354f83);
  background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #4d71b7), color-stop(1, #354f83));
  background-image: -webkit-linear-gradient(#4d71b7, #354f83);
  background-image: linear-gradient(top, #4d71b7, #354f83);
  filter: progid:DXImageTransform.Microsoft.gradient(startColorStr='#4d71b7', endColorStr='#354f83');
}

#caja-nav>ul>li.active>a,
#caja-nav>ul>li.child-active>a {
  color: #ffffff;
}

/* ---------------------------------- Main ----------------------------------------------*/

.contenedor {
  min-height: 460px;
  position: relative;
  width: 966px;
  margin: 0 auto 10px;
  clear: both;
}

.contenido-ancho {
  width: 966px;
  min-height: 460px;
}

.contenido-ancho-interno {
  min-height: 404px;
  padding: 20px 15px;
  width: 920px;
}

/* ---------------------------------- Footer ----------------------------------------------*/

footer {
  min-height: 70px;
  background-color: #191919;
  background-image: -moz-linear-gradient(top, #191919, #000000);
  background-image: -o-linear-gradient(top, #191919, #000000);
  background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #191919), color-stop(1, #000000));
  background-image: -webkit-linear-gradient(#191919, #000000);
  background-image: linear-gradient(top, #191919, #000000);
  filter: progid:DXImageTransform.Microsoft.gradient(startColorStr='#191919', endColorStr='#000000');
  border-top: 1px solid rgba(50, 50, 50, 0.3);
  width: 100%;
  position: relative;
  clear: both;
  margin-top: 0px;
  padding-top: 0px;
  overflow: visible;
}

.footer {
  border-top: 1px solid #222;
}

.post-footer {
  width: 950px;
  margin: 0 auto;
}

Home

Ofertas

Fonendos

Oximetros

Articulos y Accesorios

Repuestos

Hacer Pedido

Faq

Mi sitio web

Mi sitio web creado en html5

          google 1

          google 2

    ¿Cómo hago para mantener el footer pegado abajo siempre?

A: Si quieres que el footer SIEMPRE se mantenga en la parte inferior de la pantalla entonces lo más sencillo (y lo que no he visto en ninguna de las respuestas que te han dado hasta el momento) es cambiarle la propiedad position para que sea fija e indicarle que siempre se muestre en la parte inferior de la pantalla (con la propiedad bottom: 0).
También podrás observar que en el lado tanto izquierdo como derecho de la página web el footer no llega a tocar los laterales. Esto se debe a que la etiqueta body tiene un margen por defecto. Si se lo asignamos a 0 ya no verás estos huecos en ambos laterales.
Tendrías que modificar lo siguiente:
body{
  margin: 0;   /* NUEVO */
}

footer {
  min-height: 70px;
  background-color: #191919;
  background-image: -moz-linear-gradient(top, #191919, #000000);
  background-image: -o-linear-gradient(top, #191919, #000000);
  background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #191919), color-stop(1, #000000));
  background-image: -webkit-linear-gradient(#191919, #000000);
  background-image: linear-gradient(top, #191919, #000000);
  filter: progid:DXImageTransform.Microsoft.gradient(startColorStr='#191919', endColorStr='#000000');
  border-top: 1px solid rgba(50, 50, 50, 0.3);
  width: 100%;
  /*position: relative;
  clear: both;
  margin-top: 0px;            ELIMINADO
  padding-top: 0px;
  overflow: visible;*/
  position: fixed;
  bottom: 0;              /* NUEVO */
}

Tu ejemplo corregido:

body{
  margin: 0;   /* NUEVO */
}

/*-----------General-----------*/

#pagina {
  width: 100%;
  margin: 0 auto;
  position: relative;
}

/* -----fuente y color del menu ----- */

.menu {
  color: #b40404;
  font-weight: normal;
  font-family: 'Roboto', sans-serif;
  font-size: 17px;
  line-height: 16px;
}

/* ----- Color del link (titulo) del menu ----- */

.menu a {
  color: #b40404;
}

/* ----- Color del título del menú al pasar el ratón por encima----- */

.menu a:hover {
  color: #354f83;
}

/* ----------color, fuente tamaño del texto body------------*/

body {
  color: #5e5e5e;
  font-weight: normal;
  font-family: 'Arial', sans-serif;
  font-size: 13px;
  line-height: 18px;
  text-align: left;
  /*------------reemplazar imagen cuando este en el servidor----------------*/
  background: #e5e2db url("http://dynamic.websimages.com/s/themes/savvy/v1.72/images/simple/bg.png") repeat fixed center 0;
  z-index: 1;
}

/* ---------------------------------- Color de los link en body ------------------------------------------*/

body a {
  color: #3f5b87;
}

/* -------------------------- Color de los link al pasar el ratón en body ----------------------------------*/

body a:hover {
  color: #000000;
}

/* ------------------------------------------ general ----------------------------------------------- */

a {
  text-decoration: underline;
  outline: none;
}

a:hover {
  text-decoration: none;
}

p {
  padding: 0 0 20px;
}

.interno {
  width: 950px;
  margin: 0 auto;
  background: #ffffff none repeat fixed center 0;
  -moz-box-shadow: 0 0 5px #555555;
  -webkit-box-shadow: 0 0 5px #555555;
  box-shadow: 0 0 5px #555555;
  -moz-border-radius: 4px;
  -webkit-border-radius: 4px;
  border-radius: 4px;
  position: relative;
  top: 8px;
  height: auto;
}

.externo {
  width: 966px;
  margin: 0 auto;
  -moz-border-radius: 4px;
  -webkit-border-radius: 4px;
  border-radius: 4px;
  background: #c5beaf;
  background: rgba(154, 143, 115, 0.15);
}

/* ---------------------------------- Header ----------------------------------------------*/

header.header {
  width: 100%;
  /*height: 130px;*/
  position: relative;
}

/*.header-area {
  width: 950px;
  height: 130px;
  margin: 0 auto;
  z-index: 1;
  overflow: visible;
 }
.w-header-area {
  min-height: 130px;
 }*/

/* ---------------------------------- Nav y menu ------------------------------------------*/

.cabecera-menu {
  height: 90px;
  position: relative;
  margin: 0 auto 10px;
  width: 966px;
}

.cabecera-menu {
  width: 966px;
}

.interno-cabecera-menu {
  width: 920px;
  height: 74px;
  position: relative;
  margin: 0 auto;
  top: 8px;
  padding: 0 15px;
}

#caja-nav>ul {
  list-style: none;
  position: relative;
  top: 0;
  z-index: 20;
}

#caja-nav>ul>li {
  float: left;
  padding: 15px 15px;
  margin-top: 14px;
  position: relative;
  /* -- Este es el espacio entre dos items del menu -- */
  margin-left: -5px;
}

#caja-nav>ul>li>a {
  display: block;
  text-decoration: none;
}

#caja-nav>ul>li.active,
#caja-nav>ul>li.child-active {
  color: #FFFFFF;
  display: block;
  outline: medium none;
  border: 1px solid #161616;
  -moz-border-radius: 6px;
  -webkit-border-radius: 6px;
  border-radius: 6px;
  background-color: #4d71b7;
  background-image: -moz-linear-gradient(top, #4d71b7, #354f83);
  background-image: -o-linear-gradient(top, #4d71b7, #354f83);
  background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #4d71b7), color-stop(1, #354f83));
  background-image: -webkit-linear-gradient(#4d71b7, #354f83);
  background-image: linear-gradient(top, #4d71b7, #354f83);
  filter: progid:DXImageTransform.Microsoft.gradient(startColorStr='#4d71b7', endColorStr='#354f83');
}

#caja-nav>ul>li.active>a,
#caja-nav>ul>li.child-active>a {
  color: #ffffff;
}

/* ---------------------------------- Main ----------------------------------------------*/

.contenedor {
  min-height: 460px;
  position: relative;
  width: 966px;
  margin: 0 auto 10px;
  clear: both;
}

.contenido-ancho {
  width: 966px;
  min-height: 460px;
}

.contenido-ancho-interno {
  min-height: 404px;
  padding: 20px 15px;
  width: 920px;
}

/* ---------------------------------- Footer ----------------------------------------------*/

footer {
  min-height: 70px;
  background-color: #191919;
  background-image: -moz-linear-gradient(top, #191919, #000000);
  background-image: -o-linear-gradient(top, #191919, #000000);
  background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #191919), color-stop(1, #000000));
  background-image: -webkit-linear-gradient(#191919, #000000);
  background-image: linear-gradient(top, #191919, #000000);
  filter: progid:DXImageTransform.Microsoft.gradient(startColorStr='#191919', endColorStr='#000000');
  border-top: 1px solid rgba(50, 50, 50, 0.3);
  width: 100%;
  /*position: relative;
  clear: both;
  margin-top: 0px;            ELIMINADO
  padding-top: 0px;
  overflow: visible;*/
  position: fixed;
  bottom: 0;              /* NUEVO */
}

.footer {
  border-top: 1px solid #222;
}

.post-footer {
  width: 950px;
  margin: 0 auto;
}

Home

Ofertas

Fonendos

Oximetros

Articulos y Accesorios

Repuestos

Hacer Pedido

Faq

Mi sitio web

Mi sitio web creado en html5

          google 1

          google 2

    ¿Cómo hago para mantener el footer pegado abajo siempre?

A: Intenta poner en el css en footer esto
.footer {
    bottom: 0;
}

A: Prueba añadiendo la propiedad top en los estilos de footer y poniendo position:absolute, lo deja como tú buscas:
footer {
  min-height: 70px;
  background-color: #191919;
  background-image: -moz-linear-gradient(top, #191919, #000000);
  background-image: -o-linear-gradient(top, #191919, #000000);
  background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #191919), color-stop(1, #000000));
  background-image: -webkit-linear-gradient(#191919, #000000);
  background-image: linear-gradient(top, #191919, #000000);
  filter: progid:DXImageTransform.Microsoft.gradient(startColorStr='#191919', endColorStr='#000000');
  border-top: 1px solid rgba(50, 50, 50, 0.3);
  width: 100%;
  position: absolute;
  clear: both;
  margin-top: 0px;
  padding-top: 0px;
  overflow: visible;
  top:93%;
}

A: Prueba en añadir esta propiedad al footer, a mi me funciona
footer{
    clear: both;
}

A: Agrega min-height: 100vh  y position: relative a tu contenedor en CSS.

.contenedor {
 min-height:100vh;/*importante*/
 position:relative;/*importante*/
 border:2px solid blue;
}

footer{
 background-color:red;
 color:white;
 padding:15px;
}

/*coloca esto si deseas eliminar el margen*/
body {
 margin:0;
}

 *******AQUI DEBES COLOCAR TU CONTENIDO******

 ESTO ES EL FOOTER

A: Este es el css
body{
    min-height: 100%;
    top: 0;
    margin:0;
    padding:0;
}

footer,
section#main,
body{
    width: 100%;
    position: absolute;
}

section#main{
    min-height: 100%;
}

footer{
    bottom: 0;
}

y este es el HTML

            Codigo del footer

A: .footer{

  position:static; /*mantener el footer abajo*/
  bottom: 0;
}