text:
Q: AngularJS - Using custom filter in ng-repeat for prefixing comma
Need to remove comma if value is empty works good if I have value
  present at start or middle; But same doesn't work in this scenario.

app.filter('isCSV', function() {
  return function(data) {
    return (data !== '') ? data + ', ' : '';
  };
});

Angularjs ng repeat for addressline - Plunker

A: I would instead operate on arrays of properties and use a pair of filters, one to remove empty values, and one to join the array.
This way it's very explicit about what properties you are displaying.

      {{ [ item.address0, item.address1, item.address2, item.address3] | removeEmpties | joinBy:', ' }}

With the following filters:
app.filter('removeEmpties', function () {
    return function (input,delimiter) {
        return (input || []).filter(function (i) { return !!i; });
    };
});

app.filter('joinBy', function () {
    return function (input,delimiter) {
        return (input || []).join(delimiter || ',');
    };
});

Here's the updated Plunkr

A: Tricky but should work in your case Also no filter need
{{ item.address0 }} ,
 {{ item.address1}},{{
item.address2}}
,{{ item.address3}}

Here is working example

A: I would prefer writing a function instead of adding a filter so many times.
$scope.mergeAddresses = function(item) {
  var address = item.address0;

  [1,2,3].forEach(function(i) {
    var add = item["address"+i];

    if (!add) return;

    address += (address ? ", " : "") + add;
  });

  if (address) address += ".";

  return address;
}

Plunker


text: Q: Can we save multiple faces for face recognition using OpenCV in android Hi I've been trying to develop an app that needs to store multiple faces but it's not working as expected it's only saving one face at a time once you record a new face it will just override the existing face.  Is it possible?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Not Hausdorff quotient by a properly discontinuous action I can't find a counterexample to this sentence:

Let $X$ be a $T2$ topological space, and $G \subset Hom(X)$ be a group of homeomorphisms which acts properly discontinuously on X (i.e. $\forall x \in X \ \ \exists U$ neighborhood of $x$ such that $\forall g \in G\setminus \{id\} \ \ g(U) \cap U=\varnothing).$ Then the quotient $X/G$ is $T2.$

The following theorem gives me some hints about what to avoid while making the counterexample :
Let $A \subset X$ (with $X$ Hausdorff) be an open set such that: $A$ intersects every orbit of $G,$ and $A \cap g(A) \neq \varnothing$ for a finite quantity of $g \in G.$ Then $X/G$ is $T2.$
Clearly $G$ cannot be finite, otherwise the quotient is automatically $T2,$ taking $A=X.$ Moreover, this condition is somehow similar to the hypothesis of properly discontinuous action, and I can't find an example where they don't "coincide".
Do you have some hints? Thanks to everybody.

A: This contradicts the theorem you posted, so I'm not sure if our definitions of properly discontinuous actions are the same. Anyhow,
$\mathbb{Z}/2$ acts on the disjoint union of $\mathbb{R} \times \{a\}$ and $\mathbb{R} \times \{b\}$ by $g \cdot (0, a) = (0, a), g \cdot (0, b) = (0, b)$, and otherwise $g \cdot (t, a) = (t, b)$ and vice-versa. This is a properly discontinuous action (the group is finite). Furthermore, the original space is certainly Hausdorff in the disjoint union topology; the resulting space is the line with two origins which is not Hausdorff at the origins.


text:
Q: How can I change the range of countif() inside an arrayformula()? I want to find duplicates that happen after the current row.  I can find duplicates that happen anywhere with this formula but I don't want to flag the last occurrence of a particular value as being a duplicate.
=arrayformula(if(row(B:B) = 1, "Duplicate", if(not(isblank(A:A)), if(countif(A:A, A:A) > 1, "Yes", "No"), "")))
If I statically specify a starting cell in the lookup range it only finds duplicates after that spot. However I need to have the starting spot change based on the row I'm on.
=arrayformula(if(row(B:B) = 1, "Duplicate", if(not(isblank(A:A)), if(countif(A5:A, A:A) > 1, "Yes", "No"), "")))
I tried using indirect() and row() but it doesn't seem to update for each row.
=arrayformula(if(row(B:B) = 1, "Duplicate", if(not(isblank(A:A)), if(countif(indirect("A"&row(B:B)&":A"), A:A) > 1, "Yes", "No"), "")))

A: try:
={"Duplicate"; ARRAYFORMULA(IF(INDIRECT("A"&ROW()+1&":A")<>"",
 IF(COUNTIF(INDIRECT("A"&ROW()+1&":A"), INDIRECT("A"&ROW()+1&":A")) > 1, "Yes", "No"), ))}

UPDATE:
={"Duplicate";
 ARRAYFORMULA(IF(A2:A="",,
 IF(COUNTIFS(A2:A, A2:A, ROW(A2:A), ">="&ROW(A2:A))>1, "Yes", "No")))}


text:
Q: how to 1 patterntText to replaced with Regex.Replace string inputText="lorem impsum dolar sit amet lorem";
string patternText="lorem";
string replacementText="XXXX";
Regex.Replace(inputText, patternText, replacementText, RegexOptions.IgnoreCase);

output:XXXX impsum dolar sit amet XXXX
But how do I make only one change ?
should be such that  : XXXX impsum dolar sit amet lorem

A: I think you can use the overload of Regex. Replace to specify the maximum number of times to replace.
var regex = new Regex(Regex.Escape("o"));
var newText = regex.Replace("hi", "Foo", 1);


text:
Q: how do I write the function for getting different background image and text upon clicking its designated button? I am aware of the script that calls the text according to its button, but I have no clue how I can place a background image on that text. My plan is that the background image can also change according to the button that was clicked.  Here is what I've done so far...
This is actually for a school project and I want it to be as action-oriented or somewhat interactive in a way with just functions and methods. I also wanted to add another cell table and just place an image there with some texts just like a gaming avatar profile.

function myFunction(elem) {
  var x = document.getElementById("js-description");
  var description = elem.getAttribute('data-description');
  x.innerHTML = description;
  var button = document.getElementsByClassName('js-button');
  for (var i = 0; i < button.length; i++) {
    button[i].classList.remove('active-buton');
  }
  elem.classList.add('active-button');
}
body,
html {
  height: 100%;
  background-color: #190a48;
  margin: 0;
}

.btn-group button {
  font-family: SF;
  letter-spacing: 5px;
  background-color: transparent;
  /* Green background */
  border: 1px solid #504c7c;
  /* Green border */
  color: white;
  /* White text */
  padding: 2.5% 1%;
  /* Some padding */
  cursor: pointer;
  /* Pointer/hand icon */
  width: 15vw;
  height: 6vw;
  /* Set a width if needed */
  display: block;
  /* Make the buttons appear below each other */
  margin-left: 20%;
  border-radius: 4%;
  -webkit-box-shadow: inset 1px 6px 12px #544e88, inset -1px -10px 5px #2e2d3a, 1px 2px 1px #2e2d3a;
  -moz-box-shadow: inset 1px 6px 12px #544e88, inset -1px -10px 5px #2e2d3a, 1px 2px 1px #2e2d3a;
  box-shadow: inset 1px 6px 12px #544e88, inset -1px -10px 5px #2e2d3a, 1px 2px 1px #2e2d3a;
  font-size: 1vw;
}

.btn-group button:not(:last-child) {
  border-bottom: none;
  /* Prevent double borders */
}

.active-button:hover {
  background-color: #83a1a7;
}

.description {
  text-align: center;
  color: white;
  font-size: 50px;
  font-family: St;
  letter-spacing: 3px;
}

        <button data-description="Vivamus, moriendum est" onclick="myFunction(this)">   HOBBY    </button>
        <button data-description="Forsan et haec olim meminisse iuvabit" onclick="myFunction(this)">   MEMORY     </button>
        <button data-description="Sapere aude" onclick="myFunction(this)">
       CONQUEST    </button>
        <button data-description="Audentes fortuna iuvat" onclick="myFunction(this)">    AMBITION  </button>
        <button data-description="Ad astra per aspera" onclick="myFunction(this)">    TARGET    </button>

       content

A: You are almost there. You can use the same aproach for the background image as you already do for the description text. Just define another data-attribute with your image-url and set the respective CSS property like this:

function onButtonClick() {
  var descriptionElement = document.getElementById("description");

  descriptionElement.innerHTML = event.target.dataset.description;
  descriptionElement.style['background-image'] = event.target.dataset.backgroundImage;
}

Press one of the buttons below.

<button
  data-description="First description"
  data-background-image="linear-gradient(red, orange)"
  onclick="onButtonClick()">first</button>
<button
  data-description="Second description"
  data-background-image="linear-gradient(teal, green)"
  onclick="onButtonClick()">second</button>

I use gradients here because I don't have an image at hand. To use an actual image you can specify it like data-background-image="url('path/to/your/image')".


text:
Q: Is there any way to let a child process be listed under its parent process in Task Manager? I'm using Windows 11.
Running processes are listed in the "Processes" tab in Task Manager.
They are expandable, and if I click on the [>] mark on the left side of a process's name, the tree will be expanded.
My application launches some child processes, by calling the Win32 CreateProcess() API.
Now, my application and child processes are listed as separate processes. I want to make the child processes be listed underneath my application in the tree. But I can't found the parameter to do that.
Is this possible with CreateProcess(), or another API? Or is it impossible?


text:
Q: Google Analytics Variant Testing different CSS files In my ecommerce store I have a "checkout process" that consist of 3/4 pages. I want to run an experiment on this (A/B testing) with Google Analytics. Specifically; I want to try a different stylesheet that hides a couple of elements (display:none;) to make the checkout more simplistic.
Basically I want Google Analytics to use global.css for the "original" page and global_b.css for the "variant".
Making different variants for every page is not the ideal solution. In the documentation there is a soluton but I don't really understand how to implement this: https://developers.google.com/analytics/solutions/experiments-client-side#implement-choose.
How do I modify the given script to only work for the pages I want to test (e.g. checkout_1.php, checkout_2.php, checkout_3.php) and switch between the two stylesheets?

A: The way I've approached this is to
1) Add an additional CSS class definition to global.css :
.ga-experiment-no-display{
    display:none;
}

2) Add an additional html class to each element that can be hidden on checkout_1|2|3.php, such as '.ga-experiment'
3) The Checkout pages each loads the GA experiment code and includes a JS file (checkout.js).  This has code that:
var chosenVariation = cxApi.chooseVariation();
if (chosenVariation > 0){
   //Search for all elements with $('.ga-experiment')
   //Add the class '.ga-experiment-no-display'
}


text:
Q: Проверка для всего контролера в yii2 Как сделать проверку всего контролера на определённые параметры, а не для каждого action отдельно.
Что бы 100 раз не писать проверку на гостя.
Например
class NameController extends Controller {

    public function actionoIndex()
    {
        if (Yii::$app->user->isGuest)
        {
            return $this->goHome();
        }
     }

    public function actionOther()
    {
        if (Yii::$app->user->isGuest)
        {
            return $this->goHome();
        }
     }
 }

A: Определите в контроллере метод beforeAction(){} и в нем опишите всю интересующую Вас логику.
Этот метод вызывается перед вызовом определонного action контроллера.
Если это нужно для всех контроллеров - создайте между ними прослойку в виде контроллера, и наследуйтесь от него

A: Используйте RBAC:
public function behaviors()
{
return [
    'access' => [
        'class' => \yii\filters\AccessControl::className(),
        'only' => ['create', 'update'],
        'rules' => [
            // deny all POST requests
            [
                'allow' => false,
                'verbs' => ['POST']
            ],
            // allow authenticated users
            [
                'allow' => true,
                'roles' => ['@'],
            ],
            // everything else is denied
            [
                'allow' => true,
                'actions' => ['delete'],
                'roles' => ['admin'],
            ],
            //доступ в экшену удаления имеет только пользователь с ролью админ
        ],
    ],
];
}

В доке это описано.


