text:
Q: How to disable Launch when ready checkbox when installing appx bundle? For our sideloaded application we need to disable the user to start the UWP application after install or update.
I went through the package manifest and all of the properties without success in finding a way to disable the Launch when ready checkbox and Launch button.
Any idea is appreciated?
Thanks

A:
For our sideloaded application we need to disable the user to start the UWP application after install or update.

For your requirement, we suggest your add splash screen for the app. And store current app's version to LoclSetting, when you launch the app please compare current version with LocalSetting value in the splash screen, if they are different, you could hidden DismissSplash button that make app will not navigate main page.
public static string GetAppVersion()
{
    Package package = Package.Current;
    PackageId packageId = package.Id;
    PackageVersion version = packageId.Version;

    return string.Format("{0}.{1}.{2}.{3}", version.Major, version.Minor, version.Build, version.Revision);
}

A: I am afraid it's not possible to modify or customize the installation UI to hide the Launch button or disable the Launch when ready checkbox.
Custom installation dialogs are not supported when using MSIX or APPX.


text:
Q: C# "ORA-12154: TNS:could not resolve the connect identifier specified"} First I have searched other posts which I have not found one that matches my issue.
I using Oracle.ManagedDataAccess version 4.122.1.0
my app.config file connectionstring is
<add name="connstring1" connectionString="Data Source=NAMEOFTNS;User ID=**UserNAME**;Password=***pass***;" providerName="Oracle.ManagedDataAccess.Client"/>

OracleConn = OracleProviderFactory.CreateConnection();
            OracleConn.ConnectionString = ConfigurationManager.ConnectionStrings["connstring1"].ConnectionString;
 OracleConn.Open();

it is at the  OracleConn.Open(); that I get the error
ORA-12154: TNS:could not resolve the connect identifier specified

I have tested the TNSNAME with TNSPING and it comes back fine.
I can put the connection information from the TNS file and replace the TNSNAME in the connection string with the connection info and it works fine. The issue though is we need this to work by the TNS file so that we only have to update the single file when ever we perform updates with the different severs versus changing all of the app config files for each of our applications.
most suggestions are to bypass the TNS file entirely and put the connection info directly into the app.config file but as mentioned above that is not what I am looking for.

A: Found my answer, although not specifically using Oracle.ManagedDataAccess
instead using Oracle.DataAccess
found the answer at the link below
After the OracleCommand instantiation you have to OracleCommand.BindByName = true;
my specific code is
OracleCommand oracleCommand = new OracleCommand
        {
            BindByName = true
        };

I have to say I am surprised that Oracle requires you to specify to use the TNS file instead of having that as a default
http://www.oracle.com/technetwork/topics/dotnet/code-154692.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: Do Jedi pay taxes? Inspires by the comments in this question.
Is any money given to the Jedi Order taxed, or are they tax-free being that they're supposed to be the defenders of the Republic? Or do they not own money, and thus can't be taxed?

A: The Jedi had money-they've used it at several points in the series(Ep 1, Qui-Gonn paying for ship parts with republic credits). But there is 0 mention of them paying any kind of taxes. In fact, there is more evidence pointing to Jedi receiving taxes in some small amount.
We know that a lot of Jedi don't sleep at the Temple, which means they had to get their housing somehow. We know that no one ever comes to collect a monetary debt from a Jedi. We know Jedi are the Peacekeepers of the Galaxy, which hints at some kind of special police or military force. And we know they deal with high members of political standing, so it would be logical to deduce that Jedi don't pay taxes because they are received for the kind of work they do-risking their lives so others don't have to.
They could be paid because of what they do by rich donors, but we never see anyone paying for those services.


text:
Q: How do I access a field in an associated model? I have 2 models that are associated with eachother, every Entry can have one category. Inversely I guess that Category could also have many entries.
class Entry < ActiveRecord::Base
  has_one :category
end

class Category < ActiveRecord::Base
  belongs_to :entry
end

My Schema for the two models looks like this:
create_table "categories", :force => true do |t|
  t.string   "name"
  t.text     "description"
  t.datetime "created_at",  :null => false
  t.datetime "updated_at",  :null => false
end

create_table "entries", :force => true do |t|
  t.text     "description"
  t.datetime "created_at",  :null => false
  t.datetime "updated_at",  :null => false
  t.text     "address"
  t.float    "longitude"
  t.float    "latitude"
  t.integer  "user_id"
  t.string   "name"
  t.integer  "category_id"
end

My index page is based on @entries.all which currently builds an array of the data taken from the Entry model. My index page shows the category_id which is fine but what would be better, would be to extract the name from the join model of Category.
So if entry.category_id gives me the id how can I get the name?

A: You association looks incorrect. According to your db schema, the relationship is Category has_many entries, and Entry belongs_to Category. If judging from your models, the categories table should have entry_id instead of entries table having category_id.
To refactor, if your logic is to only allow one category per entry, it's easy.
class Entry < ActiveRecord::Base
  belongs_to :category
end

class Category < ActiveRecord::Base
   has_many :entries
end

# Then `entries` table should have one field `category_id`

# To access an entry's category as per you requested:
@entry.category

If your logic is one entry may have more than one entries, you need to use many to many relationship and an intermediate table.


text:
Q: PHP Form Only Submitting Emails From Gmail and No Other Addresses I have an html from. When the user submits the form, I'm sending an email to the given email address using php. Emails to gmail accounts go through perfectly fine. However, mails to providers like yahoo, aol etc does not go through.There is no filter mechanism in my code to filter out email addresses. Some mails to yahoo mail addresses goes through rarely. But aol doesn't go at all. What is the issue here?
My html code:

Get in touch

Leave a comment, review, or general musings.

    <form method="post" id="captcha_form" name=
    "captcha_form" action="mailform.php"><fieldset>

Email address:
    (required)<input type="text" class="solo
    input" name="email" id="email" value="" />

Name:<input type=
    "text" class="solo input" name="name" id="name" value="" />

Subject:
    (required) <input type="text" class=
    "solo input" name="subject" id="subject" />

Message:
    (required)

<textarea class="solo input" name="message" id=
    "message" ></textarea>

<input name="submit" id="submit" type="submit" value="Send" style=
    "float:  right;" />

    </fieldset></form>

