text:
Q: left-edge vertical alignment in gb4e I use gb4e for formatting linguistic examples. I came to an example in which I want to show that one translation is correct and another reading is not allowed. I'd like to indicate that the second translation is bad by placing a raised asterisk before it. gb4e provides a way to align the left-edge vertically when an asterisk is placed in front of the first line (to indicate that the example itself is ungrammatical). Is there a way to align the left-edge when an asterisk is put on the second translation line (the \glt line)?
A MWE is as follows (I'm using xelatex):
\documentclass{article}
\usepackage{fontspec,xunicode}
\usepackage{gb4e}
\begin{document}
\begin{exe}
\ex
\gll  bites dog cat\\
    verb dd  cc\\
 \glt   `The dog bites the cat.'\\
 $^*$`The cat bites the dog.'
\end{exe}
\end{document}

A: You don't need to roll your own: Latex provides \llap, which will do just what you're after.
\glt     `The dog bites the cat.'\\
  \llap{$^*$}`The cat bites the dog.'

The contents of \llap{} are typeset in a box aligned to the left of the insertion point. The box is assigned nominal zero width, keeping the insertion point unchanged.
Note that the contents of \llap{} are effectively plastered over whatever is on its left. In your case this is always whitespace, but if you use it at the very start of an example, i.e., immediately after \ex, it may overstrike the example number if there is not enough space.


text:
Q: Button menu below table row when mouse over I am doing a project where I will have lots of information on a single row of a table. So to not lose space, I'm trying to find a way to put a centralized row with buttons, just below the row selected in the table. just like this:

$('#mytable tr').hover(function() {
    $(this).addClass('hover');
}, function() {
    $(this).removeClass('hover');
});
#mytable tr:hover {
    background-color:lightblue;
}

  HEADER 1
  HEADER 2
  HEADER 3
  HEADER 4

  Item 1
  a
  aa
  aaa

  Item 2
  b
  bb
  bbb

  Item 3
  c
  cc
  ccc

A: Are you looking for something like this?

$(document).ready(function() {

  $('#mytable tbody tr').hover(function() {
    $(this).addClass('hover');

    var rowP = $(this).offset();
    var rowH = $(this).height();
    var offset = rowP.top + rowH;
    var left = $('td:first', $(this)).width() + 20;

    $('td:first', $(this)).prepend($('.button-pane'));
    $('.button-pane', $(this)).css({
      'margin-top': offset + 'px',
      'margin-left': left + 'px'
    }).show();

  }, function(event) {
    $(this).remove('.button-pane');
    $(this).removeClass('hover');
    $('.button-pane').hide();
  });

});
#mytable tbody tr:hover {
  background-color: lightblue;
}

.button-pane {
  display: none;
  position: absolute;
  float: left;
  top: 0px;
  left: 0px;
  background-color: lightblue;
  width: 150px;
  height: 30px;
  padding: 4px;
  text-align: center;
}

.button-pane button {
  display: inline;
  cursor: pointer;
}

      HEADER 1
      HEADER 2
      HEADER 3
      HEADER 4

      Item 1
      a
      aa
      aaa

      Item 2
      b
      bb
      bbb

      Item 3
      c
      cc
      ccc

  <button id="button1">Button 1</button>
  <button id="button2">Button 2</button>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Robust line numbers in Mathematica notebook Is there any way to reference a particular output in Mathematica notebook robustly?
The usual way we refer a particular output is by invoking the command %n where n is the number that is alloted to a particular result based on the order of evaluation. If I re-run the same input, the output reference gets modified to n+1, so one has to refer to as %n+1. Is there a way to refer to particular output by some way that is not susceptible to this evaluation scheme. I know that just assigning a name will do the job. But lets say, I don't want to and just want to do something similar to % yet robust enough that it doesn't change even if I evaluate it again.
Workflow sample :

You can see that output nos 150,151,159 are referenced. Now, if I modify input 150 say, I cannot re-run all the subsequent operations without changing all the output reference nos. In a much bigger project that demands a lot of experimentation, you can see I how frustrating this can be. Given that I don't want to use Set as I have too many things to start naming myself, I thus want a way of referencing the outputs that is somehow just positional.

A: You can try the following (evaluate the code once at the beginning of your session):
SetOptions[EvaluationNotebook[],
 StyleDefinitions -> Notebook[
   {
    Cell[StyleData[StyleDefinitions -> "Default.nb"]],
    Cell[
     StyleData["Input"],
     ShowCellTags -> True,
     CellProlog :>
      ($Line = PersistentIDs`curLine=
        CurrentValue[EvaluationCell[], {TaggingRules, "ID"}] /.
          Inherited :> (CurrentValue[EvaluationCell[], {TaggingRules, "ID"}] =
            Last[DownValues[Out], {{{0}}}][[1, 1, 1]] + 1)),
     CellEpilog :> SetOptions[
       EvaluationCell[],
       CellLabel -> StringTemplate["In[``]:="]@PersistentIDs`curLine
     ]
    ]
   }
  ]
]

Essentially, this freezes the line numbers of any cell evaluated after this point. As the complete state is stored in StyleDefinitions and TaggingRules, this should persist across different sessions, without needing to reevaluate anything.
To unfreeze the line numbers, go select Format>Stylesheet>Default.
Installing
If you intend to use this frequently, you can install the stylesheet for easier reuse. To do so, execute the above code, go to Format>Edit Stylesheet.... Then, go to File>Install, select "Stylesheet" and the notebook that just opened (most likely called Untitled-1 or so) and give it a name. Now, you can apply this to any notebook by choosing Format>Stylesheet>"Name you entered"
How it works
This works by defining CellProlog and CellEpilog of all input cells to do the following (via the stylesheet):

*

*Before the cell is evaluated: Set $Line to the following (also, save this value in curLine for later):

*

*If the Cell is tagged with "ID" (i.e. was already executed), this value

*Otherwise, take the highest defined Out value +1. Also, assign this value to {TaggingRules,"ID"}

