text:
Q: Firefox Addon : Event on a specific command line I'm trying that when the user enters a command in the Web console, I get this command in the script of my addon before to be executed?
For example, when the user enters the command line "screenshot --fullpage" this command to be sent to a function of the script of my addon before being executed.
I did some research but I only found an event on the opening of the web console.
https://developer.mozilla.org/en-US/docs/Observer_Notifications#Developer_tools

A: Solution posted here - https://discourse.mozilla-community.org/t/firefox-addon-event-on-a-specific-command-line/6028/10?u=noitidart
Alrighty here we go, this works:
var { require } = Cu.import("resource://devtools/shared/Loader.jsm", {});

var tmp = {};
Cu.import("resource://devtools/client/shared/DeveloperToolbar.jsm", tmp);

var gcliInit = require('devtools/shared/gcli/commands/index');
var { TargetFactory } = require("devtools/client/framework/target");

var a = new tmp.DeveloperToolbar(window, document.getElementById("developer-toolbar"));

var sysTarget= TargetFactory.forTab(a._chromeWindow.gBrowser.selectedTab);

gcliInit.getSystem(sysTarget).then(
    system => {
        console.log('system:',system);
        system.addItems([{
            name: 'greet',
            description: 'Show a greeting',
            params: [{
                name: 'name',
                type: 'string',
                description: 'The name to greet'
            }],
            returnType: 'string',
            exec: function(args, context) {
                return 'Hello, ' + args.name;
            }
        }]);
    },
    y => console.error('y:',y)
);

Note, the path changes in Firefox 45. So this code is for Fx45+ prior to this you would use resource://gre/modules/devtools/Loader.jsm instead of resource://devtools/shared/Loader.jsm.
TargetFactor was the key component I was missing, it's important, it's got these methods:
 Object { forTab: function (), forRemoteTab: function (), forWorker: function (), isKnownTab: function () }


text:
Q: Cannot install netbeans plugin - netbeans instalation corrupt? While trying to install the Node.js Projects plugin, it says that:

Some plugins require plugin Progress API to be installed.
The plugin Progress API is requested in version >= 1.40 but only
  1.38.1 was found. The following plugin is affected:       Node.js Projects
Some plugins require plugin Ant-Based Project Support to be installed.
The plugin Ant-Based Project Support is requested in version >= 1.62
  but only 1.60.1 was found. The following plugin is affected:
  Node.js Projects
Some plugins require plugin File System API to be installed.
The plugin File System API is requested in version >= 9.0 but only
  8.12.1 was found. The following plugin is affected:       Node.js Projects
Some plugins require plugin Datasystems API to be installed.
The plugin Datasystems API is requested in version >= 7.61 but only
  7.57.2 was found. The following plugin is affected:       Node.js Projects
Some plugins require plugin Utilities API to be installed.
The plugin Utilities API is requested in version >= 9.3 but only
  8.39.1 was found. The following plugin is affected:       Node.js Projects
Some plugins require plugin org.openide.util.ui to be installed.
The plugin org.openide.util.ui is requested in version 9.3. The
  following plugin is affected:       Node.js Projects Some plugins not
  installed to avoid potential installation problems.

I asked the author of the plugin, and he said that my netbeans version is ancient.
The thing is this is a freshly installed netbeans and have tried to cleanup every cache and setting found on my system, I have removed:

*

*/Applications/NetBeans/

*~/Library/Application Support/NetBeans

*~/Library/Caches/NetBeans

*/private/var/db/receipts/org.netbeans.*

Tried on netbeans: 8.0.1 PHP, 8.0.2 full
OSX: Mavericks, updated
Plugin version: 2.21

Tried to install plugin both as an .npm and from the authors update site. The plugin is not yet available in the official update center.
I have a second mac where the plugin works fine (NetBeans 8.0.0, OSX Mountain Lion), so this can be installed, but somehow on this system this install is stuck with an outdated plugin version somewhere in the system.
How to fully reset my netbeans instalation?

Additional information after some checks:

*

*It is not dependant on user, newly created user has the same problem - so not a problem with any file in $HOME

*It is the only instalation of netbeans on the computer, there was a Visual VM tool embeded into the system JRE, but removing it didn't help.

*I tried a dtruss (OSX strace equivalent, monitors system calls) on NetBeans, and it is not opening any suspicious files - only from JRE and NB 8.0.2's folder.

A: The author of the plugin has released a patch that fixed the versioning issue.

A: Error Clearly shows that you are using older version of netbeans, or your netbean is not successfully upgraded.
see the version of  plugin org.openide.util.ui is 9.3 and in error it is showing 8.39.1
If you just drag the netbean directory to thrash it will be removed from your OSX and also clear the Cache of Netbean. After that download and install a fresh copy of NetBeans.