And here is snippets of mailform.php:
 <?php
    $dontsendemail = 0;
    $possiblespam = FALSE;
    $strlenmessage = "";
    $email = $_REQUEST['email'];
    $message = $_REQUEST['message'];
    $subject = $_REQUEST['subject'];
    $emailaddress = "email@gmail.com";

    / Check human test input box
    if(isset($_REQUEST["htest"]) && $_REQUEST["htest"] != "") die
    ("Possible spam     detected. Please hit your browser back button
    and check your entries.");
    // Check email address function
    function checkemail($field) {
    // checks proper syntax
    if( !preg_match( "/^([a-zA-Z0-9])+([a-zA-Z0-9._-])*@([a-zA-Z0-9_-])+
    ([a-zA-Z0-  9._-]+)+$/", $field))
    {
        die("Improper email address detected. Please hit your browser back
    button and enter a proper email address.");
        return 1;
    }
    }

    // Spamcheck function
    function spamcheck($field) {
    if(preg_match("/to:/i",$field) || preg_match("/cc:/i",$field)
    ||   preg_match("/\r/i",$field) || preg_match("/i\n/i",$field)
    ||    preg_match("/%0A/i",$field)){
        $possiblespam = TRUE;
    }else $possiblespam = FALSE;
    if ($possiblespam) {
        die("Possible spam attempt detected. If this is not the case, please
    editthe content of the contact form and try again.");
        return 1;
    }
    }

    if ($dontsendemail == 0) {
    $message="";
    $message.="Name: ".$name."\r\n";
    $message.="Mailing Address: \r\nLine 1: ".$addressline1."\r\nLine
    2: ".$addressline2."\r\nCity: ".$city."\r\nState: ".$state."
    \r\nZip:  ".$zip."\r\n";
    $message=$message."\r\nMessage:\r\n".$_REQUEST['message'];
    mail($emailaddress,"$subject",$message,"From: $email" );
    include "email_sent.php";
    echo "Thank you, I will respond shortly.";
}

A: Don't use a regex to confirm email addresses. The real regex is like a day long. Use http://www.w3schools.com/php/filter_validate_email.asp or https://code.google.com/p/php-smtp-email-validation/ or https://github.com/appskitchen/emailverifier/blob/master/class.emailverify.php . You'll notice they are much more complicated than a basic regex. The email spec is insane: https://www.rfc-editor.org/rfc/rfc2822


text:
Q: Angular 4 get queryString Making an angular onboarding page for a corporate website. People will navigate to the page via a link in a welcome email which will contain a user specific token. I need to get this token out of the url querystring and use it in all ajax calls for auth purposes. My problem is reading the querystring.
Angular version is 4.2.4
I have combed through pages of docs on the '@angular/common' Location, LocationStrategy, PathLocationStrategy and have copy pasted the import and adding them to the providers, I get error after error after error. I can't find a simple example anywhere of importing location and using it to get the querystring from the page url. If this were javascript it's a super simple couple lines of code. Why is this so difficult? Any help would be greatly appreciated!
What I tried:
app.module.ts
import { Location, LocationStrategy, PathLocationStrategy } from '@angular/common';

providers: [Location, {provide: LocationStrategy, useClass: PathLocationStrategy}],

page.services.ts
constructor(private location: Location) {
  console.log('location: ', location);
}

A: You can do this using Angular's ActivatedRoute in the @angular/router package. Import it into your module as you do with the others, and inject it into your component as you already are with Location. Then you can access the queryParamMap like:
constructor(private route: ActivatedRoute) {
  console.log(route.snapshot.queryParamMap);
}

That will return a ParamMap interface, which was actually inspired by URLSearchParams interface :)
You can do things like route.queryParamMap.get('myQueryParam') and it works as you would expect.


text:
Q: Java Number error i seen to be having a problem with the line:
int xPos = ((x / maxX) * X_AXIS_LENGTH) + X_AXIS_OFFSET; =

for testing purposes i have assigned:
int x = 10;
int maxX = 52;

but when used in this calculation x / maxX gives me 0 instead of 0.19!
http://s12.postimage.org/uawn8b6l9/image.png

A: You're doing integer division here:
x / maxX

Integer division will truncate the fractional part.
Cast one of the parameters to floating-point to fix it:
(double)x / maxX

You might also want to store the whole thing into a double instead of int:
double xPos = (((double)x / maxX) * X_AXIS_LENGTH) + X_AXIS_OFFSET;

A: Both of the operands for / are integers, so it's performing integer arithmetic. Options:

*

*Use floating point arithmetic:
double xPos = (((double) x / maxX) * X_AXIS_LENGTH) + X_AXIS_OFFSET;

*Multiply before the division, and you can still do everything in integer arithmetic, although you'll need to beware of overflow:
int xPos = ((x * X_AXIS_LENGTH) / maxX) + X_AXIS_OFFSET;

A: Integer division did it to you.
If you expect a floating point value, do it this way:
double ratio = ((double)x)/maxX;

That int type all the way though is a problem.  I'd put more thought into that.  Where do you want to truncate the fractional part?

A: xPos should be declared as double, not an integer.  Otherwise, the data after the decimal point is truncated.


text:
Q: Package not recognized in the program I have installed the package rorolite from the pypi.python.org website directly i.e.without using pip. I extracted the package in python3.6\Lib\site-packages. I am using windows 10. The problem I am facing is when I import this package in my code
import rorolite

I get the error:
Traceback (most recent call last):
  File "E:/all_study/python/project/roro_Test.py", line 1, in <module>
    import rorolite
ModuleNotFoundError: No module named 'rorolite'

Due to some problem which I don't know, I cannot install packages using pip.

A: You extracted it in a wrong way. You have to extract the source archive somewhere else and run pip install . in the extracted directory.
After that verify that you have a directory python3.6\Lib\site-packages\rorolite and have a file __init__.py in it.
Or download a wheel (*.whl) file and install it using pip install rorolite*.whl.

A: As phd said already you can install it like that. If you are in a Linux, depending on your version you may be able to use a native command such as yum to install the package.
If pip does not work/is not found, remember that you may need to be on the folder that has pip to run it.
I hope you can make it work soon!

A: Just using "pip" in the terminal (I'm a Mac user) has never worked for me. Try replacing it with "pip3" instead.


text:
Q: Airflow - Error raised from sqlalchemy when try to run a TaskInstance I'm testing the execution of a crawler inside of the airflow structure. If I ran the following script, everything works fine and the payloads is printed.
from airflow import DAG
from airflow.models import BaseOperator, TaskInstance
from hooks.crawler_hook import CrawlerHook

from datetime import datetime
import time

class CrawlerOperator(BaseOperator):
    def __init__(self, conn_id=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.conn_id = conn_id

    def execute(self):
        hook = CrawlerHook(conn_id=self.conn_id)
        print(hook.run())

if __name__ == "__main__":
    CrawlerOperator(task_id='test_run').execute()

But when I try to run a TaskInstance inside a DAG, I've got the an error and cannot understand why:
if __name__ == "__main__":
    with DAG(dag_id="DAG1", start_date=datetime.now(), catchup=False) as dag:
        to = CrawlerOperator(task_id="test_run")
        ti = TaskInstance(task=to)
        ti.run()

The error:
Traceback (most recent call last):
  File "/home/../.env/lib/python3.8/site-packages/airflow/utils/session.py", line 67, in wrapper
    return func(*args, **kwargs)
  File "/home/../.env/lib/python3.8/site-packages/airflow/models/taskinstance.py", line 1123, in get_dagrun
    dr = session.query(DagRun).filter(DagRun.dag_id == self.dag_id, DagRun.run_id == self.run_id).one()
  File "/home/../.env/lib/python3.8/site-packages/sqlalchemy/orm/query.py", line 3500, in one
    raise orm_exc.NoResultFound("No row was found for one()")
sqlalchemy.orm.exc.NoResultFound: No row was found for one()

Any suggestions?

A: I assume you are using it in some kind of unit test. What you are missing (and as the error indicates) is a DagRun:
from airflow.models import DagRun
DagRun(dag_id=self.dag.dag_id, execution_date=timezone.utcnow(), run_id="test")
ti.dag_run = dag_run

This is needed because tasks are associated to a DagRun not to a DAG.
DAG can have many DagRuns.
You can see example in one of the unit tests in Airflow codebase.


text:
Q: Fluent UI dropdown required not identified I have used the fluent UI dropdown in my form. The dropdown is a required field for me. I have used the "Required Dropdown" from Fluent UI but that doesn't work.
I have tried this
<Dropdown styles={{ title: {},dropdown: {}}} title="" placeholder={} onRenderLabel={} options={} onChange={} required={true} errorMessage={}/>
and this also
<Dropdown styles={{ title: {},dropdown: {}}} title="" placeholder={} onRenderLabel={} options={} onChange={} required errorMessage={}/> but none of them work.
Can someone please help me solve this issue?

A: I am also facing the same issue. Adding Required={true} or aria-required="true" did not help.
Required property- just add an asterisk to indicate it as required field but not validated during submit. This property works as expected in controls like TextField.
Issue screenshot
My code:
render() {
    return (
      <div className='dropdownExample'>
        <form>
          <Dropdown required={true} aria-required="true" label='Required dropdown contrsl'
            options={
              [
                { key: 'A', text: 'Option a' },
                { key: 'B', text: 'Option b' },
                { key: 'C', text: 'Option c' },
                { key: 'D', text: 'Option d' },
                { key: 'E', text: 'Option e' },
                { key: 'F', text: 'Option f' },
                { key: 'G', text: 'Option g' },
              ]
            } />
          <TextField label="Required textfield control" required={true} />
          <button type="submit">Submit</button>
        </form>
      </div>
    );
  }

A: At Fluent UI documentation you have example of Dropdown with error message. This is a basic idea how you can control errorMessage property:
const Options = [
  { key: 'A', text: 'Option a' },
  { key: 'B', text: 'Option b' },
  { key: 'C', text: 'Option c' },
  { key: 'D', text: 'Option d' },
  { key: 'E', text: 'Option e' },
];

const DropdownErrorExample = () => {
  const [dropdownValue, setDropdownValue] = React.useState(null)
  return (
    <Dropdown
      placeholder="Select an option"
      label="Dropdown with error message"
      options={Options}
      errorMessage={!dropdownValue ? 'You need to select a value' : undefined}
      required={true}
      onChange={(_, __, index) => setDropdownValue(Options[index].key)}
      selectedKey={dropdownValue}
    />
  );
};

Codesandbox example.


text:
Q: Can I use a data object as a scope in Angular? My app gets a json object from a server I want this very object to be the scope of my controller, that is without having to remap all its properties to the same properties of a scope. Us there a way to do that?

A: This is not going to work the way you want it to even if you manage to hack it together so that angular accepts it as a scope. The scope does more than just contain data, it also contains the functionality (scope.$watch(), scope.$apply(), etc.) that is needed for basic angular operations like data-binding.
You could just store your data as a variable on the scope in your controller:
$scope.jsonData = JSON.parse(yourJSONData);

then instead of accessing it with yourJSONData.someProperty you would just use $scope.jsonData.someProperty. You won't have to remap any properties.
Adding one extra level of depth to your model is a lot less of a pain than recreating something like the $apply function (for example) on your own data object, which you would need to have defined in order for your model and view to communicate.


text:
Q: Optimize multiple JDBC queries with Spark I am trying to pull incremental data from Greenplum database using Spark. We have incremental data for each table coming with a key called transactionId.
Each transactionId could contain data of one row or many number of rows. All these are stored in a metadata table: incKeyTable.
We also have the last moved transactionID of every table in another metadata table: incKeyLoads. This table contains one entry per table which is the last updated transactionId into the production table.
In order to find out the incremental transactionid for each table, I have come up with the below logic.
val spark = SparkSession.builder().master("yarn").enableHiveSupport().config("hive.exec.dynamic.partition", "true").config("hive.exec.dynamic.partition.mode", "nonstrict").getOrCreate()
import spark.implicits._
Class.forName("org.postgresql.Driver").newInstance()
val tableStatus = s"select tablename, last_update_transaction_id from prod.incKeyLoads where source_system='DB2' and tablename='table1' and final_stage='PROD' and load='Successfull'"
val tableMetaDF = spark.read.format("jdbc").option("url", "url").option("dbtable", s"(${tableStatus}) as LoadedData").option("user", "user").option("password", "pwd").load()
val lutransIdTableMap   = tableMetaDF.map(r => (r.getString(0),r.getLong(1))).collect().toMap

Now I have my last updated transaction ID in a scala Map as below:
lutransIdTableMap.foreach(println) =
(table1 -> 123)
(table2 -> 113)
(table3 -> 122)
...
(tableN -> 098)

To find out the latest transactionId(incremental data) coming greenplum, I have written the following logic to query the metadata table: incKeyTable
Class.forName("com.pivotal.jdbc.GreenplumDriver").newInstance()
def sortLogIds(incTransIds:DataFrame, lastMovedTransId:Long, tablename: String):String = {
    val returnMsg = "Full loads on this table"
    val count = incTransIds.where($"load_type" === "FULLLOAD").count
    if(count == 0) {
      incTransIds.createOrReplaceTempView("incTransID")
      val execQuery  = s"SELECT transactionId from incTransID order by transactionId desc"
      val incLogIdDf = spark.sql(execQuery)
      incLogIdDf.show
      val pushTransIds = "select * from schema.tablename where transactionID in(" + "'" + incLogIdDf.select($"transactionId").collect().map(_.getInt(0).toString).mkString("','") + "')"
      pushLogIds
    } else {
      println("Full load count is greater than zero..")
      returnMsg
    }
}

var incTransIdMap = Map[String, String]()
lutransIdTableMap.keys.foreach(keyTable => if(lutransIdTableMap(keyTable) !=0) {
    val tablename = keyTable.split("\\.")   // Tablename = schema.tablename
    val cdf = spark.read.format("jdbc").option("url", "url").option("dbtable", s"(select transactionId, load_type, source_system, tablename from schema.incKeyTable where source_system='DB2' and target_table='${tablename(1)}' and transactionId > ${lutransIdTableMap(keyTable)}) as controlTableDF").option("user", "user").option("password", "pwd").load()
    incTransIdMap += (keyTable -> sortLogIds(cdf, lutransIdTableMap(keyTable), tablename(1)))
    }
)

This method is working but it is taking so long that I can pull whole data from greenplum on a table level before this search completes as the dataframe cdf is a huge one. I tried to cache the dataframe: cdf but that contains nearly 5million rows and was advised not to cache such big table in to cache.
I couldn't think of other way where I can make this search faster. Could anyone let me know of an idea to make this an efficient process ?

A: The code in the question cannot be what you are actually running because you are returning pushLogIds in sortLogIds, which is never defined, and you are selecting from schema.tablename as opposed to from s"schema.$tablename". This makes it difficult to know for sure what's going on...
That said, from a patterns of big data processing standpoint, there are several potential problems with your approach:

*

*Iteration instead of UNION tranformations. Other things being equal, rather than issuing many separate queries and then assembling the results on the driver, it is preferable to think of ways to issue a single query. This is how the optimizer has a chance to help. In your case, consider creating a Greenplum view that combines all the tables that are in lutransIdTableMap.

*Actions instead of join transformations. In sortLogIds you are executing a count action just to decide whether to run additional queries. Other things being equal, it's better to express this via a join transformation in order to delay running the action. Later you issue a show, which, under the covers is equivalent to take(n). Is this action really necessary? Later you use collect in order to generate a SQL expression to use in an IN operator. This is another example where you should be using a join instead. All in all, you are executing the same Greenplum base query represented by incTransId three times. If you insist on this type of processing, you should absolutely persist incTransId in some way.

*SQL assembly instead of DSL use. As a rule, if you are using Spark via a programming language and not via SparkSQL, you should be using the DSL instead of assembling SQL expressions as strings. This way, you wouldn't need to redefine views, etc.
There is too much to fix here without having the full code and without knowing the exact Greenplum schema + distribution strategy + indexes (if any) and the data sizes involved. However, the above should give you a starting point.
Here is an example of how to switch from using iteration to unions.
val allData = Map("table1" -> 101, "table2" -> 212)
  .map { case (tableName, id) =>
    spark.table(tableName).withColumn("id", lit(id))
  }
  .reduceLeft(_ union _)

Here is an example of how to use joins instead of collect + IN.
val allIds = spark.range(100)
val myIds = spark.createDataset(Seq(11, 33, 55, 77, 99)).toDF("id")
allIds.where('id.isin(myIds.as[Int].collect: _*)) // premature action
allIds.join(myIds, Seq("id")) // inner join delays action

The above example also shows how you can use datasets with collect, replacing, for example, .collect().map(_.getInt(0).toString) with .as[String].collect, which is simpler, safer and faster.
Hope this helps!


text:
Q: Hide a tab previously added to Qt TabWidget I've a dialog which contains a Qt TabWidget with a number of tabs added.
I'd like to hide one of the tabs.
_mytab->hide()

doesn't work.  I don't want to just delete the tab and all its widgets from the .ui file because other code relies on the widgets within the tab.  However, it would be fine to generate the tab code but somehow not ::insertTab in the generated uic_mydialog.cpp.  Setting the hidden property in the ui file does not work either.
I'm using Qt 3.3

A: I would use QTabDialog::removePage(QWidget* pTabPage) which does not delete pTabPage, which is what you want.
_myTabDlg->removePage(_mytab);

I'm using it and it works fine !

A: I had encountered the same problem. I am using the following approach.
Now here is the data.

genTab is the name of my QTabWidget
tabX  is the name of the tab that i want to remove.

(Note that this is the second tab in the Tab Widget. Hence, i will be using "1" as the index to refer to this tab)
The code to remove and add is as below.
ui.genTab->removeTab(1); // removes the tab at the index 1 which is the second tab from left

ui.genTab->insertTab(1, ui.tabX, "<Name of TabX>"); // The tab is added back.

Here, note that it is easy to do this if you have the tab added statically in the design time. Because we will have an object name associated with the tab and hence we can refer to it using, ui.tabX. From what you say, in your case the tab is indeed added statically in the design time.
However, if you are adding the tabs dynamically, then probably you will have to maintain the tabs in a list and then have another list for deletedTabs.
But the first solution will most likely work for you.
Hope this helps.
-Arjun


text:
Q: Open link in background when anchor's attribute "href" contains javascript I support web enterprise-level application with some legacy parts, where some windows are opened by using window.open command inside of anchor's href attribute. (e.g.  ... function MyFunction(url, id) { window.open(url, id) ...)
Now I have to open link in the background tab by pressing ctrl + click (or middle click), but for IE (9, 10, 11) it always becomes focused. Same works fine in chrome.
Here is a link where it can be tested:
<a href="javascript:OpenNewTab('http://google.com', 1)"> Open google tab </a>

OpenNewTab = function(url, id){
    window.open(url, id);
}

http://jsfiddle.net/hj3gud9j/
Are there any ways to open those new tabs in the background (only when ctrl is pressed)?
P.S. I know that it would be better to provide real url inside of href attribute, but unfortunatelly I don't have such options, due to application specific.
Thank you in advace for your help!

A: You can run a piece of javascript everytime the page loads, or every time you request a page (single-page app).
This code is not fully functional but I hope you catch my drift :)
function createListener(url){
    return function(event){
        if(event.ctrlKey){
            console.log(url); //Here you can do anything you want with the url
        }
        event.preventDefault();
    }
}

function runOnce(){
    var allAnchors = document.getElementsByTagName('a');
    for(var i = allAnchors.length; i--;){
        var a = allAnchors[i],
            href = a.getAttribute('href'),
            split = href.split('('),
            url = split[1].split(',')[0];
        a.href = '#';
        a.addEventListener('click', createListener(url));
    }
}
runOnce();

jsfiddle


text:
Q: How can I add function name as route in Laravel 5.7? I have a controller which returns enums for respective fields. e.g.
// Expected route - /api/getFamilyTypes - only GET method is allowed
public function getFamilyTypes()
{
    return [
        'Nuclear Family',
        'Joint Family'
    ];
}

I've around 20 functions like this. How can I add this without manually adding an entry per function in routes file?
Thanks in advance.

A: In your routes file, add something like this,
Route::get('/something/{func}', 'SomeController@functionRoute');

Where something is whatever path you're wanting to use and SomeController is the controller with the 20 functions you're using and functionRoute is the action that we're about to make.
Then in your controller, make a function like this,
public function functionRoute($func)
{
    return $this->$func();
}

This will make it so that whenever someone browses to /something/* on your website, it'll execute the function name at the end. So if you navigate to /something/getFamilyTypes it'll run your getFamilyTypes function.
This isn't particularly secure. If you do this, the user will be able to run any of the controller's methods. You could set up a blacklist like this.
public function functionRoute($func)
{
    $blacklist = [
        'secret',
        'stuff',
    ];
    return in_array($func, $blacklist) ? redirect('/') : $this->$func();
}

Or you could set up a whitelist like this,
public function functionRoute($func)
{
    $whitelist = [
        'getFamilyTypes',
        'otherUserFriendlyStuff',
    ];
    return in_array($func, $whitelist) ? $this->$func() : redirect('/');
}

A: If the responses are always from hard-coded arrays (as opposed to being from a database) then one way might be to have a variable in your route:
Route::get('/api/enum/{field}', 'EnumController@getField');

And then in your controller method, use the variable to get the correct data from a keyed array:
public function getField($field)
{
    $fields = [
        'family' => [
            'Nuclear Family',
            'Joint Family'
        ],
        // ...
    ];

    return $fields[$field];
}

If you want to continue using different methods for every field then Michael's answer is the easiest option, with one caveat. Allowing users to call any method by name on your controller is a security risk. To protect yourself, you should validate the method name against a whitelist.


text:
Q: Linq using string.format on a string array I have a string array.
var array = new string[] { "test", "test2", "test3" };

I am trying to join it into a string with a $ in front of each value in the array see example below.

$test, $test2, $test3

I have been trying to do this using Linq but so far all of my attempts have failed.
My current attempt
var formated = array.Select(a => string.Format("${0}", a)).ToArray();

Results in:

'Index (zero based) must be greater than or equal to zero and less than the size of the argument list.'

I know i have done this before but i cant seam to remember how.  I intended to dump formated into a String.Join unless someone has a better idea.

A: You were close
var formated = array.Select(a => string.Format("${0}", a)).ToArray();

A: You have the wrong index in String.Format, indexes are zero based.
With C#6 you can use string interpolation ...
array = array.Select(s => $"${s}").ToArray();

... to avoid such issues

A: You can do this too,
var newArray = array.Select(x => "$" + x ).ToArray();

A: instead of using string.format in the linq, why not concatenate strings.
var array = new string[] { "test", "test2", "test3" };
var formated = array.Select(x => "$" + x).ToArray();


text:
Q: JPA Date is output to wrong date/time when running on Weblogic server, but displays correctly when running locally embedded Tomcat I have a spring boot application using spring data to retrieve data from an Oracle database.  When I run the code locally in embedded Tomcat, the date appears correctly.  However, the same code when deployed to Weblogic server gives a completely different date/time result.  I have confirmed that the timezone on the Weblogic server is the same as my local timezone (US/Eastern).
What is odd is that the minutes are being stripped out and always set to 00, and also the time difference between the correct date and the date displayed is unpredictable (one example is 16 hours behind, and with a different example, it's 19 hours)
jpa mapping:
import java.util.Date;
...
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "INITIAL_CREATE_DATE")
private Date initialCreateDate;

controller log statement:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm z");
...
log.info("~~create date: " + medley.getInitialCreateDate() + " sdf " + sdf.format(medley.getInitialCreateDate()));

output from Weblogic (WRONG):
~~create date: Thu Oct 26 20:00:00 EDT 2017 sdf 10/26/2017 08:00 EDT

output from local Tomcat and spring data unit tests (CORRECT):
~~create date: 2017-10-27 11:57:53.0 sdf 10/27/2017 11:57 EDT

Two things that stand out to me (besides the date/time being totally wrong)
1. The time is missing the minutes
2. The format is different on the .toString() output for the date
Any help or ideas how I can further troubleshoot this problem are very much appreciated!

A: I figured my problem out - posting my answer, maybe it will help someone else.
My "medley" object was not retrieved directly from the database here.  It was retrieved by a job that then posted this medley object as JSON to this method here that outputs the date.  While I still don't understand the odd date/time behavior, at least now I know the fix.
My previous version of the code was using @Temporal(TemporalType.DATE)
and serializing json as this...
"initialCreateDate": "2017-10-27",

which I don't understand why this was being converted to Thu Oct 26 20:00:00 - but at least I know that applying the @Temporal(TemporalType.TIMESTAMP) in my job fixed the problem. (i.e. updating the version of the repository code in pom.xml to the same version used by the service)
This is the correct serialization of the date/time:
"initialCreateDate":1509119873000


text:
Q: UIScrollView contains more views than exist when looping programmatically I'm resizing my scroll view's content size programmatically.  To do this, I look through all of the views contained within it and get the highest value for the view origin plus the view height, then set my content size to that plus 10.  For some reason, I have a lot of white space at the bottom of my page.  I used an NSLog() to find out what object it thought was this big and found that it is an object that does not even exist.  Here is my code:
- (void)resize_scrollview_to_fit {
    CGFloat scrollViewHeight = 0.0f;
    for (UIView *view in scrollView.subviews) {
        if (view.frame.size.height + view.frame.origin.y > scrollViewHeight) {
            scrollViewHeight = view.frame.size.height + view.frame.origin.y + 10;

            NSLog(@"Scroll View Height: %f \nView Type: %@", scrollViewHeight, view.class);
        }
    }

    [scrollView setContentSize:(CGSizeMake(scrollView.frame.size.width, scrollViewHeight))];
}

The output is:
2014-05-16 10:40:56.757 eTicket[5542:907] Scroll View Height: 175.000000
View Type: UIImageView
2014-05-16 10:40:56.767 eTicket[5542:907] Scroll View Height: 301.000000
View Type: UILabel
2014-05-16 10:40:56.773 eTicket[5542:907] Scroll View Height: 345.000000
View Type: UITextField
2014-05-16 10:40:56.780 eTicket[5542:907] Scroll View Height: 399.000000
View Type: UILabel
2014-05-16 10:40:56.787 eTicket[5542:907] Scroll View Height: 441.000000
View Type: UILabel
2014-05-16 10:40:56.794 eTicket[5542:907] Scroll View Height: 520.000000
View Type: UIImageView

There is only one UIImageView on this page within the scroll view, which is the first item listed.  That second UIImageView does not exist in either code or the storyboard.  The above code should end with the result of 441.  I have no code creating an UIImageView, and the only other 2 UIImageViews in the storyboard are on the same level as the UIScrollView and not within it.  Plus they would result in given 558 if it was seeing them.  So where is this extra UIImageView coming from, and how do I get rid of it?
Thanks,
James
EDIT
Are there really no other solutions for this?  I'd hate for Sasha's answer to be the only way to resolve this.  It just doesn't seem logical that a UIImageView would just be added automatically to a UIScrollView.  If his answer is correct though, can someone confirm it?
Thanks,
James

A: You should keep your own track of subviews, don't rely on scroll view subviews. For example the second UIImageView might be a scroll indicator - an internal view, displayed when you scroll to track position.


text:
Q: How to two column (same table) references to a single column of other table I am new in Stack overflow forum. This is my first question.
I am creating web application using spring mvc with jpa. But I can't over come with this situation as I want both side relationship in entity model. Sorry for my bad English.
Database Structure and data for reference

A: As per your question you want to have a table free product which have withId,toId but both pointing to the same table Product.
In that case, design your Free Product table like below.
@OneToOne
@JoinColumn(name = "withId")
private Product withProduct;

@OneToOne
@JoinColumn(name = "toId")
private Product toProduct;


text:
Q: working with images in pymongo API Im doing a pymongo connectivity program that uses python to create a gridfs database on mongodb and adds an image into the database.I've use command line parser to call the methods.I have successfully added the image in the db and it also reflects in the mongodb db but when I call show function it says image not found.
Here is the code :
import argparse
from PIL import Image
from pymongo import Connection
import gridfs
from bson.binary import Binary
# setup mongo
MONGODB_HOST = 'localhost'
MONGODB_PORT = 27017
# connect to the database & get a gridfs handle
mongo_con = Connection(MONGODB_HOST, MONGODB_PORT)
fs = gridfs.GridFS(mongo_con.ank1)

def add_image():
    """add an image to mongo's gridfs"""
    gridfs_filename = 'ofc2.jpg'
    fileID = fs.put(open('C:\Python27\ofc2.jpg','r'),filename='ofc2.jpg')
    print "created new gridfs file {0} with id {1}".format(gridfs_filename, fileID)

def show():
    """start the flask service"""
    filename='ofc2.jpg'
    if not fs.exists(filename="ofc2.jpg"):
       raise Exception("mongo file does not exist! {0}".format(filename))
    im_stream = fs.get_last_version(filename)
    im = Image.open(im_stream)
    im.show()

def main():
    # CLI
    parser = argparse.ArgumentParser()
    parser.add_argument('--show', action='store_true', help='start the service')
    parser.add_argument('--add', action='store_true', help='add an image via URL')
    args = parser.parse_args()
    if args.show:
        show()
    elif args.add:
        add_image()

main()

Following is the op:`
D:\>python img.py

D:\>python img.py

D:\>python img.py --add
 created new gridfs file ofc2.jpg with id 580237fb0f84ea10789b20e6

D:\>python img.py --show
 Traceback (most recent call last):
  File "img.py", line 62, in <module>
  main()
  File "img.py", line 57, in main
   show()
  File "img.py", line 47, in show
   im = Image.open(im_stream)
  File "C:\Python27\lib\site-packages\PIL\Image.py", line 1980, in open
  raise IOError("cannot identify image file")
   IOError: cannot identify image file

on mongodb
mongodb output
MongoDB Enterprise > show dbs;
ank             0.000GB
ank1            0.000GB
ankit           0.000GB
gridfs_example  0.000GB
local           0.000GB
MongoDB Enterprise > use ank1
switched to db ank1
MongoDB Enterprise > show collections
fs.chunks
fs.files
 MongoDB Enterprise > db.fs.files.find().pretty()
  {
    "_id" : ObjectId("5802397f0f84ea122c6176a6"),
    "chunkSize" : 261120,
    "filename" : "ofc2.jpg",
    "length" : 335,
    "uploadDate" : ISODate("2016-10-15T14:13:19.882Z"),
    "md5" : "ef937ff6e6a00e64a2dda34251ca03b5"
    }

i don't know what the problem is ive done the same program in fedora it worked.but in windows im having this problem is that related to os or the python versions

A: You may need to convert the im_stream to bytes for reading using the BytesIO class.
im = Image.open(io.BytesIO(im_stream.read()), 'r')


text:
Q: Белый экран при переходе между активити Мне нужно чтоб после успешной регистрации пользователя его сразу кидало на гланвый экран (MainActivity). Но почему то вместо нормальной загрузки я получаю только белый экран, MainActivity не загружается.
AuthAndReg.java
    public class AuthAndReg extends AppCompatActivity {

        private EditText EdTextPassword, edUserEmail;
        private FirebaseAuth mAuth;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_auth_and_reg);

            init();
            final EditText et_password = (EditText) findViewById(R.id.EdTextPassword);
            final ImageButton bt_change_mode = (ImageButton) findViewById(R.id.bt_change_mode);
            final TextView ChangeModText = (TextView) findViewById(R.id.ChangeModText);
            bt_change_mode.setOnClickListener(new View.OnClickListener() {

       @Override
      public void onClick(View view) {
     if (EdTextPassword.getInputType () == 128
        EdTextPassword.setInputType (129);
        ChangeModText.setText ("Показывать пароль");
}
else {
     EdTextPassword.setInputType (128);
       ChangeModText.setText ("Скрыть пароль");

}
            EdTextPassword.setSelection (EdTextPassword.getText (). length ());}});

        }

        @Override
        protected void onStart() {
            super.onStart();
            FirebaseUser cUser = mAuth.getCurrentUser();
        }

        private void init()
        {

            EdTextPassword = findViewById(R.id.EdTextPassword);
            edUserEmail = findViewById(R.id.edUserEmail);
            mAuth = FirebaseAuth.getInstance();
        }

        public void onClickAuth(View view){
            Intent intent = new Intent(this, AuthUser.class);
            startActivity(intent);
        }

        public void OnClickHelp(View view)
        {
            Intent intent = new Intent(this, RegInfoPage.class);
            startActivity(intent);
        }

        public void onClickReg(View view){
            if(!TextUtils.isEmpty(edUserEmail.getText().toString()) && !TextUtils.isEmpty(EdTextPassword.getText().toString()) )
            {

                mAuth.createUserWithEmailAndPassword (edUserEmail.getText().toString(),EdTextPassword.getText().toString()).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if(task.isSuccessful())
                        {

                            Toast.makeText(AuthAndReg.this, "Добро пожаловать, вы успешно зарегистрировались", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(AuthAndReg.this, MainActivity.class);
                            startActivity(intent);

                        }
                        else
                        {
                            Toast.makeText(AuthAndReg.this, "Что-то пошло не так" ,
                            Toast.LENGTH_SHORT).show();
                        }

                    }
                });

            }

            else
            {
                Toast.makeText(AuthAndReg.this, "Пожалуйста, заполните все поля" , Toast.LENGTH_SHORT).show();
            }

        }

        public void onClickGoBack(View view){
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
        }

    }

MainActivity.java
    public class MainActivity extends AppCompatActivity {
        private FirebaseAuth mAuth;
        private TextView   edUserEmail;

            @Override
            public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
                super.onCreate(savedInstanceState, persistentState);
                setContentView(R.layout.activity_main);
                //Intent intent = getIntent();
                ImageButton RegButton = (ImageButton) findViewById(R.id.RegButton);

                RegButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent(MainActivity.this, AuthAndReg.class));
                    }
                });
            }

        public void buttonclick(View view){
            Intent intent = new Intent(this, CatalogActivity.class);
            startActivity(intent);

        }

        public void openRegPage(View v){
            Intent intent1 = new Intent(this, AuthAndReg.class);
            startActivity(intent1);

        }}

activity_auth_and_reg.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/regButton"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".AuthAndReg">

    <EditText
        android:id="@+id/edUserEmail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:autofillHints=""
        android:ems="10"
        android:hint="@string/enterEmail"
        android:inputType="textEmailAddress"
        android:minHeight="48dp"
        android:textColorHint="#757575"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView9"
        app:layout_constraintVertical_bias="0.04000002" />

    <!--    <ImageButton-->
    <!--        android:id="@+id/auth_button"-->
    <!--        android:layout_width="wrap_content"-->
    <!--        android:layout_height="wrap_content"-->
    <!--        android:layout_marginTop="5dp"-->
    <!--        android:layout_marginBottom="40dp"-->
    <!--        android:contentDescription="@string/app_name"-->
    <!--        android:onClick="onClickAuth"-->
    <!--        app:layout_constraintBottom_toBottomOf="parent"-->
    <!--        app:layout_constraintEnd_toEndOf="parent"-->
    <!--        app:layout_constraintStart_toStartOf="parent"-->
    <!--        app:srcCompat="@drawable/ic_button_auth" />-->
    <!--    <ImageButton-->
    <!--        android:id="@+id/Reg_Button"-->
    <!--        android:layout_width="wrap_content"-->
    <!--        android:layout_height="wrap_content"-->
    <!--        android:layout_marginTop="50dp"-->
    <!--        android:layout_marginBottom="8dp"-->
    <!--        android:contentDescription="@string/app_name"-->
    <!--        android:onClick="onClickReg"-->
    <!--        app:layout_constraintBottom_toTopOf="@+id/auth_button"-->
    <!--        app:layout_constraintEnd_toEndOf="parent"-->
    <!--        app:layout_constraintHorizontal_bias="0.511"-->
    <!--        app:layout_constraintStart_toStartOf="parent"-->
    <!--        app:layout_constraintTop_toBottomOf="@+id/EdTextEmail"-->
    <!--        app:srcCompat="@drawable/ic_button_reg" />-->

    <!--    <ImageView-->
    <!--        android:id="@+id/imageView"-->
    <!--        android:layout_width="366dp"-->
    <!--        android:layout_height="287dp"-->
    <!--        android:layout_marginBottom="60dp"-->
    <!--        app:layout_constraintBottom_toTopOf="@+id/edName"-->
    <!--        app:layout_constraintEnd_toEndOf="parent"-->
    <!--        app:layout_constraintStart_toStartOf="parent"-->
    <!--        app:layout_constraintTop_toTopOf="parent"-->
    <!--        app:srcCompat="@drawable/ic_def_shop" />-->

    <EditText
        android:id="@+id/EdTextPassword"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:autofillHints=""
        android:ems="10"
        android:hint="@string/firstpassword"
        android:inputType="text|textPassword"
        android:minHeight="48dp"
        android:textColorHint="#757575"
        app:layout_constraintBottom_toTopOf="@+id/RegButton"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/edUserEmail"
        app:layout_constraintVertical_bias="0.00999999" />

    <ImageView
        android:id="@+id/imageView9"
        android:layout_width="408dp"
        android:layout_height="338dp"
        android:layout_marginStart="15dp"
        android:contentDescription="@string/app_logo1"
        app:layout_constraintBottom_toBottomOf="@+id/AuthButton"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.01999998"
        app:srcCompat="@drawable/ic_defshop" />

    <ImageButton
        android:id="@+id/AuthButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentDescription="@string/app_name"
        android:onClick="onClickAuth"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/RegButton"
        app:layout_constraintVertical_bias="0.04000002"
        app:srcCompat="@drawable/ic_authbutton" />

    <ImageButton
        android:id="@+id/RegButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentDescription="@string/app_name"
        android:onClick="onClickReg"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.85"
        app:srcCompat="@drawable/ic_regbutton" />

    <TextView
        android:id="@+id/RegText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="sans-serif-black"
        android:text="@string/reg_title"
        android:textColor="#0E0E0E"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="@+id/imageView9"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.050000012" />

    <ImageButton
        android:id="@+id/backbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentDescription="@string/app_name"
        android:onClick="onClickGoBack"
        app:layout_constraintBottom_toBottomOf="@+id/imageView9"
        app:layout_constraintEnd_toStartOf="@+id/RegText"
        app:layout_constraintHorizontal_bias="0.38"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        app:srcCompat="@drawable/ic_gobackbutton" />

    <TextView
        android:id="@+id/ChangeModText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="sans-serif-medium"
        android:text="@string/ShowPasswrod"
        android:textColor="#272727"
        app:layout_constraintBottom_toTopOf="@+id/RegButton"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.41"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/EdTextPassword"
        app:layout_constraintVertical_bias="0.32999998" />

    <ImageButton
        android:id="@+id/bt_change_mode"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentDescription="@string/app_name"
        app:layout_constraintBottom_toTopOf="@+id/RegButton"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.72"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/EdTextPassword"
        app:layout_constraintVertical_bias="0.0"
        app:srcCompat="@drawable/ic_button_password" />

    <ImageButton
        android:id="@+id/InfoButton"
        android:layout_width="48dp"
        android:layout_height="50dp"
        android:layout_marginStart="3dp"
        android:layout_marginEnd="32dp"
        android:contentDescription="@string/app_name"
        android:onClick="OnClickHelp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toEndOf="@+id/EdTextPassword"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.59000003"
        app:srcCompat="@drawable/ic_infobutton" />

</androidx.constraintlayout.widget.ConstraintLayout>


text:
Q: Add css runtime to table row and data bind the row I am really not sure how to solve. However i am quite close the solution and now just need one small help from you experts here. My working fiddle is here. When the page loads the 2 checkboxes are checked. My view is binded as below

            <input type="checkbox" data-bind="checked: $root.duplicates.indexOf(name1) !== -1" />

My view model as below
var data1 = [{
name1: "one",
id: 1,
display: "Test1"
}, {
 name1: "two",
id: 2,
 display: "Test2"
}, {
name1: "three",
id: 3,
 display: "Test3"
}];
var data2 = [{
name2: "five"
}, {
name2: "two"
}, {
name2: "three"
}];

var viewModel = {
dataOne: ko.observableArray(data1),
dataTwo: ko.observableArray(data2),
duplicates: ko.observableArray()

};

 viewModel.dataTwo.push({
  name: "four"
  }); //add one on the end

  var flattenedOne = ko.utils.arrayMap(viewModel.dataOne(), function (item) {

     return item.name1;
   });

  var flattenedTwo = ko.utils.arrayMap(viewModel.dataTwo(), function (item) {

   return item.name2;
  });

  var differences = ko.utils.compareArrays(flattenedOne, flattenedTwo);
    //return a flat list of differences
  ko.utils.arrayForEach(differences, function (difference) {
   if (difference.status === 'retained') {
      viewModel.duplicates.push(difference.value);
    }
   });

Now when user click on Update button it again load data and now 3 checkboxes are checked. What i am trying to achieve is

*

*When user click on update button it should add css to table row and only make that row bold.

*It should not check the checkbox as checked when user click's on update button.
So in our example when user click's on update button it should make row as bold but checkbox should not be checked. So only first row will be bold on clicking update button. Currently when page is loading it is making 2 rows bold and checked which is wrong. It should make row bold only clicking update button. Please help me guys.

A: Hope this solves your problem.
Check this Fiddle
I have given separate condition using another observable .

Html :-

            <input type="checkbox" data-bind="checked: $root.checkDuplicate.indexOf(name1) !== -1" />

<button class="btn" data-bind="click: $root.UpdateData"> Update </button>

Script:-
 var data1 = [{
  name1: "one",
  id: 1,
  display: "Test1"
 }, {
  name1: "two",
  id: 2,
  display: "Test2"
 }, {
  name1: "three",
  id: 3,
  display: "Test3"
 }];
var data2 = [{
  name2: "five"
 }, {
 name2: "two"
 }, {
  name2: "three"
 }];

var viewModel = {
 dataOne: ko.observableArray(data1),
 dataTwo: ko.observableArray(data2),
 duplicates: ko.observableArray(),
 checkDuplicate : ko.observableArray() // new observable to handle condition

};

viewModel.UpdateData = function(){
  data2 = [{
     name2: "one"
  }, {
     name2: "two"
  }, {
     name2: "three"
  }];

 viewModel.dataTwo(data2);

 var flattenedOne = ko.utils.arrayMap(viewModel.dataOne(), function (item) {

   return item.name1;
 });

 var flattenedTwo = ko.utils.arrayMap(viewModel.dataTwo(), function (item) {
   return item.name2;
 });

 var differences = ko.utils.compareArrays(flattenedOne, flattenedTwo);
//return a flat list of differences
ko.utils.arrayForEach(differences, function (difference) {

  if (difference.status === 'retained' && viewModel.checkDuplicate().indexOf(difference.value) == -1 ) {
     viewModel.duplicates.push(difference.value);
  }
  });

};

viewModel.dataTwo.push({
  name: "four"
 }); //add one on the end

 var flattenedOne = ko.utils.arrayMap(viewModel.dataOne(), function (item) {
  return item.name1;
 });

 var flattenedTwo = ko.utils.arrayMap(viewModel.dataTwo(), function (item) {
  return item.name2;
 });

  var differences = ko.utils.compareArrays(flattenedOne, flattenedTwo);
   //return a flat list of differences
  ko.utils.arrayForEach(differences, function (difference) {
    if (difference.status === 'retained') {
      viewModel.checkDuplicate.push(difference.value);
    }
  });

 ko.applyBindings(viewModel);


text:
Q: wrong $_GET request I have a URL:
http://missk.co.uk/index.php/admin/catalog_category/index/key/a47a4f77942acca6e40cdca9736d2a3d/

var_export($_GET) :

array ( '/index_php/admin/catalog_category/index/key/a47a4f77942acca6e40cdca9736d2a3d/' => '', )

Why I receive not the empty array though $ _GET has to give out parameters only after a question mark?

A: I believe, that this is being caused by rewrite module in web server. Check your .htaccess file for RewriteRule.


text:
Q: ionic checklist with object array - how to dertermine if checkbox is checked my code app.js:
jt.controller('TheorieCtrl', function($scope, $window, $ionicPlatform) {
// .log($window.localStorage);
// Ready functions
if ($window.localStorage.getItem('themen') === null) {
    $scope.themen = [{
        name: "Setting1",
        checked: false
    }, {
        name: "Setting2",
        checked: false
    }
    ];
} else {
    $scope.themen = JSON.parse($window.localStorage['themen']);
};

$scope.updateThemaLocalStorage = function(items) {
    $window.localStorage['themen'] = JSON.stringify(items);
};

});
my html code:
 <ion-list>
    <ion-checkbox ng-repeat="thema in themen track by $index" class="checkbox-positive item-checkbox-right" type="checkbox" id="{{thema.id}}" ng-model="thema.checked" ng-change="updateThemaLocalStorage(themen)">
        {{ thema.name }}
    </ion-checkbox>
</ion-list>

In a other controller I would like to determine if Setting1 is checked.
Is it something like:
if($scope.thema.Setting1.checked){ "do something" }
But this doesn't work. I just need help with syntax for this.
I guess this is a absolutely newbie question. sorry for that, I did really searched and tried a lot.

A: I think you should just change the lookup. if the array never changes.
current:
if($scope.thema.Setting1.checked){ "do something" }

expected:
if($scope.thema[0].name.checked){ "do something" }


text:
Q: Internet connectivity in iphone when application is minimize i want to check  for internet availability in whenever my application make call to webservice during my application was minimized.
I had done some google work and found this :-
How to check for an active Internet connection on iOS or OSX?
http://forums.macrumors.com/showthread.php?t=635200
But this doesnt not gives me how do i check when application is minimized i.e paused!!
please help me

A: When your application is running in background mode you cannot check for internet connectivity. You can run audio, VOIP or location services in background mode.
Any open or listening sockets will be closed when the application enters background mode.


text:
Q: Shorten a long if statement How can i write this code in a shorter way?
This is only part of my code. It is very long and my system runs it a bit slow. I want this to run every time user adds a value like number in range N2:P & last row.
Sub TEST()

lastrow = Range("A10000").End(xlUp).Row

For i = 2 To lastrow

'---1
If Cells(i, "P").Value >= 1 And Cells(i, "P").Value <= 5 And Cells(i, "I").Value >= Cells(i, "K").Value And Range("P" & i).Value * Range("K" & i).Value <= Cells(i, "I").Value Then
Cells(i, "P").Value = Range("P" & i).Value * Range("K" & i).Value

'----2
ElseIf ((Cells(i, "P").Value >= Cells(i, "I").Value) Or (Range("I" & i).Value - Range("P" & i).Value < Range("K" & i).Value)) And Cells(i, "O").Value >= 1 And Cells(i, "O").Value <= 5 And Cells(i, "H").Value >= Cells(i, "K").Value And Range("O" & i).Value * Range("K" & i).Value <= Cells(i, "H").Value Then
Cells(i, "O").Value = Range("O" & i).Value * Range("K" & i).Value
'---3
ElseIf ((Cells(i, "P").Value >= Cells(i, "I").Value) Or (Range("I" & i).Value - Range("P" & i).Value < Range("K" & i).Value)) And Cells(i, "N").Value >= 1 And Cells(i, "N").Value <= 4 And Cells(i, "H").Value >= Cells(i, "K").Value And Range("N" & i).Value * Range("K" & i).Value <= Cells(i, "H").Value Then
Cells(i, "O").Value = Range("N" & i).Value * Range("K" & i).Value
Range("N" & i) = vbNullString

'----4
ElseIf ((Cells(i, "P").Value < Cells(i, "I").Value) Or (Range("I" & i).Value - Range("P" & i).Value >= Range("K" & i).Value)) And Cells(i, "O").Value >= 1 And Cells(i, "O").Value <= 5 And Cells(i, "I").Value >= Cells(i, "K").Value And Range("O" & i).Value * Range("K" & i).Value <= Cells(i, "I").Value Then
Cells(i, "P").Value = Range("O" & i).Value * Range("K" & i).Value
Range("O" & i) = vbNullString
'---5
ElseIf ((Cells(i, "P").Value < Cells(i, "I").Value) Or (Range("I" & i).Value - Range("P" & i).Value >= Range("K" & i).Value)) And Cells(i, "N").Value >= 1 And Cells(i, "N").Value <= 4 And Cells(i, "I").Value >= Cells(i, "K").Value And Range("N" & i).Value * Range("K" & i).Value <= Cells(i, "I").Value Then
Cells(i, "P").Value = Range("N" & i).Value * Range("K" & i).Value
Range("N" & i) = vbNullString

'---6
ElseIf ((Range("I" & i).Value - Range("P" & i).Value < Range("K" & i).Value) Or (Range("H" & i).Value - Range("O" & i).Value < Range("K" & i).Value)) And Cells(i, "N").Value >= 1 And Cells(i, "N").Value <= 4 And (Cells(i, "H").Value >= Cells(i, "K").Value Or Cells(i, "I").Value >= Cells(i, "K").Value) Then
Range("N" & i) = vbNullString
MsgBox "You already"

'---6
ElseIf Cells(i, "I").Value = vbNullString And Cells(i, "H").Value = vbNullString And Cells(i, "N").Value >= 1 And Cells(i, "N").Value <= 4 Then
Range("N" & i) = vbNullString
MsgBox "There is no "

A: Extract functions for your tests that return a Boolean.  For example, the first If test (line continuations added for clarity)...
If Cells(i, "P").Value >= 1 And _
   Cells(i, "P").Value <= 5 And _
   Cells(i, "I").Value >= Cells(i, "K").Value And _
   Range("P" & i).Value * Range("K" & i).Value <= Cells(i, "I").Value Then

...can be written as the following function:
Private Function WhateverTheTestIsFor(rowNumber As Long) As Boolean
    Dim columnI As Variant
    Dim columnP As Variant

    columnP = Cells(rowNumber, "P").Value
    columnI = Cells(rowNumber, "I").Value
    columnK = Cells(rowNumber, "K").Value
    Select Case True
        Case columnP < 1
        Case columnP > 5
        Case columnI < columnK
        Case columnP * columnK > columnI
        Case Else
            WhateverTheTestIsFor = True
    End Select
End Function

Then your first If clause becomes:
If WhateverTheTestIsFor(i) Then

Note that as mentioned in the comments, you should only read the values from the Worksheet once.  There are other issues with the code too - you need to qualify your references to Cells and Range, and pick a convention to use between the two.  Mixing Cells(i, "K") and Range("K" & i) is confusing.

A: Have you tried to use data validation for this?
You can create multiple rules that overlap in complex ways without writing complex  code.
in excel, select your desired range PN:PN,
then in the data tab select data validation.
you will see a wizard that can help you add layers of rules that can warn users whenever specific  values ate entered, or even prevent entry of unacceptable values.
http://www.excel-easy.com/basics/data-validation.html


text:
Q: How to properly query Kafka REST Proxy? I'm running a dockerized distribution of Confluent platform:
CONTAINER ID   IMAGE                                             COMMAND                  CREATED        STATUS        PORTS                                                                                NAMES
e6963904b485   confluentinc/cp-enterprise-control-center:7.0.1   "/etc/confluent/dock…"   11 hours ago   Up 11 hours   0.0.0.0:9021->9021/tcp, :::9021->9021/tcp                                              control-center
49ade0e752b4   confluentinc/cp-ksqldb-cli:7.0.1                  "/bin/sh"                11 hours ago   Up 11 hours                                                                                ksqldb-cli
95b0982c0159   confluentinc/ksqldb-examples:7.0.1                "bash -c 'echo Waiti…"   11 hours ago   Up 11 hours                                                                                ksql-datagen
e28e3b937f6e   confluentinc/cp-ksqldb-server:7.0.1               "/etc/confluent/dock…"   11 hours ago   Up 11 hours   0.0.0.0:8088->8088/tcp, :::8088->8088/tcp                                              ksqldb-server
af92bfb84cb1   confluentinc/cp-kafka-rest:7.0.1                  "/etc/confluent/dock…"   11 hours ago   Up 11 hours   0.0.0.0:8082->8082/tcp, :::8082->8082/tcp                                              rest-proxy
318a999e76dc   cnfldemos/cp-server-connect-datagen:0.5.0-6.2.0   "/etc/confluent/dock…"   11 hours ago   Up 11 hours   0.0.0.0:8083->8083/tcp, :::8083->8083/tcp, 9092/tcp                                    connect
0c299fbda7c5   confluentinc/cp-schema-registry:7.0.1             "/etc/confluent/dock…"   11 hours ago   Up 11 hours   0.0.0.0:8081->8081/tcp, :::8081->8081/tcp                                              schema-registry
a33075002386   confluentinc/cp-server:7.0.1                      "/etc/confluent/dock…"   11 hours ago   Up 11 hours   0.0.0.0:9092->9092/tcp, :::9092->9092/tcp, 0.0.0.0:9101->9101/tcp, :::9101->9101/tcp   broker
135f832fbccb   confluentinc/cp-zookeeper:7.0.1                   "/etc/confluent/dock…"   11 hours ago   Up 11 hours   2888/tcp, 0.0.0.0:2181->2181/tcp, :::2181->2181/tcp, 3888/tcp                          zookeeper

Kafka REST Proxy is running on port 8082
When I issue an HTTP GET call against the REST proxy:
curl  --silent -X GET http://10.0.0.253:8082/kafka/clusters/ | jq

All I get is:
{
  "error_code": 404,
  "message": "HTTP 404 Not Found"
}

Given  my configuration, what can I change to actually get some useful information out of Kafka REST Proxy?


text:
Q: Android Studio installation doesn't work with gradle I am absolute beginner with Android Studio (especially Gradle) and having big trouble getting Android Studio to work. I downloaded and installed the most recent version of Android Studio (0.8.0). I have set the JDK_HOME variable. However, after I create a new project, I always receive the following message:
Error:Unknown host 'jcenter.bintray.com'.
Enable Gradle 'offline mode' and sync project.
Learn about configuring HTTP proxies in Gradle

If I try to compile the project, I get the following message dialog:

After reading a post, I manually downloaded the Gradle binaries (latest, 2.0), extracted it onto the local drive, went to Settings and set the Gradle path to the respective directory using the following:

I also tweaked the build.gradle file under the project to point to the latest Gradle 2.0 version. However, now I get the following error message:
Error:A problem occurred configuring root project 'HelloAndroidStudio'.
Could not resolve all dependencies for configuration ':classpath'.
Could not resolve com.android.tools.build:gradle:2.0.+.
Required by:
  :HelloAndroidStudio:unspecified
    Failed to list versions for com.android.tools.build:gradle.
    Unable to load Maven meta-data from     http://jcenter.bintray.com/com/android/tools/build/gradle/maven-metadata.xml.
    Could not GET 'http://jcenter.bintray.com/com/android/tools/build/gradle/maven-metadata.xml'.
    jcenter.bintray.com

Please can someone help. Being my first time with Gradle, I have been trying for so many days without any clue to the problem. Thanks.

A: Change the Gradle version to lower ones and restart the Android Studio, you may get it.
Add this in build.gradle
classpath 'com.android.tools.build:gradle:1.1.0'

A: Setting the http_proxy under appearance & behaviour -> system settings -> http proxy has solved the problem

A: Change to the latest classpath in the dependencies.
For AS 1.5.1 I will do like this :
buildscript {
repositories {
    jcenter()
  }

dependencies {
    **classpath 'com.android.tools.build:gradle:1.5.0'**
  }
}


text:
Q: update table inside for loop I am trying to update a mysql table while inside a c# for loop and a if statement well a few if statements. While running with a break point it will run the executenonquery once but the next loop it does not hit that. Even when i does hit the nonquery it does not change the table information.
the ffi string is the name of the column in my table and string val is what i want to put in. I know this is not the safe way to do it but I will change it when i can get it working the way it should.
Updated code it now runs the NONQUERY every time it should but still not updating the table
Code:
for (a = 0; a <= z; a++)
 {

   if (ds3.Tables[0].Rows[a][1].ToString() == dataGridView1.Rows[i].Cells[0].Value.ToString())
     {
      if (ds3.Tables[0].Rows[a][2].ToString() == dataGridView1.Rows[i].Cells[1].Value.ToString())
         {
           if (ds3.Tables[0].Rows[a][3].ToString() == dataGridView1.Rows[i].Cells[2].Value.ToString())
            {
              MessageBox.Show("We have a match " +  dataGridView1.Rows[i].Cells[0].Value.ToString() + " " + dataGridView1.Rows[i].Cells[1].Value.ToString() + " " + dataGridView1.Rows[i].Cells[t].Value.ToString());
                     try
                       {
                         string ffi = textBox1.Text;
                          decimal val = decimal.Parse(dataGridView1.Rows[i].Cells[t].Value.ToString());

                                                MySqlCommand cmd = new MySqlCommand("Update spt_results  SET " + ffi + " = " + val + " where project_Id =" + dataGridView1.Rows[i].Cells[0].Value.ToString() + "",connection2);
                                                //cmd.Connection = connection2;'
                                               // cmd.Connection.Open();

                                                cmd.ExecuteNonQuery();
                                                //cmd.Connection.Close();
                        }
                      catch
                      {

                      }

The message box does show every loop and the connection2.open will run everytime
Thank you for looking and your help
The update string looks like        "update spt_results  SET FFI 300 = '15' where project_Id =AAA007" when it runs
Brent

A: Look at your code:
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = // ... snip SQL injection invitation
connection2.Open();
cmd.ExecuteNonQuery();
connection2.Close();

The MySqlCommand has no connection. You're opening and closing a connection, but it's got nothing to do with the command. I'd actually expect cmd.ExecuteNonQuery() to throw an exception because it has no connection...
Note that you should use using statements for the command and connection, to ensure that all the resources get cleaned up even in the face of an exception.

A: use  cmd.Connection = connection2; just after connection2.Open();.
When you trying to execute the cmd.ExecuteNonQuery(), it is raising the error for no Connection bounded with the Command and error is caught in catch block. You didn't came to know because you have not doing anything in catch block for the errors.

A: If uncomment your code: The connection is open correctly and your code should work. But I'd suggest you to open connection once, before the loop, and close it at the end.
Another point is that you catched ALL exceptions, it is not good. The problem can be with the query, try to run "update spt_results SET FFI 300 = '15' where project_Id =AAA007" in the console or another MySQL client. It will throw an error. The field name 'FFI 300' must be quoted because it contains a white space and the value 'AAA007' must be quoted as a string literal. Try this query -
UPDATE spt_results SET `FFI 300` = '15' WHERE project_Id = 'AAA007'


text:
Q: Closure of closed cone with cone: is there a formula? I have two sets $A$ and $B$ which are subsets of a Hilbert space, which are both cones (i.e. $a \in A$ implies that $\gamma a \in A$ for all $\gamma > 0$, and likewise with $B$). Furthermore, $B$ is a closed set.
Is there a nice formula for $\overline{A \cap B}$ (the closure) in terms of $\bar A$ and $B$? I know there is always
$\overline{A\cap B} \subset \bar A \cap B$, but what about a reverse?

A: There is no formula for $\overline{A\cap B}$ in terms of $\overline{A}$ and $B$.  For instance, let $A$ be any non-closed cone containing $0$, let $b\in \overline{A}\setminus A$, and let $B=\{cb:c\in[0,\infty)\}$.  Then $\overline{A\cap B}=\{0\}$.  But, if you take $A'=\overline{A}$ then $A'$ has the same closure as $A$ and $\overline{A'\cap B}$ contains $b$ and so is not the same as $\overline{A\cap B}$.  So, $\overline{A\cap B}$ is not determined by $\overline{A}$ and $B$.


text:
Q: Vibrational anharmonic coupling and noise-induced spontaneous symmetry breaking in a hexagonal finite mechanical lattice Happy holidays, everyone! The following is part question, part visual gallery, and part classical mechanics problem. Inspired by snow over the weekend I began simulating the vibrations of the following hexagonal lattice system:

The 271 purple dots represent point masses of mass $m=1$ and are spaced apart by a spacing $a=1$, and each point mass is connected to each of its six nearest neighbors via springs with rest length $L=1$ and spring constant $k$. The red dots are fixed in place, and essentially act as an immovable boundary condition, while the purple dots are free to move horizontally and vertically in the plane. The lattice has $D_{6}$ symmetry, and three of the elements (vertical reflection $\sigma_v$, horizontal reflection $\sigma_h$, and $\pi/3$ rotation $C_6$) are shown for reference.
The entire system potential becomes
$$U(\mathbf{r})=\sum_{i,j}\frac{1}{2}k\left(L-\left|(\mathbf{r}_i^{e}+\mathbf{r}_i)-(\mathbf{r}_j^{e}+\mathbf{r}_j)\right|\right)^2$$
where $$\mathbf{r}=(\mathbf{r}_1,\mathbf{r}_2,...,\mathbf{r}_{271})^\mathsf{T}=(x_1,y_1,x_2,y_2,...,x_{271},y_{271})^\mathsf{T}$$
is the vector which represents the state of deformation of the system away from the equilibrium configuration $\mathbf{r}^e$ in the image above ($\mathbf{r}_i$ represents the vector displacement of the $i$th point from equilibrium), and where the sum runs over nearest-neighbor pairs.
As per the usual normal mode analysis, it's easy to show that $U(\mathbf{0})=0$ and $\nabla U(\mathbf{0})=\mathbf{0}$, and thus the system admits the second-order Taylor expansion
$$U(\mathbf{r})=\mathbf{r}^\mathsf{T}\mbox{H}\mathbf{r}+O\left(\mathbf{r}^3\right)$$
where
$$\mbox{H}=\nabla\nabla U(\mathbf{0})$$
is the $542 \times 542$ Hessian matrix of the potential at equilibrium. For small oscillations, the normal mode picture is applicable, and the eigenvibrations are the columns of the orthonormal eigenbasis $\Lambda$ of $\mbox{H}$. $\mbox{H}$ has a closed-form block matrix expression, although I omit it here for brevity.
Note that $$U(\mathbf{r})=U(\Gamma_g\mathbf{r})$$ for all $\mathbf{r}$ and for all  $g\in D_6$ where $\Gamma_g$ is the matrix representation of the symmetry operation $g$- for example, $\Gamma_{C_6}$ is the block matrix that maps every coordinate to the one 60 degrees CCW rotated from it, and also rotates each vector by 60 degrees. Since $U(\mathbf{r})=U(\Gamma_g\mathbf{r})$, we can take derivatives twice to obtain $$\nabla\nabla U(\mathbf{r})=\Gamma_g^\mathsf{T}\nabla\nabla U(\Gamma_g\mathbf{r})\Gamma_g.$$ By noting that $\Gamma_g^\mathsf{T}=\Gamma_g^{-1}$ for all $g\in D_6$ and setting $\mathbf{r}=0$, we obtain
$$\Gamma_g\mbox{H}=\mbox{H}\Gamma_g$$ and hence $$[\mbox{H},\Gamma_{D_6}]=0.$$
Mathematica revealed that 180 of the 542 eigenstates $\Lambda_k$ of $H$ were singly-degenerate. As is well-known, a singly-degenerate eigenstate of a matrix $\mbox{H}$ is automatically an eigenstate of any $\mbox{A}$ for which $[\mbox{H},\mbox{A}]=0$, and thus all 180 singly-degenerate vibrations satisfy $$\Gamma_g\Lambda_k=\lambda_k^g\Lambda_k$$ and thus manifest in numerical outputs as strikingly beautiful patterns, which I'll show in a second. In particular, they are eigenstates of $\sigma_v,\sigma_h,C_6$ and the inversion operator $i$.
Meanwhile, the other 362 eigenstates are doubly degenerate and so Mathematica simply spits out an arbitrary pair spanning each eigenspace, so they don't look very nice. However, they can be "symmetry-projected" via the usual means, which I experimentally found was best done by choosing the pair to be a simultaneous eigenbasis of $\mbox{H}$ and $\Gamma_{\sigma_v}$ (which, again, can be done since $[\mbox{H},\Gamma_G]=0$). Likewise, since $\sigma_v$ commutes with $\sigma_h$, they are also in a definite eigenstate of $\sigma_h$, and by extension, eigenstates of $i=\sigma_v\sigma_h$. However, they are not necessarily eigenstates of rotation $C_6$ since $C_6$ doesn't commute with reflections. As a cheap aesthetic surrogate, I define "generalized" eigenvalues as $$\lambda_k^{g}=\left<\Lambda_k,\Gamma_{g}\Lambda_k\right>,$$ which gives the correct result whenever $\Lambda_k$ is an eigenstate of $g$, and gives a sort of average value when it is not.
The 542 symmetry-classified vibrations were visualized in Mathematica and exported as a gigantic 5343 x 8913 pixel image. Here is a considerably smaller preview image (it's far too small to read the words, click the full-size to see everything in detail):

They've been color-coded, with the yellow ones being singly-degenerate ("pure") and the orange ones being doubly-degenerate ("mixed"), their eigenvalue of $\mbox{H}$ is given ("$\lambda$"), and their symmetry numbers with respect to the four symmetry operations I've mentioned is also given. They're ordered by vibrational frequency, from highest to lowest. Many of them are reminiscent of snowflakes when viewed at lower resolution, which I thought was kind of pretty.
At this point, all I've done is just compute a bunch of normal modes, which are valid for small oscillations. For large-amplitude vibrations, anharmonic coupling effects come into play, mixing the modes together and distorting their frequencies. To visualize this nonlinear mixing process, I numerically simulated the system starting out displaced in the direction of a single eigenmode, but with large vibrational amplitude. The time-varying vector output $\mathbf{r}(t)$ from NDSolve was then converted into the symmetry-adapted eigenbasis as $$\mathbf{r}'(t)=\Lambda^\mathsf{T}\mathbf{r}(t)$$ to yield the "population" in each eigenmode over time, and the result was plotted using ArrayPlot. For visual simplicity, I used a smaller 37-point lattice, rather than the 271-point lattice I've been using previously, although the same code can be used interchangeably for both.
For example, starting in one of the $(C_6,\sigma_v,\sigma_h,i)=(-1,-1,1,-1)$ symmetry states with an amplitude such that the points traveled a distance of about 1/8 (ie, smaller than lattice displacement, but still reasonably large) yielded the following:

The $x$-axis is time (from left to right), and each of the 74 horizontal bars represents an eigenmode, which have been grouped together by which of the 8 symmetries it belongs to. White indicates no amplitude, black indicates large amplitude, and the color scale is somewhat logarithmic to make things easier to see. As can be seen, near the very beginning amplitude gets mixed into other states, but the mixing is confined to states with $(-1,-1,1,-1)$ symmetry or $(1,1,1,1)$ symmetry only. Similarly, repeating this with a $(\frac{1}{2},-1,1,-1)$ symmetry state yielded the following:

This time, the coupling is limited to four symmetry classes. I found that coupling only depended on symmetry, which I'm sure people more knowledgeable than myself will know well. Finally, I noted that such symmetry restrictions would spontaneously lift themselves at extremely large displacements without warning after some time; the time at which the sudden change occurred was strongly dependent on the precision of the numerical solver, and random noise added to the initial conditions caused an immediate breaking of symmetry. Here is an example of such a phenomenon:

Here's a question: is this an classical-mechanical example of spontaneous symmetry breaking? It seems that the system starts out in a state of definite symmetry, but that upon provocation by numerical noise, population 'tips over the edge' and spills into the rest of the symmetry classes, equalizing everything.
Here's another question. I found that coupling was nonreciprocal, in the sense that population from $(1,-1,-1,1)$ modes could spill into modes of $(1,1,1,1)$ symmetry, but that the reverse was not possible (ie, the flow of amplitude seems to have sources and sinks). To be more specific, the coupling directions looked like this:

If the $i,j$ entry is black, then energy can couple from symmetry class $i$ to symmetry class $j$, and if it's white, it's forbidden (with the exception of when spontaneous breaks occur at extreme amplitudes). Note that not only is it upper triangular with the way I ordered the symmetry blocks here, but it's actually a $2\times 2$ block matrix of the form
$$\left(\begin{array}{cc}
A & A\\
0 & A
\end{array}\right)$$
where $A$ is a $4\times 4$ matrix which is also upper-triangular. Does anybody have any idea how or why this happens? I have to admit it's all a bit over my head. I did all of this intending to print out posters as a Christmas present for my parents, but I noticed all this wacky stuff in the process. I suspect it's some kind of weird "classical mechanics selection rule" but I'm not very good at algebra, so the reasons are all opaque to me, and I haven't formally taken classical mechanics.
As a final example of pretty pictures, I should point out that my choice of symmetry projection for the doubly-degenerate modes was in a realistic one, as it matches the eigenmodes of the corresponding lattice with a unitary horizontal shear transformation applied to the equilibrium positions in the limit as the shear matrix approaches the identity matrix. To be specific, applying the shear transform
$$\left(\begin{array}{cc}
\frac{x}{1-x} & 0\\
0 & \frac{1-x}{x}
\end{array}\right)$$
to the lattice and computing the eigenfrequencies as a function of $x$ yielded the following beautiful pattern:

It's available in higher resolution here. The $x$-axis is $x$, and each line represents an eigenfrequency. They have lots of crossings and avoided crossings, reminiscent of Stark effect perturbations in atoms. In the limit as $x\rightarrow\frac{1}{2}$, the eigenstates of $\mbox{H}$ approach the symmetry-adapted ones.

A:
the time at which the sudden change occurred was strongly dependent on the precision of the numerical solver, and random noise added to the initial conditions caused an immediate breaking of symmetry.

This is the most important bit of information. What causes the symmetry breaking seems to be nonlinearity introduced by numerical errors. So what you are doing is somewhat similar to the Fermi-Pasta-Ulam-Experiment. The big problem is, that you don't know how exactly the non-linearity looks like, how it acts on the system and how strong it is. You can control it by precision of the numerical solver, which is nice, but you don't know, if it conserves energy or if it is a sink/source of energy. Since you are using linear springs to couple the atoms, this simulation has no non-linearity coming from the model itself, only from the implementation on a computer. So you have 3 options here a) insert a nonlinearity, which you can understand and control very well and see how symmetry breaking arises (it should be constructed so that numerical nonlinearities are negligible compared to your model instability). Or b) you try to remove these numerical errors, which is not easy, but it seems to be possible, see this paper:
http://zfn.mpdl.mpg.de/data/Reihe_A/52/ZNA-1997-52a-0585.pdf
Lastly option c) means you try to understand your numerical errors. This involves understanding the differences between floating point arithmethic (float, double), and fixed-point arithmetic, how your algorithm approximates and cuts off values, in the case of NDSolve of Mathematica, this might be well documented but with a lot of special routines, so that handling is easier for the Mathematica user. In this case it is very advisable to write your own implementation.

A: I believe I have an answer for the second question, namely, why the coupling table takes the upper-triangular form it does.
In particular, the upper-triangular coupling direction table can be more or less generated by the following simple rule: given an initial state with symmetry numbers $\{\lambda_g|g\in D_6\}$, the lattice applies a force of $g$-gerade symmetry in the generalized coordinates if and only if the state is of $g$-gerade symmetry. I proved the backwards direction here, and I'm conjecturing that the forward direction is usually true, although no one has yet answered my question. so I'm not sure.


text:
Q: This Python code for a Custom Calculator was working now I broke it and I can't figure out where I went wrong I had this working and now I cannot figure out what I did to make it not function the way I intend it to. When the program is called by the pyshell it asks the questions as it is supposed to but when the reply is given this is where it loses it mind. It was working and would call the function I have defined but now it will not do so.
I might just redefine the responses to use numbers instead of strings to make it easier and faster to complete the entries, but at the moment it is not working so there is no point in doing that until I can get it figured out.
The error is in the run_time() section, it is not calling the function as it should be, I might be missing something. I want it to call the function when the proper response is given.
I did try:
k = (query())
f = function_list[k]
f()

This did not worth either, so I am stuck. I appreciate any help.
def f_to_c():
    temp = int(input("How warm is it out?"))
    f_or_c = str(input("Is it C or F?"))
    if f_or_c == 'c' or f_or_c == 'C':
        updatedtemp = float(temp * 9 / 5 + 32)
        print (updatedtemp, 'F')
    elif f_or_c == 'f' or f_or_c == 'F':
        updatedtemp = float((temp - 32) * 5 / 9)
        print (updatedtemp, 'C')

def calc_trapezoid_area():
    height = float(Input('What is the height of the trapezoid?'))
    length1 = float(Input('What is the length of the bottom base?'))
    length2 = float(Input('What is the length of the top base?'))
    formula = float((1 / 2 * (length1 + length2)) * height)
    print ("The area of the trapezoid is:", (formula))

def cal_circle():
    pi = float(245850922 / 78256779)
    rad_or_diam = str(input('Diameter or Radius?'))
    width = float(input('What is the %s of your Circle?' % rad_or_diam))
    if rad_or_diam == 'r' or rad_or_diam == 'R':
        print (float(pi * width ** 2))
    elif rad_or_diam == 'd' or rad_or_diam == 'D':
        print (float(pi * width))

def query():
    query = str(input('What would you like to calculate? Degrees, Trapezoids, or Circles?')).lower

function_list = {
    "degrees": f_to_c,
    "trapezoids": calc_trapezoid_area,
    "circles": cal_circle
    }

def run_time():
    try:
        f = function_list[query()]
        f()
    except KeyError:
        print ("You messed up!")

if __name__ == '__main__':
    while True:
        run_time()
        x = str(input('True or False?'))
        if x == 'True':
            break

A: There are two problems with your query function:

*

*It doesn't return anything; and

*It doesn't call lower.

Instead, try:
def query():
    prompt = 'What would you like to calculate? Degrees, Trapezoids, or Circles?'
    return input(prompt).lower()

Note the following:

*

*input already returns a string, no need to call str();

*You need to explicitly return the value; and

*Parentheses () are required to actually call lower, otherwise you return the method itself.

Also, in f_to_c, "flaot" != "float".
Finally, you could improve your run_time function, minimising the amount of code in the try block:
try:
    f = function_list[query()]
except KeyError:
    print ("You messed up!")
else:
    f()

This prevents a KeyError from f() being accidentally silenced.


text:
Q: Help me better automate changes to our static routes I have been assigned the task of maintaining and configuring my organization's firewall and gateway routers, and I'm looking for some advice on how to manage the static route table.
(As context, please keep in mind that A) I'm a programmer, not a sysadmin, B) I'm very new to maintaining this piece of infrastructure, and C) I'm not interested in defending my company's decision to put me in charge of it; I'm not sure I agree, but it's the job I've got)
Here's the current setup, as far as I'm able to tell:

*

*An OpenBSD firewall that uses pf for firewall rules with a default of block in log all, pass out and a set of rules that permit traffic between VLANs (I'm oversimplifying, here, I'm sure, but that's the basics. Also, not the focus of my question.

*Redirects from external IPs to internal hosts are accomplished using either rdr pass entries in pf.conf or static routes. When should I use one or the other??

*pf.conf and rc.local are managed in a VCS, and are pushed to the firewall by a remote script that does (essentially) this:
scp confs/pf.conf fw:/etc/pf.conf
scp confs/rc.local fw:/etc/rc.local
ssh fw "/sbin/pfctl -f /etc/pf.conf"
This works fine for firewall rule changes; those are applied immediately, but the real trick is with static routes. They're set up in rc.local as a series of route add statements:
...
route add 192.0.32.136/32 192.0.32.11
route add 192.0.32.137/32 10.10.3.13
...

The problem here is that when I change the set of routes in VCS, I can't just re-run rc.local to refresh the routing table. I'd like to create a script that I can store in VCS that will both run on startup to set up the static routing, and be runnable whenever the routes change in order to set them up the same way every time.  Is this possible? If so, how?

A: It's been awhile since I've played with OpenBSD, but I believe the main difference between rdr and a static route is whether or not NATing is applied. Hosts with externally routable IPs can use either, but non-routable IPs would only work with rdr.
As far as the routes, would switching the commands to route change rather than route add work? That way rerunning the script would modify, rather than add new routes.


text:
Q: MySQL Error Strict
The sql-mode strict_trans_tables is enabled in your mysql server, please contact your host provider to disable it.

Me sale esto cuando quiero instalar la pagina (uso x10hosting y manejo mysql en phpmyadmin) y no aparece

ONLY_FULL_GROUP_BY STRICT_TRANS_TABLES NO_ZERO_IN_DATE NO_ZERO_DATE ERROR_FOR_DIVISION_BY_ZERO NO_AUTO_CREATE_USER NO_ENGINE_SUBSTITUTION si no STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION


text:
Q: Get DN from certificate in ASN.1 format I'm trying to get the DN from a certificate in ASN.1/DER format. I have searched OpenSSL but still cannot find the exact function to get the DN.
Does anyone have any experience regarding this or can point me to books or any website?

A: I already found a way to do this. I just put here if anyone want to do the same.
X509_NAME * cert_entry = X509_get_issuer_name(cert);
unsigned char buff[100] = {0};
unsigned char * p = buff;
int i = i2d_X509_NAME(cert_entry,&p);

for(int b = 0;b<i;b++)
{
    printf("%02X ",buff[b]);
}

This will print an hexa format.


text:
Q: Hibernate generic composite key and cascade saving I have a problem with writting a generic class for composite keys that I use in my db.
All tables that are using composite key have relation ManyToOne and use 2 FK. I have written following class:
import java.io.Serializable;

import javax.persistence.Embeddable;
import javax.persistence.ManyToOne;

@Embeddable
public class CompositeKey<K, T> implements Serializable {
@ManyToOne
K firstKey;
@ManyToOne
T secondKey;

public CompositeKey() {
}

public CompositeKey(K firstKey, T secondKey) {
    this.firstKey = firstKey;
    this.secondKey = secondKey;
}

public K getFirstKey() {
    return firstKey;
}

public void setFirstKey(K firstKey) {
    this.firstKey = firstKey;
}

public T getSecondKey() {
    return secondKey;
}

public void setSecondKey(T secondKey) {
    this.secondKey = secondKey;
}

@Override
public String toString() {
    return "CompositeKey [firstKey=" + firstKey + ", secondKey="
            + secondKey + "]";
}

@Override
public int hashCode() {
    /* HashCode implementation */
}

@Override
public boolean equals(Object obj) {
           /* */
}

}

And example class with CompositeKey:
import javax.persistence.AssociationOverride;
import javax.persistence.AssociationOverrides;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;

@Entity
public class TestClass {

@EmbeddedId
@AssociationOverrides({
        @AssociationOverride(name = "firstKey", joinColumns = @JoinColumn(name = "FirstTable")),
        @AssociationOverride(name = "secondKey", joinColumns = @JoinColumn(name = "SecondTable")) })
private CompositeKey<A, B> compositeKey;

@Lob
private String description;

    /* Getters and Setters */

    }

Now the questions:
1. Is this approach correct? Or its better to write separate composite key for each entity?
2. If this approach is correct, then how can I move annonation @ManyToOne from CompositeKey class to TestClass ?
3. Is it possible to use cascade in this case? I would like to save Entities that are in composite keys when entity with composite key is saved.
Thanks in advance for Your replies!


text:
Q: Ререндер при изменении стейта Есть список карточек. При нажатии кнопки происходит фильтрация и кол-во элементов изменяется. Сделаны пустые элементы, чтобы верстка оставалось нормальной(flex, наверное так не делается, но увы))).
Так же при определенной ширине экрана количество столбуов уменьшается.
Вопрос: почему количество пустых элементов при изменении размера numenclature остается прежним?

const [numenclature, setNumemclature] = React.useState([]);

  {numenclature.length > 0 ? (
    numenclature.map(item => (
      <NumenclatureItem
        pltk={style_pltk}
        cur={props.cur}
        key={item.ps}
        link={item.url}
        item={item}
      />
    ))
  ) : (

Товаров не найдено

  )}
  {console.log(numenclature.length % 4 == 2)} // вот этот лог выдает нормальное (измененное) значение
  {window.innerWidth >= '1690px' ? (
    (isTablet || isBrowser) && numenclature.length % 4 == 1 ? (
      <>

      </>
    ) : (isTablet || isBrowser) && numenclature.length % 4 == 2 ? (
      <>

      </>
    ) : (isTablet || isBrowser) && numenclature.length % 4 == 3 ? (
      <>

      </>
    ) : (
      <></>
    )
  ) : (isTablet || isBrowser) && numenclature.length % 3 == 1 ? (
    <>

    </>
  ) : (isTablet || isBrowser) && numenclature.length % 3 == 2 ? (
    <>

    </>
  ) : (
    <></>
  )}

A: Это очень глупо, но вся ошибка была в том, что window.innerWidth возвращает не "1690px", a "1690"