*After the cell is evaluated: Set the CellLabel to curLine (we need to do this in CellEpilog as it gets overridden after CellProlog


text:
Q: sql 3 tables sum I have 3 tables, bookings, companies and flights. bookings has no_seats andseat_price. I need to calculate sum of no_seats * seat_price for each company (for all their flights together). flight has company_id and booking has flight_id. What's the best way to do that?

A: Assuming "companies" has a 1-to-many relation with "flights" and "flights" have 1-to-many relation with "bookings":
select c.CompanyName, sum(b.no_seats * b.seat_price) as total
from Companies c
inner join Flights f on f.Company_Id = c.Company_id
inner join Bookings b on b.Flight_ID = f.Flight_ID
group by c.Company_ID, c.CompanyName;

A: Your question doesn't provide enough informations, but I guess this is what you want ?
Select C.Company_Id, SUM( B.no_seats * B.seat_price) as [Desired Calculation]
From Company C, Flights F, Bookings B
    Where C.Company_Id = F.Company_Id
    And   F.Flight_Id = B.Flight_Id
Group By C.Company_Id

If there are any further questions please feel free to ask.


text:
Q: Где ошибка SqlConnection UPDATE? Пишу
cmd3.CommandText = "UPDATE RememberAllTable SET Дата = @Дата, Событие = @Событие, Примечание = @Примечание, КогдаНапомнить = @КогдаНапомнить, Резерв1 = @Резерв1, Резерв2 = @Резерв2"
cmd3.Parameters.Add("@Дата", SqlDbType.NVarChar, 50, "Дата")

и так перечислены все Parameters.Add. При выполнении заполняет одной строкой всю базу. Пробую по другому:
cmd3.Parameters.Add("@Событие", SqlDbType.VarChar, 100).Value = Событие

Аналогично - прочие. Говорит, не удалось преобразовать значение из DataGridViewTextBoxColumn в String. База типа .mdf.
A: Вы условие не указали, по которому надо выбрать строку, которую требуется обновить.
A: Там может cmd3.Parameters.Add("@Дата", SqlDbType.NVarChar, 50, "Дата") это всё же дата а не варчар? "Дата" я так понимаю это переменная? Если всё же в базе это варчар сделайте .ToString();


text:
Q: Removing a view from it's superview causes memory error - why? Xcode is throwing an error at me:

malloc: * error for object
  0x103f000: pointer being freed was not
  allocated
  * set a breakpoint in malloc_error_break to debug

I tracked down the code until a line where I do this:
- (void)inputValueCommitted:(NSString *)animationID finished:(BOOL)finished context:(void *)context {
        // retainCount of myView is 2! (one for the retain-property, one for beeing a subview)
        [self.myView removeFromSuperview]; // ERROR-LINE !!
        self.myView = nil;
}

When I remove that errorful line, the error is gone. So in conclusion: I can't get rid of my view!
It's an UIImageView with nothing else inside, just showing an image. What I do is this: I create an UIView Animation Block, create that UIImageView, assign it to an retain-property with self.myView = ..., and after the animation is done, I just want to get rid of that view. So I remove it from it's superview and then set my property to nil, which lets it go away - in theory.
Did anyone else encounter such issues? iPhone SDK 3.0.

A: There a bug in Simulator in SDK 3.0 that can cause that error:
iPhone development: pointer being freed was not allocated
It doesn't occur in Simulator in 3.1+, or on the device under any SDK version.


text:
Q: Symbian textshell mode border problem I edited epoc.ini
added textshell in the first line.
When I run from the emulator:
NO window border is shown when I run.
It prints directly to the screen, so I can't interact with it
and the console window is isolated from the emulator window
I'm runninbg Windows 7 with Screen Resolution 1280*780

A: Instead of running textshell and get all this headache , just run the normal emulator and run the eshell from it, and type the name of your console application to run it.


text:
Q: Illegal parameter number in definition I found a nice solution to edit the look of hyperlinks, but I have another problem:
\documentclass{article}

\usepackage{hyperref}
\newcommand{\link}[1]{\href{#1}{#1}}

\begin{document}

% error: Illegal parameter number in definition of \Hy@tempa. ...tes/guides/collections/designfaq.html#a14}
\link{https://docs.oracle.com/javase/8/docs/technotes/guides/collections/designfaq.html#a14}
%   \href{https://docs.oracle.com/javase/8/docs/technotes/guides/collections/designfaq.html#a14}{Test}

\end{document}

Why does \link{...} not work? Exact the same url does work with \href{...}{...}.
Thank you for your help!!

A: Why don't use
\documentclass{article}

\usepackage{hyperref}

\begin{document}
\url{https://docs.oracle.com/javase/8/docs/technotes/guides/collections/designfaq.html#a14}
\end{document}

But take care! Shorten your link or use \href with a good description, because such a long link makes the document looks bad.


text:
Q: Get role in controller symfony2 FOSUserBundle How can i know the roles of my personel.
$personal = $em->getRepository('AuthenticationBundle:User')->FindPersonel($id);

dump($personal->getRoles());
die();

there is nothing blank page.

A: if(in_array('ROLE_ADMIN', $this->getUser()->getRoles())){
   //Is ADMIN !!!
}

A:     foreach( $personal->getRoles() as $role){
        echo $role;
    }
    die();

we must loop the getRoles()


text:
Q: Django - save copy of instance in inherited model Using Django 2.1.5, I have one model that is completely inherited by another model. Both tables in DB. I want to save 'revisions' of the model as the inherited model. All fields should be the same at the time of the copy (including the id/pk).
What's the right and quick way to copy the instance of the parent model to the inherited?
Let's say these are the models (but with a lot of fields, foreign keys, json fields..):
class MyModel(models.Model):
    id = models.UUIDField(default=uuid.uuid4, editable=False, db_index=True, unique=True, primary_key=True)
    identifier = models.IntegerField(default=-1)
    title = models.CharField(max_length=1000)
    revision = models.IntegerField(default=0)

class MyModelRevisions(MyModel):
    pass

Now, I want to take an instance of MyModel and completely copy it to MyModelRevisions.
I thought of something like this:
model_revision = MyModelRevisions(MyModel.objects.get(pk=my_model.pk))
model_revision.save()

But I'm getting an error message saying that the title of my_model is not a valid UUID.

A: A simple answer would be something like serialize/deserialize the object to create a new one:
from django.forms.models import model_to_dict

revision = MyModelRevisions(**model_to_dict(my_model_instance, fields=['id', 'identifier', 'title', 'revision']))
revision.save()

But maybe you want to give a look to something like django-reversion


text:
Q: How to use routing in vue js? I am working on a vue js project, to use the router , I installed via command -> npm install vue-router and created a router.js file , but when i try , npm run serve, i get compile warnings and the app doesn't work as intended.
Error

warning in ./src/router.js
export 'default' (imported as 'Router') was not found in 'vue-router' ( possible exports: NavigationFailureType, RouterLink ....)

Directory Structure
vuejsproj
  > node_modules
  > public
  > src
      > assets
      > components
      App.vue
      main.js
      router.js
    ...

router.js
import Vue from "vue";
import Router from "vue-router";
Vue.use(Router);
export default new Router({
  mode: "history",
  routes: [
    {
      path: "/",
      alias: "/list",
      name: "list",
      component: () => import("./components/somecomponent")
    }
  ]
});

main.js
import Vue from 'vue'
import App from './App.vue'
import vuetify from './plugins/vuetify'
import router from './router'
Vue.config.productionTip = false
new Vue({
  router,
  vuetify,
  render: h => h(App)
}).$mount('#app')

package.json
{
  "name": "app",
  "version": "0.1.0",
  "private": true,
  "scripts":{
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "axios": "^0.27.2",
    "core-js": "^3.8.3",
    "vue": "^2.6.14",
    "vue-axios": "^3.4.1",
    "vue-router": "^4.015",
    "vuetify": "^2.6.0"
  },

}


text:
Q: filenames including "/bin/sh" pattern are not served by apache I have been tracking down a bug which I have reduced to the following case. We have a web server running apache and it doesn't serve filenames including "/bin/sh" pattern outside of the campus in which the server is located (e.g. www.example.com/some/sub/folders/bin/show.html. Maybe related is that the same url with https in the beginning instead of http works without a problem once you skip the certification error. It is difficult to change all such filenames in our application so I'm trying to fix this issue instead. How can I debug this any further?
Log file /etc/httpd/logs/access_log shows an unrelated GET request url for this filename. Other filenames show up as they are. I have checked configuration files under /etc/httpd/conf and /etc/httpd/conf.d but I couldn't see anything related, although I'm not familiar with these configuration files.
Apache version is as follows:
# httpd -v
Server version: Apache/2.0.52
Server built:   Oct 29 2008 09:20:05

Any ideas?
EDIT
Log messages from inside the campus (response 304 for regular cached browser window and response 200 is for private non-cached browser window):
(ip addr) - - [27/Apr/2017:13:06:45 +0300] "GET /appserv/bin/sh.html HTTP/1.1" 304 - "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:53.0) Gecko/20100101 Firefox/53.0"
(ip addr) - - [27/Apr/2017:13:06:54 +0300] "GET /appserv/bin/sh.html HTTP/1.1" 200 154 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:53.0) Gecko/20100101 Firefox/53.0"

Log messages from outside of campus (tested with tor and various vps nodes):
(ip addr) - - [27/Apr/2017:13:08:08 +0300] "GET /cosbiom/component/option,com_extcalendar/Itemid,99999999/extmode,day/date,2031-02-04/ HTTP/1.1" 200 28936 "-" "Mozilla/5.0 (compatible; YandexBot/3.0; +http://yandex.com/bots)"

A: If this works on-campus but not from outside then it seems unlikely that it's an issue with the web server config (it could be but I suspect that sort of config would be pretty obvious).
It seems more likely to me that there's some sort of inspection-based firewall at the edge of the campus network based on a simple regular expression match. That wouldn't (in general) affect https traffic (since it's encrypted and so not open to inspection).
You need to talk to whoever looks after the campus's network connection (I'm assuming that you've try from multiple external connections so you're sure the problem is towards the server end).


text:
Q: ExtJs window widget needs 5 seconds to load iframe I am using ExtJS 4 for my app, and when i click on a button I open an ExtJS window widget. I load an iframe in it and the iframe loads other controler that loads view from CodeIgniter MVC. So basically it goes like this
extjs window widget -> iframe -> controller -> view.
My problem is that the window widget needs about 5 seconds to load the controller, i.e see whatever output from it.
Any idea what is causing this problem? Is it the ExtJs problem here? Why it cant load the iframe it 1-2 seocnds or less?


text:
Q: How to change the stringformat of Oxyplot track value? If I change the stringformat of axis, it works for the axis (see the black circle of the picture). But how can I change the stringformat of the track value (the red circle)?

A: I'd like to answer my own question based on Ramin's hint to me.
I dug into the source code a little bit, and found out there is a TrackerFormatString that I can change:
<oxy:LineSeries TrackerFormatString="{}{0}
{1}: {2:0.0}
{3}: {4:0.0}"/>

Please note the
 in my code, that how a newline char is input in XAML.
Please also note the {} in the very beginning, that's kind of escape char in XAML.
if in c#, it's just:
{0}\n{1}: {2:0.0}\n{3}: {4:0.0}

A: You should set DefaultTrackerTemplate. Here a small example that shows you the way:
<Grid>
    <oxy:Plot Title="AAA">
        <oxy:Plot.Axes>
            <oxy:LinearAxis Position="Left" Title="Left: " />
            <oxy:LinearAxis Position="Bottom"  Title="Bottom: " />
        </oxy:Plot.Axes>
        <oxy:Plot.Series>
            <oxy:LineSeries x:Name="ls" ItemsSource="{Binding Points}"/>
        </oxy:Plot.Series>
        <oxy:Plot.DefaultTrackerTemplate>
            <ControlTemplate>
                <oxy:TrackerControl Position="{Binding Position}"
                                BorderThickness="1">
                    <oxy:TrackerControl.Content>
                        <StackPanel >
                            <DockPanel>
                                <TextBlock Text="{Binding XAxis.Title}" Foreground="Red" />
                                <TextBlock DockPanel.Dock="Right" Text="{Binding DataPoint.X}" Foreground="Red" />
                            </DockPanel>
                            <DockPanel>
                                <TextBlock Text="{Binding YAxis.Title}" Foreground="Green" />
                                <TextBlock DockPanel.Dock="Right" Text="{Binding DataPoint.Y}" Foreground="Green"
                                       FontWeight="Bold" />
                            </DockPanel>
                        </StackPanel>
                    </oxy:TrackerControl.Content>
                </oxy:TrackerControl>
            </ControlTemplate>
        </oxy:Plot.DefaultTrackerTemplate>
    </oxy:Plot>
</Grid>

Hope it helps.


text:
Q: SSIS Conditional Split Lineage Error I'm trying to run an Excel table through an SSIS Package and 3 nodes in, it has a Conditional Split. I'm using a previously known working spreadsheet with some data added to it.
The error I'm getting specifically is:

Conditional Split.Inputs[Split Input].Columns[ColumnName] has lineage ID 147 that was not previously used.

I've tried a couple spreadsheets with no avail. I was getting ID 105 initially.
My specific questions are: What do the IDs correspond to? Where do I look to try troubleshooting them?
Some additional logs.
Output:

Error at Data Flow Task 1 [SSIS.Pipeline]: Conditional Split.Inputs[Conditional Split Input].Columns[ColumnName] has lineage ID 147 that was not previously used in the Data Flow task.
Error at Data Flow Task 1 [SSIS.Pipeline]: "Conditional Split" failed validation and returned validation status "VS_NEEDSNEWMETADATA".
Error at Data Flow Task 1 [SSIS.Pipeline]: One or more component failed validation.
Error at Data Flow Task 1: There were errors during task validation.

A: "Lineage ID is a property of the component or transformation used in the data flow task. It contains an integer value that will work as buffer pointer. Each column in the data flow task will be assigned a lineage ID." Read about lineage ID in this Microsoft TechNet article
LINEAGE ID Error implies that a Source metadata was changed, just re-validate source (connection and component) by double click on the the Conditional split and close it , then check the columns metadata (using the advanced editor). (Note that when double-clicking on a component that contains errors it will prompt to fix it)
Or you can try removing Conditional Split and adding it again (if previous solution doesn't works)

A: Right click Conditional Split -> Advanced Editor -> Input and Output Properties -> expend those columns, you will see each column has a LineageID.

A: I believe SSIS assigns unique identifiers (lineage IDs) to each column in each pipe connecting your components. SSIS gets confused when a component is expecting a lineage ID of x, but can't find it in the input pipe.
Generally, you try to find the offending pipe (in BIDS/SSDT, using @Wendy's method). Double-clicking the pipe or connected components will sometimes produce a dialog box offering the option to fix the issue. If not, then removing and recreating the pipe is your best chance.
Downstream components can be adversely affected when you change things upstream of them. Often, the only recourse when doing midstream modifications is to rebuild the entire downstream. SSIS is a bit brittle in this area.


text:
Q: getting Error while IONIC build properties.gradle does not Exist
*

*i am trying to creating ionic build, but getting error, here is my step.

*ionic cordova platform remove android

*ionic cordova platform add android

*ionic cordova build android

while i run last command then got below Error.

FAILURE: Build failed with an exception.

*

*Where:
Script 'D:\Projects\corporatesolutionmobileapp\platforms\android\cordova-android
-support-gradle-release\sancial-cordova-android-support-gradle-release.gradle' l
ine: 11

*What went wrong:
A problem occurred evaluating script.

Could not read script 'D:\Projects\corporatesolutionmobileapp\platforms\androi
  d\app\cordova-android-support-gradle-release\properties.gradle' as it does not e
  xist.

*Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug
option to get more log output.

*Get more help at https://help.gradle.org
BUILD FAILED in 1s
[ERROR] An error occurred while running subprocess cordova.
    cordova build android exited with exit code 1.

    Re-running this command with the --verbose flag may provide more
    information.

A: I was getting this error while only using Capacitor which I thought was strange so I nuked the android path in my root folder and then npx cap add android again and the build worked after that

A: Updating Capacitor did the trick for me:
npx cap update

A: I was having a similar problem, running the command
ionic capacitor run android
I was getting androidmanifest.xml doesn't exist.
It was solved by running the command
ionic capacitor update

A: Updating to the most recent version (v2.0.1) of cordova-android-support-gradle-release should resolve your issue:
ionic cordova platform rm android
ionic cordova plugin rm cordova-android-support-gradle-release
ionic cordova plugin add cordova-android-support-gradle-release@latest
ionic cordova platform add android
ionic cordova build android

A: This issue is mostly faced, when you add/remove a new plugin. So by just running cordova clean can resolve that issue.
Inside your CMD/Terminal:
C:\<project folder>\cordova clean

A:   It is related to M1 chipset of mac.

   % brew uninstall node
   % brew install nodenv
   % echo 'export PATH=${PATH}:~/.nodenv/shims' >> ~/.zprofile
   % nodenv install 17.7.2
   % nodenv global 17.7.2

   % npx cap run android
   ✔ Copying web assets from www to android/app/src/main/assets/public in 7.48ms
  ✔ Creating capacitor.config.json in android/app/src/main/assets in 745.25μs
  ✔ copy android in 12.87ms
  ✔ Updating Android plugins in 3.42ms
  [info] Found 3 Capacitor plugins for android:
   @capacitor/camera@1.3.1
   @capacitor/filesystem@1.1.0
   @capacitor/geolocation@1.3.1
  ✔ update android in 32.04ms
  ✔ Running Gradle build in 1.32s
  ✔ Deploying app-debug.apk to emulator-5554 in 1.88s

 ref https://github.com/ionic-team/capacitor/issues/5545

A: Solved:

*

*Delete the Android Directory from your folder

*Follow the steps mentioned in the ionic capacitor troubleshoot documentation at

https://capacitorjs.com/docs/android/troubleshooting#recreating-your-project


text:
Q: Planarity found in inducing $K_5$ I was interested in studying whether or not if when we remove an arbitrary
two edges from $K_5$, we get a planar graph. I understand that a planar graph
has at most $3v-6$ edges, where $v$ is the number of vertices in the graph.
Hence, given that $K_5$ has $\binom{5}{2} = 10$ and because it is apparent that
$10 > 9 = 3(5)-6$, $K_5$ is obviously not planar. However, given the fact
that this is not necessarily an "if-and-only-if" assumption on the bounds of
the edges of a planar graph, I wasn't entirely sure if removing edges on
a graph such that $E(G) \leq 9$ was going to be a simple solution. Is there
an induced subgraph of $K_5$ that has $8$ edges and is not planar?

A: $K_5-e$ is planar for any edge. By Kuratowski's theorem, a graph is planar iff it contains no subgraph that is a subdivision of $K_5$ or $K_{3,3}$. Since $K_5-e$ cannot contain a subdivision of $K_5$, and doesn't have enough vertices to contain a subdivision of $K_{3,3}$, it is planar. The same can be said if you delete two edges.

A: We may just take $K_5$, remove an edge (any edge has the same role by transitivity) and show that the resulting graph is planar. How? This way:


text:
Q: Beam Python Dataflow, writing to BigQuery table with schema provided throws AttributeError: May not assign arbitrary value tpe to message I am trying this code on dataflow. Reading from a csv file on gs:/ storage bucket, creating BigQuery table and appending data. The code is as follows:
from __future__ import absolute_import

import argparse
import logging
import os

import apache_beam as beam
from apache_beam.io import ReadFromText, ReadAllFromText
from apache_beam.io import WriteToText
from apache_beam.metrics import Metrics
from apache_beam.metrics.metric import MetricsFilter
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.options.pipeline_options import SetupOptions
from google.cloud import storage

import regex as re

# storage_client = storage.Client()
# bucket = storage_client.get_bucket('mybucket')
#
# blobs = bucket.list_blobs()
# l=list(blobs)
# x=[y.name for y in l]
# c=x[1:]
# print(len(c))
# details and location of source csv file
source_file = ['gs://xxx/DUMMY.csv']

class DataIngestion:
    """A helper class which contains the logic to translate the source csv file into a format BigQuery will accept."""

    def parse_method(self, string_input):

        values = re.split(",",re.sub('\r\n', '', re.sub(u'"', '', string_input)))
        row = dict(
            zip(('ID', 'CLUSTERED', 'SCATTERED', 'RANDOMISED', 'RANDOM_STRING', 'SMALL_VC', 'PADDING'),
                values))
        return row

def run(argv=None):
    """Main entry point; defines and runs the pipeline."""

    data_ingestion = DataIngestion()
    p = beam.Pipeline(options=PipelineOptions())

    (p
    | 'Create PCollection' >> beam.Create(source_file)
    | 'Read from a File' >> beam.io.ReadAllFromText(skip_header_lines=1)  ## ignore the csv header
    | 'String To BigQuery Row' >> beam.Map(lambda s: data_ingestion.parse_method(s)) # s is each of the String elements read in the beam.io.ReadAllFromText transform, and we apply a lambda
    | 'Write to BigQuery' >> beam.io.Write(
    beam.io.WriteToBigQuery(
    'DUMMY',
    dataset='test',
    schema = {
  "fields": [
  {
    "name" : "ID",
    "type" : "FLOAT",
    "mode" : "REQUIRED"
  },
  {
    "name" : "CLUSTERED",
    "tpe"  : "FLOAT",
    "mode" : "NULLABLE"
  },
  {
    "name" : "SCATTERED",
    "tpe"  : "FLOAT",
    "mode" : "NULLABLE"
  },
  {
    "name" : "RANDOMISED",
    "tpe"  : "FLOAT",
    "mode" : "NULLABLE"
  },
  {
    "name" : "RANDOM_STRING",
    "tpe"  : "STRING",
    "mode" : "NULLABLE"
  },
  {
    "name" : "SMALL_VC",
    "tpe"  : "INTEGER",
    "mode" : "NULLABLE"
  },
  {
    "name" : "PADDING",
    "tpe"  : "STRING",
    "mode" : "NULLABLE"
  }
]
},

    create_disposition=beam.io.BigQueryDisposition.CREATE_IF_NEEDED,
    write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND)))

    result = p.run()
    result.wait_until_finish()

if __name__ == '__main__':
  logging.getLogger().setLevel(logging.INFO)
  run()

The code throws this error
  File "/usr/local/lib/python3.7/site-packages/apitools/base/protorpclite/messages.py", line 976, in __setattr__
    "to message %s" % (name, type(self).__name__))
AttributeError: May not assign arbitrary value tpe to message TableFieldSchema [while running 'Write to BigQuery/WriteToBigQuery/BigQueryBatchFileLoads/TriggerLoadJobsWithoutTempTables/TriggerLoadJobsWithoutTempTables']

If I try the following
schema='SCHEMA_AUTODETECT'

instead of adding Json schema as above, it works fine. Moreover, if I try to reference a Json file in schema=, it fails. What is the root cause of this? It is my first dataflow/beam program and appreciate any advice.

A: This is because schema accepts type string of the form 'field1:type1,field2:type2,field3:type3' or TableSchema object that defines a comma separated list of fields. You may refer to this documentation: https://beam.apache.org/releases/pydoc/2.9.0/apache_beam.io.gcp.bigquery.html#apache_beam.io.gcp.bigquery.WriteToBigQuery
from __future__ import absolute_import

import argparse
import logging
import os

import apache_beam as beam
from apache_beam.io import ReadFromText, ReadAllFromText
from apache_beam.io import WriteToText
from apache_beam.metrics import Metrics
from apache_beam.metrics.metric import MetricsFilter
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.options.pipeline_options import SetupOptions

import re

# storage_client = storage.Client()
# bucket = storage_client.get_bucket('mybucket')
#
# blobs = bucket.list_blobs()
# l=list(blobs)
# x=[y.name for y in l]
# c=x[1:]
# print(len(c))
# details and location of source csv file
source_file = ['gs://<your_bucket>/1.csv']

class DataIngestion:
    """A helper class which contains the logic to translate the source csv file into a format BigQuery will accept."""

    def parse_method(self, string_input):

        values = re.split(",",re.sub('\r\n', '', re.sub(u'"', '', string_input)))
        row = dict(
            zip(('ID', 'CLUSTERED', 'SCATTERED', 'RANDOMISED', 'RANDOM_STRING', 'SMALL_VC', 'PADDING'),
                values))
        return row

def run(argv=None):
    """Main entry point; defines and runs the pipeline."""

    data_ingestion = DataIngestion()

    pipeline_options = PipelineOptions(
    runner='DirectRunner',
    project='your-project',
    temp_location='gs://<your_bucket>/temp',
    region='us-central1')

    p = beam.Pipeline(options=pipeline_options)

    (p
    | 'Create PCollection' >> beam.Create(source_file)
    | 'Read from a File' >> beam.io.ReadAllFromText(skip_header_lines=1)  ## ignore the csv header
    | 'String To BigQuery Row' >> beam.Map(lambda s: data_ingestion.parse_method(s)) # s is each of the String elements read in the beam.io.ReadAllFromText transform, and we apply a lambda
    | 'Write to BigQuery' >> beam.io.Write(
    beam.io.WriteToBigQuery(
    'your_table',
    dataset='your_dataset',
    schema ='ID:FLOAT,CLUSTERED:FLOAT,SCATTERED:FLOAT,RANDOMISED:FLOAT,RANDOM_STRING:STRING,SMALL_VC:INTEGER,PADDING:STRING',
    create_disposition=beam.io.BigQueryDisposition.CREATE_IF_NEEDED,
    write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND)))

    result = p.run()
    result.wait_until_finish()

if __name__ == '__main__':
  logging.getLogger().setLevel(logging.INFO)
  run()

Input file csv:
ID,CLUSTERED,SCATTERED,RANDOMISED,RANDOM_STRING,SMALL_VC,PADDING
12,5,23,55,team,5,bigdata

Output:


text:
Q: Android Security Changing UID 1) Is it possible to CHANGE UID  if i get a ROOT ACCESS to my android device ?
2) If 2 Appz developed by same developer having SHARE ID with different Applications permissions will work ?

A: Two applications that are signed with the same developer certificate can run with the same UID if you specify a common value for sharedUserId in the manifest file. Applications that are signed with different developer certificates cannot run with the same UID. If you root your device, you can modify the kernel and all bets are off, but this is not possible with a non-rooted/modified Android system.
If two applications are developed by the same entity, and signed by the same developer certificate, the common UID runs with a union of the declared permissions. So if app1 has permissions A and B and app2 has permission C, and they run under the same UID, they both will have permissions A, B, and C.


text:
Q: Prove that a series-parallel hamiltonian graph is outerplanar. A graph is series-parallel (SP) iff it contains no $K_4$ minor.
I know that if the graph has no $K_4$ or $K_{2,3}$ minors, it is outerplanar.
So maybe there is a way to use the fact that it is hamiltonian to prove that the graph has no $K_{2,3}$ minor.
Or maybe there is another way: since $K_5$ and $K_{3,3}$ contain $K_4$ minors, the graph cannot contain these minors and hence is planar by kuratowski's theorem.
And then somehow the fact that the graph is hamiltonian shows that is outerplanar.
Any guidance on how to complete these thoughts is appreciated.

A: Start by drawing the hamiltonian cycles in the plane. Then add the all chords inside the cycle. Note that there will be no crossing edges because crossing edges imply $K_4$ minor.


text:
Q: PHP Echoing in the wrong location in the page Im trying to create a page that will display orders from a database. If it doesnt find any results it should be display "No results" or so. It does display it when there arent any. However, it displays on top of the headers instead of the body of the table where the results are displayed.

                Order Number
                Image
                Buyer Name
                Product Name
                Order Date
                Price
                Status
                Action

            <?php
                $userid = $_SESSION['userid'];
                $sql = "
                select
                O.orderid as 'orderid', O.totalprice as 'totalprice', U.firstname as 'firstname', U.lastname as 'lastname', P.productname as 'productname', O.userid as 'userid', O.orderstatus as 'orderstatus', OS.status as 'status', OS.statusid as 'statusid', P.image as 'productPhoto'
                from
                orders O
                INNER JOIN
                users U ON
                O.userid = U.userid
                INNER JOIN
                orderstatus OS ON
                O.orderstatus = OS.statusid
                INNER JOIN
                products P ON
                P.productid = O.productid
                WHERE
                P.userid = $userid AND O.orderstatus = 3;
                ";

                $result = mysqli_query($conn, $sql);
                $resultCheck = mysqli_num_rows($result);

                if($resultCheck > 0 ){
                  while($row = mysqli_fetch_assoc($result)){
                    echo '

                      '.$row['orderid'].'

                      '.$row['firstname'].' '.$row['lastname']. '

                      '.$row['productname'].'

                      06/28/2020

                      <form action="../inc/manageorders_actions.inc.php" METHOD="POST">
                        <input type="hidden" value=" '. $row['orderid'] .' " name="orderid">

                        '.'PHP '.$row['totalprice'].'

                        '. $row['status'] .'

                           <input type="submit" value="To pack" name="topack">

                            <input type="submit" value="Packed" name="packed">

                            <input type="submit" value="In delivery" name="beingdelivered">

                           <input type="submit" value="Delivery" name="delivered">

                      </form>

                    ';
                  }
                }else{
                  echo 'No results';
                }

            ?>

A: You can't just echo No results inside
.

                Order Number
                Image
                Buyer Name
                Product Name
                Order Date
                Price
                Status
                Action

            <?php
                $userid = $_SESSION['userid'];
                $sql = "
                select
                O.orderid as 'orderid', O.totalprice as 'totalprice', U.firstname as 'firstname', U.lastname as 'lastname', P.productname as 'productname', O.userid as 'userid', O.orderstatus as 'orderstatus', OS.status as 'status', OS.statusid as 'statusid', P.image as 'productPhoto'
                from
                orders O
                INNER JOIN
                users U ON
                O.userid = U.userid
                INNER JOIN
                orderstatus OS ON
                O.orderstatus = OS.statusid
                INNER JOIN
                products P ON
                P.productid = O.productid
                WHERE
                P.userid = $userid AND O.orderstatus = 3;
                ";

                $result = mysqli_query($conn, $sql);
                $resultCheck = mysqli_num_rows($result);

                if($resultCheck > 0 ){
                  while($row = mysqli_fetch_assoc($result)){
                    echo '

                      '.$row['orderid'].'

                      '.$row['firstname'].' '.$row['lastname']. '

                      '.$row['productname'].'

                      06/28/2020

                      <form action="../inc/manageorders_actions.inc.php" METHOD="POST">
                        <input type="hidden" value=" '. $row['orderid'] .' " name="orderid">

                        '.'PHP '.$row['totalprice'].'

                        '. $row['status'] .'

                           <input type="submit" value="To pack" name="topack">

                            <input type="submit" value="Packed" name="packed">

                            <input type="submit" value="In delivery" name="beingdelivered">

                           <input type="submit" value="Delivery" name="delivered">

                      </form>

                    ';
                  }
                }else{
                  echo '
No results
';
                }

            ?>

The
 element required
 and  before display the contents. See document here.

A: This is because you are outputting it directly in the body tag. You need to at least wrap it inside

echo "
No results
";

A: Why don't echoing a  formatted row like the results of the query? An then putting "no results" instead of data in it…


text:
Q: Extra records when used as a sub query: Access I'm a rookie developer with basic SQL experience and this problem has been 'doing my head in' for the last couple of days. I've gone to ask a question here a couple times and thought... not yet... keep trying.
I have a table:

*

*ID

*Store

*Product_Type

*Delivery_Window

*Despatch_Time

*Despatch_Type

*Pallets

*Cartons

*Many other columns (start_week and day_num are two of them)

My goal is to get a list of of store by product_type with the minimum despatch_time with all the other column information.
I've tested the base query.
SELECT Product_Type, Store, Min(Despatch_Time) as MinDes
FROM table
GROUP BY Store, Product_Type

Works well, I get 200 rows as expected.
Now I want those 200 rows to have the other related record information : Delivery_Window, start_week, etc
I've tried the following.
SELECT * FROM Table WHERE EXISTS
(SELECT Product_Type, Store, Min(Despatch_Time) as MinDes
FROM table
GROUP BY Store, Product_Type)

I've tried doing inner and right joins all returned more than 200 records, my original amount.
I inspected the additional records and it is where there is the same despatch time for a store and product type but for a different despatch type.
So I need a hand in creating a query where I limit it by the initial sub query but even if there is matching minimum despatch times it will still limit the count to one record by store and product type.
Current Query is:
SELECT *
FROM table AS A INNER JOIN
(Select Min(Despatch_Time) as MinDue, store, product_type
FROM table
WHERE day_num = [Forms]![FRM_SomeForm]![combo_del_day] AND start_week =[Forms]![FRM_SomeForm]![txt_date1]
GROUP BY store, product_type) AS B
ON (A.product_type = B.product_type) AND (A.store = B.store) AND (A.Despatch_Time = B.MinDue);

A: I think you want:
SELECT t.*
FROM table as t
WHERE t.Dispatch_Time = (SELECT MIN(t2.Dispatch_Time)
                         FROM table as t2
                         WHERE t2.Store = t.Store AND t2.Product_Type = t.Product_Type);

The above will return duplicates.  In order to avoid duplicates, you need a key to provide uniqueness.  Let me assume you have a primary key pk:
SELECT t.*
FROM table as t
WHERE t.pk = (SELECT TOP (1) t2.pk
              FROM table as t2
              WHERE t2.Store = t.Store AND t2.Product_Type = t.Product_Type
              ORDER BY t2.Dispatch_Time, t2.pk
             );


text:
Q: Tab Delimited to Square Matrix I have a tab delimited file like
A   B   0.5
A   C   0.75
B   D   0.2

And I want to convert it to a square matrix, like
       A      B      C       D
A      0     0.5    0.75     0
B             0      0      0.2
C                    0       0
D                            0

How can I go about it in R?
Thanks,

A: If you have the data in a data frame with the following column names:
Var1    Var2    value

you can use
xtabs(value ~ Var1 + Var2, data = df)

See the plyr package for some more general data reshaping functions also.

A: Another approach (not as elegant as JoFrhwld's)
df<- read.table(textConnection("
Var1    Var2    value
A   B   0.5
A   C   0.75
B   D   0.2
"),header = T)

lev = unique(c(levels(df$Var1),levels(df$Var2)))
A = matrix(rep(0,length(lev)^2),nrow=length(lev))
colnames(A) = lev
rownames(A) = lev
apply(df,1,function(x) A[x[1],x[2]]<<-as.numeric(x[3]))

> A
  A   B    C   D
A 0 0.5 0.75 0.0
B 0 0.0 0.00 0.2
C 0 0.0 0.00 0.0
D 0 0.0 0.00 0.0
>

A: I'm guessing this is a weighted adjacency matrix for a graph.  If so, you might be interested in the igraph package, to read the data as a weighted edge list.


text:
Q: Java - Including BST I have this BST problem I'm trying to solve in java, but I don't know why it's not working.
Here's the problem:

*

*Binary search tree (BST) is a binary tree where the value of each
node is larger or equal to the values in all the nodes in that node's
left subtree and is smaller than the values in all the nodes in that
node's right subtree.
Write a function that checks if a given binary search tree contains a
given value.
For example, for the following tree:
n1 (Value: 1, Left: null, Right: null) n2 (Value: 2, Left: n1, Right:
n3) n3 (Value: 3, Left: null, Right: null) Call to contains(n2, 3)
should return true since a tree with root at n2 contains number 3.
This is how I am trying to solve it:
    class Node {
    public int value;
    public Node left, right;

    public Node(int value, Node left, Node right) {
        this.value = value;
        this.left = left;
        this.right = right;
    }
}

public class BinarySearchTree {
    public static boolean contains(Node root, int value) {
       if(root.value == value)
           return true;

       else if(value < root.value){
           if(root.left == null)
               return false;
           contains(root.left, value);
       }
       else if(value > root.value){
           if(root.right == null)
               return false;
           contains(root.right, value);
       }

        return false;
    }

    public static void main(String[] args) {
        Node n1 = new Node(1, null, null);
        Node n3 = new Node(3, null, null);
        Node n2 = new Node(2, n1, n3);

        System.out.println(contains(n2, 3));
    }
}

This should return true, but it doesn't... Thank you in advance.

A: return contains(...) instead of just calling contains(...) for those recursive calls, so that you don't lose values when they are made

A: public class BinarySearchTree {
    public static boolean contains(Node root, int value) {
       if(root.value==value)
           return true;
        else if(value<root.value && root.left!=null)
            return contains(root.left,value);
            else if(value> root.value && root.right!=null)
                return contains(root.right,value);
                else return false;
    }

A: I have written one c++ version. It seems that it is more clear to understand.
#include <stdexcept>
#include <string>
#include <iostream>
#include <algorithm>

class Node
{
public:
   Node(int value, Node* left, Node* right)
   {
      this->value = value;
      this->left = left;
      this->right = right;
   }

   int getValue() const
   {
      return value;
   }

   Node* getLeft() const
   {
      return left;
   }

   Node* getRight() const
   {
      return right;
   }

private:
   int value;
   Node* left;
   Node* right;
};
class BinarySearchTree
{
public:

   static bool isValidBST( Node& root)
   {

    if ((root.getLeft())&&(root.getValue()<=(root.getLeft()->getValue())))
        return false;
    if ((root.getRight())&&(root.getValue()>=(root.getRight()->getValue())))
    {
        return false;
    }
    if (root.getRight())
    {
        if(!isValidBST(*(root.getRight()))) return false;
    }
    if(root.getLeft())
    {
        if(!isValidBST(*(root.getLeft()))) return false;
    }

    return true;

    }
};

#ifndef RunTests
int main(int argc, const char* argv[])
{
    Node n7(7, NULL, NULL);
    Node n10(11, NULL, NULL);
    Node n2(2, NULL, NULL);
    Node n5(5, NULL, NULL);
    Node n4(4, &n2, &n5);
    Node n9(9, &n7, &n10);
    Node n6(6, &n4, &n9);

    std::cout << BinarySearchTree::isValidBST(n6);

    return 0;
}
#endif

A: using System;

public class Node
{
    public int Value { get; set; }

    public Node Left { get; set; }

    public Node Right { get; set; }

    public Node(int value, Node left, Node right)
    {
        Value = value;
        Left = left;
        Right = right;
    }
}

public class BinarySearchTree
{
    public static bool Contains(Node root, int value)
    {
          if(root.Value == value){
            return true;
          }
          else if(value < root.Value && root.Left !=null ){
           return Contains(root.Left,value);
          }
          else if(value > root.Value && root.Right !=null){
            return Contains(root.Right,value);
          }
          else{
            return false;
          }
    }

    public static void Main(string[] args)
    {
        Node n1 = new Node(1, null, null);
        Node n3 = new Node(3, null, null);
        Node n2 = new Node(2, n1, n3);

        Console.WriteLine(Contains(n2, 3));
    }
}


text:
Q: Generate a custom path from XML tags with attribute and value in java I need a Java program to generate path for each tag value including the attributes also in path. Need to generate path even if the value is empty.
My sample XML file
<root>
    <elemA>one</elemA>
    <elemA attribute1='first' attribute2='second'>two</elemA>
    <elemB>three</elemB>
    <elemA>four</elemA>
    <elemC>
        <elemB>five</elemB>
    </elemC>
    <elemD/>
</root>

My Goal is to produce the following output
//root[1]/elemA[1]='one'
//root[1]/elemA[2][@attribute1='first' and attribute2='second']='two'
//root[1]/elemB[1]='three'
//root[1]/elemA[3]='four'
//root[1]/elemC[1]/elemB[1]='five'
//root[1]/elemD[1]=

I need this to compare two XML files generated from different tools and create a comparison result. I used XMLUnit but it is having false positives if the elements are repeated twice or more (Arrays) in different orders


text:
Q: Split equation inside \sum or \int I'm trying to break up a sum of many terms into multiple lines as follows:
\documentclass[12pt,a4paper]{book}
\usepackage{amsmath}
\begin{document}
\begin{align*}
        L &= \sum { A && \text{This equation sums ABC} \\
                    \times B \\
                    \times C  }
\end{align*}
\end{document}

but I get Missing } inserted.
The motivation is for the \text to not get pushed too far to the right.

A: As already pointed out by @daleif in a comment, you must remove the spurious pair of curly braces that enclose the material after \sum. In addition, you should almost certainly provide alignment points for the material on rows 2 and 3.

\documentclass[12pt,a4paper]{book}
\usepackage{amsmath}
\begin{document}
\hrule % just to illustrate width of textblock
\begin{align*}
L &=     \sum   \text{A-stuff}   \tag*{This equation sums ABC} \\
  &\quad \times \text{B-stuff} \\
  &\quad \times \text{C-stuff}
\end{align*}
\end{document}

A: Use aligned:
\documentclass[12pt,a4paper]{book}
\usepackage{amsmath}
\begin{document}

\begin{align*}
L &= \sum \Bigl( \begin{aligned}[t]
                 & A \\
                 & \times B \\
                 & \times C \Bigr)
                 \end{aligned}
  && \text{This text is not so far}
\\
M &= ABC && \text{This text is not so far}
\end{align*}
Just for a check:
\begin{align*}
M &= ABC && \text{This text is not so far} \\
K &= XYZ && \text{This text is not so far}
\end{align*}

\end{document}

A: Thanks. Tossing in parentheses and
\phantom instead of \quad ...
\documentclass[12pt,a4paper]{book}
\usepackage{amsmath}
\begin{document}

\begin{align*}
        L &= \sum \big( A \\
                    & \phantom{= \sum \big(} \times B \\
                    & \phantom{= \sum \big(} \times C
                \big)
\end{align*}

\end{document}

and it works nicely.

Now, is there a way to do something like this:

        L &\setphantom{= \sum \big(} A \\
                    & \getphantom \times B \\
                    & \getphantom \times C
                \big)


text:
Q: Move image to pre-defined x,y position I'm building a custom location selector for the user, which is essentially a map (image) and a text input where the user enters his country. The custom map is about 1500x1000px. The final goal is to slowly auto-scroll the map to a certain pre-defined x,y of the selected country. How can I define, lets say, that Germany is located at 700x800, and center the map image around that point when the user selects that country from the drop down list?
Here's my fiddle, which includes the move-able map (I'm not adding any code in here because it is long, please excuse me and use the fiddle to browse the code)

A: Use the Position object for this. Let's say
var germany = new Position(-700,-800);

You can set the position by using the rest of your code:
germany.Apply(document.getElementById('draggableElement'));

Although I guess that it will set the position of the top left corner and not the center, so you'd need to keep that in mind.
EDIT: Changed the numbers to negative numbers because this will actually move the picture up and left which I assume is the behaviour you want.
For presentation purposes I have added a button to your Fiddle. Although this is definitely not germany ;)
EDIT2:
To animate the position change with jQuery's animate just use this syntax:
$('#draggableElement').animate({
    left: germany.X,
    top: germany.Y
});

Also see the updated JSFiddle.


text:
Q: Inductance value of an Isolation Transformer There is a small isolation transformer 'L1' of 1:1 ratio as shown in the image. A 0-24V, 75kHz square wave is applied from push-pull mosfets stage at the 'V_SW' input of the circuit. I want to find out the approx inductance value of the isolation transformer using calculation. Is there some way to do this calculation?

New Edit:
I have found this transformer and it is actually not a transformer but a Common mode choke for EMI suppression filter. But in the above circuit it is used for isolation purpose as it is just 1:1 turns ratio.
My question is that this choke is available from 33 mH to 0.5 mH values. Should I use lower Inductance value or higher or some middle value? How will it effect the working of this circuit?
The exact part is found at this link:
http://www.mycoiltech.com/emi-suppression-filter-common-mode-choke-coil-uu9-for-ac-power-lines_p75.html

A: There's no way to do it from calculation alone, you need some measurements.
Take all the secondary loading off, and measure the current waveform as you apply your 24v 75k square wave. Then you'll have enough data to compute primary inductance, via V = Lpri * dI/dt

A: C1 is after the diode rectifier, so it will be a DC voltage with a small voltage ripple of 150 kHz.

A: If you know the winding turn number \$N\$ and the core geometry and core material you can calculate the inductance as
\$L_m = \frac{N^2}{R_m}\$
with
\$R_m = \frac{l_m}{\mu_0 \cdot \mu_r \cdot A_q}\$
where at 75 kHz the core is usually ferrite. \$l_m\$ is the average length of the flux line in the core and \$A_q\$ is the (center leg) cross section.


text:
Q: Relationg between tables in MySQL I have two tables in my DB.
Person

*

*id int(11) primary key A_I,

*fName varchar(30),

*lName varchar(30)

Details
which holds detail information about the person

*

*id int(11) primary key A_I,

*gender varchar(30),

*email varchar(30),

*age varchar(30)

My question is how can i make a relation between the two and a trigger when deleting a person from Person table also to delete his/her detailed information from Details?
Thanks

A: I think maybe you don't need 2 tables. Why storing person details in separate table. you can use the same table Person. This is has more sense.
Else if you are really in need to do it like that you have just to add a column "personId" in your person details as a foreign key.
So to get all data of a person you just join 2 tables:
Select * from Person p join PersonDetails pd on p.personId = pd.personId

Trigger depends on the database that you are using. If you are using SQL Server please refer to this link:
http://msdn.microsoft.com/fr-fr/library/ms189799.aspx
For mysql refer to this:
http://dev.mysql.com/doc/refman/5.5/en/trigger-syntax.html

A: Two ways it could be done either by setting a foreign key constraint with ON DELETE CASCADE
Now looking at the schema I do not see you are storing the person id in the detail table.
You may need to add a column as person_id in the Details table and store the id from Person table into this table.
http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html
http://www.mysqltutorial.org/mysql-on-delete-cascade/
Here is a DEMO how to create foreign key constraint with on delete cascade
Or you can write a trigger to handle it something as
delimiter //
create trigger delete_person after delete on Person
for each row
begin
 delete from Details where person_id = old.id ;
end; //

delimiter ;


text:
Q: Google Maps API complaining in IE11 about polyfill Array.from() I'm trying to figure out an issue with Google Maps v3 and a polyfill we use for non-ES6 browsers (IE11 for example). The error we get is:
This site overrides Array.from() with an implementation that doesn't support iterables, which could cause Google Maps JavaScript API v3 to not work correctly.

The polyfill is: ( from https://vanillajstoolkit.com/polyfills/arrayfrom/ )
if (!Array.from) {
  Array.from = (function () {
    var toStr = Object.prototype.toString;
    var isCallable = function (fn) {
      return typeof fn === 'function' || toStr.call(fn) === '[object Function]';
    };
    var toInteger = function (value) {
      var number = Number(value);
      if (isNaN(number)) { return 0; }
      if (number === 0 || !isFinite(number)) { return number; }
      return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number));
    };
    var maxSafeInteger = Math.pow(2, 53) - 1;
    var toLength = function (value) {
      var len = toInteger(value);
      return Math.min(Math.max(len, 0), maxSafeInteger);
    };

    // The length property of the from method is 1.
    return function from(arrayLike/*, mapFn, thisArg */) {
      // 1. Let C be the this value.
      var C = this;

      // 2. Let items be ToObject(arrayLike).
      var items = Object(arrayLike);

      // 3. ReturnIfAbrupt(items).
      if (arrayLike == null) {
        throw new TypeError('Array.from requires an array-like object - not null or undefined');
      }

      // 4. If mapfn is undefined, then let mapping be false.
      var mapFn = arguments.length > 1 ? arguments[1] : void undefined;
      var T;
      if (typeof mapFn !== 'undefined') {
        // 5. else
        // 5. a If IsCallable(mapfn) is false, throw a TypeError exception.
        if (!isCallable(mapFn)) {
          throw new TypeError('Array.from: when provided, the second argument must be a function');
        }

        // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.
        if (arguments.length > 2) {
          T = arguments[2];
        }
      }

      // 10. Let lenValue be Get(items, "length").
      // 11. Let len be ToLength(lenValue).
      var len = toLength(items.length);

      // 13. If IsConstructor(C) is true, then
      // 13. a. Let A be the result of calling the [[Construct]] internal method
      // of C with an argument list containing the single item len.
      // 14. a. Else, Let A be ArrayCreate(len).
      var A = isCallable(C) ? Object(new C(len)) : new Array(len);

      // 16. Let k be 0.
      var k = 0;
      // 17. Repeat, while k < len… (also steps a - h)
      var kValue;
      while (k < len) {
        kValue = items[k];
        if (mapFn) {
          A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);
        } else {
          A[k] = kValue;
        }
        k += 1;
      }
      // 18. Let putStatus be Put(A, "length", len, true).
      A.length = len;
      // 20. Return A.
      return A;
    };
  }());
}

This works fine on other pages - but for some reason Google Maps seems to have an issue with it!
Even more frustratingly, is that it then breaks one of my other plugins (a lazy load script), which works fine until the Google map stuff is loaded
Any ideas on what its moaning about, and how to fix it?
If you have IE11 or a VM, you can test it at: https://www.chambresdhotes.org/Detailed/1768.html (click on the map at the bottom of the page, and this will load the Google Map - but then you get this annoying error, and it breaks the lazyload scrolling after)
Thanks!


text:
Q: How to create a custom clock for use in std::chrono functions? I have some arbitrary epoch, like July 13, 1988. Essentially I want to measure the time relative to this. I was thinking of writing a custom clock class, so that I could write code like this:
using std::chrono;
time_point<My_Clock> tp;
std::cout << duration_cast<seconds>(tp.time_since_epoch()).count() << std::endl;

Is this possible? If not, what's the cleanest way to accomplish this?

A: The hard part of writing this custom clock is figuring out how to write its now() function.  In the example below I base the now() off of system_clock's now().  First I do some detective work to discover that my system_clock has an epoch of New Years 1970, neglecting leap seconds.  This is known as unix time.  As it turns out, every implementation I'm aware of (and I think I've checked them all) have this very same epoch (but this is unspecified by the C++11 standard).
Next I compute that 1988-07-13 is 6768 days after 1970-01-01.  Using these two facts, the rest is easy:
#include <chrono>

struct My_Clock
{
    typedef std::chrono::seconds              duration;
    typedef duration::rep                     rep;
    typedef duration::period                  period;
    typedef std::chrono::time_point<My_Clock> time_point;
    static const bool is_steady =             false;

    static time_point now() noexcept
    {
        using namespace std::chrono;
        return time_point
          (
            duration_cast<duration>(system_clock::now().time_since_epoch()) -
            hours(6768*24)
          );
    }
};

MyClock needs nested typedefs to describe its duration, rep, period, and time_point.  Based on your question, I've chosen seconds as the duration, but you can choose anything you want.
For the now() function I just call the system_clock::now() and subtract off the epoch in units of seconds.  I got just a little clever with this computation by writing everything in terms of MyClock::duration so that I can more easily change duration.  Note that I was able to subtract off the epoch in terms of hours, which implicitly converts to duration (which is seconds).  Alternatively I could have built myself a custom duration of days:
typedef std::chrono::duration<int, std::ratio_multiply<std::chrono::hours::period,
                                                       std::ratio<24>>> days;

And then the return of now() could have been written:
        return time_point
          (
            duration_cast<duration>(system_clock::now().time_since_epoch()) -
            days(6768)
          );

At any rate, now you can use this like:
#include <iostream>

int
main()
{
    using namespace std::chrono;
    time_point<My_Clock> tp = My_Clock::now();
    std::cout << tp.time_since_epoch().count() << '\n';
}

Which for me just printed out:
786664963

Which demonstrates that today (2013-06-16) is approximately 24.9 years after 1988-07-13.
Update for C++20
In C++20 you can use the updated <chrono> calendrical services to eliminate the "magic number" from the implementation:
#include <chrono>

struct My_Clock
{
    typedef std::chrono::seconds              duration;
    typedef duration::rep                     rep;
    typedef duration::period                  period;
    typedef std::chrono::time_point<My_Clock> time_point;
    static const bool is_steady =             false;

    static time_point now() noexcept
    {
        using namespace std::chrono;
        return time_point
          {
            duration_cast<duration>(system_clock::now() - sys_days{July/13/1988})
          };
    }
};

There is no run-time expense for this convenience.  The sub-expression sys_days{July/13/1988} is optimized at compile-time into a count of days since the system_clock epoch, and then further converted to system_clock::duration (still at compile-time) before being subtracted from system_clock::now().


text:
Q: How to retrieve number of hours past midnight from an NSDate object? I need to retrieve the number of hours past midnight from a UIDatePicker control in an iPhone project. datePickerMode is set to UIDatePickerModeTime, so the user only can set a time, no date. When the user is done and dismisses the view the UIDatePicker is on, the following date might be retrieved (as an example):
NSDate *returnTime = timePicker.date;
NSLog(@"returnTime: %@", returnTime); // returns for example @"1970-01-01 10:13:00 PM +0000"

As said, I'm looking for the number of hours past midnight. In the example above, that value should be 22. I wanted to achieve this by creating an NSDateFormatter object and have it extract the hour of day in 24 hour clock format, thus using setDateFormat:@"H" (capital H rather than 'h'):
NSDateFormatter *formatHour = [[NSDateFormatter alloc] init];
[formatHour setDateFormat:@"H"];
NSInteger intHoursPastMidnight = [[formatHour stringFromDate:returnTime] integerValue];

This however does not always work as expected. When the user has disabled the 24 hour clock in the system wide Preferences (i.e. the user uses AM/PM), intHoursPastMidnight will contain 10 rather than 22. 10 is indeed the value that's visible in the UIDatePicker, but I had expected NSDateFormatter to convert this to 22 because of @"H".
What's wrong here? Is my convert assumption incorrect? Is this a bug with UIDatePicker? How can I solve the problem, so I can essentially access the number of hours past midnight set in the UIDatePicker, independent from the user's 12 or 24 hour clock preference? Is this the way to go anyway?
The end goal, to make it clear, is to retrieve the number of minutes past midnight (so hours*60+minutes, value always betweet 0 and 1440).

A: Dave's answer is correct, however it is not as performant as the example below. In my Instruments profile tests my solution was more than 3x as fast -- the total time taken by his method across all calls in my test app was 844ms, mine 268ms.
Keep in mind that my test app iterates over a collection of objects to calculate the minutes since midnight of each, which is then used as a basis for sorting. So, if your code isn't doing something similar, his more-readable, more-standard answer is probably a better choice.
int const MINUTES_IN_HOUR  = 60;
int const DAY_IN_MINUTES   = 1440;

#define DATE_COMPONENTS (NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekCalendarUnit |  NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekdayCalendarUnit | NSWeekdayOrdinalCalendarUnit)
#define CURRENT_CALENDAR [NSCalendar currentCalendar]

- (NSUInteger)minutesSinceMidnight
{
    NSDateComponents *startComponents = [CURRENT_CALENDAR components:DATE_COMPONENTS fromDate:self.startTime];
    NSUInteger fromMidnight = [startComponents hour] * MINUTES_IN_HOUR + [startComponents minute];

    return fromMidnight;
}

A: You can do this with your NSCalendar.
First, get your date:
NSDate *date = [timePicker date];

Next, convert it into its date components:
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSIntegerMax fromDate:date];

Now we'll reset the hours and minutes of the date components so that it's now pointing at midnight:
[components setHour:0];
[components setMinute:0];
[components setSecond:0];

Next, we'll turn it back in to a date:
NSDate *midnight = [[NSCalendar currentCalendar] dateFromComponents:components];

Finally, we'll ask for the hours between midnight and the date:
NSDateComponents *diff = [[NSCalendar currentCalendar] components:NSHourCalendarUnit fromDate:midnight toDate:date options:0];

NSInteger numberOfHoursPastMidnight = [diff hour];


text:
Q: Can AngularJS components modify their wrapper element? I like to think of Angular components as element directives. Given a component called hero I can use it in the parent template like this:
<hero myparam="something"></hero>

I'd like to use the hero element as a component-managed container, with the component being in charge of the whole element.
EXPECTED
Here's what I hope to get out of the binding from above:
<hero id="component123" class="alien" custom="foo">text</hero>

My custom component transforms the given element and uses it as it sees fit.
ACTUAL
However, it seems the component can only render its template inside the hero element. Best I can get is:
<hero myparam="something">
    <div id="component123" class="alien" custom="foo">
        text
    </div>
</hero>

I feel this is bad because the hero element is not actually the hero, but merly a wrapper for the actual hero. This mixes up the semantics and creates unwanted extra elements.
Is it best practice in Angular to use components as pure wrappers and putting the actual components inside?
Here's an official sample to play around with:
https://plnkr.co/edit/NKjCDS8OEngYHNrBmC5O?p=preview

A:
I like to think of Angular components as element directives.

A component could be thought of as a special kind of directive that updates a template. If you want to change attributes, use an actual directive (attribute directive)

My custom component transforms the given element and uses it as it
  sees fit.

When you talk about transforming, you want directives, not components.


text:
Q: Как узнать, куда ведет pipe:[номер] из /proc/self/fd/4? Я решаю такую задачу: нужно отправлять вывод PHP-скрипта, работающего в фоновом режиме (background), внутри контейнера, в журнал докера. Запись в /dev/stderr и /dev/stdout для этого не подходит (они ведут в итоге в /dev/null).
Поэтому нужно среди /proc/self/fd найти дескриптор, запись в который выведется в журнале докера. Я выяснил, что /proc/self/fd/4 для этого подходит и работает. Вот все дескрипторы:
root root 64 Feb 11 15:24 0 -> /dev/null
root root 64 Feb 11 15:24 1 -> pipe:[13054229]
root root 64 Feb 11 15:24 10 -> pipe:[13054229]
root root 64 Feb 11 15:24 11 -> pipe:[13054229]
root root 64 Feb 11 15:24 12 -> pipe:[13230601]
root root 64 Feb 11 15:24 2 -> pipe:[13054229]
root root 64 Feb 11 15:24 3 -> /var/www/artisan
root root 64 Feb 11 15:24 4 -> pipe:[13054229]
root root 64 Feb 11 15:24 5 -> pipe:[13054230]
root root 64 Feb 11 15:24 6 -> /var/www/artisan
root root 64 Feb 11 15:24 7 -> pipe:[13235313]
root root 64 Feb 11 15:24 8 -> pipe:[13235314]
root root 64 Feb 11 15:24 9 -> /var/www/artisan

Но эта цифра "4" может меняться из-за пересборки образа. Образ на основе Debian, сборкой управляю не я, набор средств ограничен, lsof отсутствует.
Поэтому я решил среди пайпов find -L /proc/$pid/fd -type p отфильтровать и найти подходящий - по названию процесса.
stat /proc/$pid/fd/4:
/proc/263/fd/pipe:[13054229]
  File: /proc/263/fd/4 -> pipe:[13054229]
  Size: 64          Blocks: 0          IO Block: 1024   symbolic link

Вопрос 1. Как понять, куда ведет эта труба? Интересует название процесса. По нему я смогу вычислить, подходит она или нет.
Вопрос 2. Как эта труба правильно называется? "named pipe" не подходит, это другой механизм.
PS. Решить проблему проще не удастся.


text:
Q: How many ways can six distinct black books and four distinct red books be arranged on a shelf if no two red books are adjacent? Question : There are $10$ different books on a shelf. Four of them are red and the other six are black. How many different arrangements of these books are possible if no two red books may be next to each other?
So what I have done is
1) The # of ways to range the black books $= 6!$
2) So two red books can't be placed together $= 6! \cdot \frac{7!}{3!} = 604 800$
3) I am kind of confused right now. I don't know what I should subtract $604~800$ from.
Thank you!

A: This is a perfect problem to solve with stars and bars.
We have to place 6 black books in total. We can treat the red books as "dividers", and if we do that, the problem becomes how many ways are there to rearrange (*'s are black books, |'s are red)
******||||

However, to enforce that no two red books touch, we have to place 1 book in between 3 of the dividers. So, we only have 3 black books that we have to place
***||||

So, our answer, if the books are indistinguishable, is $${7\choose3}=\color{red}{35}$$
Now, as you note, the books are different. So, we multiply by the number of arrangements of red books and black books.
So, our final answer is $$35\cdot6!\cdot4!=\color{red}{604,800}$$

A: Your answer is correct.
Let's justify your argument:
Method 1:  The six black books can be arranged in a row in $6!$ ways.  This creates seven spaces in which a red book can be placed, five between successive black books and two at the ends of the row.
$$\square B \square B \square B \square B \square B \square B \square$$
To ensure that no two of the four red books are adjacent, we must choose four of these spaces in which to place a red book, which can be done in $\binom{7}{4}$ ways.  The four red books can be arranged in these spaces in $4!$ ways.  Hence, the number of admissible arrangements is
$$6!\binom{7}{4}4! = 6! \cdot \frac{7!}{3!} = 604800$$
as you found.  There is no need to subtract.
Let's confirm your result.  The following argument is more formal.  Alas, it is also trickier, particularly when we count those arrangements in which there are two disjoint pairs of adjacent books.
Method 2:  We use the Inclusion-Exclusion Principle.
Since there are $10$ different books on the shelf, they can be arranged in $10!$ ways.  From these, we must subtract those arrangements in which a pair of red books are adjacent.
A pair of adjacent red books:  A pair of adjacent red books can be selected in $\binom{4}{2}$ ways.  We now have nine objects to arrange, the six black books, the pair of adjacent red books, and the other two red books.  The objects can be arranged in $9!$ ways.  The pair of adjacent books can be arranged internally in $2!$ ways.  Hence, there are
$$\binom{4}{2}9!2!$$
arrangements with a pair of adjacent red books.
However, if we subtract the number of arrangements with a pair of red books from the total, we will have subtracted too much since we will have subtracted each arrangement with two pairs of adjacent red books twice, once for each way of designating one of the pairs as the pair of adjacent red books.  Thus, we add those arrangements to the total.
Two pairs of adjacent red books:  This can occur in two ways.  Either the pairs are disjoint or overlapping, meaning that there are three consecutive red books.
Two disjoint pairs of adjacent red books:  Since the red books are distinct, there must be some ways of distinguishing them.  Say they have different titles.  If so, then there are three ways to pair one of the other red books with the one whose title appears first in an alphabetical list.  The other two red books must form the other pair of adjacent red books.  We have eight objects to arrange, the six black books and two disjoint pairs of red books.  The objects can be arranged in $8!$ ways.  Each pair of adjacent red books can be arranged internally in $2!$ ways.  Hence, there are
$$\binom{3}{1}8!2!2!$$
arrangements with two disjoint pairs of red books.
Two overlapping pairs of adjacent red books:  The three consecutive red books can be selected in $\binom{4}{3}$ ways.  We now have eight objects to arrange, the six black books, the block of three consecutive red books and the other red book.  The objects can be arranged in $8!$ orders.  The trio of consecutive red books can be arranged internally in $3!$ ways.  Hence, there are
$$\binom{4}{3}8!3!$$
arrangements with two overlapping pairs of red books.
Hence, there are
$$\binom{3}{1}8!2!2! + \binom{4}{3}8!3!$$
arrangements with two pairs of adjacent red books.
However, if we subtract the number of arrangements with a pair of adjacent red books and then add the number of arrangements with two pairs of adjacent red books from the total, we fail to exclude those arrangements with three pairs of adjacent red books, which can only occur if there are four consecutive red books since there are only four red books.  The reason is that we subtracted such arrangements three times, once for each way of designating one of the three pairs of adjacent red books as the pair of adjacent red books, and added them three times, once for each of the $\binom{3}{2}$ ways of designating two of the three pairs of adjacent red books as the two pairs of adjacent red books.
Three pairs of adjacent books:  There are seven objects to arrange, the six black books and the block of four red books.  The objects can be arranged in $7!$ ways.  The block of four red books can be arranged internally in $4!$ ways.  Hence, there are
$$7!4!$$
arrangements with three pairs of adjacent red books.
Hence, the number of arrangements of six distinct black books and four distinct red books in which no two red books are adjacent is
$$10! - \binom{4}{2}9!2! + \binom{3}{1}8!2!2! + \binom{4}{3}8!3! - 7!4! = 604800$$
as you found.


text:
Q: how to validate a required and numeric textbox using jquery? I want to validate a textbox have numeric values using the following code, but i dont know the filter term there for numeric, my code is:
    function validateRequiredNumeric(Control, msgInfo) {
    var ControlId = $('#' + Control);
    var msgInfoId = $('#' + msgInfo);
    //testing regular expression
    var a = ControlId.val();
    var filter = /[^\d]/;
    alert(a.length);
    if (a.length != 0) {
        if (filter.test(a)) {
            msgInfoId.text('');
            ControlId.css({ 'border': '1px solid green' });
            return true;
        } else {
            //msgInfoId.css({ 'color': 'red', 'font-size': '12px', 'font-style': 'italic' });
            msgInfoId.text("Numeric Onlydd fdf dfd");
            ControlId.css({ 'border': '1px solid red' });
            return false;
        }
    }
    else {
        //msgInfoId.css({ 'color': 'red', 'font-size': '12px', 'font-style': 'italic' });
        msgInfoId.text("You can't leave this empty.");
        ControlId.css({ 'border': '1px solid red' });
        return false;
    }

}

Please help me.. i have tried the "[^0-9]" this also..

A: The regexp should be either:
For only numeric /^[\d]+$/
For any non-numeric /^[^\d]+$/
I am not sure what you mean in your question since your regexp try was for non-numeric.
Another answer made me think about it, if you expect users to use decimals, you should add some character cases...
For decimals /^[\d]+[,.]?[\d]*$/
requires at least one number before the decimal.

A: try the Texottela plugin, enables using a numeric() function for that, and you can supply a callback that runs when focus is lost and the value in the text box is not a valid number.

A: I believe the term you're looking for is a regular expression
This should do it:
var filter = /^\d*$/;

The carat ^ symbol will anchor the decimal to the start of the string
The $ symbol anchors the decimal to the end of the string
and the \d* matches one or more decimal values
If there is any non-decimal in the string, the regex will return false

A: You don't need a regex for that
    var a = Number($.trim(controlID));  //or parseInt($.trim(controlID))
    if (!isNaN(a)) {
        //a is valid number
    } else {
        //a is not a number or is empty
    }


text:
Q: Find the value of $a$ for which two lines are perpendicular Two vectors are perpendicular when their dot product is zero. But how to get the dot product of two lines?
$r_1= (8,-3,1)+s(12,-5,0)$
$r_2= (1,14,3)+t(5,a,b)$
The question asks for the value of $a$ given that the two lines are perpendicular.

A: The vectors $(12,-5,0)$ and $(5,a,b)$ are the direction vectors of the lines. If the dot product of those two vectors is zero, then the lines are perpendicular.
Hence you have to calculate: $$(12,-5,0)\cdot(5,a,b)=0$$
This gives: $12\cdot5-5\cdot a=0 \Longleftrightarrow 60-5a=0 \Longrightarrow \boxed{a=12}$


text:
Q: Eclipse Javadoc-like window for PHP I have a question about Eclipse which I'm starting to use as a PHP IDE. I'm not sure if the question is at the right place here.
Is there a window much like the Javadoc window where you can see all the information Eclipse has to offer about a certain PHP function or class?
Thanks in advance!

A: I've not used Eclipse as a PHP editor but I'm sure there's a plugin that can do that. Maybe PHPEclipse.
I would recommend Netbeans for PHP editing, tho. It definitely contains the PHP language reference, as well as support for git, Smarty and plugins for just about anything else.

A: The behavior you're looking for is indeed available in the Eclipse PDT (PHP Development Tools) plugin.  Just hover over a class name, a method name, whatever, and if there has been any PHP docblock information in the code for that code element, then the hover popup will show it.  Further, native PHP functions will display the info from the PHP Manual.


text:
Q: correct syntax for form_for url in rails This is probably simple, I'm still coming to terms with rails syntax. What is the right syntax to pass the address_id in the url for form_for to a modified route?
This is the form - note the "address_id parameter"

    <%= form_for address, :url => edit_address_path(:id => address.id), :method => :get do |f| %>
        <%= content_tag(:button, :class => 'btn btn-inverse') do %> Edit Address
        <% end %>
    <% end %>

And this is the route I've configured:
get "edit_address/:id" => "member/addresses#edit"

Id is not being passed to the controller for some reason...

A: form_for address should be enough if address is a persisted object, but if it's not enough, then form_for address, url: edit_address_path(address) is what you want.

A: This is very simple.  In place of url, you put your post method route:
<%= form_for(@post, url: super_posts_path) do |f| %>

...
<% end %>

You also call by action
 <%= form_for @friend,:url=> { action: "create_friend"} do |f|%>

  <%= f.label :u_from %>
      <%= f.text_field :u_from %>
     <%= f.label :u_to %>
     <%= f.text_field :u_to %>
    <%= f.submit%>
 <% end %>


text:
Q: How to use local p2 site to solve dependency issue in RCP application development? I'm new to RCP development. Here is my problem.

*

*First the following sreenshot is my directroy structure.

*I want to use Unirest for Java in my plug-in project, which is com.example.e4.rcp.todo in our case.

*I follow this runs a p2 update site locally by mvn jetty:run successfully, and I added following line into <artifacts>
<artifact><id>com.mashape.unirest:unirest-java:1.4.9</id></artifact>

*And now I want to use Maven to build my project through Tycho. Here are my pom.xml, which under com.example.e4.rcp.todo directory.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example.e4.rcp</groupId>
  <artifactId>com.example.e4.rcp.todo</artifactId>
  <version>1.0.0-SNAPSHOT</version>
  <packaging>eclipse-plugin</packaging>

  <repositories>
    <repository>
      <id>neon</id>
      <url>http://download.eclipse.org/releases/neon</url>
      <layout>p2</layout>
    </repository>
  </repositories>

  <build>
    <plugins>
      <plugin>
        <groupId>org.eclipse.tycho</groupId>
        <artifactId>tycho-maven-plugin</artifactId>
        <version>0.26.0</version>
        <extensions>true</extensions>
      </plugin>
      <plugin>
        <groupId>org.eclipse.tycho</groupId>
        <artifactId>tycho-p2-repository-plugin</artifactId>
        <version>0.26.0</version>
      </plugin>
      <plugin>
        <groupId>org.eclipse.tycho</groupId>
        <artifactId>target-platform-configuration</artifactId>
        <version>0.26.0</version>
        <configuration>
          <environments>
            <environment>
              <os>linux</os>
              <ws>gtk</ws>
              <arch>x86</arch>
            </environment>
            <!-- and others... -->
          </environments>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

*When I run mvn clean package, it shows the following error:

[ERROR] Cannot resolve project dependencies: [ERROR]   Software being
  installed: com.example.e4.rcp.todo 1.0.0.qualifier [ERROR]   Missing
  requirement: com.example.e4.rcp.todo 1.0.0.qualifier requires 'bundle
  com.mashape.unirest.java 1.4.9' but it could not be found [ERROR]
  [ERROR] See
  http://wiki.eclipse.org/Tycho/Dependency_Resolution_Troubleshooting
  for help. [ERROR] Cannot resolve dependencies of MavenProject:
  com.example.e4.rcp:com.example.e4.rcp.todo:1.0.0-SNAPSHOT @
  C:\Users\wangzen\workspace2\com.example.e4.rcp.todo\pom.xml: See log
  for details -> [Help 1] [ERROR] [ERROR] To see the full stack trace of
  the errors, re-run Maven with the -e switch. [ERROR] Re-run Maven
  using the -X switch to enable full debug logging. [ERROR] [ERROR] For
  more information about the errors and possible solutions, please read
  the following articles: [ERROR] [Help 1]
  http://cwiki.apache.org/confluence/display/MAVEN/MavenExecutionException

What should I do to solve this problem? Do I have to add the local p2 update site into pom.xml?
BTW: I'd really appreciate it if anyone who can help me to format my question description, especially in pom.xml section. I've tried using <code> block, but it seems doesn't work.

A: You need to add
<repository>
  <id>unirest</id>
  <url>file:/path/to/unirest/p2/repo</url> <!-- or an http:// based one if available -->
  <layout>p2</layout>
</repository>


text:
Q: copying file between folders using bash script I am trying to submit several jobs in a consecutive manner.
Each job is located in a separate folder and each time that a job wants to be submitted, I need to copy some files from the previous folder into the new folder.
I wrote the below SLURM script, but it fails into copying files between folders.
Can someone please let me know what is the problem with my bash script?
#!/usr/bin/bash
#SBATCH --time=120:00:00
#SBATCH --partition=...
#SBATCH --ntasks=...
#SBATCH --job-name ...
#SBATCH --nodes=...
#SBATCH --gpus-per-node=...
#SBATCH --cpus-per-gpu=...
#SBATCH --account=...
#SBATCH --qos=...
#SBATCH --output=slurm-out
#SBATCH --error=slurm_error

cd $SLURM_SUBMIT_DIR
module load gcc/9.3.0
for((i=0;i<=4;i++))
  do
      cd $i
      if [$i -gt 0]
      then
          j=$(($i - 1))
          cp $j/file1  ./file2

      fi
    csh README > log
    cd ../
done

I tried to use the bash script, but it failed into copying files between folders.

A: Because $j is not an absolute path, you need to modify your script to handle what @tjm3772 pointed out.  Namely, change
cp $j/file1  ./file2

to
cp ../$j/file1  ./file2

Also, if you don't care if the file is modified from step to step, you might even consider using
ln ../$j/file1 ./file2

making your process both faster and using less disk space.


text:
Q: LUKS with separate /home within encrypted volume First time using full disk encryption with LUKS. Sorry for a lot of novice questions.
Before using full disk encryption, I used to have separate partitions /boot, /, home which allow to to reinstall the OS while preserving the data in the /home partition.
I would like to keep the same principle of separate partitions with full disk encryption. The Kubuntu 22.04 installer doesn't allow manual partition definition when encryption is enabled. There is only one option "Erase everything and enable encryption" (sorry don't remember the exact wording). Other boot options selected: secure boot and UEFI. Here is the partition layout after Kubuntu 22.04 has been successfully installed.
lsblk -e7

NAME                   MAJ:MIN RM   SIZE RO TYPE  MOUNTPOINTS
sda                      8:0    1     0B  0 disk
nvme0n1                259:0    0 476.9G  0 disk
├─nvme0n1p1            259:1    0   512M  0 part  /boot/efi
├─nvme0n1p2            259:2    0   1.7G  0 part  /boot
└─nvme0n1p3            259:3    0 474.8G  0 part
  └─nvme0n1p3_crypt    253:0    0 474.8G  0 crypt
    ├─vgkubuntu-root   253:1    0 473.8G  0 lvm   /
    └─vgkubuntu-swap_1 253:2    0   980M  0 lvm   [SWAP]

No idea what the sda disk is, the machine has a single NVMe disk. Now there is only one root partition / in the encrypted partition nvme0n1p3. Let's assume I would like to reinstall the OS from scratch, with disk encryption, same passphrase. The /home directory would be lost.
Q1. Is it possible to add a separate volume and assign /home partition? In such a way that an OS reinstall would preserve the existing encrypted data? I am OK to use terminal, reformat existing disk to restart clean from scratch. The important point here is LUKS allows to preserve existing /home volume for future OS install.
Q2. Let's assume Q1 is doable and now there are separate / and /home partitions within the encrypted disk. I would like to install an OS, this could be anything, newer Kubuntu, Arch, EndeavourOS, etc. Would the native installer of the OS allow to select Full disk encryption, re-use same passphrase, re-use the existing partition layout, reformat /boot and /. But preserve the existing encrypted /home?
Q3. Is it normal that LUKS asks for the encryption passphrase at every reboot? I saw a Windows 10 user enabling Bitlocker. Somehow, Windows manages to encrypt the disk without asking for an additional password. The user continues to use Windows the same way as before Bitlocker, ie. boot straight to the login Windows. At a high level, what is the fundamental difference between LUKS and Bitlocker so that LUKS needs a separate password?

A: I can't fully answer everything, but here is a partial answer (way to much to go into comments)
Q1. It is possible to have /home as a separate LUKS partition, but its going to be fiddly to get working - at least under Ubuntu - I don't think you can get there using just the installer.
You could actually do this with your current setup as you are using LVM under LUKS.  The answer would be to

*

*Shrink your vgkubuntu-root partition (shrink the filesystem down as much as you can - which would need to be done from a boot disk,

*Then shrink the vgkubuntu-root partition in LVM

*Then expand the filesystem to the new size of that partition

*Then create a new partition in LVM for home

*Then mount it.  Because the LVM is on encrypted disk /home will be encrypted.

Q2.  Probably not, but it depends on how intelligent the installer is.  It is certainly technically possible, and no doubt some distros will do it.
Q3.  Yes, it is normal for LUKS to ask the encryption password at every reboot. I don't know why (at least Ubuntu and Debian) don't do facilitate this, and it is a major PITA to try and retrofit it - but it is doable (I have done it, its horrible).   AFAIK there is no fundamental reason LUKS needs a password, it is quite possible to munge the PCR registers (ie TPM) to produce a key you can use to unlock the partition.   I comment that this is all analogous to how Bitlocker works - AFAIK Bitlocker and LUKS are not compatible.  (Its likely of very limited use, but I wrote a blog when I did this on a previous laptop - https://davidgo.gottschen.com/2017/06/20/dell-venue-11-pro-7139-as-a-linux-tablet-with-full-disk-encryption/ - and this has links to other useful resources )


text:
Q: Run Program and wait for process to complete I have a simple BAT sdcript that should run the WTVCnverter. I want it to match all files by *.wtv and using the program convert to dvr-ms. Before executing the second or third file it should wait for the WTVConverter to exit before proceeding.
 @echo off

 for %%f in (*.in) do (

      echo %%~nf
      C:\Windows\ehome\WTVConverter.exe "%%~nf.wtv""%%~nf.dvr-ms" /ShowUI | out-null

 )

A: In a batch file (though your code works as is if typed) preface the command with cmd /c start "" /w so
cmd /c start "" /w C:\Windows\ehome\WTVConverter.exe "%%~nf.wtv""%%~nf.dvr-ms" /ShowUI | out-null

GUI processes (ie not console) are waited on in batch but not when typed. See start /?.
Pipes are also implemented by cmd.exe. If your pipe character is for your program escape with a ^.
You seem to be lacking a space between in and out filename.


text:
Q: Error[Pe020]: identifier "FILE" is undefined in IAR Workbench // Preprocessor directive mention in <> formate :
#include "stdio.h"
#include "stdlib.h"
#include "math.h"
#include "string.h"
#include "limits.h"
#include "stddef.h"
#include "stdint.h"
...
int main()
{
 FILE *fin, *fout;  //Error[Pe020]: identifier "FILE" is undefined
 ...
 ...
 ...
 fprintf(stderr, "%s\n", opus_get_version_string());
                         //Error[Pe020]: identifier "stderr" is undefined

}

As per above code I got an two Errors :
1) "Error[Pe020]: identifier "FILE" is undefined"
when I found stdlib.h then there are no any kind of "FILE" directive define or typedef.
   So,please tell me which changes needed in stdlib.h or stdio.h
2) Error[Pe020]: identifier "stderr" is undefined
So,In which header file stderr define ?
Please tell me How to solve above errors ?
Thanks in advance.

A: First, FILE is in stdio.h not in stdlib.h. Second, the default library does not include FILE support since this feature uses a lot of space and is seldom needed in embedded systems. To use FILE you must switch to full libraries in the configuration dialog (if you use the IDE) or by using the command line switch --dlib full (if you use the compiler from the command line).
Note that the full library is much larger than the normal library so if the only use of FILE is to print diagnostic messages to stderr I suggest that you use some other way of presenting the messages.

A: FILE is defined in stdio.h standard header file. As Johan mentioned the default library configuration in IAR IDE does not include full Dlib support.
We can change to Full Dlib support under project options.
Project options shall be opened with ALT + F7 Hotkey or project tab and then options. Check this Image.
Project Options


text:
Q: Add a link to display posts with a specific tag within a date range I'm trying to create a WP-based website with lots of documents about various people from different dates. I would like to have a dedicated page for each individual where there'll be links to display the posts about that person from a specific year.
Could you help me find a way to do this?
Thank you!

A: Check out wp_get_archives().
As described by the Function Reference linked to above, "This function displays a date-based archives list. This tag can be used anywhere within a template."
It gives several examples of how you can use the function, including if you wish to use a dropdown rather than listing every archive.
By default this function will take in to account every post, not just the ones about your author.  However, you needn't fear - there are hooks that you can use to fix this. For example, you can add a specific author -
On your template add this -
$args = array(
    'author' => $author_id,  // Obviously this relies on you knowing the ID of the author
    'type' => 'yearly'
)
wp_get_archives($args);

And then in functions.php
add_filter('getarchives_where', 'my_edit_getarchives_where');
function my_edit_getarchives_where($where, $args){

    if(isset($args['author']) :  // Ensure that an author has been specified
        $where.= ' AND `post_author` IN (' . $args['author'] . ')';
    endif;

    return $where;

}

Note that while auhor is not a default argument of the wp_get_archives() function, it won't be stripped out and thus will be available for your custom use in a scenario such as that described above.
If that example doesn't quite do it for you then there are two other filter hooks that you can use

*

*getarchives_join - Allows you to JOIN additional tables (so that you can link to archives of a certain category/tag).

*the_title - You can amend the title output if you wish (place 'Archive - ' before it, for example). Not much help in your situation, but good to know about.
I'd encourage you to look through the function in question to fully understand how it works. wp_get_archives() can be found in /wp-includes/general-template.php on line 1321 (I'm using version 4.1).


text:
Q: setInterval() not working after clearInterval() I am currently making a pomodoro timer in Javascript with start and stop buttons. I'm running into issues with using setInterval() to start the countdown after it has been stopped using clearInterval(). I have 2 functions which are called on click of a button, one starts the countdown using setInterval(), the other stops it using clearInterval(). I'm not sure what's going on, this is my implementation below:
var startTime = 25; // this value will change depending on what the user selects, default value is 25:00
var time = startTime * 60; //number of seconds total
var intervalID; //used for setInterval()

var pomodoroTimer = document.getElementById('pomodoro-timer');

function updateTimer(){
    let minutes = Math.floor(time/60);
    let seconds = time % 60;

    minutes = minutes < 10 ? '0' + minutes : minutes;
    seconds = seconds < 10 ? '0' + seconds : seconds;

    pomodoroTimer.innerHTML = minutes + ':'+ seconds;
    time--;
}

function startTimer(){
    if(!intervalID){ // to prevent multiple setIntervals being queued up
        updateTimer(); // call this once to stop clock from taking too long on first use of the setInterval function
        intervalID = setInterval(updateTimer, 1000);
    }
}

function stopTimer(){
    clearInterval(intervalID);
}

A: function stopTimer(){
    clearInterval(intervalID);
    intervalID = undefined;
}