Note that NetBeans leaves some hidden configuration directories in your home directory. You might want to delete those too:
.asadminpass and .asadmintruststore - directories that contain stuff for Glassfish (Java EE application server)
.netbeans and .netbeans-registration - NetBeans configuration directories
.nbprofiler - something from the NetBeans profiler
In a terminal window, you can list all files and directories (including hidden ones) with ls -la, and you can delete them with for example rm -rf .netbeans (BE CAREFUL with that last command, it deletes stuff so that you can't get it back). answer posted On SO by jesper

https://stackoverflow.com/questions/1014099/how-can-i-uninstall-netbeans-on-a-mac

redpajama_set_name: RedPajamaStackExchange


text:
Q: Notation for fields I'm trying to get caught up wit my abstract algebra class, but I'm getting lost with notation . Can someone help explain these things to me regarding fields?
$\mathbb{Q}$ is the field of all rational numbers?
$\mathbb{Q}[x]$ is the field of rational numbers with polynomials?
$\mathbb{Q}(x)$ is ???
An example like $\mathbb{Q}(\sqrt{2},\sqrt{3})$ is ??
Any insight would be great. Thank you in advance.

A: $\mathbb{Q}$ is the field of rational numbers.
$\mathbb{Q}[x]$ is the ring of polynomials in one indeterminate $x$ with rational coefficients.
$\mathbb{Q}(x)$ is the field of fractions of $\mathbb{Q}[x]$; it is called the field of rational functions with coefficients in $\mathbb{Q}$. Its elements are of the form $\frac{p(x)}{q(x)}$, where $p(x)$ and $q(x)$ are polynomials with rational coefficients, and where
$$\frac{p(x)}{q(x)} = \frac{r(x)}{s(x)}\iff p(x)s(x)=q(x)r(x);$$
etc.
$\mathbb{Q}(\sqrt{2},\sqrt{3})$ is the smallest subfield of $\mathbb{C}$ that contains $\mathbb{Q}$, $\sqrt{2}$, and $\sqrt{3}$. In principle, it will be equal to
$$\left.\left\{\frac{p(\sqrt{2},\sqrt{3})}{q(\sqrt{2},\sqrt{3})}\right| p(x,y),q(x,y)\in\mathbb{Q}[x,y], q(\sqrt{2},\sqrt{3})\neq 0\right\},$$
though in fact one can show that every element can be written uniquely as
$$a+b\sqrt{2}+c\sqrt{3}+d\sqrt{6},\qquad a,b,c,d\in\mathbb{Q}.$$
In general, if $F\subseteq K$ are fields, and $\alpha\in K$, then $F[\alpha]$ denotes the smallest subring of $K$ that contains $F$ and $\alpha$, and $F(\alpha)$ denotes the smallest subfield of $K$ that contains $F$ and $\alpha$. It is not hard to prove that, as sets,
$$\begin{align*}
F[\alpha] &= \{ p(\alpha)\mid p(x)\in F[x]\},\\
F(\alpha) &= \{p(\alpha)/q(\alpha)\mid p(x),q(x)\in F[x], q(\alpha)\neq 0\}.
\end{align*}$$
Though if $\alpha$ is algebraic over $F$, there are simpler expressions.
Similarly, if $S\subseteq K$ is a subset of $K$ (finite or infinite), then
$$\begin{align*}
F[S] &= \{ p(s_1,\ldots,s_n)\mid n\in\mathbb{N}, p(x_1,\ldots,x_n)\in F[x_1,\ldots,x_n], s_1,\ldots,s_n\in S\}\\
F(S) &= \left.\left\{ \frac{p(s_1,\ldots,s_n)}{q(s_1,\ldots,s_n)}\right| n\in\mathbb{N}, p,q\in F[x_1,\ldots,x_n], q(s_1,\ldots,s_n)\neq 0\right\}.
\end{align*}$$

A: $\mathbb{Q}[x]$ is a ring of polynomials with rational coefficients, $\mathbb{Q}(\sqrt{2}, \sqrt{3})$ is the smallest extension of $\mathbb{Q}$ in which equations $x^2 = 2$ and $x^2 = 3$ have solutions.


text:
Q: Airflow with Vertica as metadata backend I am trying to set up airflow with Vertica Database as metadata backend. Facing the below error when I try to run airflow initdb.
Following is the configuration used in airflow.cfg file.
sql_alchemy_conn = vertica+vertica_python://username:password@host:port/dbname

Error msg received :
Traceback (most recent call last):
  File "/usr/local/bin/airflow", line 37, in <module>
    args.func(args)
  File "/usr/local/lib/python3.7/site-packages/airflow/bin/cli.py", line 1131, in initdb
    db.initdb(settings.RBAC)
  File "/usr/local/lib/python3.7/site-packages/airflow/utils/db.py", line 106, in initdb
    upgradedb()
  File "/usr/local/lib/python3.7/site-packages/airflow/utils/db.py", line 376, in upgradedb
    command.upgrade(config, 'heads')
  File "/usr/local/lib/python3.7/site-packages/alembic/command.py", line 298, in upgrade
    script.run_env()
  File "/usr/local/lib/python3.7/site-packages/alembic/script/base.py", line 489, in run_env
    util.load_python_file(self.dir, "env.py")
  File "/usr/local/lib/python3.7/site-packages/alembic/util/pyfiles.py", line 98, in load_python_file
    module = load_module_py(module_id, path)
  File "/usr/local/lib/python3.7/site-packages/alembic/util/compat.py", line 173, in load_module_py
    spec.loader.exec_module(module)
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/usr/local/lib/python3.7/site-packages/airflow/migrations/env.py", line 92, in <module>
    run_migrations_online()
  File "/usr/local/lib/python3.7/site-packages/airflow/migrations/env.py", line 82, in run_migrations_online
    compare_type=COMPARE_TYPE,
  File "<string>", line 8, in configure
  File "/usr/local/lib/python3.7/site-packages/alembic/runtime/environment.py", line 822, in configure
    opts=opts,
  File "/usr/local/lib/python3.7/site-packages/alembic/runtime/migration.py", line 218, in configure
    return MigrationContext(dialect, connection, opts, environment_context)
  File "/usr/local/lib/python3.7/site-packages/alembic/runtime/migration.py", line 146, in __init__
    self.impl = ddl.DefaultImpl.get_by_dialect(dialect)(
  File "/usr/local/lib/python3.7/site-packages/alembic/ddl/impl.py", line 71, in get_by_dialect
    return _impls[dialect.name]
KeyError: 'vertica'

Please let me know if this configuration is supported(airflow + vertica as backend). Any help or input regarding this would be much appreciated.

A: Yes, you can use any database as a backend.
https://airflow.apache.org/docs/stable/howto/initialize-database.html
 As Airflow was built to interact with its metadata using the great
 SqlAlchemy library, you should be able to use any database backend
 supported as a SqlAlchemy backend. We recommend using MySQL or
 Postgres.

And to be able to connect Vertica, you should install and configure unixODBC,
And  you can find the rest below,
Connecting to Vertica database using SQLAlchemy


text:
Q: How to disable JMS spring listener in test evnvironment I am using spring JMSTemplate to connect to a queue on a different weblogic domain.
I wired all the components like jndiTemplate, connectionfactory, destination etc in the Spring config.
Messages are handled by a simple implementation of MessageListener.

It all works fine. But when I try to deploy this application where the destination is not available, deployment fails. this is very important for me as we dont have JMS infrastructure in some of our environments.

I tried with lookupOnStartup=false on all the components and tried injecting them into DMLC based on a environment variable. But the issue is, the listener doesnt seem to be starting up. All the messages are left in the queue.
Any help is highly appreciated.
Spring-config:
<bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate">
    <property name="environment">
        <props>
            <prop key="java.naming.factory.initial">weblogic.jndi.WLInitialContextFactory</prop>
            <prop key="java.naming.provider.url">t3://wp2128.xyz.int:7001</prop>
            <prop key="java.naming.security.authentication">none</prop>
            <prop key="java.naming.security.principal"></prop>
            </props>
    </property>
</bean>
<bean id="connectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean" >
    <property name="jndiTemplate" ref="jndiTemplate" />
    <property name="jndiName" value="jms/connectionFactory" />
</bean>
<bean id="destination" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiTemplate" ref="jndiTemplate" />
    <property name="jndiName" value="jms/testQueue" />
</bean>

<bean id="simpleConsumer"
    class="org.springframework.jms.listener.DefaultMessageListenerContainer">
    <property name="concurrentConsumers" value="5" />
    <property name="connectionFactory" ref="connectionFactory" />
    <property name="destination" ref="destination" />
    <property name="messageListener" ref="simpleMessageListener" />
</bean>

A: You can set autoStartup to false. This property value can be externalized in a properties files.
<bean id="simpleConsumer"
    class="org.springframework.jms.listener.DefaultMessageListenerContainer">
    <property name="concurrentConsumers" value="5" />
    <property name="connectionFactory" ref="connectionFactory" />
    <property name="destination" ref="destination" />
    <property name="messageListener" ref="simpleMessageListener" />
   <property name="autoStartup" value="false"/>
</bean>


text:
Q: Sylius, add/remove/update associated product i'm trying to add an associated product or replace it if exists. Here's the code i'm using:
/** @var ProductAssociationInterface $association */
$association = $this->associationFactory->createNew();
/** @var ProductAssociationTypeInterface $associationType */
$associationType = $this->associationTypeRepository->findOneBy(['code' => 'similar_products']);
$association->setType($associationType);
if ($similar_product = $this->productRepository->findOneByCode(trim($row['Similar product']), $this->locale)) {
    if (!$association->hasAssociatedProduct($similar_product)) {
        $association->addAssociatedProduct($similar_product);
    }

    if (!$product->hasAssociation($association)) {
        $product->addAssociation($association);
        $this->associationManager->persist($product);

        if (!$this->associationRepository->findOneBy(array('owner' => $similar_product->getId(), 'type' => $associationType->getId()))) {
            $this->associationRepository->add($association);
        }
    };
}

but while it's working great if there is no associated product - if there is, or even if it's the same product - it throws a duplicate entry error in "product_association_idx" table and I can't figure why or how to set up the check to see if this product is already associated or not.
Any help would be greatly appreciated, thanks

A: ok, figured it out myself
/** @var ProductAssociationInterface $association */
$association = $this->associationFactory->createNew();
/** @var ProductAssociationTypeInterface $associationType */
$associationType = $this->associationTypeRepository->findOneBy(['code' => 'similar_products']);
$association->setType($associationType);
if ($similar_product = $this->productRepository->findOneByCode(trim($row['Similar product']), $this->locale)) {
    $flag = true;
    foreach($product->getAssociations() as $productAssociation) {
        if ($productAssociation->hasAssociatedProduct($similar_product)) {
            $flag = false;
        }
    }

    if ($flag) {
        $association->addAssociatedProduct($similar_product);
        $product->addAssociation($association);
        $this->associationManager->persist($product);

        if (!$this->associationRepository->findOneBy(array('owner' => $similar_product->getId(), 'type' => $associationType->getId()))) {
            $this->associationRepository->add($association);
        }
    };
}


text:
Q: Header: text/icons positioning and keeping text/icons inside header when zooming out in different browsers I'm very new to HTML and CSS. Right now i'm trying to create a header, you can see the demo here
Basically I want the text and icons from "Login" move to the right side of header so it looks more like this:

I also want the text and icons positioned inside the header when you zoom out in different browser.
I've tried to position the a tags to the right but it keeps going outside of the header on different browser. I've also tried to create a div class for the left part and the right part in the header, but some how the text and icons keeps going out of the header in Safari and Chrome.
Is there any simple solution for these two problems?
Here is the full code for the header.
HTML:

    Free Shipping
    Free Returns
    Same-day Dispatch
    Login
    Create Account
    Language
    Delivery Country

CSS:
/* ------------------ TOP HEADER ------------------ */

    #header {
      border-bottom: 1px solid #ddd;
      background: #f5f5f5;
      height: 45px;
      white-space: nowrap;
      width: 1024px;
    }

    .free-shipping {
      background-image: url("images/shipping.png");
      background-position: left center;
      background-repeat: no-repeat;
      font-size: 11px;
      font-weight: bold;
      padding-left: 23px;
      margin-left: 15px;
    }
    .free-returns {
      background-image: url("images/returns.png");
      background-position: left center;
      background-repeat: no-repeat;
      font-size: 11px;
      font-weight: bold;
      padding-left: 23px;
    }
    .same-day-dispatch {
      background-image: url("images/dispatch.png");
      background-position: left center;
      background-repeat: no-repeat;
      font-size: 11px;
      font-weight: bold;
      padding-left: 23px;
    }

    .login {
      font-weight: bold;
      text-decoration: none;
      font-size: 11px;
      padding-right: 8px;
      line-height: 45px;
      color: #202020;
    }

    .login:hover { text-decoration: underline; }

    .create-account {
      font-weight: bold;
      text-decoration: none;
      font-size: 11px;
      padding-right: 8px;
      line-height: 45px;
      color: #d13030;
    }

    .create-account:hover { text-decoration: underline; }

    .language-icon {
      border: 1px solid #ddd;
      color: #202020;
      font-weight: bold;
      padding-right: 8px;
      padding-left: 27px;
      display: inline-block;
      font-size: 11px;
      width: auto;
      height: 24px;
      margin-top: 10px;
      line-height: 25px;
      text-align: right;
      text-decoration: none;
      border-radius: 4px;
      background: #f5f5f5 url("images/language-sprite.png") no-repeat 0 0 ;
    }

    .language-icon:hover { background: #fff url("images/language-sprite.png") no-repeat 0 -20px ; color: #d13030; }

    .delivery-country-icon {
      border: 1px solid #ddd;
      color: #202020;
      padding-right: 9px;
      padding-left: 30px;
      font-weight: bold;
      display: inline-block;
      font-size: 11px;
      height: 24px;
      line-height: 25px;
      text-align: right;
      text-decoration: none;
      border-radius: 4px;
      background: #f5f5f5 url("images/delivery-country-sprite.png") no-repeat top left ;
    }

    .delivery-country-icon:hover { background: #fff url("images/delivery-country-sprite.png") no-repeat 0 -20px ; color: #d13030; }

Thank you in advance.

A: See in this link an example of this:
http://codepen.io/anon/pen/Gitjl
I used float to position the elements, one on the left and the other on the right.
Hope it helps you. :D


text:
Q: TypeORM activeRecord style query for "where (a & b) or (c & d)"? I want to use TypeORM to run a query like
... WHERE (a=1 && b=true) OR (a=2 && b=false)

I see a bunch of references to doing this in the QueryBuilder style, but I need to know how to do this using the ActiveRecord style.

A: You can do this by providing an array of objects to the where: property:
Item.find({
    where: [
        { user: { id: userId }, confirmed: "true" },
        { user: { id: userId }, status: "active" }
    ]
});

The query above would find items that belong to a user where

*

*user matches user id AND is confirmed, or...

*user matches user id AND is active

A: I do not know about TypeORM, however I found this on ruby on rail active query methods:
https://guides.rubyonrails.org/active_record_querying.html#conditions
raw code: ...where("orders_count = ? AND locked = ?", params[:orders], false)
Example Code: ...where(["(a= ? and b= ?) Or (a=? and b=?)", 1, true, 2, false])


text:
Q: How to check if rufus-scheduler is already running for my Rails Application I have a Rails application that uses rufus-scheduler to schedule some of its tasks. The scheduler get initialised in the after_fork of a unicorn script initiating the Rails application (Reference: https://gist.github.com/jkraemer/3851917).
Recently, I encountered a scenario where the unicorn scheduler thread got killed while the unicorn process hosting it was still active. This lead to the scheduler being down for a considerable time without notice.
I would like to setup an alert and monitoring system to handle such scenarios that should be capable of:
1. Throwing an alert whenever the scheduler thread is killed/aborted.
2. Restart the scheduler if the Rails process is running.
What would be a suitable way to know the running status of the scheduler, through perhaps a cron task and handle the auto-restart ?

A: If you bring in a cron task to watch rufus-scheduler, why don't you simply drop rufus-scheduler and use Whenever for all the scheduling? You'll thus have a 100% crond solution.
Another alternative, use Foreman to manage a) your Rails application b) a separate process hosting your rufus-scheduler schedules (it could be a "schedule only" version of your Rails application) (here is a nice example in a blog post). There is also God.
If you look at Clockwork, a gem that was inspired by rufus-scheduler, they detail such one application / multiple processes scenarii.
Then you could look at the various tools out there to watch your logs and alert you in case of error.
Update:
Maybe this gist could help: https://gist.github.com/jmettraux/5f716c8568f6ab7bb016a4bc11528bc2


text:
Q: can't install php-gd ext 7.0 when i tried to install php7.0-gd i found this error

dfiadm@dc2-magneto-test:~$ sudo apt-get install php7.0-gd
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 php7.0-gd : Depends: libgd3 (>= 2.1.1) but it is not going to be installed
             Depends: libxpm4 but it is not installable
E: Unable to correct problems, you have held broken packages.

output of this command : apt-cache policy php7.0-gd

php7.0-gd:
  Installed: (none)
  Candidate: 7.0.33-57+ubuntu20.04.1+deb.sury.org+1
  Version table:
     7.0.33-57+ubuntu20.04.1+deb.sury.org+1 500
        500 http://ppa.launchpad.net/ondrej/php/ubuntu focal/main amd64 Packages
     7.0.33-57+0~20211119.61+debian9~1.gbp5d8ba5 500
        500 https://packages.sury.org/php stretch/main amd64 Packages

my os ubuntu server LTS 20.04

A: Sury PPA + Ubuntu20.04 here. Those packages are fine and installable, but the problem in your case should be fixed by
apt install -f libgd3 libxpm4

To figure out what are your options for the package, you can use
apt-cache policy libxpm4

Which should give you something like
libxpm4:
  Installed: 1:3.5.12-1
  Candidate: 1:3.5.12-1
  Version table:
 *** 1:3.5.12-1 500
        500 http://pl.archive.ubuntu.com/ubuntu focal/main amd64 Packages
        100 /var/lib/dpkg/status


text:
Q: How to update a cloned branch I am cloning a branch using the below code
git clone -b branch remote_repo
It clones fine, but now I would like to update it as the branch owner changed code. How do I go about doing that.

A: You should probably do git pull
But if you already changed something in the cloned repo, then you can do this
git fetch --all

And then
git reset --hard origin/master

But if you're on any other branch , then git reset --hard origin/<yourbranch>


text:
Q: .java files of android that initiates the installation of new apk files in android Can someone help me with the installation steps in android.Specifically I want to know the .java files of android that initiates the installation of new apk files that includes parsing of manifest files and validating them.

A: In android application first starts from the main Activity that you signed in your manifest file.So you can think of the java file that includes your main Activity.
onCreate() is the first method that fired automatically when android application starts


text:
Q: Abandoned pull request in Azure DevOps is still active, how to remove it from "Active" view? I created a pull request in Azure DevOps but found out it needed to be cancelled so I abandoned it. But it is still in the "Active" section (and "Abandoned" section). I want it to only stay in the "Abandoned" section and couldn't find a solution for it.
For GitLab, we can just simply "Close" the pull request without merging the code. How to handle this in Azure DevOps?
Thanks.


text:
Q: Slow MYSQL query using COUNT and LEFT JOIN I'm using the following query the COUNT records and display records in MySQL.  While it displays fine and works correctly it is very slow.  I think this is in part due to the HTG_ScheduleRequest table being very large.  Is there a better way to arrange this query to speed this up?
SELECT HTG_TechProps.EmpNumber,
       HTG_TechProps.EmpFirstName,
       HTG_TechProps.EmpLastName,
       HTG_TechProps.Veh_Number,
       COUNT(HTG_ScheduleRequest.ID) AS current_job
    FROM HTG_TechProps
        LEFT JOIN HTG_ScheduleRequest
            ON HTG_TechProps.EmpNumber = HTG_ScheduleRequest.SSR
                AND (HTG_ScheduleRequest.ScheduleDateCurrent = CURDATE())
                AND HTG_ScheduleRequest.JobStatus = '3'
    GROUP BY HTG_TechProps.EmpNumber
    ORDER BY HTG_TechProps.EmpNumber ASC

A: Assuming EmpNumber is unique, try this version (indexes follow the query):
SELECT tp.EmpNumber, tp.EmpFirstName, tp.EmpLastName, tp.Veh_Number,
       (SELECT COUNT(*)
        FROM HTG_ScheduleRequest sr
        WHERE tp.EmpNumber = sr.SSR AND
              sr.ScheduleDateCurrent = CURDATE() AND
              sr.JobStatus = '3'
       )
FROM HTG_TechProps  tp
ORDER BY tp.EmpNumber ASC;

Before running the query, create these indexes:  HTG_TechProps(EmpNumber) and HTG_ScheduleRequest(SSR, JobStatus, ScheduleDateCurrent).


text:
Q: How to build a dynamic model in rails? I am building an editable user-form using Ruby on Rails. I currently have a model to store the question title and a separate model to store options for each question.
The form has a list of all the questions and for each question, the user can view the form in a drop down list.
My problem is that I want to create a model for a user that can select an option for each questions and I want to store these options for each user in the database. If the manager deletes a question from the questions table, then the user form will not have that question.

And I am displaying a form to the user showing these questions by means of a form:
But I do not know how to create a model to store answer for all the questions for different users of the system. Can someone suggest how to create such a dynamic model?


text:
Q: Time multiple commands without a subshell? Is there a way to use the time reserved word in zsh to time multiple commands, without starting a subshell?
I know that this works:
{ time (
    sleep 5
    sleep 3
    PROMPT='foobar> '
) }

However the parentheses mean that a subshell is created, and variables initialized don't get exported.
I know I can capture the variables before and after, like
start=$(time)
# do something
end=$(time)
echo start - end | bc

Though for ad hoc timing this is a little cumbersome.

A: No, time can only work on a different process. So, it won't work with { ... } or with a builtin, like:
time { ls }
time echo

Note that your method capturing the time output won't work if there are already children (as their times when running the commands will also be taken into account). Ditto if you have traps and corresponding signals occur.


text:
Q: How to query data from a second table when the table's name is in first table's column data I have a weird database schema (that I can't change) where the rows in TableA will contain a table name where more information are stored. I want to query data from TableA and join them with the extended values contained in the table from the queried row.
e.g. assuming i have the following data
TableA
Event ID     Accnt ID    DetailTable
-----------  ----------  ----------------
1            UserA       Table1
2            UserA       Table2
3            UserB       Table2

Table1
Accnt ID    Status
----------  ------------
UserA       Active

Table2
Accnt ID    Status
----------  ------------
UserA       Inactive
UserB       Active

I would like to have the following resulset
select ... from ...

Result
Accnt ID   DetailTable    Status
---------  -------------  ---------
UserA      Table1         Active
UserA      Table2         Inactive
UserB      Table2         Active

It can probably be done using a loop on each of the record from TableA and then querying the proper detail table, but I was wondering if it was doable in a single Select statement in Oracle SQL.
Thank you

A: This can be a common problem where someone avoids the EAV anti-pattern and jumps into the opposite anti-pattern of having dynamically generated detail tables for every type of object that is stored in a "main" table. When you find yourself storing table or field names as data, then it might be time to rethink your schema. But, like EAV, sometimes it's unavoidable.
If you know the table names already that might appear in your DetailTable column then you could join in those in conditionally, or use a UNION query (assuming the columns match up nicely in your detail table):
SELECT
    TableA.AccntID,
    unionDetail.DetailTable,
    unionDetail.Status
FROM
    TableA
    INNER JOIN
        (
            SELECT AccntID, Status, 'Table1' as DetailTable FROM Table1
            UNION ALL
            SELECT AccntID, Status, 'Table2' FROM Table2
        ) AS unionDetail ON
        TableA.AccntID = unionDetail.AccntID AND
        TableA.DetailTable = unionDetail.DetailTable

Of course this all falls apart if the columns don't match up in the detail tables, or if you have a ton of detail tables or they are being dynamically added or removed.


text:
Q: Embedd binary data in executable using CMake I faced some problem with embedding binary data into executable when I use CMake. The code for both options is the same and as follows:
#include <iostream>

extern char _binary_res_txt_start;
extern char _binary_res_txt_end;

int main (int, char**) {
    for (char* c = &_binary_res_txt_start; c != &_binary_res_txt_end; ++c) {
        std::cout << *c;
    }
    return 0;
}

When I compile it with GCC:
g++ -std=c++17 -Wall -Wextra -Wpedantic -Werror=return-type -Wl,--format=binary -Wl,res.txt -Wl,--format=default  main.cpp -o main

And my res.txt file stores simple "HELLO WORLD" text I get appropriate output, so everything as expected.
Now I would like to compile this code using CMake, so my attemp was:
cmake_minimum_required(VERSION 3.10)
set(app_name main)
project(${app_name} CXX)
set(BIN_DIR "${PROJECT_SOURCE_DIR}/bin")
set(OPTIMIZATION_LEVEL " -O0")
set(COMPILE_FLAGS_MAIN "-Wall -Wextra -Wpedantic -Wno-deprecated-declarations -Wno-unused-parameter -Wno-unused-variable -Wl,--format=binary -Wl,res.txt -Wl,--format=default")
set(COMPILE_FLAGS_RELEASE "${COMPILE_FLAGS_MAIN} ${OPTIMIZATION_LEVEL}")
set(CPP_STD "17")
set(CPP_STD_REQUIRED "ON")
set(CPP_EXTENSION_REQUIRED "OFF")

file(GLOB_RECURSE SOURCES "${PROJECT_SOURCE_DIR}/src/cpp/*.cpp")

add_executable(${app_name} ${SOURCES})

set_target_properties(${app_name} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${BIN_DIR}
                                                COMPILE_FLAGS ${COMPILE_FLAGS_RELEASE}
                                                CXX_STANDARD ${CPP_STD}
                                                CXX_STANDARD_REQUIRED ${CPP_STD_REQUIRED}
                                                CXX_EXTENSIONS ${CPP_EXTENSION_REQUIRED})

And unfortunately during linkage I got:
main.cpp:(.text+0x13): undefined reference to `_binary_res_txt_start'
main.cpp:(.text+0x1b): undefined reference to `_binary_res_txt_end'

I did: cmake -Bbuild -H. && cmake --build build and my "project" structure looks like this:
├── CMakeLists.txt
├── res.txt
└── src
    └── cpp
        └── main.cpp

My observations and things that I have done so far:

*

*When I compile with command line nm main shows that objects are initialized
0000000000601050 D _binary_res_txt_end
000000000000000c A _binary_res_txt_size
0000000000601044 D _binary_res_txt_start

*When I compile it with CMake then those objects are not initialized:
U _binary_res_txt_end
U _binary_res_txt_start

*It looks like CMake ignores linker option that I have passed, so I tried also with LINK_FLAGS, so I removed -Wl ... from COMPILE_FLAGS_MAIN and I modified set_target_properties call to:
set_target_properties(${app_name} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${BIN_DIR}
                                                    COMPILE_FLAGS ${COMPILE_FLAGS_RELEASE}
                                                    CXX_STANDARD ${CPP_STD}
                                                    CXX_STANDARD_REQUIRED ${CPP_STD_REQUIRED}
                                                    CXX_EXTENSIONS ${CPP_EXTENSION_REQUIRED}
                                                    LINK_FLAGS "-Wl,--format=binary -Wl,${PROJECT_SOURCE_DIR}/res.txt -Wl,--format=default")

So here when I pass file that does not exist, linker cries that's why I used PROJECT_SOURCE_DIR but still does not work.

*

*When I pass wrong path to file in COMPILE_FLAGS_MAIN then nothing happens.

Can anybody help me with this? I am not sure what wrong I am doing.

A: Instead of shoehorning the custom resource into your link flags, you could create a separate build rule for it: (idea taken from here)
add_custom_command(
        OUTPUT res.o
        COMMAND ld -r -b binary -o res.o res.txt
        DEPENDS res.txt)
add_executable(${app_name} ${sources} res.o)


text:
Q: Can't get the data from nested components within dynamic zones Related to Strapi forum -> https://forum.strapi.io/t/resolved-cant-get-the-data-from-nested-components-within-dynamic-zones/15896/3
Is there any elastic way to request dynamic zones via Graphql without explicitly defining each of them in a query?
For example, I DON'T want to do something like this:
query Homepage {
  components {
    ... on SliderComponent {
      image
      text
    }
    ... on ParagraphComponent {
      title
      description
    }
    // and so on...
  }
}

Instead, somehow, I'd like to be able to get all of the dynamic zones without querying them separately.
So ideally would be something like this:
query Homepage {
  components
}

and that would return all of the possible dynamic zone components with their nested fields.
The best scenario is to query all the nested data within the dynamic zones using something like in RestApi http://localhost:1337/api/pages?populate[dynamiczones]
NOTE: I know that the queries above are not correct, but this is just an idea of the query shape.


text:
Q: Is there a way to create a flickering frequency to be dependent on speed of the person looking at it? Is there a way to  make a screen or a road sign flash at different rates, depending on the velocity of the observer looking at it?

*

*I would like to achieve a state where two observers going at different speeds would see the screen flash at different rates at the same time.

*another thing i would like to check if possible is - is there a way to make the observer see a different image depending on his/her velocity? (without a radar).

A: You can use a reflector with gaps.  Then the light from a car will alternate between reflecting and not reflecting at a rate dependent on their velocity towards the reflector.  Please excuse my crude diagram:

As the car moves right to left, gaps in the reflector will cause it to appear to flash on an off.

A: Due to the speed of light, the "dopler shift" would be too small, at the usual speed of the observers.


text:
Q: problem installing mysqldb for python2.6 My mysql database is located on a remote machine... So i dont have any local copy of mysql on my local machine.. i get the registry key error... (file not found)...
serverKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, options['registry_key'])
WindowsError: [Error 2] The system cannot find the file specified

I think it requires to have a local copy of mysql... How do i install the mysqldb for database residing on another machine???

A: You will indeed need a local copy of MySQL in order to compile the MySQL extension for Python. This page seems to contain a step-by-step guide for Windows.
However, you might have some luck with a pre-compiled MySQL module. This should work for Python 2.6.


text:
Q: Jenkins installation windows 10 "Service Logon Passwords" |I have added Administrator User in Local Policy-logon Services but dont know password I am new to jenkins.
1.I downloaded Jenkins from https://www.jenkins.io/download/
2.Added Administrator User to Log on services
3.Now what password should I enter to login in to Jenkins.


text:
Q: Changing values of imported variables in JS. One method works, the other doesn't, why is so? This works:
//a.js
export let x = false;

export function toggle_x() {
  if (x) {
    x = false;
  } else {
    x = true;
  }
}

//b.js

import {x, toggle_x} from {'/a.js'}
toggle_x()
console.log(x) //outputs true, great!

This does not work:
//a.js
export let x = false;

export function toggle(v) {
  if (v) {
    v = false;
  } else {
    v = true;
  }
}

//b.js

import {x, toggle} from {'/a.js'}
toggle(x)
console.log(x) //outputs undefined

Why? I want to create a function to toggle between true/false the entered variable.
Thanks!


text:
Q: offsetHeight not working properly in chrome I come across a funny problem. I don't know the what could be the reason. I tried to search on internet but no solutions I got. The problem is offsetWidth is working perfect in Chrome but offsetHeight is not working properly. Sometime it returns the value but sometime not. May I know is there any solution to sort out this issue.
Note: I have tried to use id.height, id.clientHeight. But all are giving me the same problem. In my projects we use Prototype and JQuery also.
I have used prototype getHeight() also.. but not working in Chrome. getWidth() is working perfect. But all these are working well in Firefox... :(
This is the code block
$('leftImage_<?php echo $iExtLoop; ?>').style.position="relative";
$('leftImage_<?php echo $iExtLoop; ?>').style.left= ($('leftImageDiv').offsetWidth - $('leftImage_<?php echo $iExtLoop; ?>').offsetWidth)/2 + "px";
$('leftImage_<?php echo $iExtLoop; ?>').style.top= ($('leftImageDiv').offsetHeight - $('leftImage_<?php echo $iExtLoop; ?>').offsetHeight)/2 + "px";

if($('stripLeft_<?php echo $iExtLoop; ?>')){
    $('stripLeft_<?php echo $iExtLoop; ?>').style.position="relative";
    $('stripLeft_<?php echo $iExtLoop; ?>').style.left= ($('leftImageDiv').offsetWidth - $('stripLeft_<?php echo $iExtLoop; ?>').offsetWidth) + "px";
    $('stripLeft_<?php echo $iExtLoop; ?>').style.top= ($('leftImageDiv').offsetHeight - $('stripLeft_<?php echo $iExtLoop; ?>').offsetHeight) + "px";
}

Refactored code, added by Šime Vidas:
var img = $( 'leftImage_<?php echo $iExtLoop; ?>' );
var div = $( 'leftImageDiv' );
var strip = $( 'stripLeft_<?php echo $iExtLoop; ?>' );

img.style.position = "relative";
img.style.left = ( div.offsetWidth - img.offsetWidth ) / 2 + "px";
img.style.top = ( div.offsetHeight - img.offsetHeight ) / 2 + "px";

if ( strip ) {
    strip.style.position = "relative";
    strip.style.left = ( div.offsetWidth - strip.offsetWidth ) + "px";
    strip.style.top= ( div.offsetHeight - strip.offsetHeight ) + "px";
}

A: Since at least one of the elements appears to be an IMG element, I'm guessing that the element has not finished loading by the time that code is executed.
Images have to be retrieved separately (by the browser), so you have to make sure that you read their height only after they've finished loading.


text:
Q: How do the different difficulty levels vary? The differences between the difficulties in XCOM:EU  was well known, but I can't find any information on how they differ in XCOM 2. The differences are probably all stored away in config files, but I haven't had time to dig through them yet.
How do the different difficulty levels vary?

A: AI
On difficulties below Legend, AI will hold back if you pull too many enemies at once:

*

*On Rookie any additional enemies after 4 will do "non-aggressive behavior", such as overwatch, movement to flanking or defensive position without attacking or just skip a turn

*On Veteran and Commander - after 6 enemies

*On Legend - no holding back

Targets selection logic depends on the difficulty as well:

*

*On Rookie and Veteran, AI is more likely to spread attack over different targets

*On Rookie and Veteran, the first variation of Advent Commanders you encounter (called M1 internally) will never throw grenades

Source: defaultai.ini. I didn't do in-game testing of this.

A: They vary a lot. The below is by no means an exhaustive list; it contains just the highlights of what I've found from perusing the INI files and a bit of the code.
Aim cheating
Found in: XComGameCore.ini, AimAssistDifficulties
On every difficulty except Legend, the game applies a number of modifiers to both your attacks and the aliens' attacks. There are five categories:

*

*Base aim multiplier (Rookie and Veteran): Your shots have an invisible multiplier applied to make it easier to hit.

*Miss streaks (Rookie, Veteran, and Commander): For each consecutive miss in a turn, your soldiers are given an invisible aim bonus.

*Hit streaks (Rookie only): The aliens take a penalty to aim for each consecutive hit they have in a turn.

*XCOM hit chance for dead soldiers (Rookie and Veteran): For each soldier you've had die on the current mission (below 4 soldiers), your soldiers are given an invisible aim bonus.

*Alien hit chance for dead soldiers (Rookie and Veteran): For each soldier you've had die on the current mission (below 4 soldiers), the aliens take a penalty to aim.

I'm not sure why Commander gives you a miss streak bonus (which is actually higher than Rookie or Veteran). Judging by the comments in the code, it's an oversight and might get patched out.
Other tactical game tweaks

*

*Enemy stats, mostly health and armor but occasionally also crit chance, dodge, and aim (maybe more)

*How likely your soldiers are to be shaken after a mission, and how many missions it takes to recover from being shaken

*Whether the alien AI goes easy on you; aliens will limit their number of attacks per turn on easier difficulties

*How long it takes your soldiers to heal from injury (significantly longer on Legend)

Strategic game
Found in: XComGameData.ini, all over the place
Almost too much to list here.

*

*Rookie recruiting costs

*Research time, soldier recovery time, and the time to clean rooms on the Avenger

*How quickly the Avatar Project makes progress, especially based on how many facilities the aliens have

*How quickly the aliens adjust their "force level", which influences what enemy types can spawn on missions and what kind of loot you can find

*Whether you get bonus mission reward intel at regular events (Rookie and Veteran only)

*How much rushing research at the Black Market helps you (halved on Legend)

*The chance you'll get given a reward you "need" (e.g. a Scientist or Engineer if you're low on them, or soldiers of a particular class, etc)

*The intel costs of items at the Black Market

*The initial game difficulty and how much difficulty increases month-by-month

*The relative likelihood of which Dark Event you will receive, and how much intel it costs to reveal a hidden Dark Event

*How long it takes to train a rookie, respec a soldier, or complete psi training

*How many corpses you need to complete an autopsy instantly

*How many supplies you get per region per month, and how long it takes to make contact with a region or build a comm tower

Many of the changes are designed so that Legend, which starts out harder, doesn't quickly scale into an unwinnable mess. For example, general difficulty starts higher on Legend, but it grows more slowly than even Veteran does. Legend will still remain ahead of Veteran even with the scaling, though.


text:
Q: Unable to validate the following destination configurations (s3 to SNS) I am trying to setup an event Notification system on s3 to publish notifications to SNS when a file is being uploaded to s3. Here 's how I implemented it via CDK :
import * as sns from "monocdk/aws-sns";
import * as iam from "monocdk/aws-iam";
import {
  GAMMA_ACCOUNT,
  PROD_ACCOUNT,
  UAT1_ACCOUNT,
  UAT2_ACCOUNT,
  PERFECT_MILE_ACCOUNT,
} from "../utils/constants/awsAccounts";
import { Construct } from "monocdk";
import * as s3 from "monocdk/aws-s3";
import * as s3n from "monocdk/aws-s3-notifications";
import { CommonResourceStackProps, Stage } from "../stack/CommonResourcesStack";

export class S3NotificationToSNSCustomResource extends Construct {
  constructor(
    scope: Construct,
    id: string,
    bucket: s3.IBucket,
    stackProps: CommonResourceStackProps
  ) {
    super(scope, id);
    const topic = new sns.Topic(this, "Topic", {
      displayName: "Sherlock-s3-Event-Notifications-Topic",
      topicName: "Sherlock-s3-Event-Notifications-Topic",
    });
    const topicPolicy = new sns.TopicPolicy(this, "TopicPolicy", {
      topics: [topic],
    });

    const s3ServicePrincipal = new iam.ServicePrincipal("s3.amazonaws.com");

    topicPolicy.document.addStatements(
      new iam.PolicyStatement({
        sid: "0",
        actions: ["sns:Publish"],
        principals: [s3ServicePrincipal],
        resources: [topic.topicArn],
        conditions: {
          StringEquals: {
            "AWS:SourceOwner":
              stackProps.stage == Stage.Prod
                ? PROD_ACCOUNT
                : stackProps.stage == Stage.Gamma
                ? GAMMA_ACCOUNT
                : stackProps.stage == Stage.UAT1
                ? UAT1_ACCOUNT
                : UAT2_ACCOUNT,
          },
          ArnLike: { "AWS:SourceArn": bucket.bucketArn },
        },
      }),
      new iam.PolicyStatement({
        sid: "1",
        actions: ["sns:Subscribe"],
        principals: [new iam.AccountPrincipal(PERFECT_MILE_ACCOUNT)],
        resources: [topic.topicArn],
      })
    );

    bucket.addEventNotification(
      s3.EventType.OBJECT_CREATED,
      new s3n.SnsDestination(topic),
      { prefix: "output/reportingData/openItems/", suffix: "_SUCCESS" }
    );
  }
}

But, when I try to deploy this, I am getting the following error : An error occurred (InvalidArgument) when calling the PutBucketNotificationConfiguration operation: Unable to validate the following destination configurations
Can anyone help me with it?
I read this post(https://aws.amazon.com/premiumsupport/knowledge-center/unable-validate-destination-s3/) but its resolution is using the templates and I am implementing using the CDK package. Also I have added all the access policies to publish and subscribe.

A: aws:SourceAccount and aws:SourceOwner are condition keys which are not supported by all services. Amazon S3 notifications use aws:SourceAccount Refer - https://docs.aws.amazon.com/sns/latest/dg/sns-access-policy-use-cases.html#source-account-versus-source-owner


text:
Q: Qué significa el costo en una consulta utilizando EXPLAIN en postgresql? Tengo una consulta que compara el contenido de una tabla foranea contra una tabla local utilizando el EXCEPT. La cosa aquí es que utilicé el EXPLAIN VERBOSE sobre mi consulta y me regresó los siguientes datos.

Aquí mi duda está en el COST. Estuve leyendo y habla algo sobre "unidades de captura de página de disco" pero qué significa eso?
Dice que de los dos números que salen en COST uno es el tiempo mínimo que le toma en regresar el primer dato y el segundo como el tiempo total. Pero tiempo en qué? Milisegundos?
Esos 97794.35 que sale en mi imagen qué significa? Que tomará 97.7 segundos en ejecutarse mi query?
Por cierto, la información que compara de la tabla 1 son casi 1 millón de registros contra mi tabla local que tiene ese millón de registros más otros 30 millones pertenecientes a otra tabla.
Mi consulta es de tipo:
SELECT * FROM tablaforanea1
EXCEPT
SELECT * FROM tablalocal WHERE tipo = 'tablaforanea1'

Muchas gracias

A: El cost es una medida arbitraria en unidades determinada por varios parámetros de configuración y un cálculo basado en las estadísticas de las tablas como por ejemplo la cantidad de filas/paginas, etc, es solo para calcular el valor de un plan de ejecución y deternimar cual es más óptimo, el valor real del tiempo te lo retorna  EXPLAIN (ANALYZE,VERBOSE) que retorna además del plan,  una parte de que te dice el tiempo real, como por ejemplo:
(actual time=0.061..28.848 rows=10000 loops=1)
Ahí si es tiempo de regresar el primer dato y el segundo como el tiempo total, además de la cantidad de rows real retornadas


text:
Q: Datetime to seasons I have an example data as :
datetime.            column1

2021-04-01 01:00.     11
2021-04-05 02:00.     10
2021-04-12 03:00.      1
2021-04-11 04:00.      5
2021-04-07 05:00.      20

I would like to create a new column called season which outputs cooling season if the datetime values is between the month of May and September, while heating season if the datetime values are between october and April. The example output should look like this:
datetime.            column1.  seasons

2021-01-01 01:00.     11.       Heating season
2021-05-01 02:00.     10.       Cooling season
2021-12-01 03:00.      1.       Heating season
2021-11-01 04:00.      5.       Heating season
2021-07-01 05:00.      20.      Cooling season

A: There are many ways,
df['datetime'] = pd.to_datetime(df.datetime)

With np.select with specific conditions for months
conditions = [
    df.datetime.dt.month.isin(np.arange(5,10)),
    (df.datetime.dt.month.isin(np.arange(1,5))) | (df.datetime.dt.month.isin(np.arange(10,13))),
]
choices = ['Cooling season','Heating season']
df['seasons'] = np.select(conditions, choices)
df

With np.select with a default
conditions = [
    df.datetime.dt.month.isin(np.arange(5,10)),
]
choices = ['Cooling season']
df['seasons'] = np.select(conditions, choices, default='Heating season')
df

With np.where
df['seasons'] = np.where(df.datetime.dt.month.isin(np.arange(5,10)), 'Cooling season','Heating season')
df

Output
    datetime            column1     seasons
0   2021-01-01 01:00:00 11      Heating season
1   2021-05-01 02:00:00 10      Cooling season
2   2021-12-01 03:00:00 1       Heating season
3   2021-11-01 04:00:00 5       Heating season
4   2021-07-01 05:00:00 20      Cooling season

A: df["seasons"] = np.where((df["datetime"].dt.month >= 5)
                          & (df["datetime"].dt.month <= 9),
                         "Cooling season", "Heating season")

>>> df
             datetime  column1         seasons
0 2021-01-01 01:00:00       11  Heating season
1 2021-05-05 02:00:00       10  Cooling season
2 2021-12-12 03:00:00        1  Heating season
3 2021-11-11 04:00:00        5  Heating season
4 2021-07-07 05:00:00       20  Cooling season


text:
Q: Default value in sql laravel table I not sure if this is related to Laravel or not but I created the table with Laravel. I've got a table called programmers
DESC programmers;
+--------------+---------------------+------+-----+---------+----------------+
| Field        | Type                | Null | Key | Default | Extra          |
+--------------+---------------------+------+-----+---------+----------------+
| id           | bigint(20) unsigned | NO   | PRI | NULL    | auto_increment |
| name         | varchar(255)        | NO   |     | NULL    |                |
| age          | int(11)             | NO   |     | NULL    |                |
| created_at   | timestamp           | YES  |     | NULL    |                |
| updated_at   | timestamp           | YES  |     | NULL    |                |
| framework_id | int(10) unsigned    | NO   |     | NULL    |                |
| test         | tinyint(1)          | NO   |     | NULL    |                |
+--------------+---------------------+------+-----+---------+----------------+

as you can see there's a column called test that's not nullable and has a default value of null. When I to run the following command from the database I expected an error
INSERT INTO  programmers (name, age, framework_id) VALUES ('Melly2', 19, 2)

it actually worked fine and here's the data
SELECT * FROM programmers;
+----+--------+-----+---------------------+---------------------+--------------+------+
| id | name   | age | created_at          | updated_at          | framework_id | test |
+----+--------+-----+---------------------+---------------------+--------------+------+
|  1 | melly  |  20 | 2022-05-03 16:36:12 | 2022-05-03 16:36:12 |            1 |    0 |
|  2 | Melly2 |  19 | NULL                | NULL                |            2 |    0 |
+----+--------+-----+---------------------+---------------------+--------------+------+

the test column actually defaulted to 0 not null, and if I were to run the following command it tells me I can't have null as a value as expected
INSERT INTO  programmers (name, age, framework_id, test) VALUES ('Melly2', 19, 3, null);
ERROR 1048 (23000): Column 'test' cannot be null

question: can someone briefly explain why test column didn't default to null?

A: In this scenario, the default value is null only if you don't provide a value. But when you provide some value, it should be compatible with the datatype you set for the column.
Here the datatype is tinyint. So, you should provide the values from true/false which infact will be converted into 1/0; else you should insert integers example:0,1,2,... etc.


text:
Q: Why do val and def implement abstract methods at different times? I was working with scala and did something like this:
trait Foo { val a: String }
trait Foo2 extends Foo { val a = "foo" }
trait Bar extends Foo { val b = a + "-bar" }
object Bar2 extends Bar with Foo2

I expected that Bar2.b would be "foo-bar", but it ends up being "null-bar". Bar2.a is "foo" as expected.
If I change from val to def for definitions of 'a' like this:
trait Foo { def a: String }
trait Foo2 extends Foo { val a = "foo" }
trait Bar extends Foo { val b = a + "-bar" }
object Bar2 extends Bar with Foo2

Bar2.b is actually "foo-bar".
In example 2, the def 'a' from Foo2 that implements the abstract one in Foo is put into the definition of Bar2 before the val 'b' is evaluated. In example 1, the val 'a' from Foo2 overrides the val 'a' from Foo after val 'b' is defined in Bar/Bar2.
Why is this the case? Why do val and def implement abstract methods at different times?

A: You always want to use either def or lazy val in traits (rather than just val) to avoid the awkward behavior you discovered.
As for why, which gets to the low-level details of Scala's implementation in the JVM, check out Josh Suereth's excellent talk "Binary Resilience" from Scala Days 2012.

A: It's because there is Java behind. Initialized (non abstract) vals are translated to public getters with private fields and they are initialized in certain order. Abstract vals are just getters. Check Java documentation on this. You may also see early initializers feature of Scala to find a better solution:
In Scala, what is an "early initializer"?
And also order of mixing-in matters. This should give you the right result:
object Bar2 extends Foo2 with Bar


text:
Q: Yii2 - How to add custom error messages on input fields In my database I named 'password' as 'password_hash' so automatically I'd get 'password_hash' in my error message, even tho I changed the label to 'Current password'.
Example:

What I want is:

A: From what you described it seems that you changed the label displayed in the form, not attribute label.
No need to duplicate error message and separate attributes to different rules, for most of the cases changing the attribute label in attributeLabels() method is enough.
That way if you change the language of application, it will show correct error message.
In your model:
public function attributeLabels()
{
    return [
        ...
        'password_hash' => 'Current password',
    ];
}

All default validators take the label of attribute from this section, if it's not defined it will be transformed to "Password Hash".

A: So basically all I did was add
'message' => 'Current password cannot be blank.'

to my rules.
Make sure you seperate the correct rules, so you don't get that message on multiple fields, where it doesn't make sense. Also make sure you add it on the 'required' rule, unless you want that message to show when it's another rule..
I hope this helped you guys, as I spent a bit too much time searching for it.


text:
Q: automatically start voice recording like talking tom on this first word is missing in my code i am using 2 AVAudioRecorder one for monitoring the audio and another one for recording. In that recording is good but problem is the second recorder can't able to record the first 2 words or 2 sec. sample like this suppose i am say like "hi how are you" means it will record the "are you" words. http://purplelilgirl.tumblr.com/post/9377269385/making-that-talking-app with use of this tutorial only i wrote the recording functionality to my code. any one facing this same issue. let me know please regarding on this.

A: I think you should keep recording it all the time with low or high threshold, what you need to do is just, start playing from time when your lowPassResults exceeds to 0.5 in case ajDanny's example.


text:
Q: Is it possible to select a range of cells and include charts? I have an excel sheet that shows a report. I want to take that report, and format it nicely into an email.
I used some very helpful code I found here to get started. It works [almost] great! The only problem is my report in the sheet contains charts, that I would like copied over into the email as well.
Is there a way to get my charts over into the HTML as well? Or into the email body in their rightful positions? I don't think selecting the range and ALSO selecting all charts on sheet would work, and don't think it's even possible to select both at once to process them into the HTML.
Another method I tried was copying the range as a picture, this works but the picture is very small. Is there a way to make it larger? Here is the code for that:
Function emailaspic()

Dim rng As Range

Set rng = Sheets("Report").Range("A1:V182")
rng.Copy

'Open a new mail item
Dim outlookApp As Object
Set outlookApp = CreateObject("Outlook.Application")
Dim outMail As Object
Set outMail = outlookApp.CreateItem(olMailItem)

'Get its Word editor
outMail.Display
Dim wordDoc As word.Document
Set wordDoc = outMail.GetInspector.WordEditor

'To paste as picture
wordDoc.Range.PasteAndFormat wdChartPicture

End Function

Thank you all in advance! I've tried googling this exact scenario and thought it would be common, but haven't found someone who is trying to get the range AND the charts at the same time...


text:
Q: how to plot a sequence of numbers (not co-ordinates as such) using pgfplots I have a data file containing a sequence of numbers, to be plotted against integers starting from 1. So the x co-ordinate is the row number of the data in the file. How to plot this data using pgfplots?
UPDATE1: my data file looks like this
%cmc curve of nist14G21600V0P8T1sumFuse.bin

73.037

75.2963

76.7407

77.8889

79.1111

79.8519

80.3333

80.7407

81.0741

81.4444

UPDATE 2:
When the above data is plotted using the command
\addplot  table [x expr=\coordindex + 1,y index=0]{datafile.txt};

the x axis does not start with 1. It starts with 0. Any suggestions?

A: Based on the new request of @suresh:
pgfplots can read a data file and plot the contents. To use a special column of the data file you can use y index for the y values. The first column has the index 0. For the x axis you can use \coordindex started by 0. To start at 1 you can use \coordindex+1.
\documentclass{article}
\usepackage{amsmath}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\usepackage{filecontents}
\begin{filecontents*}{datafile.dat}
%cmc curve of nist14G21600V0P8T1sumFuse.bin

73.037

75.2963

76.7407

77.8889

79.1111

79.8519

80.3333

80.7407

81.0741

81.4444
\end{filecontents*}
\begin{document}
\begin{tikzpicture}
\begin{axis}
\addplot +[only marks,] table[x expr=\coordindex+1,y index=0] {datafile.dat};
\end{axis}
\end{tikzpicture}
\end{document}

ORIGINAL
You can use the option x expr=\coordindex.
\documentclass{article}
\usepackage{amsmath}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\usepackage{filecontents}
\begin{filecontents}{datafile.dat}
Y-Value
2
5
8
1
5
7
6
\end{filecontents}
\begin{document}
\begin{tikzpicture}
\begin{axis}
\addplot +[only marks] table[x expr=\coordindex,y=Y-Value] {datafile.dat};
\end{axis}
\end{tikzpicture}
\end{document}


text:
Q: Server Side or Client Side Long Polling? What are best practices for long polling?
Currently what I have set up is javascript making an xmlhttprequest to a server with PHP running server side checking if there is anything new and return new content or no new content variable. Then client side will wait for n seconds after receiving the returned value before making another request.
But I'm seeing a lot online with a different approach, that if the server does not have anything new don't return just yet instead wait for n seconds and check again for new content until a certain number of attempts then return new content or no new content and the client side makes a new request right after receiving the returned value.
So with the above 2 which one would be the best approach to give less strain on a server or maybe conserve more server resources? My current setup or the 2nd setup? Or maybe a different approach?
Thanks!

A: Your first option isn't long-polling at all, it's just sending a request every n seconds. Long-polling means you send a request that stays open until a timeout is reached, or new data is available.
Long-polling is better than sending a request every n seconds because the data is closer to real-time without needing to send a request every <less than 10> seconds.
Typically on the server-side you would handle a long-polling request by using a sleep loop that repeatedly checks the db for new data with a short delay, say, 1 or two seconds. So, if you did it with a 2second delay and a 30 second timeout, you'll be hitting that database 15 times per user per 30 seconds.
Yes, long-polling can be resource intensive. You as the developer have to decide how much of the server's resources you can allocate to improve the user experience.
websockets is the go-to solution now days for chat systems because it bypasses this problem, allowing the server to contact the client(s) when there is a change rather than having n clients contacting the server every x seconds asking if something changed. It would normally work by having a "Post Message" command that the client calls when a new message is added by a client, that command would then broadcast the new message to all connected clients.


text:
Q: Make a child occupy 100% of its parent when the parent height is undefined I have a parent container, <DIV>, and two child containers <p> and <a>.
I have applied a float to <p> to make <a> & <p> appear on one line.
I have applied padding to <a> which causes <DIV> to expand in height. I would now like to make <P> occupy 100% of the height of <DIV>. How can I do this?
I know it would work if I assigned a specific height to <DIV> and then set <p> to height: 100%. However, I am trying to make my CSS code re-useable and don't want to hard code heights.
Here is a fiddle.

A: You should not apply float to <p> to make it appear on one line with the div. Use display: inline-block instead.
Fiddle: http://jsfiddle.net/nLX75/5/
floating elements are taken out of the document flow. Therefore they "don't know" about the height of their parents anymore. So you can't really rely on layout properties of a floating element's parents to style it properly.


text:
Q: How to factorise a cubic? What are the steps in factorising a cubic?
For example $x^{3} - 2x^{2} - 7x - 4$
I know that $-1$ is a root so it will start off as $(x+1)$(...something?)

A: Since you know $-1$ is a root you can use Ruffini's rule:

Then $x^3-2x^2-7x-4=(x+1)(x^2-3x-4)$
And you can easily see that $-1$ and $4$ are roots of $(x^2-3x-4)$
Then $x^3-2x^2-7x-4=(x+1)(x^2-3x-4)=(x+1)(x+1)(x-4)$
Note: Before using Ruffini's rule you can also see that $4$ is a root using Rational root theorem

A: Yes, then $\, f = (x\!+\!1)(x^2\!+bx-4)$  $\,\overset{\large x\,=\,1}\Longrightarrow\,-12 = f(1) = 2(b-3)\,\Rightarrow\, b = -3$

A: Since you already know that $x+1$ is a factor, try to extract it i.e
$$x^{3} - 2x^{2} - 7x - 4 = (x^3+x^2) -(3x^2+3x) -(4x+4) $$
$$(x^3+x^2) -(3x^2+3x) -(4x+4) = (x+1)(x^2-3x-4)=(x+1)(x+1)(x-4)$$
Hence you have $$x^{3} - 2x^{2} - 7x - 4= (x+1)(x+1)(x-4) $$

A: I think a numerical approach is possible. By The Fundamental Theorem of Algebra, we know $x^3−2x^2−7x−4=0=(x+1)(ax^2+bx+c)$. So lets, consider $g(x)=\frac{x^3-2x^2-7x-4}{x+1}$
and let
$$x_{n+1}=x_n-\frac{g(x_n)}{g'(x_n)}$$
Start with $x_0=0$ and iterate until $|x_{n+1}-x_n|$ is stable or within some predetermined small value, $\epsilon>0$.
A stable $x_n$ should be a root, call it $r_1$.
then instead of $g(x)$, use $h(x)=g(x)/(x-r_1)$ and iterate. This should give you the second root.
Things need to be adjusted if there are not 3 real roots.


text:
Q: How is it shown using the additive cancellation law that $x\mapsto x+h$ has an inverse? See Fundamentals of Mathematics, Volume 1 page 101, for context.
This is one of those facts that is so obvious that I find it difficult to prove. My question regards part of the proof of the principle of induction beginning with the natural number $k>1$. That principle can therefore not be used to prove the following claim:
Square brackets $\left[\dots\right]$ enclose function parameter lists. Let $\mathbb{N}_{n}\equiv\left\{ x\in\mathbb{N}\backepsilon x\ge n\right\},$ $k=h+1,$ and the mapping $f:\mathbb{N}_{1}\to\mathbb{N}_{k}$ be $f\left[x\right]\equiv x+h.$
From the cancellation law of addition, $a+c=b+c\implies a=b,$ it follows that the inverse mapping $f^{-1}:\mathbb{N}_{k}\to\mathcal{N}\supseteq\mathbb{N}_{1}$ exists.
It is trivial to show by induction that $f$ is one-to-one, and therefore invertable. But I don't know how best to express this in terms of the cancellation law. What comes to mind is to write a cancellation function
$g:\mathbb{N}_{k}\to\mathbb{N}_{1}$ as
$$g\left[a+h\right]=g\left[b+h\right]=a=b.$$
But I'm not sure how to prove the uniqueness and existence of $g$ in a way that doesn't use induction beginning with $k$, and actually makes use of the cancellation law.
What is a good way to show that the mapping $f^{-1}$ follows from the cancellation law?


text:
Q: Excel: How to multiply with blanks cell in range? Formula Work Perfectly, however when I have empty cells in the range A1:A3 I get error: #VALUE! How to fix? Original Post: Excel: Dynamic formula for change unit size in KB, MB, GB, TB, etc... Automatically
Version: 1
=TRUNC(SUMPRODUCT(LEFT(A1:A3,FIND(" ",A1:A3)-1)*10^(MATCH(RIGHT(A1:A3,2),{"KB","MB","GB","TB"},0)*3))/(10^(INT((LEN(SUMPRODUCT(LEFT(A1:A3,FIND(" ",A1:A3)-1)*10^(MATCH(RIGHT(A1:A3,2),{"KB","MB","GB","TB"},0)*3)))-1)/3)*3)),2)&" "&INDEX({"KB","MB","GB","TB"},INT((LEN(SUMPRODUCT(LEFT(A1:A3,FIND(" ",A1:A3)-1)*10^(MATCH(RIGHT(A1:A3,2),{"KB","MB","GB","TB"},0)*3)))-1)/3))

Version: 2
=TRUNC(SUMPRODUCT(A1:A4*10^(MATCH(B1:B4,{"KB","MB","GB","TB"},0)*3))/(10^(INT((LEN(SUMPRODUCT(A1:A4*10^(MATCH(B1:B4,{"KB","MB","GB","TB"},0)*3)))-1)/3)*3)),2)&" "&INDEX({"KB","MB","GB","TB"},INT((LEN(SUMPRODUCT(A1:A4*10^(MATCH(B1:B4,{"KB","MB","GB","TB"},0)*3)))-1)/3))

A: I found a nice guide that helps here.
To sum it up:

To ignore a formula or don't calculate if the specific cell is blank in Excel, we need to check the specific cell is blank or not with IF function, if it's not blank, we can go ahead to calculate with original formula.
=IF(Specific Cell<>"",Original Formula,"")

So you could try this:
=IF(CELL_TO_CHECK_IF_BLANK<>"",INSERT_FORMULA_HERE,"")

A: You will need to add IFERROR to capture the Error that come due to empty cells.
IFERRORForces us to use Ctrl-Shift-Enter to enter the formula and make it an array.  Since I had to use an array entry I changed to SUM to save some typing in this massive formula.
=TRUNC(SUM(IFERROR(LEFT(A1:A3,FIND(" ",A1:A3)-1)*10^(MATCH(RIGHT(A1:A3,2),{"KB","MB","GB","TB"},0)*3),0))/(10^(INT((LEN(SUM(IFERROR(LEFT(A1:A3,FIND(" ",A1:A3)-1)*10^(MATCH(RIGHT(A1:A3,2),{"KB","MB","GB","TB"},0)*3),0)))-1)/3)*3)),2)&" "&INDEX({"KB","MB","GB","TB"},INT((LEN(SUM(IFERROR(LEFT(A1:A3,FIND(" ",A1:A3)-1)*10^(MATCH(RIGHT(A1:A3,2),{"KB","MB","GB","TB"},0)*3),0)))-1)/3))

Being an Array formula it REQUIRES the formula be entered with Ctrl-Shift-Enter instead of Enter when exiting edit mode.


text:
Q: Call two times service
I have this code for when anyone call me store in database but when anyone call me this caused two times saved number and date in the same time,all code for my problem phone service..

CallBlocker = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent)
        {
            telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            Class c = null;
            try {
                c = Class.forName(telephonyManager.getClass().getName());
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            Method m = null;
            try {
                m = c.getDeclaredMethod("getITelephony");
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
            m.setAccessible(true);
            try {
                telephonyService = (ITelephony) m.invoke(telephonyManager);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            telephonyManager.listen(callBlockListener,PhoneStateListener.LISTEN_CALL_STATE);
        }

///acording pnone state
     PhoneStateListener callBlockListener = new PhoneStateListener()
        {
            public void onCallStateChanged(int state,String incomingNumber)
            {
                if (state == TelephonyManager.CALL_STATE_RINGING)
                {

                    if (blockAll_cb.isChecked() && sarjda)
                    {

                        Toast.makeText(getApplicationContext(), incomingNumber, Toast.LENGTH_SHORT).show();
                        telephonyService.endCall();
                        phoneNo = incomingNumber;

                        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy  HH:mm:ss");
                        String tarih = sdf.format(new Date());
                        gelenArama.createGelenArama(new GelenAramaItem(phoneNo, tarih));

                        Timer timer = new Timer();
                        TimerTask timerTask = new TimerTask() {
                            @Override
                            public void run() {
                                triggerNotification();
                            }
                        };
                        timer.schedule(timerTask, 20000);
                    }

                }
            }
        };

    };
    IntentFilter filter = new IntentFilter("android.intent.action.PHONE_STATE");
    registerReceiver(CallBlocker, filter);

A: According to this, it might happen if your CallStateListener isn´t declared static.
From TelephonyManager.CALL_STATE_RINGING calls twice while one call ringing:

public class ServiceReceiver extends BroadcastReceiver {
    static CallStateListener phoneListener;

    @Override
    public void onReceive(final Context context, Intent intent) {

        if (phoneListener == null) {
            phoneListener = new CallStateListener();
            TelephonyManager tm = (TelephonyManager)context.getSystemService("phone");
            tm.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
        }

    }

}


text:
Q: UITableView inside UITableViewCell - didSelectRowAtIndexPath I am making an interface which have UITableView with four custom UITableViewCell's. And every other UITableViewCell have also UITableView. This mean I have TableView inside a TableView.
Let me call first tableView - ParentTableView and nested tableView - ChildTableView. So I implemented method didSelectRowAtIndexPath on both tableView's. But when the app is running, only the method of the ChildTableView is being called. I need to know inside the ParentTableView, which cell is being tapped.
How can I transfer that information further from ChildTableView to ParentTableView.
This may be a silly question, but I can not find any reliable solution so far, so please help me.
Thank You in advance, kind Sir

A: First, I think nested table views is a bad idea. But I don't know your use case, so it might be an exception.
The table view controller class used inside a cell have its own @protocol definition and set the outer table view as its delegate. In the inner didSelectRowAtIndexPath: it can inform the outer table view about the selected indexPath, its own indexPath and any other information you might want to transmit.

A: Try using collection views. You can do a layout that works like a regular table view and then in the cells that need to have a table, you can make those separate cells with another collection view inside or a table view inside of it.
As mentioned before, it's not easy doing table views inside of cells, and it can be very tricky to get things to work correctly.
This is an old tutorial I wrote which may help and be of guidance. But since then there's been collection views and auto layout, so keep in mind it's very old.


text:
Q: XPath "how many elements in node?" with Microsoft EXCEL I'm trying to use Microsoft Excel's FILTERXML function to grab data from an XML form.
I'm not quite sure why I'm unable to get a number response when I use certain XPath arguments.
Here's my XML:
<result>
<status>1</status>
<num_results>1</num_results>
<total_results>500</total_results>
<results_remaining>499</results_remaining>
<matches>
    <match>
        <radiant_team_id>0</radiant_team_id>
        <dire_team_id>0</dire_team_id>
        <players>
            <player>
                <account_id>141684701</account_id>
                <player_slot>0</player_slot>
                <hero_id>0</hero_id>
            </player>
            <player>
                <account_id>4294967295</account_id>
                <player_slot>1</player_slot>
                <hero_id>0</hero_id>
            </player>
            <player>
                <account_id>4294967295</account_id>
                <player_slot>2</player_slot>
                <hero_id>0</hero_id>
            </player>
        </players>
      </match>
   </matches>
</result>

I'm trying to use this XPath argument to count how many players pop up in a dynamic API that refreshes an XML form every so ofter. The player count varies from 0-10.
/result/matches/match/players[count(player)]

I get a #!VALUE error. Here's the MS Excel function argument I use:
=FILTERXML($A$2,"/result/matches/match/players/player[count(player)]")

Both arguments fail. Is there a way I can report how many player elements exist in the XML form by reporting to another cell in MS Excel?

A: Why not use regular expressions instead?
<player>((?:.|\n)*?)</player>

Will get you all player tags and no wrestling with XPath.
Inside this tag you can get the remaining ones e.g.
<account_id>((?:.|\n)*?)</account_id>

You can either use the VBA CreateObject("VBScript.RegExp") objects:
http://msdn.microsoft.com/en-us/library/ms974570.aspx
Or I also created an addin with an embeded Excel UDF function  - "GetRegex" (a function u can use just as the FilterXML in Excel). See here:
http://blog.tkacprow.pl/excel-tools/excel-scrape-html-add/
An example to get the first player tag:
=GetRegex(A1;"<player>((?:.|\n)*?)</player>";0)

An example to get the second player tag:
=GetRegex(A1;"<player>((?:.|\n)*?)</player>";1)

You can nest them also:
=GetRegex(GetRegex(A1;"<player>((?:.|\n)*?)</player>");"<account_id>((?:.|\n)*?)</account_id>")

e.g. to get the first account_id.


text:
Q: Insert or Update with LINQ to Entity I am trying to use Linq to Entity as my DAL for a new project.
In my DAL I have this method to get the Job Entity
    public Job LoadJob(int id)
    {
        Job job = new Job();

        using (TNEntities context = new TNEntities())
        {
            var jobEntity = (from c in context.Jobs
                      where c.id == id
                      select c).First();

            job = (Job)jobEntity;
        }

        return job;
    }

I use the Job entity in my program and then I would like to save it:
I have tried a few different things, but currenlt my method looks like this (it does not work)
    public void SaveJob(Job job)
    {
        using (TNEntities context = new TNEntities())
        {
            context.Jobs.AddObject(job);
            context.SaveChanges();
        }
    }

I have tried context.jobs.attach(job) which does not throw an error but it does not update my Job. I assume its because the Job is out of Context as its out of scope of the using context. But Im not sure how to re-attach it so it updates the job that I selected in my first method.

A: Ideally, you want to read your job from a context, make changes, then call SaveChanges on the same context you originally read it from.  It might (should) be possible to attach the modified entity to a new context, and set its status to modified, but I've found modified child objects are mistreated with this approach.
One of the easier approaches is to have all of these operations in a DataAccess object that has one instance of your TNEntities context, and uses it to read your job entity, and save changes.
public class JobDao : IDisposable {

    TNEntities context = new TNEntities();

    public Job LoadJob(int id)
    {
       return this.context.Jobs.First(c => c.id == id);
    }

    public void Save(){
       this.context.SaveChanges();
    }

    public void Dispose(){
        this.Context.Dispose();
    }
}

(of course you'll want to put a lot of that boilerplate code into a base class)
using(JobDao dao = new JobDao()) {
   Job j = dao.LoadJob(12);
   j.JobTitle = "Software Developer";
   dao.Save();
}

A: I would suggest you consider leaving a property in your application.xaml.cs like
public TNEntities context {get; private set;}

which has its TNEntities initalized at startup.  It will make your life easier.


text:
Q: Struggling to compile gdal with hdf4 support I am unable to compile gdal with hdf4 support using bash on a mac osx el capitan version 10.11.6.  I began with the homebrew approach to building gdal described on the osgeo website.  Unfortunately, hdf4 is not by default supported by gdal.  The hdf format page includes a great description of the hdf4 data structure but fails to help getting support for gdal.  I've installed the szip, zlib, and jpeg libraries discussed here, and reviewed the struggles described by /u/dschneiderch here.  The github thread lead me to a final link, which is the basis for my current post.
Using homebrew, I have installed hdf4 (brew install homebrew/versions/hdf4 returns a warning that versions was deprecated and homebrew will use science instead).  I've been fighting with this gdal problem for a while, and sure enough, homebrew/science/hdf4-4.2.11_2 already installed.  So, I linked hdf4 using brew link -overwrite-hdf4, and a warning comes back that it's already been linked.
I used brew remove gdal to start fresh with the install, then followed Shaun's approach in the sig-geo listserv to complete the gdal installation.  Thus, my total workflow was:
brew tap homebrew/versions
brew install hdf4
brew link --overwrite hdf4
brew install gdal --complete --enable-unsupported --with-hdf4

Unfortunately, even after linking the overwrite, I get a warning: Warning: gdal: this formula has no --with-hdf4 option so it will be ignored!.  The installation continues, though, and homebrew is able to build gdal.
Checking gdalinfo --formats, hdf4 is still not included in the list.  Any tips for what else to try?

A: I've made some progress using this source, in that gdalinfo --formats' now includes HDF4 as a supported product. However, using pyModis to download data, I still pull a GDAL installation has no support for HDF4, please update GDAL` error.
Importantly, though, after installing Macport the following code works well for installing GDAL on Mac with HDF4 support:
 sudo port install gdal +hdf4 +hdf5 +netcdf


text:
Q: 2D vector issue in c++ this is part of a larger basic minesweeper program. In the main cpp file of this program, I am loading all of the values of a matrix into a 2d vector of type int. Basically this matrix is filled with 1's and 0's which will be used to indicate whether a mine is there or not. I have confirmed through cout's that both the original vector and the referenced vector are outputting the matrices I loaded into them.
I have create a struct cell which contains 3 various conditions that it can be in. I have created a 2d vector of type cell which basically creates 3 vectors simultaneously. I am having trouble loading the referenced vector's values of 1's and 0's into minesweeperBoard[i][j].isMine.
Here is my code:
include <iostream>
include <vector>

using namespace std;

struct cell{
int state;                      //( 0 hidden, 1 revealed, 2 marked)
int value;                      //(-1 mine, 0 no surrounding, # > 0 number of surrounding mines)
bool isMine;
};

void minesweeper(int row, int col, int numOfMines, vector<vector<int> >&mineField) {

rowNum = row;
colNum = col;
minesNum = numOfMines;

    int temp;

for (int i = 0; i < rowNum; i++) {
        for (int j = 0; j < colNum; j++) {
        temp=mineField[i][j];
            if (temp ==0) {
                minesweeperBoard[i][j].isMine = false;  //will set minesweeper to false if the condition is met
            }
            else {
                minesweeperBoard[i][j].isMine = true;   //wil set minesweeper to true if the condition is met
            }
        }
    }
}

The program is compiling but throws an error once it reaches this point. What am I doing wrong is this not how I should transfer the states to the isMine vector.
In my main, I open the file and read several pieces of data, the rows, columns, and amount of mines. Then the file contains a giant matrix of said rows and columns which I feed into the vector. I then pass the vector. Keep in mind that the original void function is actually a class member hence the declaration in the main resembling that. I hope I'm not confusing you guys.
 file >> rows >> columns >> mines;

//declare mine field vector of int
vector<vector<int> > mineField(rows, vector<int> (columns));

//Set's the elements of the .txt matrix to an array
for (int i = 0; i < rows; i++){
    for (int j = 0; j < columns; j++){
        file_difficulty >> mineField[i][j];
    }
}

minesweeper:minesweeper play(columns, rows, mines, mineField);

Just realized that minesweeperBoard is not declared at all in either the constructor or the other function.

A: Let me guess: you have inverted the order of rows and columns in this declaration
minesweeper:minesweeper play(columns, rows, mines, mineField);

and should be
minesweeper:minesweeper play(rows, columns, mines, mineField);


text:
Q: How can I compare variables and set a variable to new text found in one of the variables in c# I need to compare files found in a directory with another directory and print the files new files found in a directory into the console. I have it setup so it takes the files and assigns it to a variable. The other directory is assigned to another variable. How can I print the new data in one of the variables to command prompt?
The language I am using is c#.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Write the path of the old file folder: ");
            string path = Console.ReadLine();
            listFilesFromDirectory(path);

            Console.Write("Write the path of the new file folder: ");
            string pathTwo = Console.ReadLine();
            listFilesFromDirectoryMore(pathTwo);
            Console.WriteLine("Press Enter to continue:");
            Console.Read();
        }

        static void listFilesFromDirectory(string workingDirectory)
        {
            // get a list of files in a directory,
            // based upon a path that is passed into the function
            string[] filePaths = Directory.GetFiles(workingDirectory);
            foreach (string filePath in filePaths)
            {
                // use the foreach loop to go through the entire
                // array one element at a time write out
                // the full path and file name of each of the
                // elements in the array
                Console.WriteLine(filePath);
                string oldfile = (filePath);

            }
        }

        static void listFilesFromDirectoryMore(string workingDirectoryTwo)
        {
            // get a list of files in a directory,
            // based upon a path that is passed into the function
            string[] filePathsTwo = Directory.GetFiles(workingDirectoryTwo);
            foreach (string filePathTwo in filePathsTwo)
            {
                // use the foreach loop to go through the entire
                // array one element at a time write out
                // the full path and file name of each of the
                // elements in the array
                Console.WriteLine(filePathTwo);
                string newfile = (filePathTwo);

            }
        }
    }
}

A: using System;
using System.Collections.Generic;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Write the path of the old file folder: ");
            string pathA = Console.ReadLine();

            Console.Write("Write the path of the new file folder: ");
            string pathB = Console.ReadLine();
            Console.WriteLine("Press Enter to continue:");

            List<string> folderA = new List<string>();
            foreach (string filePath in Directory.GetFiles(pathA))
            {
                folderA.Add(Path.GetFileName(filePath));
            }

            List<string> folderB = new List<string>();
            foreach (string filePath in Directory.GetFiles(pathB))
            {
                folderB.Add(Path.GetFileName(filePath));
            }

            Console.Write("New files in folder" + pathA + " : ");
            Print(folderA, folderB);

            Console.WriteLine("------------------------------------");

            Console.Write("New files in folder" + pathB + " : ");
            Print(folderB, folderA);

            Console.Read();
        }

        static void Print(List<string> lstA, List<string> lstB)
        {
            foreach (string fileName in lstA)
            {
                if (!lstB.Contains(fileName))
                {
                    Console.Out.WriteLine(fileName);
                }
            }
        }
    }
}


text:
Q: On clicking Highlight background of div in master page The master page have some link.The static part has a list of anchor.onclick the content part is change.
How to make a highlight to the click anchor tag?
e.g
master page content
HOME   PROFILE  MASSEGES

content part here

I want to change the background when I clicking perticular anchor tag. on the static view.
Suppose this is the code in masetr page. static code for all pages.

Home

Profile

Messeges

I want to clicking on particular event, the background of that anchor has to change.

A: You could use jQuery for this.
$("#yourTagId").click(function(){
    $("#yourTagId").css('background-color','yellow');
});

In your case you should give al li tags an unique ID


text:
Q: Having permission issues when using itext7 to convert PNG files to PDFs, some commands seems to have access others dont https://itextpdf.com/en/demos/convert-image-to-pdf-free-online
I got the demo code on how to do it from their site, I am building this in c# visual studio, with selenium/ nunit
It seems pretty straight forward, but im getting some issue that I dont understand. Here is my code:
using System;
using iText.IO.Image;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
namespace TesingPDFConvert
{

        internal class Program
        {
            private static string ORIG = @"C:\Users\$username\Documents\c_projects\SeleniumScreenshots";
            private static string OUTPUT_FOLDER = @"C:\Users\$username\Documents\c_projects\pdf_output\";

            public static void Main(string[] args)
            {
                PdfDocument pdfDocument = new PdfDocument(new PdfWriter(OUTPUT_FOLDER + "ImageToPdf.pdf"));
                Document document = new Document(pdfDocument);

                ImageData imageData = ImageDataFactory.Create(ORIG);
                Image image = new Image(imageData);
                image.SetWidth(pdfDocument.GetDefaultPageSize().GetWidth() - 50);
                image.SetAutoScaleHeight(true);

                document.Add(image);
                pdfDocument.Close();
            }
        }
    }

When I run this, I am getting access denied to the SeleniumScreenshots folder, but the other folder (pdf_output) seems to have access. If i change the folder to the pdf_output folder to get the images from there, im still getting access denied, however, it is writing the empty pdf to the output folder so it seems to have access. I tried changing the folders from "Read only" attribute but its not saving for some reason, I dont think thats the issue cause ive written to my documents folder in other selenium or c# projects and havent had issues. My thoughts are that im using itext7 wrong.
The goal here is to get grab the PNGs in my SeleniumScreenshots folder and turn them into a PDF and drop in the pdf_outputs folder after running a selenium/nunit test(not seen in code).
After not being able to get it to work with my selenium/nunit project, I opened a new project and set up their code to work(console application) and still had the same results. Im stumped.
I am pretty new to c# and visual studio code/developement in general. Thanks for any help in advance.

A: According to the comment, the solution is as follows:

*

*ORIG is a file name at the end, you can't refer to the folder.

*OUTPUT_FOLDER last refers to the space under the folder, you are missing \.

There is no problem with the code itself.


text:
Q: Implementing disqus on a php blogging website I have this code to include in my php website but I keep getting this error: We were unable to load Disqus. If you are a moderator please see our troubleshooting guide.
I have left trusted domains field empty in disqus dashboard to allow development on localhost.
The id is specific to each post.
<script type="text/javascript">
                var disqus_config = function () {
                var id = <?php echo $_GET['id']; ?>;
                this.page.url = 'localhost/blog/viewimage.php?id='+id;
                this.page.identifier = id;
                };
                (function() { // DON'T EDIT BELOW THIS LINE
                    var d = document, s = d.createElement('script');
                    s.src = 'https://ashexcreations.disqus.com/embed.js';
                    s.setAttribute('data-timestamp', +new Date());
                    (d.head || d.body).appendChild(s);
                })();
            </script>


text:
Q: Loop through multi-dimensional arrays I've found this article on how to loop through multi-dimensional arrays quickly.
I am using Method 6: Nested loops with linear array and single incrementing index.
It says Method 8: Single loop with linear array and incrementing index is faster, but I require nested loops indexes as well. When I try to calculate the nested loops indexes via if clauses, my code slows down (at least worst than nested loop approach).
Can you recommend anything for calculating individual indexes?
 int x1=0,x2=0;
  for (int i1 = 1; i1 <= 10000; i1++){
             for (int i = 0; i < 10000; i++){

            x1++;
            if(x1>=100){
                x1=0;
                x2++;
             }

             if (x1 > 10)
             {
                 a[i] += a[i - 10*1];
             }
             if (x2 < 95)
             {
                 a[i] += a[i + 5*100];
             }
         }
     }

For  multidimensional array structure a[x1][x2]. I want to calculate
a[x1][x2]=a[x1-10][x2]+a[x1][x2+5] which a[x1][x2] is converted to a[x1+x2*100]
Program code
 method 8: 462 ns
method 6 297 ns

Is there a way I can improve this code in terms of speed?

A: Looking at your code, your avoid the two loops by doing its computation yourself which is certainly less efficient than what compiler can do. I would suggest you to keep two loops but spliting the loops to avoid conditions in them so that compiler can transform it to SIMD code.
for(int i=0; i<10; i++) {
    for(int j=0; j<95; j++) {
        a[i * 100 + j] = a[i *100 + j + 5]
    }
}
for(int i=10; i<100; i++) {
    for(int j=0; j<95; j++) {
        a[i * 100 + j] = a[(i - 10) * 100 + j] + a[i *100 + j + 5]
    }
}
for(int i=10; i<100; i++) {
    for(int j=95; j<100; j++) {
        a[i * 100 + j] = a[(i - 10) * 100 + j]
    }
}

Your code will be easier to read.
I didn't test it here but for bigger matrix, performance can be improved thantks to cache locality. Looking at your code, you may use tiling to do it.

A: You are using the wrong index, it should be a[ROWS][COLS] and the index i = row * COLS + col.
Then you don't need the ifs in the inner loop, you can write it like this:
double *v = a + 1000;    // destination
double *c = a;           // source is 10 rows before, using another pointer
                         // to take advantage of proximity in cache
for( x1 = 10; x1 < 100; x1++ ) {
    for( int x2 = 0; x2 < 95; x2++) {
        *v += *c + *(v + 5);
        ++v;
        ++c;
    }
    v += 5;  // skip the last 5 columns
    c += 5;
}

This give me a result of ~130 using the on line compiler at the link you posted


text:
Q: Dataproc - Pyspark - java.lang.ClassNotFoundException - although the dependency jars are in the classpath I'm running PySpark application on Dataproc cluster.
The dependency jars are in a cloud storage bucket.
While creating the cluster I've set the "spark.jars" property to point to the "gs://" path of the jars in cloud storage. In SparkUI for the application, I could see the dependency jars under ClassPath entries. But the Spark application fails with "ClassNotFoundException".
Alternatively I've tried to submit the job using "gcloud dataproc" cli command and passed the jars using "--jars" flag. Still I get the same error.
What am I missing here?


text:
Q: Can't tap button in Sencha I'm developing a mobile app using Sencha Touch. The problem is my button not switch to new view after I tap it.
My code:
view/LoginUsername.js
Ext.define('RibMobile.view.LoginUsername', {
    extend: 'Ext.form.Panel',
    xtype: 'loginusernamepage',
    requires: ['Ext.form.FieldSet', 'Ext.form.Password', 'Ext.Label',
        'Ext.Img'
    ],
    config: {
        title: 'Login',
        items: [{
            /* ? */
        }, {
            xtype: 'button',
            itemId: 'nextButton',
            ui: 'action',
            padding: '10px',
            text: 'Next'
        }, {
            /* ? */
        }]
    }
});

controller/Login.js
Ext.define('RibMobile.controller.Login', {
    extend: 'Ext.app.Controller',
    config: {
        refs: {},
        control: {
            nextButton: {
                // On the tap event, call onNewTap
                tap: 'onPasswordTap'
            }
        }
    },
    //called when the Application is launched, remove if not needed
    launch: function(app) {},
    onPasswordTap: function() {
        // When the user taps on the button, create a new reference of our New view, and set it as the active
        // item of Ext.Viewport
        Ext.Viewport.setActiveItem(Ext.create('RibMobile.view.LoginPassword'));
    }
});

app.js
Ext.application({
    name: 'RibMobile',

    requires: [
        'Ext.MessageBox'
    ],

    controllers: [ 'Main', 'Login' ],

    views: [
        'Contact',
        'Locate',
        'LoginUsername',
        'LoginPassword',
        'Main',
        'Promotion'
    ],
    /* ? */

How can I trigger the button?

A: You miss the mapping between your button and its control.
Add a reference to it and it should work:
refs: {
    nextButton: 'button[itemId=nextButton]'
}