text:
Q: Plugin permissions for Editor role I've added a plugin called Orbisius Simple Notice but I notice this applied to several plugins I have installed. The plugin works fine when logged in as an Admin. However, my clients who manage the site use accounts set to Editor roles. When any of the Editor accounts try to access the options page for the plugin, they get the following message:
"You do not have sufficient permissions to access this page."
I use User Role Editor to ensure they have permissions to edit plugins. However, I know the issue is not related to this as I enabled all permissions as a test and I still got the above error. So I figure it's hardcoded into the plugin. Source for the plugin: http://pastebin.com/UhrvkiXv
The only bit I saw that seemed appropriate was:
function orbisius_simple_notice_setup_admin() {
add_options_page('Orbisius Simple Notice', 'Orbisius Simple Notice', 'manage_options', __FILE__, 'orbisius_simple_notice_options_page');

But the users have manage_options enabled. I tried changing to edit_pages etc. but still no luck.
Any ideas?!

A: manage_options is an admin role so I'd still try and changing it even if you've changed the roles elsewhere.
See http://codex.wordpress.org/Roles_and_Capabilities#Editor for more info.
Try the following:
add_options_page('Orbisius Simple Notice', 'Orbisius Simple Notice', 'edit_others_posts', __FILE__, 'orbisius_simple_notice_options_page');


text:
Q: Can't initialize mongo db using ape-nosql-mongo @UsingDataSet I want to run some integration test using Arquillian, Arquillian cube and Mongo. The desired scenario is:

*

*Start the application in a managed container. Here I want to use Shrinkwrap to add just the service I want to test (for example dao service)

*Start the database inside a docker container. Populate the db with some initial data

*Run the test against the database

My test looks like this:
@Inject
MongoProducer producer;

@Test
@UsingDataSet(locations = "initialData.json")
public void shouldGetAllFromMongo() {

    FindIterable<Document> documents = producer.getMongoClient().getDatabase("bearsdb").getCollection("bears").find();
    documents.forEach((Block<? super Document>) e-> System.out.println(e));
}

The initialData.json is under src/test/resources and format of the seeding data is as bellow:
{
  "bears": [
  {
    "firstName": "grizz",
    "lastName": "the bear",
    "age": 3
  },
  {
    "firstName": "panpan",
    "lastName": "the bear",
    "age": 3
  },
  {
    "firstName": "icebear",
    "lastName": "the bear",
    "age": 4
  }
]}

My docker-compose file looks like this:
version: '3'
services:
  mongo-test-db:
    image: mongo:latest
    environment:
      - MONGO-INITDB-DATABASE=bearsdb
      - MONGO-INITDB_ROOT_USERNAME=panda
      - MONGO-INITDB_ROOT_PASSWORD=pass
    ports:
    - 27117:27017

I don't really know if the environments help but I saw this in an example.
My pom.xml contains:
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.jboss.shrinkwrap.resolver</groupId>
            <artifactId>shrinkwrap-resolver-bom</artifactId>
            <version>${version.shrinkwrap.resolvers}</version>
            <scope>import</scope>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>org.jboss.arquillian</groupId>
            <artifactId>arquillian-bom</artifactId>
            <version>1.1.15.Final</version>
            <scope>import</scope>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>org.arquillian</groupId>
            <artifactId>arquillian-universe</artifactId>
            <version>${version.arquillian_universe}</version>
            <scope>import</scope>
            <type>pom</type>
        </dependency>
    </dependencies>
</dependencyManagement>

and as dependencies
    <dependency>
        <groupId>org.jboss.arquillian.junit</groupId>
        <artifactId>arquillian-junit-container</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.arquillian.cube</groupId>
        <artifactId>arquillian-cube-docker</artifactId>
        <version>${org.arquillian.cube.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.arquillian.universe</groupId>
        <artifactId>arquillian-ape-sql-container-dbunit</artifactId>
        <scope>test</scope>
        <type>pom</type>
    </dependency>
    <dependency>
        <groupId>org.arquillian.universe</groupId>
        <artifactId>arquillian-ape-nosql-mongodb</artifactId>
        <scope>test</scope>
        <type>pom</type>
    </dependency>
    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongo-java-driver</artifactId>
        <version>3.4.3</version>
    </dependency>

Please note that I don't use the arquillian-junit-standalone dependency.
Additional note is that I'm using ShwripWrack to package and I deploy the war into an managed Wildfly 8.2.0.Final server. Additionl in the same test class I've tested also against an Postgres running inside docker and for this the @UsingDataSet works ok. Bellow is the working sql test and the createDeploy method:
@Deployment
public static WebArchive createDeployment() {
    JavaArchive[] javaArchives = Maven.resolver().resolve(
            "org.assertj:assertj-core:3.15.0",
            "org.arquillian.cube:arquillian-cube-docker:1.18.2",
            "org.mongodb:mongo-java-driver:3.4.3")
            .withTransitivity().as(JavaArchive.class);

    WebArchive war = ShrinkWrap.create(WebArchive.class, "app.war")

            .addClasses(PersonDao.class, Person.class)
            .addClasses(MongoProducer.class, PropertyProducer.class, Property.class)
            .addAsLibraries(javaArchives)
            .addAsResource("test-persistence.xml", ArchivePaths.create("META-INF/persistence.xml"))
            .addAsResource("META-INF/application.properties", ArchivePaths.create("META-INF/application.properties"))
            .addAsManifestResource(EmptyAsset.INSTANCE, ArchivePaths.create("beans.xml"));
    System.out.println(war.toString(true));
    return war;
}

@Test
@org.arquillian.ape.rdbms.UsingDataSet("datasets/persons.xml")
public void shouldFindAll() {
    List<Person> messages = personDao.findAll();
    assertThat(messages.size()).isEqualTo(1);
}

The issue with the above test is that the database doesn't get initialize and nothing is printed out.

A: I managed to resolve my problem. The issue is that I forgot to add an Junit rule where the configuration to the Mongo database was set.
@Rule
public MongoDbRule mongoDbRule = new MongoDbRule(MongoDbConfigurationBuilder.mongoDb()
        .host("localhost")
        .port(27117)
        .databaseName("pandadb")
        .build());

The full test class looks like:
@RunWith(Arquillian.class)
public class PersonDaoDockerIT {

@Rule
public MongoDbRule mongoDbRule = new MongoDbRule(MongoDbConfigurationBuilder.mongoDb()
        .host("localhost")
        .port(27117)
        .databaseName("pandadb")
        .build());

@Deployment
public static WebArchive createDeployment() {
    JavaArchive[] javaArchives = Maven.resolver().resolve(
            "org.assertj:assertj-core:3.15.0",
            "org.arquillian.cube:arquillian-cube-docker:1.18.2",
            "org.mongodb:mongo-java-driver:3.4.3")
            .withTransitivity().as(JavaArchive.class);

    WebArchive war = ShrinkWrap.create(WebArchive.class, "app.war")

            .addClasses(PersonDao.class, Person.class)
            .addClasses(MongoProducer.class, PropertyProducer.class, Property.class)
            .addPackages(true, "com.lordofthejars.nosqlunit")
            .addAsLibraries(javaArchives)
            .addAsResource("test-persistence.xml", ArchivePaths.create("META-INF/persistence.xml"))
            .addAsResource("META-INF/application.properties", ArchivePaths.create("META-INF/application.properties"))
            .addAsResource("datasets/", ArchivePaths.create("datasets/"))
            .addAsManifestResource(EmptyAsset.INSTANCE, ArchivePaths.create("beans.xml"));
    System.out.println(war.toString(true));
    return war;
}

@Inject
PersonDao personDao;

@Inject
MongoProducer producer;

@Test
public void injectionPointShouldBeNotNull() {
    assertThat(personDao).isNotNull();
}

@Test
public void mongoProducerShouldBeNotNull() {
    assertThat(producer).isNotNull();
}

@Test
@org.arquillian.ape.rdbms.UsingDataSet("datasets/persons.xml")
public void shouldFindAll() {
    List<Person> messages = personDao.findAll();
    assertThat(messages.size()).isEqualTo(1);
}

@Test
@UsingDataSet(locations = "/datasets/initialData.json")
public void shouldGetAllFromMongo() {
    FindIterable<Document> documents = producer.getMongoClient().getDatabase("pandadb").getCollection("bears").find();
    documents.forEach((Block<? super Document>) System.out::println);
}
}


text:
Q: How can I store text file in MYSQL database using QT? I have a table which has two columns: ID, FILE;
The FILE column has BLOB type;
I want to store the full file in the database not the content of the file.
I would like to download the file later as file_name.txt
This is how I tried but after insert the FILE is NULL;
 query.exec("INSERT INTO test(ID, FILE) VALUES(1, LOAD_FILE('/home/nemeth/Documents/list.txt'));

A:
According to
MySQL documentation on LOAD_FILE(), the file must satisfy some conditions to be loaded. Not only being local but also permissions and stuff.

LOAD_FILE(file_name)
Reads the file and returns the file contents as a string. To use this
  function, the file must be located on the server host, you must
  specify the full path name to the file, and you must have the FILE
  privilege. The file must be readable by all and its size less than
  max_allowed_packet bytes. If the secure_file_priv system variable is
  set to a nonempty directory name, the file to be loaded must be
  located in that directory.
If the file does not exist or cannot be read because one of the
  preceding conditions is not satisfied, the function returns NULL.
The character_set_filesystem system variable controls interpretation
  of file names that are given as literal strings.

Also have you tried searching a little?... Lookie here :p

A: I could not figure out what is the problem so I solved differently.
I've read the file into a QByteArray and inserted the array into the database.
QByteArray byteArray = file.readAll();
QSqlQuery query;
query.prepare("INSERT INTO TEST_TABLE(ID, FILE) VALUES (1,?)");
query.addBindValue(byteArray);
query.exec();


text:
Q: Writing data to Firebase from a fragment in Android Studio So, I have a fragment class and I am trying to write data to Firebase Realtime database using the below code in onCreateView() method,
databaseReference = FirebaseDatabase.getInstance().getReference("CollectionName");
String id = databaseReference.push().getKey();
databaseReference.child(id).setValue(new myModel(param1, param2));

After running this code, whenever I try to write data, I am getting below error:

Default FirebaseApp is not initialized in this process <package_name>. Make sure to call FirebaseApp.initializeApp(Context) first.

This error points to the line where I am trying to get the instance from the firebase.
Now, I've tried many things like using below statement in onCreate() method,
FirebaseApp.initializeApp(MainActivity.getContext());

Here, MainActivity is the class from where this fragment loads.
Also, I have all the necessary dependencies installed in both my Module level and Project level gradle files.

A: I think you could just initialize the Firebase in the onCreate function of your MainActivity using the following.
FirebaseApp.initializeApp(this);

If you want to initialize it from your fragment, you could do this in the onCreateView before calling the FirebaseDatabase.getInstance().
FirebaseApp.initializeApp(getActivity());


text:
Q: Cyclotomic character in class field theory Let $K$ be an extension of $\mathbb{Q}_p$.
By local class field theory, the $p$-adic cyclotomic character $\mathrm{Gal}_K \rightarrow \mathbb{Z}_p^\times$ corresponds to a character $\chi : K^\times \rightarrow \mathbb{Z}_p^\times$.

Is there an explicit description of $\chi$?

When $K=\mathbb{Q}_p$, by Lubin-Tate's theory and using the formal group law of $\mathbb{G}_m$, I know that $\chi$ is the projection $\mathbb{Q}_p^\times = \mathbb{Z}_p^\times \times p^{\mathbb{Z}} \rightarrow \mathbb{Z}_p^\times$.
I am looking for a similar description in the general (or special) case.

A: If $K/L$ is an extension of fields, then the natural map $\operatorname{Gal}(K)^{ab} \to \operatorname{Gal}(L)^{ab}$ corresponds in class field theory to the norm map $K^\times \to L^\times$. So you just want to take the norm from $K$ to $\mathbb Q_p$ and compose it with the character you describe.


text:
Q: How to refactor ternarny operator I have
format = fromNow ? '' : 'LLL'
I saw somewhere that it can be used like that
format = fromNow && 'LLL', which i thought means = if fromNow is true then 'LLL' else nothing but I get an error

Type 'string | boolean' is not assignable to type 'string'.
Type 'boolean' is not assignable to type 'string'

A:
which i thought means = if fromNow is true then 'LLL' else nothing

That's not what it means. x && y means:

*

*Evaluate x

*If the value from Step 1 is falsy, take that value as the result of the && operation and stop

*If the value from Step 1 is truthy, evaluate y and take that value as the result of the && operation

So if your fromNow is a boolean, fromNow && 'LLL' results in either false or 'LLL' — that is, a boolean or a string. But apparently your format variable is declared as type string, so TypeScript won't let you assign a boolean to it.
Your original, using the conditional operator,¹ is preferable if you want a string result either way. You could do fromNow && 'LLL' || '' but that's getting a bit convoluted, whereas the conditional operator version is simple and clear.

¹ The proper name of the ? : operator is the conditional operator. It's a ternary operator (an operator accepting three operands, just like a binary operator accepts two and a unary operator accepts one), and for now it's JavaScript's only ternary operator, but that could change. :-)


text:
Q: get last record of a table in database? i am developing a project and after the user insert the data of the customer he suppose to print the ID and the name of the Customer ,
this is the code of the ID
int getPatnID()
    {
        int ID = (from i in Db.Patients
                  select i.patn_ID).Max();
        return ID;
    }

i have write the code to get the name but i cant finish it
string getPatnName()
    {
        string name = (from n in Db.Patients
                       select n.patn_name).

        return name;
    }

How should i write to complete it ??

A: This should always get the last inserted record at time of execution (assuming patn_id is auto-incrementing)
string GetPatnName()
{
    string name = (from n in Db.Patients
                   orderby n.patn_ID descending
                   select n.patn_name).FirstOrDefault();
    return name;
}

A: string getPatnName() {
    string name = Db.Patients.Last(p => p.patn_ID).patn_name;
    return name;
}

I suggest you spend some more time studying LINQ - it is a very rich and powerful library: http://msdn.microsoft.com/en-us/library/bb397926.aspx

A: Change getPatnName to take an id:
string getPatnName(int id)
{
    string name = (from n in Db.Patients
                   where n.patn_ID == id
                   select n.patn_name).SingleOrDefault();

    return name;
}

and give it the result of getPatnID()

A: If you are trying to get the name of the last patient you just entered, and you have the ID from the first query, you just need a where clause in your LINQ.
string name = (from n in Db.Patients
       where n.patn_ID == ID
       select n.patn_name);

A: Getting the id the way you do is wrong. Not sure what you're using, but both linq-2-sql and entity framework fill in the entity Id when saving changes:
    Patient patient = new Patient();
    Console.WriteLine(patient.Id); // will NOT be filled in
    Db.Patients.Add(patient);
    Db.SubmitChanges(); // SaveChanges in EF
    Console.WriteLine(patient.Id); // will be filled in

A: Why not just create a patient class an return an instance as shown below
public class Patient
{
    public int PatientID { get; set; }
    public string Name { get; set; }
}

static Patient getDetails()
    {
        using (DataClasses1DataContext db = new DataClasses1DataContext())
        {
            var c = (from x in db.Patients.OrderByDescending(u => u.PatientID)
                     select new Patient()
                     {
                         PatientID = x.PatientID,
                         Name = x.Name
                     }).FirstOrDefault();
            return c;
        }


text:
Q: Google Analytics not getting number for email tracking I have done all the pre work of generating tracking ID and am trying to add email tracking to my HTML email template. I have added
<img src="http://www.google-analytics.com/collect?v=1&tid=UA-12345678-1&cid=CLIENT_ID_NUMBER&t=event&ec=email&ea=open&cm=email&cn=Campaign_Name" />

to the bottom of the template. GA is not collecting any numbers when i open this email in any email client. Gmail removes the src tag completely when it loads images. What am i missing?

A: Thanks for looking! It is actually not.
I got the Google Analytics Chrome Debugger and opened the email in an Incognito Window. Both Gmail and Yahoo then got the src attribute and the debugger showed Failed to load resource: net::ERR_NAME_NOT_RESOLVED
There was an issue with extra spaces that got in as a result of line breaks and indentation. There was a %20 inserted for each space, which could not be resolved. I got rid of the extra spaces and it fixed everything.


text:
Q: spark-cassandra-connector, limit retry attempts to a dead cassandra node @here : we run cassandra in kuberenetes, and use spark-cassandra connector , the problem we face is for kubernetes POD restarts ,cassandra IP changes
whenever there is a cassandra ip change (cassandra restart)
From worker logs ,  we  see old ip as DOWN and we can see New replaced IP as newly added node , and connections are being made to new pod with correct POD_IP which is correct , but the problem is we also see connections still going to old pod_ip
and try is still happening to old dead pod_ip
com.datastax.driver.core.Host.STATES: Defuncting Connection[/100.96.1.4:9042-1, inFlight=0, closed=false] because: [/100.96.1.4:9042] Cannot connect
com.datastax.driver.core.exceptions.TransportException: [/100.96.1.4:9042] Cannot connect

any spark cassandra connector retry attempt i can set to limit no.of retry attempts to a dead node
this warning i see only in spark-worker log
any reconnection policy similar to the one in java driver we can configure in spark-cassandra-connector ?


text:
Q: Make each result stored in a different dataframe? This dictionary:
The left side: IAO,INOT_A,etc are  dataframes and the right to them are the columns.
dict1 =({'IAO' :  ['N','OBD'] ,'INOT_A' : ['CIN','OTID'],
          'IA_PST_S' : ['K','OBD'], 'IA' : ['K','jse']})

This code makes the df to be replaced in each loop in the last line (problem) :
for k, v in dict1.items():
    df = pd.DataFrame.from_records(data=arcpy.da.SearchCursor(k, v))
    df.columns = v
    column_for_count =v[0]
    df['count_of_' + column_for_count]=[df[column_for_count].value_counts().loc[x] for x in df[column_for_count]]

How to make it get stored in a different df?

A: You can create dictionary of DataFrame, with keys by by original dict1:
dfs = {}
for k, v in dict1.items():
    df = pd.DataFrame.from_records(data=arcpy.da.SearchCursor(k, v))
    df.columns = v
    column_for_count =v[0]
    df['count_of_' + column_for_count]=[df[column_for_count].value_counts().loc[x] for x in df[column_for_count]]
    dfs[k] = df

Then for select each DataFrame use:
print (dfs['IAO'])


text:
Q: angularjs - how to get files attribute in input tag without using getElementById I'm Uploading files with AngularJS.
How to get the input files just like regular JS?
This is what I need to simulate exactly
HTML:
<input type="file" name="file" id="fileImg" accept="image/*">

JS:
var filesUpload = document.getElementById("fileImg").files

This is what I have now
HTML:
<input type="file" name="file" ng-model="image" accept="image/*">
<input type="button" ng-click="submit()" value="press me">

Angular:
angular
        .module('app')
        .controller("productsCtrl", function($scope) {

            $scope.image = {};

            $scope.submit = function() {

                var filesUpload = ????????????????
            }
         }

So, how to get the "files" in the input withput using "getElementById" ?
notice - can't change nothing , only the "??????"
any help will be appreciated..
tnx

A: You can use custom directive
var app = angular.module('App', []);

app.controller('Main', function($scope, $timeout, $rootScope){
    $scope.onSubmit = function(){
        console.log($scope.file);
    }
});

app.directive('fileRead', [function () {
    return {
       scope: {
        fileRead: '='
       },
       link: function (scope, elem, attrs) {
           elem.bind('change', function (event) {
             scope.$apply(function () {
                scope.fileRead = event.target.files[0];
             });
           });
       }
    }
 }]);

usage

        <form ng-submit="onSubmit()">
            <input type="file" name="someName" file-read="file">
            <button type="submit">Submit</button>
        </form>


text:
Q: pst-3dplot's Alpha and Beta are not correctly set with pstThreeDCoor? This is a simple question

*

*when I set Alpha and Beta in \pstThreeDCoor, why doesn't it affect all the following macros?

I have to set it in psset and also add a \pstThreeDCoor{Alpha=#1,Beta=#2,drawing=false} so that everything is affected
My usual grudge comes when I have plots and dots. When I set it \pstThreeDCoor, the plots are good but the dots behave with default Alpha and Beta.
I used the following workaraound but it is quite a mistery to me why this is even necessary:
\newcommand{\setAB}[2]{%
  \psset{Alpha=#1,Beta=#2}%
  \pstThreeDCoor{Alpha=#1,Beta=#2,drawing=false}}

Update: An example
A paraboloid with tangent plane and vectors
\documentclass[11pt]{book}
\usepackage{pst-3dplot}
\begin{document}
\begin{pspicture}(-2,-1)(3,3)
%if this line is commented, the plots are ok but the dots are not
%\psset{Beta=15}
\pstThreeDCoor[
    Beta=15,
    nameX=$X$,xMin=-1.7,xMax=1.7,
    nameY=$Y$,yMin=-1.7,yMax=1.7,
    nameZ=$Z$,zMin=-0.5,zMax=2.4,
    linecolor=lightgray,linewidth=1.3pt,arrowscale=2.0
]
%--------------BACKGROUND--------------
\psset{linecolor=lightgray,linewidth=0.7pt,yPlotpoints=1}
%horizontals
\parametricplotThreeD[yPlotpoints=2](0,360){t cos 1.5 mul t sin 1.5 mul 2.25}
%verticals
\parametricplotThreeD(0,1.55){-39 cos t mul -39 sin t mul t t mul}
\parametricplotThreeD(0,1.55){129 cos t mul 129 sin t mul t t mul}
%--------------FOREGROUND--------------
\psset{linecolor=black,linewidth=1.0pt}
%curvas coordenadas
\parametricplotThreeD(-45,135){t cos 1.2 mul t sin 1.2 mul 1.44}
\parametricplotThreeD( 0,1.60){80 cos t mul 80 sin t mul t t mul}
%punto P
\pstThreeDDot(0.208,1.182,1.44)
\pstThreeDPut[pOrigin=br](0.208,1.182,1.55){$P$ }
%VECTORS
\psset{arrowscale=1.3}
%vector Circu < -0.99 , 0.16 , 0 >
\pstThreeDLine{->}(0.208,1.182,1.44)(-0.782,1.342,1.44)
%vector Parab < 0.06 , 0.36 , 0.72 >
\pstThreeDLine{->}(0.208,1.182,1.44)(0.268,1.542,2.16)
%vector Norm < 0.115 , 0.713 , -0.366 >
\pstThreeDLine{->}(0.208,1.182,1.44)(0.323,1.895,1.074)
\pstThreeDPut[pOrigin=l](0.305,1.863,1.014){$\textbf{N}$}
%Plano Pi
\pstThreeDLine[linestyle=dashed,linewidth=0.8pt](-1.205,1.93,2.46)%
(-1.385,0.85,0.30)%
( 1.585,0.37,0.30)%
( 1.765,1.45,2.46)%
(-1.205,1.93,2.46)
\pstThreeDPut[pOrigin=l](-1.205,1.97,2.5){$\Pi$}
\end{pspicture}
\end{document}

I will include a set of two compilations that demonstrate the difference

The example code is not a verbatim copy of my file but it is enough to produce an adequate result (it corresponds to the left sides of the example images)

A: Alpha and Beta must be set global! For example:
\psset{Beta=90}
\pstThreeDCoor[
    nameX=$X$,xMin=-1.7,xMax=1.7,
    nameY=$Y$,yMin=-1.7,yMax=1.7,
    nameZ=$Z$,zMin=-0.5,zMax=2.4,
    linecolor=lightgray,linewidth=1.3pt,arrowscale=2.0
]

gives:


text:
Q: Calculating the sum in C++ How do I calculate the sum to below in C++?
I tried the following code but failed.

#include <iostream>
using namespace std;
int main()
{
    int n, p, r = -1;
    cin >> n;
    for (p = 0; p < 10; p++)
        r *= (-1);
    cout << r << endl;
    return 0;
}

A: #include <iostream>
using namespace std;
int main()
{
    int p, r = 1;
    int iSum=0;
    // cin >> n;

    for (p = 0; p <= 10; p++)
    {
        r *= (-1);
        iSum+=r;
    }
    cout << iSum << endl;
    return 0;
}

A: That's basic mathematics, there is no need for a loop, you can just calculate -1 * (upperLimit + 1)%2.
Look at the series and think: -1 +1 -1 +1 -1 +1 ....

A: Although @Flavius is right, the sum starts from 0 so it'll be -1 * (upperLimit+1)%2 as the sum iterates not 10 but 11 times. The upperLimit%2 thing works for sums starting at 1
P.S: Sorry for answering, I cannot yet comment, just registered.


text:
Q: Is it necessary to use Antivirus software? If I don't use any Anti-Virus is there any problem ? To keep my data safe what should I do ?

A: If you keep your Ubuntu system up to date (software updates), you need no antivirus. I am running Linux since 1992 and never got any virus in near 25 years.
See: Do I need to have 'antivirus software' installed?


text:
Q: How to use web-item in html context? I have tab in html list in success.vm:
<a href="/path/to/web-item" id="a-link"> A tab </a>

And Web-item in atlassian-plugin.xml:
<web-item name="Atab" i18n-name-key="atab.name" key="atab" section="project-
config-group" weight="1000">
  <description key="atab.description">The Atab Plugin</description>
  <label key="atab.label"/>
  <link linkId="atab-link">/secure/TabA.jspa</link>

What should i use to refer to web-item in success.vm, in html or through the velocity?
Regards

A: web-item is only a link pointing somewhere, for example to webwork action. Then the webwork action can have specific .vm template.


text:
Q: Running Python in VS Code I just downloaded VS Code the other day to use as an IDE for my Python work, but I'm having trouble running a script. I modified my User Settings file with "python.pythonPath": "C:\\Apps\\Anaconda2\\python.exe".
I have a script that just prints "Hello World," and when I click the green arrow at the top of the debug window, I get a message that says Error File does not exist. ""
This seems like I'm overlooking something super simple. Could someone please point me in the right direction?

A: I think I figured out the issue...I had a new file in which I had typed some Python code, but I hadn't actually saved the file as a .py file. Once I do that the issue is solved.


text:
Q: Clarification needed: How does .NET runtime resolve assembly references from parent folder? I have the following output structure of executables in my solution:

%ProgramFiles%
    |
    +-[MyAppName]
          |
          +-[Client]
          |     |
          |     +-(EXE & several DLL assemblies)
          |
          +-[Common]
          |     |
          |     +-[Schema Assemblies]
          |     |     |
          |     |     +-(several DLL assemblies)
          |     |
          |     +-(several DLL assemblies)
          |
          +-[Server]
                |
                +-(EXE & several DLL assemblies)

Each project in solution references different DLL assemblies, some of which are outputs from other projects in solution, and others are plain 3rd-party assemblies. For example, [Client] EXE might reference an assembly in [Common], which is in a different directory branch.
All references have "Copy Local" set to false, to mirror the layout of the files in the final installed application.
Now, if I take a look at reference properties in the Visual Studio IDE, I see that "Path" of every reference is absolute and that it corresponds to the actual output location of the assembly. That's understandable and correct. As expected, solution compiles and runs just fine.
What I don't understand is, why everything seems to work even when I close the IDE, rename the [MyAppName] directory and run the [Client] EXE manually? How does the runtime find the assemblies if the reference paths aren't the same as they were at the time of linking?
To be clear - this is actually exactly what I'm after: a semi-dispersed set of application files that run fine regardless of where the [MyAppName] directory is located or even what it's named. I'd just like to know, how and why this works without any specific path resolution on my part.
I've read the answers to this similar question, but I still don't get it.
Help much appreciated!

A: AFAIK the only solution is to have at least "stub" exes in MyAppBase and then define subdirectories as sources for DLL's in app.config for each application.
NTFS does support "mounting" other directories (ie. hard links) as subdirectories, but they're very unautomatic and since I've not tried going that way except theoretizing, I can't tell if that would work as a hack.

A: Here's how .Net finds the assemblies that are needed: http://msdn.microsoft.com/en-us/library/yx7xezcf(VS.71).aspx
Step 4 is what might be interesting for you to read: http://msdn.microsoft.com/en-us/library/15hyw9x3(VS.71).aspx

A: Have you considered using GACutil to add your shared assemblies to the Global Assembly Cache

A: Maybe the Common folder was specified as a binpath parameter when it was compiled?
(See Probing the Private binpath)
http://msdn.microsoft.com/en-us/library/15hyw9x3%28VS.71%29.aspx
-Matt


text:
Q: how to replace all occurrances of "\\" string in java script This seems a very simple question but I haven't been able to get this to work.
How do I convert the following string:
var origin_str = "abc/!/!";     // Original string
var modified_str = "abc!!";     // replaced string

I tried this:
console.log(origin_str.replace(/\\/,''));
This only removes the first occurrence of backslash. I want to replaceAll. I followed this instruction in SO: How to replace all occurrences of a string in JavaScript?
origin_str.replace(new RegExp('\\', 'g'), '');

This code throws me an error SyntaxError: Invalid regular expression: /\/: \ at end of pattern. What's the regex for removing backslash in javascript.

A: A quick basic overview of regular expressions in JavaScript
When using regular expressions you can define the expression on two ways.

*

*Either directly in the function or variable by using /regular expression/

*Or by using the regExp contructor: new RegExp('regular expression').

Please note the difference between the two ways of defining. In the first the search pattern is encapsuled by forward slashes, while in the second one the search pattern is passed as a string.
Remember that regular expressions is in fact a search language with it's own syntax. Some characters are used to define actions: /, \, ^, $, . (dot), |, ?, *, +, (, ), [, {, ', ". These characters are called metacharacters and need to be escaped if you want them to be part of the search pattern. If not they will be treated as an option or generate script errors. Escaping is done by using the backslash. E.g. \\ escapes the second backslash and the search pattern will now search for backslashes.
There are a multitude of options you can add to your search pattern.:
Examples
adding \d will make the pattern search for a numeric value between [0-9] and/or the underscore. Simple regular expressions are parsed from left to right.

/javascript/

Searches for the word javascript in a string.

/[a-z]/

When a pattern is put between square bracket the search pattern searches for a character matching any one of the values inside the square brackets. This will find d in 229302d34330
You can build a regular expression with multiple blocks.

/(java)|(emca)script/

Find javascript or emcascript in a string. The | is the or operator.

/a/ vs. /a+/

The first matches the first a in aaabbb, the second matches a repetition of a until another character is found. So the second matches: aaa.
The plus sign + means find a one or more times. You can also use * which means zero or more times.

/^\d+$/

We've seen the \d earlier and also the plus sign. This means find one or more numeric characters. The ^ (caret) and $ (dollar sign) are new. The ^ says start searching from the begin of the string, while the $ says until the end of the string. This expression will match: 574545485 but not d43849343, 549854fff or 4348d8788.
Flags
Flags are operators and are declared after the regular expression /regular expression/flags
JavaScript has three flags you can use:

*

*g (global) Searches multiples times for the pattern.

*i (ignore case) Ignores case in pattern.

*m (multiline) treat beginning and end characters (^ and $) as working over multiple lines (i.e., match the beginning or end of each line (delimited by \n or \r), not only the very beginning or end of the whole input string)

So a regular expression like this:

/d[0-9]+/ig

matches D094938 and D344783 in 98498D094938A37834D344783.
The i makes the search case-insensitive. Matching a D because of the d in the pattern. If D is followed by one or more numbers then the pattern is matched. The g flag commands the expression to look for the pattern globally or simply said: multiple times.

In your case @Qwerty provided the correct regex:
origin_str.replace(/\//g, "")

Where the search pattern is a single forward slash /. Escaped by the backslash to prevent script errors. The g flags commands the replace function to search for all occurrences of the forward slash in the string and replace them with an empty string "".
For a comprehensive tutorial and reference : http://www.regular-expressions.info/tutorial.html

A: Looking for this?
origin_str.replace(/\//g, "")

The syntax for replace is
.replace(/pattern/flags, replacement)

So in my case the pattern is \/ - an escaped slash
and g is global flag.


text:
Q: html tags inside mathjax I already know that mathjax allows very limited html codes inside math areas, however, I have a multiple page document, each having a number of equations, so for \eqref{} to work properly, I have wrapped these commands in a clickable  which direct to the page containing the addressed equation, before the page is scrolled to the equation somewhere withing that page.
The relevant part of the markdown application is, first,
content=content
    .replace(/(\\ref\{[^\}]+\})/g, "$1")
    .replace(/(\\eqref\{[^\}]+\})/g, "$1")

and then,
// to handle cross-referencing the equations in MathJax, due to the multipage nature of the document
var perPageEqs=[];
MathJax.Hub.Queue(
    function () {
        for(pageNum=0; pageNum<totalPageNumber; pageNum++){
            var jax = MathJax.Hub.getAllJax("resultPage-"+pageNum);
            var neWLabelsInPage=[];
            for (var i=0, l=jax.length; i<l; i++) {
                jax[i].originalText.replace(/\\label\{([^\}]+)\}/g, function(x,y){
                    neWLabelsInPage.push(y);
                    return false;
                });
            }
            perPageEqs.push(neWLabelsInPage);
        }

        var eqCitationArray = document.getElementsByClassName("eqCitationSpan");
        var eqsOnWhichPage;
        for(var i=0, l=eqCitationArray.length; i<l; i++) {
            var key=eqCitationArray[i].innerHTML
                .replace(/.*\\ref\{([^\}]+)\}.*/g,"$1").replace(/.*\\eqref\{([^\}]+)\}.*/g,"$1");
            eqsOnWhichPage=perPageEqs.findIndex(function(x) {
                return x.indexOf(key) !== -1;
            });
            eqCitationArray[i].outerHTML=
                ""
                    +eqCitationArray[i].innerHTML
                +"";
        }
    }
);

Everything works well except when I want to refer to an equation from within another equation. In that case, MathJax doesn't compile the equation at all, but only the command \eqref{} inside the equation. I know it is intended to be so, but then any work around for such problems?

A: MathJax will not process math that contains HTML tags (other than a select few), so you will not be able to do the kind of replacements inside an expression like you are attempting to do here.
You can, however, use MathJax itself to handle the cross-page lining that I think you are trying to accomplish.  Here's one approach:

Put this before the script that loads MathJax.js itself.  You will need to collect the data from MathJax.Extension["TeX/AMSmath"].labels from all the pages you want to link to and put that in the var labels above (combine the data from all the pages into one object), and create the mapping from ids to page urls in var urls above.  In this example, there is \label{xyz2}\tag{2} in the file link-cross-page2.html, and any \ref{xyz2} on the page containing this code will link to link-cross-page2.html#mjx-eqn-2.
The rest of the code simply copies your labels into the AMSmath labels list when it is loaded, and configures TeX's formatURL() function to look up the file in your list and use that if it exists, otherwise it uses the base URL of the page.
Note that this does require that equation numbers are different across the pages, but I assume that is the case for you, otherwise you could not tell which page to link to.


text:
Q: How to store prices that have effective dates? I have a list of products. Each of them is offered by N providers.
Each providers quotes us a price for a specific date. That price is effective until that provider decides to set a new price. In that case, the provider will give the new price with a new date.
The MySQL table header currently looks like:
provider_id, product_id, price, date_price_effective

Every other day, we compile a list of products/prices that are effective for the current day. For each product, the list contains a sorted list of the providers that have that particular product. In that way, we can order certain products from whoever happens to offer the best price.
To get the effective prices, I have a SQL statement that returns all rows that have date_price_effective >= NOW(). That result set is processed with a ruby script that does the sorting and filtering necessary to obtain a file that looks like this:
product_id_1,provider_1,provider_3,provider8,provider_10...
product_id_2,provider_3,provider_2,provider1,provider_10...

This works fine for our purposes, but I still have an itch that a SQL table is probably not the best way to store this kind of information. I have that feeling that this kind of problema has been solved previously in other more creative ways.
Is there a better way to store this information other than in SQL? or, if using SQL, is there a better approach than the one I'm using?

A: I'd certainly store the effective date in the database.  After all, it's likely that people are going to want to be able to run queries to see how the price has changed over time or to cross-check oddities in orders against the historical product price table.  Depending on the type of queries you are running and the frequency of price changes, it may make sense to have separate tables for the current price and the historical prices.
In most systems that store prices, you would want an expiration date column in addition to the effective date to make it easier to determine which price is currently in effect since it saves you the trouble of having to look at the prior or next row to figure out which price was in effect at a given point in time.  I'm not clear on what your NOW() >= date_price_effective condition is doing-- presumably, that returns the current price along with all prior historical prices which seems odd to me.  I would think that the "effective price" would be the current price which would be defined by something like NOW() BETWEEN date_price_effective AND date_price_expired
I'm also not sure what your file is supposed to look like.  It's not clear to me what provider_1 represents-- the provider_id=1 price?-- or how you're ordering the provider data-- why does provider_1 appear first for product_id_1 and third for product_id_2.

A: If I understand your problem statement correctly, you need a way to handle generational data (i.e., the table contains multiple rows for each provider_id/product_id pair each of which is date sensistive).  In that case, you are looking for the most recent price for a product with an date_price_effective value that is less than or equal to today.  This type of situation is easy handled using an SQL subselect.
 SELECT
   provider_id, product_id, price, date_price_effective
 FROM
   price_table a
 WHERE
   date_price_effective =
     (
       SELECT
         MAX(date_price_effective)
       FROM
         price_table b
       WHERE
         b.provider_id = a.provider_id AND
         b.product_id = a.product_id AND
         b.date_price_effective <= NOW()
     );

A price is effective as long as it has the greatest date_price_effective value that is less than or equal to the date that the query is executed. A date_price_effective value that is greater than today is a future effective date. The code listed above returns the row data for each provider_id/product_id pair that has the date_price_effective value that is the closest to, but not later than the date the query is executed. The solution automatically brackets prices into effective date ranges.  The primary key for this table would be the triple { provider_id, product_id, date_price_effective };

A: For items that vary based on time (such as being able to answer things like "what was the price of X on date D" or "which cow was in feedlot Q on date E") I recommend reading the book "Developing Time-Oriented Database Applications in SQL." While this book is out of print, the author has graciously made available the PDF of the book as well as the associated CD on his website.
http://www.cs.arizona.edu/~rts/publications.html (look for the first item under "books").
For a brief introduction online, see:

*

*http://talentedmonkeys.wordpress.com/2010/05/15/temporal-data-in-a-relational-database/

*http://martinfowler.com/eaaDev/TemporalProperty.html


text:
Q: How to code this pattern using the while loop and for loop? I am supposed to code this pattern:
[1]
[0][0]
[1][1][1]
[0][0][0][0]
[1][1][1][1][1]
[0][0][0][0][0][0]
[1][1][1][1][1][1][1]
[0][0][0][0][0][0][0][0]
[1][1][1][1][1][1][1][1][1]

However, i am only able to give a output like this:
[1]
[0][0]
[1][1][1]
[0][0][0][0]
[1][1][1][1][1]
[0][0][0][0][0][0]
[1][1][1][1][1][1][1]
[0][0][0][0][0][0][0][0]
[1][1][1][1][1][1][1][1][1]
[0][0][0][0][0][0][0][0][0][0]

this is my current code:
a = '[1]'
b = '[0][0]'

for c in range(1,10,2):
    print(a)
    a = a + '[1][1]'
    print(b)
    b = b + '[0][0]'

Please help! I am supposed to the pattern with a while loop and for loop. Thanks in advance!

A: You're printing both a and b in every iteration, so naturally you can't get odd number of lines in your output.
Instead, use a normal range iterator of 9 and alternate between printing and appending to a and b depending on the counter's remainder of 2.
a = '[1]'
b = '[0][0]'

for c in range(9):
    if c % 2 == 0:
        print(a)
        a = a + '[1][1]'
    else:
        print(b)
        b = b + '[0][0]'

This outputs:
[1]
[0][0]
[1][1][1]
[0][0][0][0]
[1][1][1][1][1]
[0][0][0][0][0][0]
[1][1][1][1][1][1][1]
[0][0][0][0][0][0][0][0]
[1][1][1][1][1][1][1][1][1]


text:
Q: SQL - better way to group and sum based on condition I have data like:

Year
Amount

2001
1

2020
2

2020
2

2021
5

2022
2

2022
2

2021
2

And I want to summarise data like:

Year
Amount

2020 and before
5

2021
7

2022
4

I thought of 2 ways, and want to see whether there are any better method.

*

*Use Union

Select Year, sum(Amount) from TABLE_A
where Year <= 2020
UNION
Select Year, sum(Amount) from TABLE_A
where Year > 2020

*Added a new column

SELECT YR, SUM(Amount) FROM
(
  SELECT CASE WHEN Year <= 2020 THEN '2020_and_before') ELSE Year END as YR, *
  FROM TABLE_A ) A
GROUP BY YR

I can get the results I want, but want to see whether there is better method

A: In MySQL, you can avoid subqueries with a CASE expression in the following way:
SELECT CASE WHEN Year_ <= 2020 THEN "2020 or before"
            ELSE Year_ END AS Year_ ,
       SUM(Amount) AS total_amount
FROM tab
GROUP BY 1

Output:

Year_
total_amount

2020 or before
5

2021
7

2022
4

Check a MySQL demo here.
Note: You should avoid messing with data types. If you're supposed to store years in the year field, you could leave the integer 2020, instead of having a string like "2020 or before".


text:
Q: Checkbox stops working after triggered manually I've wrote this jQuery snippet to handle tr click, to add a bootstrap class to it and click the first checkbox in it.
$('body').on('change', '.select-all-children', function(e) {
  var checked = this.checked;

  $('.select-child').each(function() {
    $(this).prop('checked', checked);

    if(checked) {
      $(this).parent().parent().addClass('warning');
    } else {
      $(this).parent().parent().removeClass('warning');
    }
  });

});

$('body').on('click', '.table-selectable tbody tr', function(e) {
  var checkbox = $(this).find('.select-child');

  checkbox.click();

  var checked = checkbox[0].checked;

  if(checked) {
    $(this).addClass('warning');
  } else {
    $(this).removeClass('warning');
  }
});

$('body').on('change', '.select-child', function(e) {
  var checked_total = $('.select-child:checked').length;

  if(checked_total == $('.select-child').length) {
    $('.select-all-children').prop('checked', true);
  } else {
    $('.select-all-children').prop('checked', false);
  }
});

Whenever I click on the tr and thus trigger this call:
checkbox.click();

I cannot click on the checkbox no more, but the tr click works fine.
This is my HTML markup of the table:

        <input type="checkbox" class="select-all-children">

          <input type="checkbox" class="select-child">

A: You can do it more simply than your method, just like this:
Handling Select All checkbox: ( will just check/uncheck the FIRST checkbox in rows, and adding warning class to selected rows ).
$('.select-all-children').click(function (e) {
    $(this).closest('table').find('tr td:first-child input:checkbox').prop('checked', this.checked);

    if (this.checked){
        $(this).closest('table').find('tbody tr').addClass('warning');
    } else {
        $(this).closest('table').find('tbody tr').removeClass('warning');
    }
});

Handling clicks on the tr: ( also we can using toggleClass instead of add/remove class ).
$('.table-selectable tbody tr td:first-child input:checkbox').on('click', function(e) {
    $(this).closest('tr').toggleClass('warning');
});

Now see JsFiddle DEMO, I hope it works for you, Thanks.

A: I have changed the code like this and the checkbox works fine. Please see the change in JQuery code with comments.
$('body').on('change', '.select-all-children', function (e) {
            var checked = this.checked;
        $('.select-child').each(function () {
            $(this).prop('checked', checked);

            if (checked) {
                $(this).parent().parent().addClass('warning');
            } else {
                $(this).parent().parent().removeClass('warning');
            }
        });

    });

    $('body').on('click', '.table-selectable tbody tr', function (e) {
        var checkbox = $(this).find('.select-child');

        //Old code commented:
        //checkbox.click();

        //Modified Code:
        checked.click();

        var checked = checkbox[0].checked;

        if (checked) {
            $(this).addClass('warning');
        } else {
            $(this).removeClass('warning');
        }
    });

    $('body').on('change', '.select-child', function (e) {
        var checked_total = $('.select-child:checked').length;

        if (checked_total == $('.select-child').length) {
            $('.select-all-children').prop('checked', true);
        } else {
            $('.select-all-children').prop('checked', false);
        }
    });

Thank you.


text:
Q: Why there are 3 different ports for the .net core 2.1 SPA? I'm learning dotnet core 2.1 SPA, and when I run the donet core 2.1 SPA  Angular with dotnet run, I noticed that there are 3 differnt ports:

*

*https:localhost:5001

*http:localhost:5000

*http:localhost:34941
When I use the second url, it just automatically redirect to the first url, and I got security error.
For the 3rd url, it works. I think because it's for the client, where 1st and 2nd url would be used for APIs calls with authentications?
What would happen in a live environment?

The configuration in Program.cs file
public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

A: 5000 and 5001: Kestrel HTTP and HTTPS Defaults
5000 is for HTTP and 5001 is for HTTPS. Those are defaults in the ASP.NET Core Kestrel Server. 5000 redirects to 5001 because of app.UseHttpsRedirection() in your Startup class.
34941: Any available port for the NG Live Development Server
This is an arbitrary, available port that Microsoft.AspNetCore.SpaServices uses to start the NG Live Development Server. The spa.UseAngularCliServer(npmScript: "start") method in your Startup class calls the the start script from your package.json file like this:
ng serve --extract-css "--port" "50415"`

The port that it passes is any currently available port that the SpaServices find.
See also

*

*https://github.com/aspnet/JavaScriptServices

*https://github.com/aspnet/KestrelHttpServer


text:
Q: Google unable to crawl my website Recently i have a crawl error appear in my google search console :

Google couldn't crawl your site because we were unable to access your
  site's robots.txt file

my robots.txt content :
User-agent: *
Disallow: /wp-admin/
Allow: /wp-admin/admin-ajax.php
Sitemap: http://www.name.com/sitemap.xml

when i try FETCH AS GOOGLE it say :

Temporarily unreachable

A: Common causes for this error is blocked google ip address by hosting company. You can contact your hosting company and find out whether this is so.


text:
Q: Github GraphQl - How to get a list of commits between tags With Github GraphQL I want to answer the question:

What commits have been merged into master between releases/tags?

The result should be similar to the results for this question Get commit list between tags in Git if I were to do it on the command line.
I'm using the developer explorer and wondering if I will be able to do this with a single query or if I will need several. I tried the following but it does not give me the commits between tags that have not been tagged, just the tagged commits.
{
  repository(owner: "CoolCompany", name: "awesome-new-ui") {
    refs(refPrefix: "refs/tags/", first: 2, orderBy: {field: TAG_COMMIT_DATE, direction: DESC}) {
      edges {
        node {
          id
          name
          target {
            oid
            ... on Commit {
              author {
                date
                email
                name
              }
              message
            }
          }
        }
      }
    }
  }
}

A: @lee-dohm from the Github GraphQL community helped me arrive at a solution which is posted here
I can paste my solution here as well. It seems this problem is not solve-able with a single query, but it can be done with 2 that work in conjunction with each other:
Step 1: Get the most recent release information. You could modify this for tags as well.
{
  repository(owner: "CoolCompany", name: "awesome-ui") {
    releases(last: 1) {
      edges{
        node{
          tagName
          createdAt
        }
      }
    }
  }
}

Step 2: Use the value from the createdAt (associated with the release or tag) and do this:
{
  repository(owner: "CoolCompany", name: "awesome-ui") {
    nameWithOwner
    object(expression: "master") {
      ... on Commit {
        oid
        history(first: 100, since: "$createdAtDate") {
          nodes {
            oid
            messageHeadline
            author {
              user {
                login
              }
            }
            committedDate
          }
        }
      }
    }
  }
}


text:
Q: Find angle given ratio between sine and angle I know an angle is between 0 and $\pi$ (180 degrees).
I know the ratio between its sine and the angle itself. Specifically it's $\frac{15}{16}$, but I am more interested in the general case.
Since there is a one-to-one correspondence between $\theta$ and $\frac{\sin\theta}{\theta}$ in ($0$, $\pi$], I should be able to find the angle given that ratio, but I'm really struggling to. Any ideas?

A: To be an invertible function does not always mean that the inverse function is easy to compute. Your problem is an instance of Kepler's equation arising in orbital mechanics, which is usually solved numerically through Newton's method and variants (see Colwell).
In our case, assuming $\theta\in(0,\pi)$ and $\frac{\sin\theta}{\theta}=\frac{15}{16}$, a good starting point for Newton's method is given by approximating $\frac{\sin\theta}{\theta}$ with $1-\frac{\theta^2}{6}$. By setting $\theta_0=\sqrt{\frac{3}{8}}$ Newton's method
$$\theta_{n+1} = \frac{\theta_n\cos\theta_n-\sin\theta_n}{\cos\theta_n-\frac{15}{16}} $$
converges pretty fast to the actual solution $\theta=0.618254969154963\ldots\approx 35^\circ 25'24''$. As a curious coincidence, such solution is pretty close to the golden ratio $\frac{\sqrt{5}-1}{2}$.

A: I guess what you are asking is how to compute the inverse function of $f(\theta) = \frac{\sin \theta}{\theta}$.
There's no particular formula for it. You could use analytic methods to estimate it, for example by computing the first few terms of its Taylor series expansion near a value that you know (as suggested in the link provided by @JackD'Aurizio's comment).
It's not always easy to compute the function you want to compute.
Think about how hard it is to compute just the inverse function of $\sin \theta$. Having a name for it, the "arcsin", does not make it any easier to compute (and one could assign a name for the inverse function of $\frac{\sin\theta}{\theta}$, but that would not make it any easier to compute).
Actually, for that matter, think about how hard it is to compute $\sin(\theta)$ itself. Being one of the most venerable functions of mathematics does not make it particularly easy to compute, although generally we can estimate it pretty well by analytic methods.

A: As already answered, you need a numerical method for the solution of $\sin(x)=k x$.
You can generate a pretty good estimate of the solution using the approximation
$$\sin(x) \simeq \frac{16 (\pi -x) x}{5 \pi ^2-4 (\pi -x) x}\qquad (0\leq x\leq\pi)$$ was proposed by Mahabhaskariya of Bhaskara I, a seventh-century Indian mathematician (have a look here.
This would reduce to a quadratic
$$4 k x^2-(4 \pi  k-16) x+\pi(5 \pi  k-16 )=0$$ the solution looked for for being
$$x=\frac{1}{120} \left(60 \pi -256+\sqrt{65536+30720 \pi -14400 \pi ^2}\right)\approx 0.613716$$ from which Newton method would converge very fast
$$\left(
\begin{array}{cc}
 0 & \color{red}{0.61}371595846525587708 \\
 1 & \color{red}{0.618}30451936663628509 \\
 2 & \color{red}{0.6182549}7495721438489 \\
 3 & \color{red}{0.618254969154963}32702 \\
 4 & \color{red}{0.61825496915496324745}
\end{array}
\right)$$
If you want a better approximation, have alook here where Christian Blatter proposed
$$x\approx\sqrt{{\pi^2+5.95839 k - 15.828 k^2\over 1 + 2.60371 k + 0.690687 k^2}}$$ leading to $x\approx 0.617646$
If you are ready for iterations, you could make a very simple approximation $\sin(x)\sim a (\pi-x)x$ and compute $a$ minimizing with respect to $a$
$$\int_0^\pi \left(\sin(x)-a (\pi-x)x \right)^2\,dx$$ leading to $a=\frac{120}{\pi ^5}$ and then an estimate $x=\pi -k\frac{\pi ^5 }{120}$ which, for your case would be $\approx 0.750814$
Edit
Back to the problem three and half years latter, continuing from  Christian Blatter's answer, I built the following approximation
$$x=\sqrt{\frac{\pi ^2+58.834 k+73.7272 k^2-49.5852 k^3-79.9966 k^4-12.849 k^5 } {1+7.96113 k+20.3924 k^2+19.167 k^3+5.64183 k^4+0.287409 k^5}}$$ in which all parameters are highly significant from a statistical point of view.
The errors are smaller than $10^{-8}$ as shown in the table below
$$\left(
\begin{array}{ccc}
k & \text{exact} & \text{approximation} \\
 0.00 &  \pi & \pi \\
 0.05 &  2.99145643340 & 2.99145643328 \\
 0.10 &  2.85234189445 & 2.85234189458 \\
 0.15 &  2.72114256303 & 2.72114256287 \\
 0.20 &  2.59573907964 & 2.59573907964 \\
 0.25 &  2.47457678737 & 2.47457678754 \\
 0.30 &  2.35644114986 & 2.35644114992 \\
 0.35 &  2.24032553177 & 2.24032553163 \\
 0.40 &  2.12534519139 & 2.12534519122 \\
 0.45 &  2.01067452551 & 2.01067452551 \\
 0.50 &  1.89549426703 & 1.89549426722 \\
 0.55 &  1.77893894148 & 1.77893894169 \\
 0.60 &  1.66003481326 & 1.66003481330 \\
 0.65 &  1.53761467622 & 1.53761467601 \\
 0.70 &  1.41018537665 & 1.41018537635 \\
 0.75 &  1.27569810928 & 1.27569810916 \\
 0.80 &  1.13110258565 & 1.13110258592 \\
 0.85 &  0.97135215453 & 0.97135215504 \\
 0.90 &  0.78668307205 & 0.78668307214 \\
 0.95 &  0.55191097862 & 0.55191097740 \\
 1.00 &      0 & 0
\end{array}
\right)$$ For $k=\frac{15}{16}$, the approximate model would give $x=0.618254968311$.


text:
Q: .waf configure returns 'Checking for header boost/format.hpp : not found' error i am trying to install patchage 1.0.4 from this website and './waf configure' returns this error.
Also m new to linux so i don't understand much.
this is a pic of the error statement
Thanks in advance for help.

A: For latest Ubuntu 21.04 you have to use the following commands to get all dependencies and compile patchage application:
sudo apt-get install python-is-python3 libdbus-1-dev libdbus-glib-1-dev libglibmm-2.4-dev libgtkmm-2.4-dev libganv-dev libjack-dev libasound2-dev libboost1.74-dev libfmt-dev

cd ~/Downloads
wget -c http://download.drobilla.net/patchage-1.0.4.tar.bz2
tar -xf patchage-1.0.4.tar.bz2
cd patchage-1.0.4
./waf configure
./waf
sudo ./waf install


text:
Q: How to implement half-circle menu (sub item) with CSS and JavaScript on mobile web? I want to use a half-circle menu when I surf the mobile web with my right hand. Can somebody teach me how to implement half-circle menu (sub item) with CSS and JavaScript on mobile web? I have tried it with CSS transform:rotate and border-radius, but it could not be worked successfully.

There is a half-circle menu button, this button can open and close menu. When I click the menu button, the main-level will be popped up. Then I click "Main 1", the sub-level (Sub 1-1, Sub 1-2, Sub 1-3) will be popped up.

As just mentioned, When I click "Main 6", the sub-level (Sub 6-1, Sub 6-2, Sub 6-3) will be popped up.

Here is the architecture of the menu:
Menu
   Main 1
      Sub 1-1
      Sub 1-2
      Sub 1-3
   Main 2
      Sub 2-1
      Sub 2-2
      Sub 2-3
   Main 3
      Sub 3-1
      Sub 3-2
      Sub 3-3
   Main 4
      Sub 4-1
      Sub 4-2
      Sub 4-3
   Main 5
      Sub 5-1
      Sub 5-2
      Sub 5-3
   Main 6
      Sub 6-1
      Sub 6-2
      Sub 6-3

A:
No SVG, just plain css.
Basically,

*

*just turn rectangles over the same corner with increasing angles. Like a paper fan.

*Put the whole thing at the outermost level into a circle (border-radius:r px;overflow: hidden).

*Repeat for any further, outer rings.

*Add another outer overflow:hidden wrapper, if the enlarged last menu ('menu 5') bothers you...

*Javascript is only needed, as soon as you deal with clicks and want to toggle outer rings visibility for sub-options...

➪ http://codepen.io/fnocke/pen/Vazobq?editors=0100
This is simplified stylus syntax (similar to less, sass), see codepen➝'view compiled' for full css:
li
  position absolute
  top 50%
  display block
  transform-origin top right
  overflow hidden
  width r
  height r

li:nth-of-type(1)
  transform: rotate(60deg)
  background #000
li:nth-of-type(2)
  transform: rotate(40deg)
  background #222
..

A: You could do this with SVG. When you click on first-ring buttons or (Main 1, Main 2...) it will update text of second-ring buttons or (Sub 1 1, Sub 2 1...), and this is just for demo purpose. You can use js to change links inside <a xlink:href=""></a> instead of just text.

var firstRing = $('.first-ring');
var secondRing = $('.second-ring');
var siblings = firstRing.siblings('.second-ring');
var open = $('#open');

open.click(function() {
  firstRing.toggleClass('show');

  if (!firstRing.hasClass('show')) {
    siblings.removeClass('show');
  }
});

firstRing.children('g').click(function() {
  var data = $(this).data('url');
  siblings.addClass('show');

  secondRing.children('g').children('a').children('text').each(function() {
    var text = $(this).text().split(' ');
    $(this).text(text[0] + ' ' + data + ' ' + text[2]);
  });
});
svg {
  position: fixed;
  top: 50%;
  right: 0;
  transform: translateY(-50%);
  font-size: 12px;
}

g {
  fill: white;
  transition: all 0.3s ease-in;
  cursor: pointer;
}

text {
  fill: white;
}

g:not(.first-ring):not(.second-ring):hover {
  opacity: 0.6;
}

.first-ring, .second-ring {
  opacity: 0;
}

.show {
  opacity: 1;
}

.main      {fill: #2B2B2B;}
.one       {fill: #2B2B2B;}
.two       {fill: #373737;}
.three     {fill: #444444;}
.four      {fill: #515151;}
.five      {fill: #5E5E5E;}
.six       {fill: #6A6A6A;}
.sub-one   {fill: #777777;}
.sub-two   {fill: #848484;}
.sub-three {fill: #909090;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>

<svg width="400px" height="400px">
  <!-- This is First ring or Menu part-->
  <g id="open">
    <path class="main" d="M395.545,200.03l-0.08-0.12l-0.05,0.12l-22.44,54.17c-7.12-2.97-13.54-7.311-18.909-12.69
  c-5.41-5.41-9.771-11.87-12.75-19.05c-2.86-6.91-4.44-14.49-4.44-22.43c0-7.91,1.56-15.45,4.4-22.33
  c2.96-7.19,7.31-13.66,12.71-19.07c5.42-5.45,11.899-9.83,19.109-12.82L395.545,200.03z" />
    <text transform="matrix(1 0 0 1 351.7607 206.0303)" class="st1 st3">MENU</text>
  </g>

  <!-- This is second-ring -->
  <g class="first-ring">
    <g data-url="1">
      <path class="one" d="M373.095,145.81c-7.21,2.99-13.689,7.37-19.109,12.82l-50.94-50.9c12.06-12.08,26.47-21.82,42.5-28.46
  L373.095,145.81z" />
      <text transform="matrix(0.5061 0.8625 -0.8625 0.5061 332.1963 107.73)" class="st1 st3">Main 1</text>
    </g>
    <g data-url="2">
      <path class="two" d="M353.985,158.63c-5.4,5.41-9.75,11.88-12.71,19.07l-66.58-27.45c6.609-16.02,16.31-30.44,28.35-42.52
  L353.985,158.63z" />
      <text transform="matrix(0.8283 0.5603 -0.5603 0.8283 295.585 136.9624)" class="st1 st3">Main 2</text>
    </g>
    <g data-url="3">
      <path class="three" d="M341.275,177.7c-2.841,6.88-4.4,14.42-4.4,22.33h-72c0-17.63,3.49-34.44,9.82-49.78L341.275,177.7z" />
      <text transform="matrix(0.9946 0.1039 -0.1039 0.9946 283.0908 183.2314)" class="st1 st3">Main 3</text>
    </g>
    <g data-url="4">
      <path class="four" d="M341.315,222.46l-66.53,27.57c-6.391-15.4-9.91-32.29-9.91-50h72
  C336.875,207.97,338.455,215.55,341.315,222.46z" />
      <text transform="matrix(0.9891 -0.1475 0.1475 0.9891 283.0898 225.0303)" class="st1 st3">Main4</text>
    </g>
    <g data-url="5">
      <path class="five" d="M354.065,241.51l-50.841,51c-12.08-12.06-21.8-26.46-28.439-42.479l66.53-27.57
  C344.295,229.64,348.655,236.1,354.065,241.51z" />
      <text transform="matrix(0.8627 -0.5057 0.5057 0.8627 299.6768 268.6953)" class="st1 st3">Main 5</text>
    </g>
    <g data-url="6">
      <path class="six" d="M372.975,254.2l-27.56,66.53c-15.89-6.601-30.2-16.25-42.19-28.221l50.841-51
  C359.435,246.89,365.854,251.23,372.975,254.2z" />
      <text transform="matrix(0.6338 -0.7735 0.7735 0.6338 332.1963 300.0664)" class="st1 st3">Main 6</text>
    </g>
  </g>

  <!-- This is third-ring or sub part -->
  <g class="second-ring">
    <g>
      <a xlink:href="">
        <path class="sub-one" d="M345.545,79.27c-16.03,6.64-30.44,16.38-42.5,28.46c-12.04,12.08-21.74,26.5-28.35,42.52l-54.061-22.3
  c9.59-23.18,23.66-44.03,41.141-61.47c17.46-17.42,38.319-31.45,61.5-40.99L345.545,79.27z" />
        <text transform="matrix(0.7099 0.7043 -0.7043 0.7099 263.1514 75.9663)" class="st1 st3">Sub 1 1</text>
      </a>
    </g>

    <g>
      <a xlink:href="">
        <path class="sub-two" d="M274.785,250.03l-54.02,22.399c-9.271-22.29-14.391-46.75-14.391-72.4c0-25.53,5.07-49.87,14.26-72.08
  l54.061,22.3c-6.33,15.34-9.82,32.15-9.82,49.78C264.875,217.74,268.395,234.63,274.785,250.03z" />
        <text transform="matrix(1 0 0 1 213.585 200.1899)" class="st1 st3">Sub 1 2</text>
      </a>
    </g>

    <g>
      <a xlink:href="">
        <path class="sub-three" d="M345.415,320.73l-22.28,53.779c-23.01-9.49-43.74-23.41-61.109-40.68c-17.51-17.41-31.631-38.24-41.26-61.4
  l54.02-22.399c6.64,16.02,16.359,30.42,28.439,42.479C315.215,304.48,329.525,314.13,345.415,320.73z" />
        <text transform="matrix(0.7305 -0.6829 0.6829 0.7305 266.9395 328.9912)" class="st1 st3">Sub 1 3</text>
      </a>
    </g>

  </g>
</svg>

A: You have to use an SVG library. Trying to make it with basic HTML elements and jQuery is probably possible using image maps, but wrapping it around jQuery will make you want to kill yourself.
I recommend d3.js since it not only handles presentation part (looks, animations) but also data with which you'll feed it.


text:
Q: Why won't image 1 move to the right? I'm very new to coding and was wondering how I could make this image move to the right. I added all of my code so that it would be a bit more understandable for what's going on. The moveRight command will not actually move the png to the right which is why I need help fixing and understanding why it won't work. If someone can please help me it would be greatly appreciated.
 PImage background, backgroundGameState1, headbasketballbackground, player1, player2;
boolean moveRight, moveLeft;
int canvasSizeX= 1000;
int canvasSizeY = 600;
int mainBackgroundX = 1000;
int mainBackgroundY = 600;
int gameState1 = 1;
int player1X = 100;
int player1Y = 200;
int player2X = 100;
int player2Y = 200;
int backgroundGameState1X= 1000;
int backgroundGameState1Y=600;
int time;
int player1MovmentX = 100;
int player2MovmentX = 700;

void setup() {
  //size of canvas
  size(1000, 600);
  //Loaded images and called them, also made sure to resize them in order to match the canvas size or to make program more asthetically pleasing
  background = loadImage("headbasketballbackground.png");
  background.resize(mainBackgroundX, mainBackgroundY);
  backgroundGameState1 = loadImage("backgroundgamestate1.png");
  backgroundGameState1.resize(backgroundGameState1X, backgroundGameState1Y);
  player1 = loadImage("steph.png");
  player1.resize(player1X, player1Y);
  player2 = loadImage("paul.png");
  player2.resize(player2X, player2Y);

  time=millis();
}

void draw() {
  if (gameState1 == 1) {
    background(backgroundGameState1);
    if (millis() > time + 1000) {
      text("Click On Space To Enter The Game!", 100, 100);
      textSize(50);
      // delay(3000);
    }
    drawGameState1();
  }
  if (gameState1 == 2) {
    background(background);
    image(player1, player1MovmentX, 300);
    image(player2, player2MovmentX, 300);
  }
  //  if (gameState2 == 3) {
  //  text("Congrats you won!");
  //}
}

void drawGameState1() {
}
void drawGameState2() {
  drawPlayer1Movment();

}
void drawPlayer1Movment(){
    if(moveRight){
  player1MovmentX += 25;
}
}
void drawGameState3() {
}

void keyPressed() {

  if (gameState1 == 1) {
    if (keyCode == 32) {
      gameState1 = 2;
    }
  }
  else if(gameState1 == 2){
    if(keyCode == RIGHT){
    moveRight = true;
  }

  }

}
void keyReleased(){
  if(keyCode == RIGHT){
  moveRight = false;
  }
}

A: I don't think you ever called drawPlayer1Movement().  Add it to keyPressed() and player1 should move to the right when you hit the right arrow.
void keyPressed() {
  if (gameState1 == 1) {
    if (keyCode == 32) {
      gameState1 = 2;
    }
  } else if (gameState1 == 2) {
    if (keyCode == RIGHT) {
      moveRight = true;
      drawPlayer1Movment();
    }
  }
}


text:
Q: How to write SQLite update operation in two tables? I am using SQLite,
TABLE A
(
 ID
 FileNAME
 FOLDERID
)

TABLE B
(
 FOLDERID
 FOLDERPATH
)

I want to write a SQL statement to delete all files in A where its Folder is subfolder of C:\ABC\;
How can I make it in one SQLite statement, and is it the best way to do?
Many thanks!

A: the following works fine:
create table table_a (

   id int,
   file_name varchar(300),
   folder_id int
);

create table table_b (
 folder_id int,
 folder_path varchar(300)
);

insert into table_a (id, file_name, folder_id) values (1, 'file1.txt', 1);
insert into table_a (id, file_name, folder_id) values (1, 'file2.txt', 1);
insert into table_a (id, file_name, folder_id) values (1, 'file2-1.txt', 2);
insert into table_b (folder_id, folder_path) values (1, 'c:\abc\somefolder\another');
insert into table_b (folder_id, folder_path) values (2, 'c:\abcNOT\somefolder\another');

delete
from table_a
where folder_id in (select folder_id from table_b where substr(folder_path, 1, 7) = 'c:\abc\');

select * from table_a;

A: Same idea but with some modifications:
SQLite recognize referential integrity now:
CREATE TABLE Table_a (
    id int,
    file_name varchar(300),
    folder_id int,
    FOREIGN KEY(folder_id) REFERENCES Table_b (folder_id)
);
CREATE TABLE Table_b (
    folder_id int,
    folder_path varchar(300)
);
CREATE TABLE Table_b (folder_id, folder_path) VALUES (1, 'c:\abc\somefolder\another');
CREATE TABLE Table_b (folder_id, folder_path) VALUES (2, 'c:\abcNOT\somefolder\another');
CREATE TABLE Table_a (id, file_name, folder_id) VALUES (1, 'file1.txt', 1);
CREATE TABLE Table_a (id, file_name, folder_id) VALUES (1, 'file2.txt', 1);
CREATE TABLE Table_a (id, file_name, folder_id) VALUES (1, 'file2-1.txt', 2);
DELETE
FROM Table_a
WHERE folder_id IN (SELECT folder_id FROM Table_b WHERE folder_path LIKE 'c:\abc\%');
SELECT * FROM Table_a;


text:
Q: linear proposition quality(logic) wondering about that. if a set of linear properties is defined as linear if it follows for every $a,b \in \sum$ $a \Rightarrow b$ or $b \Rightarrow a$
if i wanted to prove that a set of propositions I is defined such that: I only consists of a single elementary proposition p, and the only logical property is $\rightarrow$, how can i prove that I is linear according to the given definition(for every $a,b \in \sum$ $a \Rightarrow b$ or $b \Rightarrow a$)
and to help understand this concept better, if i wanted to show that if $\sum$ is a set of linear propositions and each proposition in $\sum$ has a model in which the proposition holds true, how can i show that there exists a model for $\sum$?
my attempt:
for the first: we'll check for a single proposition: if I consists only oneproposition p such that the only logical operator is $\rightarrow$ that means that for every $a,b \in \sum$ $a \Rightarrow b$ or $b \Rightarrow a$. we'll assume it holds true for every n amount of elements in $\sum$ ad we'll check for validity for n+1 number of elements. here i have my problem - if we have more than two elements(n+1 in this case), how can we deduct that I will be linear, at about infinite elements, i think that there is a case where it might be problematic.
for the second: as far as i understand, if we can show that if $\sum$ is linear aמd each poperty in $\sum$ has a model in which the proposition is true, we can deduct that $\sum$ is not bounded, and then using the induction i couldn't yet prove, we can deduct that if all of the above holds true, then there exists a model for $\sum$.
please help me fix and improve that, using the correct mathmatical writing or sohw me what i've done wrong.
thank you very much!


text:
Q: Get the click event from a button in a django view i think the title is pretty clear. I want to know when the user clicks the button to run a piece of code in a function in my views.py. lets say i have this html:

    <input type="button" name="_mail" value="Enviar Mail">

and i want to run this code if the user clicks on it:
send_templated_mail(template_name='receipt',
                    from_email='robot@server.com',
                    recipient_list=[request.user.email],
                    context=extra_context)

that´s all i want to do.
EDIT: this is the view that i have:
def verFactura(request, id_factura):
    fact = Factura.objects.get(pk = id_factura)
    cliente = Cliente.objects.get(factura = fact)
    template = 'verfacturas.html'
    iva = fact.importe_sin_iva * 0.21
    total = fact.importe_sin_iva + iva

    extra_context = dict()
    extra_context['fact'] = fact
    extra_context['cliente'] = cliente
    extra_context['iva'] = iva
    extra_context['total'] = total

    if  (here i want to catch the click event):
        send_templated_mail(template_name='receipt',
                    from_email='imiguel@exisoft.com.ar',
                    recipient_list =['ignacio.miguel.a@gmail.com'],
                    context=extra_context)

        return HttpResponseRedirect('../facturas')

return render(request,template, extra_context)

A: You should create this function in your views.py, map it to the url in your urls.py and add event handler using JavaScript (pure JS or using jQuery as shown below):
JS (using jQuery):
$('#buttonId').click(function() {
    $.ajax({
        url: your_url,
        method: 'POST', // or another (GET), whatever you need
        data: {
            name: value, // data you need to pass to your function
            click: true
        }
        success: function (data) {
            // success callback
            // you can process data returned by function from views.py
        }
    });
});

HTML:

    <input type="button" id="buttonId" name="_mail" value="Enviar Mail">

Python:
def verFactura(request, id_factura):

    ...

    if request.POST.get('click', False): # check if called by click
        # send mail etc.

    ...

Note that if you're going to use POST method you should care about csrf (cross-site request forgery) protection as described HERE


text:
Q: Value of $\beta$ in Boltzmann statistics when degeneracy of quantum states is taken into account The relationship between entropy $S$, the total number of particles $N$, the total energy $U(\beta)$, the partition function $Z(\beta)$ and a yet to be defined constant $\beta$ is:
$$S(\beta)=k_BN \cdot \ln(Z(\beta)) - \beta k_B \cdot U(\beta)$$
Which leads to:
$$\frac{dS}{d\beta} = -k_B\beta \cdot \frac{dU}{d\beta}$$
And since $dS = \frac{dU}{T}$ this means that $\beta = -\frac{1}{k_BT}$ Source starting from sheet 40
However, this derivation does not take the degeneracy of quantum states into account. If it does then $S(\beta)$ would have an extra parameter in its formula. If the number of quantum states of an energy level is $g_j$, then I'd conclude:
$$S = k_BN \cdot \ln(Z(\beta)) - k_B\beta\cdot U(\beta) + k_B \cdot \sum^n_{j=1}\bigg[\ln(g_j)\cdot \frac{N}{Z(\beta)} \cdot e^{\beta E_j}\bigg]$$
Since $\ln(g_j) = \ln\big(\frac{N}{Z(\beta)}e^{\beta E_j}\big)- \beta E_j - \frac{N}{Z(\beta)}$, this would eventually give me:
$$\frac{dS}{d\beta} = k_B\cdot\left( - \beta\cdot\frac{dU}{d\beta} + \frac{U(\beta)\cdot N}{Z(\beta)} - U(\beta) \right)$$
Derivation. But using again $dS = \frac{dU}{T}$, this relationship does not give $\beta = -\frac{1}{k_BT}$.
Is it permitted for $\beta$ to have a different value than $-\frac{1}{k_BT}$ when quantum states is taken into account or am I misunderstanding something here?

A: I have figured it out.
The way I included degeneracy was correct but I made some subtle mistakes during substitution of some parameters.
The formula for $\ln(\Omega)$ when degeneracy $g_j$ is taken into account is:
$$\ln(\Omega)= N \cdot \ln(N) - N - \sum^n_{j=1}[n_j \cdot \ln(n_j) - n_j] + \sum^n_{j=1} [\ln(g_j) \cdot n_j]$$
Substituting $n_j = g_j \cdot \frac{N}{Z} \cdot e^{\beta E_j}$ (I erroneously left out the $g_j$ during this substitution) along with rewriting, splitting the summations and simplifying eventually gives me:
$$\ln(\Omega) = N \cdot \ln(Z) - \beta U$$
Which is the exact equation as when degeneracy is not taken into account, and thus I get the same value for $\beta$ when taking the derivative of $S = k_B \cdot \ln(\Omega)$ and putting it next to the equation of entropy $dS = \frac{dU}{T}$.
Details Derivation
Formula for $\ln(\Omega)$ when taking degeneracy into account
$$\ln(\Omega)= N \cdot \ln(N) - N - \sum^n_{j=1}[n_j \cdot \ln(n_j) - n_j] + \sum^n_{j=1} [\ln(g_j) \cdot n_j]$$
According to Boltzmann Statistics $n_j = g_j \frac{N}{Z} e^{\beta E_j}$. Furthermore, $\ln(n_j) = \ln\big(g_j \frac{N}{Z}\big) + \beta E_j$. Substituting these parameters:
$$\ln(\Omega)= N \cdot \ln(N) - N - \sum^n_{j=1}\bigg[g_j \frac{N}{Z} e^{\beta E_j}\cdot \bigg(\ln\big(g_j \frac{N}{Z}\big) + \beta E_j\bigg) - g_j \frac{N}{Z} e^{\beta E_j}\bigg] + \sum^n_{j=1} \bigg[\ln(g_j) \cdot g_j \frac{N}{Z} e^{\beta E_j}\bigg]$$
Splitting the 1st summation into 3 summations between the + and – signs and removing the brackets that appear after splitting:
$$\ln(\Omega)= N \cdot \ln(N) - N - \sum^n_{j=1}\bigg[g_j \frac{N}{Z} e^{\beta E_j}\cdot \ln\big(g_j \frac{N}{Z}\big)\bigg] - \beta\sum^n_{j=1}\bigg[g_j \frac{N}{Z} e^{\beta E_j} \cdot E_j)\bigg] + \sum^n_{j=1}\bigg[g_j \frac{N}{Z} e^{\beta E_j}\bigg] + \sum^n_{j=1} \bigg[\ln(g_j) \cdot g_j \frac{N}{Z} e^{\beta E_j}\bigg]$$
The 2nd summation is equal to the total energy $U$, and the 3rd summation is equal to the total number of particles $N$ which cancels the $-N$ term.
$$\ln(\Omega)= N \cdot \ln(N) - \sum^n_{j=1}\bigg[g_j \frac{N}{Z} e^{\beta E_j}\cdot \ln\big(g_j \frac{N}{Z}\big)\bigg] - \beta U + \sum^n_{j=1} \bigg[\ln(g_j) \cdot g_j \frac{N}{Z} e^{\beta E_j}\bigg]$$
In the 1st summation term, substituting $\ln\bigg(g_j \frac{N}{Z}\bigg) = \ln(g_j) + \ln\big(\frac{N}{Z}\big)$ and then splitting that summation between the newly created + sign as well and removing the appearing brackets:
$$\ln(\Omega)= N \cdot \ln(N) - \sum^n_{j=1}\bigg[g_j \frac{N}{Z} e^{\beta E_j}\cdot \ln(g_j)\bigg] - \ln\big(\frac{N}{Z}\big) \sum^n_{j=1}\bigg[g_j \frac{N}{Z} e^{\beta E_j}\bigg] -\beta U + \sum^n_{j=1} \bigg[\ln(g_j) \cdot g_j \frac{N}{Z} e^{\beta E_j}\bigg]$$
The first and 3rd summations cancel each other out. The 2nd summation is equal to $N$, giving:
$$\ln(\Omega)= N \bigg(\ln(N) - \ln\big(\frac{N}{Z}\big)\bigg) - \beta U$$
Since, $\ln(N) - \ln\big(\frac{N}{Z}\big) = \ln(Z)$, this gives:
$$\ln(\Omega) = N\cdot \ln(Z) - \beta U$$
The $Z$ and $U$ are functions of $\beta$. Equation for entropy is $S = k_B \cdot \ln(\Omega)$. Thus deriving $\frac{dS}{d\beta}$:
$$\frac{dS}{d\beta} = k_B \bigg(\frac{N}{Z} \cdot \frac{dZ}{d\beta} - \bigg(U + \beta \frac{dU}{d\beta}\bigg)\bigg)$$
Since $\frac{dZ}{d\beta} = \frac{UZ}{N}$ this gives:
$$\frac{dS}{d\beta} = -k_B \cdot \beta \frac{dU}{d\beta}$$
Knowing that $dS = \frac{dU}{T}$ (when a fixed volume is assumed), this yields:
$$\beta = - \frac{1}{k_B T}$$

A: The usual way to make statistical mechanics is to first derive a probability distribution of the states, such as:
$$ p(j) = \frac{e^{-\beta E_j}}{Z} $$
where $j$ is the index of the state and $Z$ is the normalization. This is compatible with the presence of degeneracy: simply, two states $j$ and $j'$ have the same energy, $E_j=E_{j'}$.
Then, some macroscopical physical quantities are defined. For defining the first law of thermodynamics, we define $U=<E>$ (the average of $E$) and for the second we define $S$ according to the Shannon entropy. Expressed in terms of probabilities:
$$ U = \sum_j E_j p(j) $$
and
$$ S = -k \sum_j p_j \log p_j $$
Also these formulas are compatible with the presence of degeneracy, as before.
Now, we notice that the two sums can be expressed in terms of $Z$, or, better, in terms of $F=-1/\beta \log(Z)$.
All this is done without any issue with degeneracy, simply by assuming that there can be two (or more) states with the same energy. Any expression obtained by making use of the degeneracy must give the same results.


text:
Q: My program doesn't make directories on Windows 8 but it does on Windows 7 My game executes and saves  wonderfully on Windows 7, even if the folder I save to doesn't exist. I used the following code (roughly):
new File("Data/Saves").mkdirs();

The problem occurred when I sent it to my friend with Windows 8. He said that the Data folder was nowhere to be found, and it wasn't saving anything. Obviously a huge problem.
Is there a compatibility problem or a workaround? Is it even the OS?

A: Try preceeding your path with the String given from new File(".").getCanonicalPath(); At least, i think it worked for me, but i have currently no acces to any Win8-System…


text:
Q: Python sorting a file by frequency I have a file that contains a list of words like:
word1 34
word2 12
word3 6
word4 498
word5 50
I want to sort the file by the numerical value. My code:
sortedfreqlist = sorted(freqlist, key=operator.itemgetter(1), reverse=True)

Doesn't quite work because it sorts the numbers as words i.e 12 comes before 6 etc.
Any ideas how I can do this?

A: The sorting is not working because your values are not of a numeric type, thus lexicographic sorting is applied. Be sure to convert your sort key to to a number, for example like this:
sortedfreqlist = sorted(freqlist, key=lambda item: int(item[1]), reverse=True)

A: Search "natural sort python" in your favorite search engine and you'll find many different solutions.
Here is one at activestate.
Here is a nice tidy solution at SO.


text:
Q: Copy-paste into Python interactive interpreter and indentation This piece of code, file test.py,
if 1:
   print "foo"
print "bar"

can be successfully executed with execfile("test.py") or python test.py, but when one tries to copy-paste it into a Python interpreter:
File "<stdin>", line 3
print "bar"
        ^
SyntaxError: invalid syntax

Why is it so? Can the interpreter by configured in such a way that it would read copy-pasted text successfully?
I guess that may affect typing in the interpreter, but that's OK for me.

A:
Continuation lines are needed when entering a multi-line construct.
  --Interactive mode, The Python Tutorial (v2) (v3)

So you need to enter:
if 1:
   print "foo"

print "bar"

I've yet to find a suitable explanation as to why it's different to a non-interactive session, alas.

A: All of the current answers suggest you change to IPython. For a Python-only solution, you can use textwrap to remove leading whitespace from lines.
For example,
>>> code="""    x='your pasted code'
                y='with common indentation'"""
>>> formatted=textwrap.dedent(code)
>>> exec(formatted)

A: Indentation is probably lost or broken.
Have a look at IPython -- it's an enhanced Python interpreter with many convenient features. One of them is a magic function %paste that allows you to paste multiple lines of code.
It also has tab-completion, auto-indentation... and many more. Have a look at their site.

Using %paste in IPython:

And copy-and-paste stuff is one of the things fixed in the Qt console. Here's using a plain old copy-and-paste of your code block that "just works" in the new IPython qtconsole:

A: I don't know any trick for the standard command prompt, but I can suggest you a more advanced interpreter like IPython that has a special syntax for multi-line paste:
In [1]: %cpaste
Pasting code; enter '--' alone on the line to stop.
:for c in range(3):
:    print c
:
:--
0
1
2

Another option is the bpython interpreter that has an automatic paste mode (if you are typing too fast to be an human):
>>> for c in range(3):
...     print c
...
0
1
2
>>>
 <C-r> Rewind  <C-s> Save  <F8> Pastebin  <F9> Pager  <F2> Show Source

A: If you are like me and use Notepad++ (to copy and paste from), try to replace tabs by spaces by going to menu Settings → Preferences → Language and check the replace by spaces.
I had this problem myself for so long and I found out that python.exe recognizes spaces.

A: Do %autoindent to make automatic indentation off. After that, you can paste your code in IPython.

A: If the pasted content has any empty lines, the interpreter triggers evaluation when encountering them.  If any line after an empty line has indentation, it will cause an IndentationError since any previous context has been closed.
Solutions:

*

*Delete any empty lines before copying to clipboard.

*Add any amount of indentation to empty lines (doesn't need to match code) before copying to clipboard.

Note that spaces vs. tabs does not seem to matter.

A: exec(pyperclip.paste())

provided you don't mind using exec. Any other third party clipboard package than pyperclip will do I guess.

A: One other solution I recently found for a similar problem:
$ python << EOF
if 1:
   print "foo"
print "bar"

EOF


text:
Q: How to replace [UNK] tokens with original tokens in BERT nlpaug I am trying to use nlpaug to swap some words out but am having issue with it replacing tokens permanently with the [UNK] token. I am using the docs here: https://nlpaug.readthedocs.io/en/latest/augmenter/word/context_word_embs.html
My code an example is as such:
aug = naw.ContextualWordEmbsAug(action='substitute', top_k=10,
                            aug_min=2, aug_max=4, stopwords=stops, batch_size=25)

aug.augment('You deposit the minimum amount (which is Rs 25/-) and buy tickets (Tickets are your entry fee) and start playing the game with others.')

Output
'[UNK] deposit the entire amount ( which is rs 10 / - ) and buy tickets ( tickets are your entry cost ) and start playing the game with ease.'

I have lost you in the sentence and would like to keep this. This happens across a universe of sentences so a simple one case fix will not be the answer here. Any help would be greatly appreciated.


text:
Q: docker container integration with LDAP groups Looking for some examples on how to set the dockerfile in order to make the container integrated with LDAP (group wise), so that root user or sudoer is not allowed (subject to the LDAP group).
Any help is appreciated.
Thnx.