text:
Q: Passing a string from database to drawString() I have a database with all the values stored in a table. I want to print a name from the table using drawString() method. I hv created a resultset and the arraylist. Is there any way to pass a string from database in drawString method??
Please provide me a code or link to a code as I am new to this..Thankyou.
public class AB1 extends JPanel
{   public static void main(String a[]) throws Exception
{
    int ID,TC;
    String FROM, TO, ATS, DTS, SOURCE, DSTN, TS, ST;
    ResultSet rs;

    ArrayList<AB> ab = new ArrayList<AB>();

    //DATABASE CONNECTION

    String TrainNo = "287972";
    try
    {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    String url = "jdbc:oracle:thin:@127.0.0.1:1521:xe";
    Connection c = DriverManager.getConnection(url, "system", "mypcdatabase");

    // STORING TABLE IN RESULTSET

    int rows = 0;

    PreparedStatement st=c.prepareStatement("select * from MT_TRAIN_CONSIST where TRAIN_NUMBER = ?" );
    rs=st.executeQuery();

    PreparedStatement st1=c.prepareStatement("select * from MT_RAKE_TRAIN_LINK_MASTER where TRAIN_NUMBER = ?");
    rs = st1.executeQuery();

    PreparedStatement st2=c.prepareStatement("select * from MT_SLIP_TRAIN_INFO  where TRAIN_NUMBER = ?");
    rs = st2.executeQuery();

    while(rs.next())
    {

    ID = rs.getInt("ID_TRAIN_DEF");
    FROM = rs.getString("COACH_FROM");
    TO = rs.getString("COACH_TO");
    TC = rs.getInt("NUMBER_OF_COACHES");
    ATS = rs.getString("ATTACH_TRANSFER_STATION");
    DTS = rs.getString("DETACH_TRANSFER_STATION");
    SOURCE = rs.getString("TRAIN_SRC");
    DSTN = rs.getString("TRAIN_DSTN");
    TS = rs.getString("TRANSFER_STATION");
    ST = rs.getString("slip_type");

    AB obj = new AB();

    obj.id = ID;
    obj.tc = TC;
    obj.from = FROM;
    obj.to = TO;
    obj.ats = ATS;
    obj.dts = DTS;
    obj.src = SOURCE;
    obj.dstn = DSTN;
    obj.ts = TS;
    obj.st = ST;
    ab.add(obj);

    rows++;
    }
}

catch(Exception ex)
{
    ex.printStackTrace();
}

getImg(new FileOutputStream("C:\\A&B" + TrainNo + ".jpg"), ab);
}

public static void getImg(OutputStream out, ArrayList<AB> ab) throws IOException
{    int imgWidth = 1024, imgHeight = 768;

BufferedImage image = new BufferedImage(imgWidth,imgHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D gx = image.createGraphics();
gx.setColor(Color.BLUE);

gx.setColor(Color.BLACK);
gx.drawLine(60,350,970,350);
gx.drawLine(970,350,960,340);
gx.drawLine(970, 350, 960, 360);
gx.drawString("", 30 , 330);
gx.drawString("", 960 , 330);

ImageIO.write(image, "PNG", out);
out.close();
}
}

A: In your these lines
PreparedStatement st = c.prepareStatement("select * from MT_TRAIN_CONSIST where TRAIN_NUMBER = ?");
rs=st.executeQuery();

You forgot to provide any value for the ?, something like
PreparedStatement st = c.prepareStatement("select * from MT_TRAIN_CONSIST where TRAIN_NUMBER = ?");
st.setString(1, TrainNo);
rs=st.executeQuery();

Please Learn Java Naming Conventions and stick to them.

A: @ gagandeep bali
the line is correct
 String TrainNo = "287972";
this value is passed in place of the ?


text:
Q: What values are used for the counter $k$ in this proof involving a convergent subsequence?
Lemma Suppose that $(x_n)$ is a Cauchy sequence in a metric space $(X,d)$, and $x\in X$. Also suppose $(x_{n_k})$ is a subsequence of $(x_n)$ such that $x_{n_k}\to x$ as $k\to \infty$. Then $x_n\to x$ as $n\to \infty$.
Proof Let $\epsilon>0$ be given. Choose $N_1\in \mathbb N^+$ such that $k\ge N_1$ implies that $d(x_{n_k},x)<\frac {\epsilon} 2$. Choose $N_2\in\mathbb N^+$ such that $m\ge n\ge N_2$ implies that $d(x_m,x_n)<\frac{\epsilon} 2$. Let $N$ be the maximum of $N_1$ and $N_2$. Now $d(x_n,x)\le d(x_n,x_{n_k})+d(x_{n_k},x)$ for all $k$. Using this, we get that $n\ge N$ implies that $d(x_n,x)<\epsilon$. $\small\blacksquare$

What condition must $k$ satisfy for the above proof to hold?
My thought is that $n_k$ must be large enough such that $n_k\ge n$ for all $k>N_k$, some $N_k\in \mathbb N$.
Related

A: What $k$ needs to satisfy is $k\geq N_1$. Since $N_1 \leq max\{N_1,N_2\}$ this implies that $k$ maintains the condition needed or else the first statement would not be true since there is a number greater than $N_1$ in which the assertion claimed is false.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Syntaxe Error with variable on Databse (MySQL / Python) at first I declared a variable "nom_of_game_db", but after that I can't find the correct syntax at the level of the MySQL to call the variable back:
    # -*- coding: utf-8 -*-

name_of_game_db = input("Name of game ?")

class QuotetutorialPipeline(object):

    def __init__(self):
        self.create_connection()
        self.create_table()

    def create_connection(self):
        self.conn = mysql.connector.connect(
                host = 'localhost',
                user = 'root',
                passwd = 'jozefleonel',
                database = 'prices'
            )
        self.curr = self.conn.cursor()

    def create_table(self):
        self.curr.execute("""DROP TABLE IF EXISTS nam_of_game_db""")
        self.curr.execute("""create table name_of_game_db(
                        name text,
                        platform text,
                        edition text
                        )""")

    def process_item(self, item, spider):
        self.store_db(item)
        return item

    def store_db(self,item):
        self.curr.execute("""insert into name_of_game_db values (%s,%s,%s)""", (
            item['name'][0],
            item['platform'][0],
            item['edition'][0]
            ))
        self.conn.commit()

I use Python and MySQL

A: After doing the execute to create table statement use self.conn.commit() to commit the db changes.and also rename the drop table exist sql command.


text:
Q: Xcode could not launch app. Process launch failed: 4294967295 I'm developing an iOS 8 app in Xcode 6.0.1 and running it on my iPhone 5 (which has iOS 8.0.2 on it). Before I updated to iOS 8.0.1 and Xcode 6.0.1, I never got the error I'm getting. However, now, sometimes when I try to run my app from Xcode onto my iPhone, this error message pops down from the top of the Xcode window:
Could not launch "[app name]". Process launch failed: 4294967295

It appears that this error only occurs when I first run the app from Xcode onto my device (i.e. if I close the error message in Xcode, but I don't close the app on my phone--so the app's still up on my phone--I don't get this error when I click the run button again in Xcode). However, there doesn't seem to be a whole lot of consistency because sometimes the error message doesn't drop down even when I launch the app onto my phone for the first time from Xcode (i.e. without the app already being up on my phone).
Also, I have tried several solutions, none of which have completely fixed the error:

*

*Clean out the build, clear out DerivedData, restart my mac, and reopen Xcode.

*Get a new certificate for the app from apple after accepting their new iOS 8.0 license agreement.

*Make sure that, when I install 3rd party Cocoa pods, the Podfile specifies iOS 8.0 platform.

*Set the app's deployment target and build settings for iOS 8.0

I can't seem to figure out how to get this error to consistently stay away even after trying the above-mentioned solution attempts. Again, I can still run the app on my phone normally sometimes, but every couple of runs it displays the strange error message in Xcode and only opens the app on my phone but won't link it with Xcode (for console output, etc).
Any help would be much appreciated. Thanks!

A: Have you tried disconnecting the device and rebooting it?
When I have seen this, the app was always running, but Xcode was not able to attach the debugger to the process (or attach it quickly enough.)

A: We have encountered this before.
The cause was we were using Distribution provisioning profile on Development.
You need to use a Development provisioning profile if you want the debugger to link to your XCode.
Hope this helps!

A: For me the fix was opening the Device Manager (Window -> Devices) and deleting the installed app (select the app and click the "-" button). On the next run the error went away.
XCode 7.3.1


text:
Q: New line in constant error from c# This line occur new line in constant error..how can i fix this?
Locations += Environment.NewLine + " map.addOverlay(new GMarker(new GLatLng(" + Latitude + "," + Longitude + ")));";

A: You can not use "\" string directly in C# code, it produces "new line in constant" error. One of your variables is equal to "\", I can not directly say since the code section you have provided does not include the related initialization code.
instead of using "\", just escape the slash character using "\\".


text:
Q: Error in input: Python I have an input with newline between each string. The end will be noted by a number between 1 to 5:
Input:
Ha
Ha
Hee
Hee
Ho
5
I need to accept this as list of strings in python where my list would contain:
['Ha', 'Ha', 'Hee', 'Hee', 'Ho']
After a lot of googling, I tried the following code:
lines = []

sentinel = range(6)

for i in iter(raw_input, [str(s) for s in sentinel]):
    if i=='':
        continue
    else:
        lines.append(i)

print lines

I don't know why but it goes into an infinite loop.
Please help me out!

A: The issue is with the way iter() interpets the sentinel.  It's a single value that indicates the end of iteration.  For your sentinel to be hit, raw_input() would actually have to return an identical list, which can never happen (since of course it returns a str).
If you wrap things up a bit, you can make it work:
sentinel = range(6)

def anything_but(values):
    values = map(str, values)
    def inner():
        i = raw_input()
        if i in values:
            return None
        return i
    return inner

lines = []
for i in iter(anything_but(sentinel), None):
    lines.append(i)

print lines

In this case, None is the sentinel value which will be returned if a number 0-5 is entered. As an aside, if you wanted 1-5 as you mentioned you should use range(1, 6) instead.
However, you're probably better served doing it with a generator:
sentinel = range(6)

def anything_but(values):
    values = map(str, values)
    i = raw_input()
    while i not in values:
        yield i
        i = raw_input()

lines = []
for i in anything_but(sentinel):
    lines.append(i)

print lines

A: You can just use a while loop:
inp = raw_input()
while inp not in {"1","2","3","4","5"}:
    if not inp:
       continue
    else:
        lines.append(inp)
    inp = raw_input()
print lines

Using the inputs in your question outputs:
['Ha', 'Ha', 'Hee', 'Hee', 'Ho']


text:
Q: php while loop failing inexplicably while fetching result rows So I'm having a very strange issue and am not quite sure what to think about it...
I have a standard database query doing a select on a table. It returns a resource, num_rows = 101, and it will fetch rows up to row 42 at which point it simply stops all script execution, no errors, not timing out (takes less than a sec to get the 42 rows) ... I can't provide a link but here's the code in question...
$select2 = "SELECT * FROM `$dbname`.`$file" . "_settings` WHERE `weight` <> 0 ORDER BY `count` ASC";
$result = mysql_query($select2);
$lpcnt = 0;
$numrows = mysql_num_rows($result);
while ($display = mysql_fetch_array($result, MYSQL_ASSOC)){
    /* This will print out 42 times */
    echo '
In The LOOP, row('.$lpcnt.'):
NumRows: '.$numrows.'
';
    print_r($display);
    echo '

';
    $domRows[] = $display;
    $aTotal[] = $display['count'];
    $aTotWeight[] = $display['weight'];
    //debug vars
    $d['url'] = $display['url'];
    $d['total'] = $total;
    $d['count'] = $display['count'];
    $d['weight'] = $display['weight'];
    $dbug['domRows'][] = $d;
    $lpcnt++;
}
/* Never Reaches this */
echo '
';die(print_r('Loop Finished'));

At a loss as to what's causing the failure midway through the results loop...
also..I know, I know...myql_ is depreciated, but's that's what I have to work with!
Thanks in advance for any light anyone can shed...this is really hurting the site!
EDIT: also this doesn't break all the time, so far it seems to be related somehow to the number of results...for example, if I run through a result set that has 39 rows, it will proccess all of them...and it's consitently failing at 42 rows... on my tables that have 100+ records
EDIT FINAL: Ok figured it out! Turns out we had our memory limit to low, so it was trying to allocate an illegal amount of memory! So we upped it and now it works! Also I had my error reporting in a spot where it was being conditionally turned back off by other code...that's why I wasn't seeing errors! Duh... anyway, thanks for the stabs, to those that responded Merry x-mas and all that jazz...


text: Q: How to store constants for a function only once? I want to do exactly what OP is trying to do here. That post is from 2013. Is this still the same in 2018 in Python 3.6.3? Or is there a better way to do this now?


text:
Q: Python - working with dictionaries - error Link: https://www.w3schools.com/python/trypython.asp?filename=demo_ref_dictionary_update
def read_wpl_file(self,start,filename):
    self.tree = ET.parse(filename)
    self.smil = self.tree.getroot()
    self.head = self.smil.find("head")
    self.title = self.head.find("title").text
    self.body = self.smil.find("body")
    self.seq = self.body.find("seq")
    self.media = self.seq.findall("media")
    self.songs = []
    for song_in_playlist in self.media:
        self.song = {}
        self.song.update({"path": song_in_playlist.attrib("src")})
        self.song.update({"album_title" : song_in_playlist.attrib("albumTitle")})
        self.song.update({"album_artist" : song_in_playlist.attrib("albumArtist")})
        self.song.update({"title" : song_in_playlist.attrib("trackTitle")})
        self.song.update({"artist" : song_in_playlist.attrib("trackArtist")})
        self.song.update({"duration" : song_in_playlist.attrib("duration")})
        self.songs.append(self.song)
    print(self.songs)

self.song.update({"path": song_in_playlist.attrib("src")})
TypeError: 'dict' object is not callable

A: The error "object is not callable" means that the object in question does not support the function call syntax (e.g. attrib("src")).
xml.etree.ElementTree.Element.attrib is a dict, so you have to use the bracket syntax (attrib["src"]) or other dict methods to access its elements.
def read_wpl_file(self,start,filename):
    self.tree = ET.parse(filename)
    self.smil = self.tree.getroot()
    self.head = self.smil.find("head")
    self.title = self.head.find("title").text
    self.body = self.smil.find("body")
    self.seq = self.body.find("seq")
    self.media = self.seq.findall("media")
    self.songs = []
    for song_in_playlist in self.media:
        self.song = {}
        self.song.update({"path": song_in_playlist.attrib["src"]})
        self.song.update({"album_title" : song_in_playlist.attrib["albumTitle"]})
        self.song.update({"album_artist" : song_in_playlist.attrib["albumArtist"]})
        self.song.update({"title" : song_in_playlist.attrib["trackTitle"]})
        self.song.update({"artist" : song_in_playlist.attrib["trackArtist"]})
        self.song.update({"duration" : song_in_playlist.attrib["duration"]})
        self.songs.append(self.song)
    print(self.songs)


text:
Q: AS3 iPhone app that runs in the background I'm developing an iPhone app using Actionscript 3.0. It uses GPS to send an email once you're within certain co-ordinates. At the moment the app automatically pauses itself when it's exited, and so isn't listening out for any geolocation changes and won't do it's job unless open.
Is there any way I can run the app in the background, or without actually being open?
Hope someone can help,
Cheers

A: Check out http://blogs.adobe.com/airodynamics/2012/05/04/air-ios-background-behavior/
So long as you set up your application descriptor properly, you can listen for location updates in the background.
You will also have to enable background task completion in the application descriptor if you want to send an email.


text:
Q: how to target a Custom Content Query Web Part order columns I just made a custom CQWP and I am loading a PICTURE LIBRARY into the CQWP. I will like to target the first item in my picture library like this
<xsl:if test="string-length($SafeImageUrl) != 0">

</xsl:if>

My question is how do I target this, is there a a variable to do something like the pseudocode below
<xsl:if test="string-length($OrderId) == 'first'">

</xsl:if>

Edit: I found out that I can use the Created column to target the first item, now the question is how do I do this in my ItemStyle.xsl.

A: You can do below rule to check that
<xsl:if test="count(preceding-sibling::*)= 0">
    <!-- First Item = Apply your style -->
</xsl:if>


text:
Q: How to check if row is used in database before trying to change it? Brief
We have editable entities. If an entity is not used it can be fully edited. If it is used elsewhere is the system (e.i. there is reference to row in DB) it can be edited partially and forbidden to remove. This is validated at back-end but also should be reflected on front-end by disabling controls in edit form.
I have an idea dynamically fill isInUse field in MyBatis mapping. But it looks a little bit ugly.
Sample
Here is SQL Fiddle. And below is the copy from fiddle
DB schema
create table relation_type (
  rt_id bigint primary key,
  rt_code varchar);
create table entity_type (
  et_id bigint primary key,
  et_code varchar);
create table entity(
  e_id bigint primary key,
  et_id bigint references entity_type,
  et_name varchar);
create table entity_relation (
  er_id bigint primary key,
  er_type bigint references relation_type,
  er_source bigint references entity,
  er_target bigint references entity);

insert into entity_type(et_id, et_code) values (1, 'USER'), (2, 'ORDER');
insert into relation_type(rt_id, rt_code) values (1, 'OWNER'), (2, 'LINK');
insert into entity(e_id, et_id, et_name) values (1, 1, 'user1'), (2, 2, 'Order1'), (3, 2, 'Order2');
insert into entity_relation(er_id, er_type, er_source, er_target) values (1, 1, 1, 2), (2, 1, 1, 3);

One possible solution
select
  rt_id,
  rt_code,
  exists (select 1 from entity_relation where er_type = rt_id limit 1) as rt_is_in_use
from relation_type;

and another
select distinct
  rt_id,
  rt_code,
  (er_id is not null) as rt_is_in_use
from relation_type
left join entity_relation
  on er_type = rt_id;

Question

*

*what are the drawbacks of my approach

*are there any other ways to check if row is used in DB?

Links
Related questions with suggestion to use what I've used

*

*PostgreSql: Get all the rows referencing (via foreign keys) a particular row in a table

*Best way of finding rows referencing a given id on PostgreSQL

*How to find out if rows are refenced from other tables?
Found this question but this should be done in MyBatis mapping and sent as a field to front-end.
Tried google search with something like select in select clause and postgres check if column used but results are not relevant for the my situation.
Clarification

*

*These entities will be rarely edited. I believe introducing counter column is_in_use which is incremented/decremented after adding/removing each link is not a good choice

*Second solution (with join) is used when row is referenced from multiple tables. In this case real query to check usage is something like

.
SELECT EXISTS (
  SELECT 1
  FROM relation_type
  JOIN entity_relation
    ON er_type = rt_id
  WHERE rt_id = #{id}

  UNION

  SELECT 1
  FROM relation_type
  JOIN another_table
    ON at_type = rt_id
  WHERE rt_id = #{id}

  UNION

  SELECT 1
  FROM relation_type
  JOIN yet_another_table
    ON yat_type = rt_id
  WHERE rt_id = #{id}
)

A: Solution
The best way I've came up with is slightly modified first solution. Since there are can be references from several tables, poor first solution (subquery in select clause) sounds bad. I used MyBatis sql tag with parameter.

This element can be used to define a reusable fragment of SQL code
  that can be included in other statements. It can be statically
  (during load phase) parametrized. Different property values can vary
  in include instances

<sql id="columns">
  rt_id,
  rt_code,
  (<include refid="isInUse"><property name="id" value="rt_id"/></include>) AS rt_is_in_use
</sql>

<sql id="baseSelect">
  select
    <include refid="columns"/>

  from relation_type
</sql>

<sql id="isInUse">
  select exists (
    select 1 from entity_relation where er_type = ${id} limit 1
  )
</sql>

<select id="findAll" resultMap="relationTypeMap">
  <include refid="baseSelect"/>
</select>

isInUse sql chunk can also accept MyBatis method parameters. So it's possible to write select
<select id="isInUse"  resultType="boolean">
  <include refid="isInUse">
    <property name="id" value="#{id}"/>
  </include>
</select>

Useful links

*

*Reusing dynamic sql fragments

*How can I reuse an SQL fragment with parameters?


text:
Q: How do you debug javascript in Safari? How do you debug javascript in Safari on Windows. I've tried google but the only thing that seems to be coming up is Safari Enhancer which is for Mac OS.

A: not sure if in Windows is the same, but on the mac version you have a Developer menu ("Develop"), at the mac this menu is shown via the preferences > advanced > show develop menu, and there you can view items such as "Start debugging javascript".
EDIT: just found this: Enabling debug menu in Safari for Windows

A: Have you tried using the develop bar?
To enable, go to preferences -> Advanced -> Check show develop menu in the menu bar

A: Right click on the page, and click "Inspect Element"
You'll get a pop-up with lots of tabs that looks kinda like firebug -- the console tab is what you want.


text:
Q: how to customize eclipse-rcp application's look and feel? Use presentation solution can only change the look&feel of Views and Editors,
Can I change the look&feel of swt widgets, such as Tree, Table , TextInput ...and the background-color of all the gray panels

A: You can use the e4's CSS engine to render the elements. It works well with 3.x as well.


text:
Q: How to fix: Uncaught SyntaxError: Unexpected token '&' How to fix: Uncaught SyntaxError: Unexpected token '&'

'use strict';
var _$_d9ef = ["Activated script", "info", "Crop", "prototype", "", ".", "split", "substring", "display", "css", "#free_play_digits", "none", "#free_play_result", "random", "floor", "html", "#multiplier_first_digit", "#multiplier_second_digit", "#multiplier_third_digit", "#multiplier_fourth_digit", "#multiplier_fifth_digit", "#free_play_first_digit", "#free_play_second_digit", "#free_play_third_digit", "#free_play_fourth_digit", "#free_play_fifth_digit", " ", "innerHTML", ".br_0_0_5_0", "#winnings",
"#balance", "balance"];
console[$_d9ef[1]]($d9ef[0]);
Number[$d9ef[3]][$_d9ef[2]] = function(mmCoreSplitViewBlock) {
  var s = this + $_d9ef[4];
  var a = s[$d9ef[6]]($_d9ef[5]);
  a[1] = a[1] || $_d9ef[4];
  return parseFloat(a[0] + _$_d9ef[5] + a[1][$_d9ef[7]](0, mmCoreSplitViewBlock));
};
var i = true;
var t = 0;
var zaderjka = 1000;
setInterval(function() {
  if ($($_d9ef[10])[$d9ef[9]]($_d9ef[8]) != _$_d9ef[11]) {
    t++;
    if (zaderjka > t && $($_d9ef[12])[$d9ef[9]]($_d9ef[8]) == _$_d9ef[11]) {
      $($_d9ef[16])[$d9ef[15]](Math[$d9ef[14]](Math[$d9ef[13]]() * 10));
      $($d9ef[17])[$d9ef[15]](Math[$d9ef[14]](Math[$d9ef[13]]() * 10));
      $($d9ef[18])[$d9ef[15]](Math[$d9ef[14]](Math[$d9ef[13]]() * 10));
      $($d9ef[19])[$d9ef[15]](Math[$d9ef[14]](Math[$d9ef[13]]() * 10));
      $($d9ef[20])[$d9ef[15]](Math[$d9ef[14]](Math[$_d9ef[13]]() * 10));
    } else

A: Here's a quick way to parse it out into readable code.

 document.querySelector('[data-outgoing]').innerHTML = document.querySelector('[data-incoming]').innerHTML;
[data-incoming]{
height:0;
opacity:0;
overflow:hidden;
}

[data-outgoing]{
padding:5px;
background;#f0f0f0;
 font-family: monospace;
    white-space: pre;
}
<div data-incoming>
  'use strict';
var _$_d9ef = ["Activated script", "info", "Crop", "prototype", "", ".", "split", "substring", "display", "css", "#free_play_digits", "none", "#free_play_result", "random", "floor", "html", "#multiplier_first_digit", "#multiplier_second_digit", "#multiplier_third_digit", "#multiplier_fourth_digit", "#multiplier_fifth_digit", "#free_play_first_digit", "#free_play_second_digit", "#free_play_third_digit", "#free_play_fourth_digit", "#free_play_fifth_digit", " ", "innerHTML", ".br_0_0_5_0", "#winnings",
"#balance", "balance"];
console[$_d9ef[1]]($d9ef[0]);
Number[$d9ef[3]][$_d9ef[2]] = function(mmCoreSplitViewBlock) {
  var s = this + $_d9ef[4];
  var a = s[$d9ef[6]]($_d9ef[5]);
  a[1] = a[1] || $_d9ef[4];
  return parseFloat(a[0] + _$_d9ef[5] + a[1][$_d9ef[7]](0, mmCoreSplitViewBlock));
};
var i = true;
var t = 0;
var zaderjka = 1000;
setInterval(function() {
  if ($($_d9ef[10])[$d9ef[9]]($_d9ef[8]) != _$_d9ef[11]) {
    t++;
    if (zaderjka > t && $($_d9ef[12])[$d9ef[9]]($_d9ef[8]) == _$_d9ef[11]) {
      $($_d9ef[16])[$d9ef[15]](Math[$d9ef[14]](Math[$d9ef[13]]() * 10));
      $($d9ef[17])[$d9ef[15]](Math[$d9ef[14]](Math[$d9ef[13]]() * 10));
      $($d9ef[18])[$d9ef[15]](Math[$d9ef[14]](Math[$d9ef[13]]() * 10));
      $($d9ef[19])[$d9ef[15]](Math[$d9ef[14]](Math[$d9ef[13]]() * 10));
      $($d9ef[20])[$d9ef[15]](Math[$d9ef[14]](Math[$_d9ef[13]]() * 10));
    } else
</div>

<div data-outgoing>
</div>

A: Passing the code through an HTML parser will change all the HTML character Entities to the characters they represent. Provided you backslash escape any tick characters and change any end script tags to <\/script> by backslash escaping the forward slash, the following example should show source in the usual characters, without executing any JavaScript code in the source:

"use strict";

let source=
// paste code with character entities after the tick:
`
'use strict';
var _$_d9ef = ["Activated script", "info", "Crop", "prototype", "", ".", "split", "substring", "display", "css", "#free_play_digits", "none", "#free_play_result", "random", "floor", "html", "#multiplier_first_digit", "#multiplier_second_digit", "#multiplier_third_digit", "#multiplier_fourth_digit", "#multiplier_fifth_digit", "#free_play_first_digit", "#free_play_second_digit", "#free_play_third_digit", "#free_play_fourth_digit", "#free_play_fifth_digit", " ", "innerHTML", ".br_0_0_5_0", "#winnings",
"#balance", "balance"];
console[$_d9ef[1]]($d9ef[0]);
Number[$d9ef[3]][$_d9ef[2]] = function(mmCoreSplitViewBlock) {
  var s = this + $_d9ef[4];
  var a = s[$d9ef[6]]($_d9ef[5]);
  a[1] = a[1] || $_d9ef[4];
  return parseFloat(a[0] + _$_d9ef[5] + a[1][$_d9ef[7]](0, mmCoreSplitViewBlock));
};
var i = true;
var t = 0;
var zaderjka = 1000;
setInterval(function() {
  if ($($_d9ef[10])[$d9ef[9]]($_d9ef[8]) != _$_d9ef[11]) {
    t++;
    if (zaderjka > t && $($_d9ef[12])[$d9ef[9]]($_d9ef[8]) == _$_d9ef[11]) {
      $($_d9ef[16])[$d9ef[15]](Math[$d9ef[14]](Math[$d9ef[13]]() * 10));
      $($d9ef[17])[$d9ef[15]](Math[$d9ef[14]](Math[$d9ef[13]]() * 10));
      $($d9ef[18])[$d9ef[15]](Math[$d9ef[14]](Math[$d9ef[13]]() * 10));
      $($d9ef[19])[$d9ef[15]](Math[$d9ef[14]](Math[$d9ef[13]]() * 10));
      $($d9ef[20])[$d9ef[15]](Math[$d9ef[14]](Math[$_d9ef[13]]() * 10));
    } else
    ... etc;
`  // end of pasted code
;
let div = document.createElement("div");
div.innerHTML = `<pre><code>${source}</code></pre>`
document.body.append( div);


text:
Q: Sum of contiguous subarrays of an array in least time This is my code:
long sum(int[] arr) {
    long sum=0;
    int j,k;
    long sumtoadd;
    for (int i = 0; i < arr.length; i++)
    {
        for (j = i; j < arr.length; j++)
        {
            sumtoadd = 0;
            for (k = i; k <= j; k++)
            {
                sumtoadd = sumtoadd + arr[k];
            }
            sum = sumtoadd + sum;
        }
    }
    return sum;
}

Example:

Array : {1,2,3} Output: 20
Array : {1,1,1} Output: 10

I am trying to find the sum of all contiguous subarrays of an array, but for some of the cases, time is exceeding. This solution is working for all cases except large sized cases. Is there any better solution for this?

A: public class Test1 {

static long sum2(int[] arr) {
    long n = arr.length;
    long sum = 0;
    for (int i = 0; i < n; i++) {
        sum += (n-i)*(i+1)*arr[i];
    }
    return sum;
}

static int[] arr1 = new int[]{1,2,3,4,5,6,7,8,9};
static int[] arr2 = new int[]{1,1,1,1};

public static void main(String[] args) {
    System.out.println("sum(arr1) = " + sum(arr1));
    System.out.println("sum2(arr1) = " + sum2(arr1));
    System.out.println("sum(arr2) = " + sum(arr2));
    System.out.println("sum2(arr2) = " + sum2(arr2));
}

//your code to check
static long sum(int[] arr) {
    long sum=0;
    int j,k;
    long sumtoadd;
    for (int i = 0; i < arr.length; i++)
    {
        for (j = i; j < arr.length; j++)
        {
            sumtoadd = 0;
            for (k = i; k <= j; k++)
            {
                sumtoadd = sumtoadd + arr[k];
            }
            sum = sumtoadd + sum;
        }
    }
    return sum;
}

}

A: Instead of three nested loops, the answer can be found in one loop over the N array elements.
Reasoning:
If a given array element A[i] occurs in K subarrays, then it contributes its value to K subarrays, meaning it contributes K-times its value to the total sum. Now the element A[i] occurs in all subarrays with a start from 0 to i (inclusive), and an end from i+1 to N (inclusive), so K = (i+1)*(N-i).
Summary: every A[i] contributes (i+1)*(N-i)*A[i]. Do that in a single loop, and you're finished.


text:
Q: C# cannot connect to vmware I have a project where i will have to build dual stacked virtual machines.  I usually work with powershell but it does not appear to be able to do that.  I may have to use C#.  I am kinda rusty on this but for some reason this code give me an error "Cannot create an instance of the abstract class or interface 'VMware.Vim.VimClient'".
using System.Text;
using VMware.Vim;

namespace Vimfunctions
{

    public class VimFunctions
    {
        protected VimClient ConnectServer(string viServer, string viUser, string viPassword)
        {
            **VimClient vClient = new VimClient();**
            ServiceContent vimServiceContent = new ServiceContent();
            UserSession vimSession = new UserSession();

            vClient.Connect("https://" + viServer.Trim() + "/sdk");
            vimSession = vClient.Login(viUser, viPassword);
            vimServiceContent = vClient.ServiceContent;

            return vClient;
        }

I added the reference to the project.  I must have forgot to do something.

A: As per https://communities.vmware.com/thread/478700:
"either stick with the PowerCLI 5.5 release as mentioned or to modify your code to use the VimClientImpl class instead of VimClient (which is now an interface)."
A complete simple example I used:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VMware.Vim;

namespace vSphereCli
{
    class Program
    {
        static void Main(string[] args)
        {
            VMware.Vim.VimClientImpl c = new VimClientImpl();
            ServiceContent sc = c.Connect("https://HOSTNAME/sdk");
            UserSession us = c.Login("admin@vsphere.local", "password");
            IList<VMware.Vim.EntityViewBase> vms = c.FindEntityViews(typeof(VMware.Vim.VirtualMachine), null, null, null);
            foreach (VMware.Vim.EntityViewBase tmp in vms)
            {
                VMware.Vim.VirtualMachine vm = (VMware.Vim.VirtualMachine)tmp;
                Console.WriteLine((bool)(vm.Guest.GuestState.Equals("running") ? true : false));
                Console.WriteLine(vm.Guest.HostName != null ? (string)vm.Guest.HostName : "");
                Console.WriteLine("");
            }
            Console.ReadLine();
        }
    }
}

Add a reference to "C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\VMware.Vim.dll". Update the hostname, password; and volia!


text:
Q: subscribe to a knockout observable for a child property and call a parent method in a binding context in TypeScript I have this TypeScript class
export class MyItem {
    public name: any;
    public active: any;

    constructor(private root: MyViewModel, public id: number, name, active) {
        this.name = ko.observable<string>(name);
        this.active = ko.observable<bool>(active);

        this.active.subscribe(() => {
            root.Update(this);
        });
    }
}

It is being used like this below where there is a binding between checked and the active observable property on the input checkbox, this is within a foreach binding context for Items which is a property on the parent MyViewModel.

                    <input type="checkbox" data-bind="checked: active" />

                <input type="button" value="Delete" data-bind="click: $parent.Delete.bind($parent)" />

How can I change this MyItem class so that I can pass the $parent context to the subscribed event on the active observable of each item, without having to pass a reference to MyViewModel in the constructor?
but also compile in the TypeScript.
Thanks

A: I have since realised that the Update method on the parent MyViewModel did not require any reference to the parent to do it's work, so I have moved it to the MyItem class, which fixes my problem.
I still haven't seen a way to do what I originally asked without passing a reference of the parent though, even if it is through some init method instead of the constructor.

A: You have MyItem subscribing for changes on its own active property in order to inform a third-party entity, MyViewModel, when changes occur.  The dilemma is that MyItem doesn't really know exactly who the third-party is.
Instead, you can simply have MyViewModel subscribe to the active property on MyItem itself, since MyViewModel is the one that cares about the changes and already has a reference to the item.


text:
Q: Reference on Operads I was reading 'Category for Scientists' by David Spivak and I'd like some references on 'Operads' with that kind of approach, using only "basic Category Theory", nothing too advanced.
I appreciate it :]

A: Higher Operads, Higher Categories by Tom Leinster might suit your purposes: http://www.maths.ed.ac.uk/~tl/hohc/
And you can read the book online.


text:
Q: ¿Por qué no funciona esta sentencia en MySQL? Estoy programando con el servidor atspace.com . He intentado crear una página para repartir rublos pero no puedo, me lanza error al lanzar la siguiente sentencia MySQL:
INSERT INTO users VALUES (`P85097925`);

Este es el error:

Error
  consulta SQL:
INSERT INTO users VALUES (P85097925)
  MySQL ha dicho: Documentación
1054 - Unknown column 'P85097925' in 'field list'

Parece muy raro. Normalmente esta sentencia se lanzaba con normalidad. Pero hasta hace poco ha comenzado a dar fallo. ¿Debería decírselo a soporte o está mal escrito el código?

A: Causa del error
El error en sí ocurre porque estás usando backticks  (comillas invertidas) para los valores. En MySQL los backticks sirven para nombrar tablas, columnas, etc, pero no valores, por eso está interpretando que P85097925 es una columna, no un valor.
Según el Manual de Referencia cada vez que usas ` el manejador interpreta que te refieres a una base de datos, tabla o columna:

The identifier quote character is the backtick (`):

El carácter identificador es la comilla invertida (`):

Como nota adicional, los backticks son opcionales. Pero si tienes nombres de tablas o columnas que a su vez son palabras reservadas (práctica no recomendada), debes usar backticks cuando escribas esas nombres en las consultas, así precisamente MySQL los va a diferenciar de las palabras reservadas.
El Manual de Referencia también dice que las comillas simples ' o la comillas dobles " se usan para encerrar cadenas:

enclosed within either single quote (') or double quote (") characters.

encerradas entre comillas simples (') o comillas dobles (")

Solución
Varias soluciones son posibles.
Solución no óptima
Si hay una sola columna en tu tabla, o dos columnas una de las cuales es auto incremental, entonces tu consulta debería funcionar así:
INSERT INTO users VALUES ('P85097925');

Simplemente, se han cambiado los backticks por comillas simples, por lo que hemos dicho antes.
De todos modos, es mejor escribir consultas explícitas, ayudan a entender mejor nuestro programa y a saber siempre con lo que estamos trabajado. Además, si ahora tu tabla users tiene solamente una o dos columnas, pero mañana se le agrega(n) otra(s) columna(s), esta consulta ya es inviable y vas a tener que recorrer por todo el programa donde usas consultas como esta para actualizar el código.
Solución óptima
Escribir una consulta que nombre la columna de forma explícita y listo.
INSERT INTO `users` (`laColumna`) VALUES ('P85097925');

A: Tienes que indicar el nombre de la columna antes de values ya que no publicas la estructura de la tabla te indico el ejemplo con nombre_columna:
INSERT INTO users (nombre_columna) VALUES ('P85097925');

A: Es sql básico, el error te dice que no existe la columna 'Pxxxxxx'
La sintaxis correcta es
INSERT INTO tabla (columna1, columna2, columna3, ...) VALUES (valor1, valor2, valor3, ...);

Sería algo asi
INSERT INTO users (id) VALUES ('P85097925');

A: Cuando defines VALUES en tu script  , debes definir el o los campos en los cuales se insertará el valor.
Ejemplo:
INSERT INTO Customer (FirstName, LastName, City, Country, Phone)
VALUES ('Werenverlivitz', 'Smith', 'York', 'Spain', 1-01-993 2800)

en este caso no esta definiendo el campo en el cual se insertaría el valor:
INSERT INTO users (< campo >) VALUES (P85097925)


text:
Q: Building a PathGeometry from list of points without tons of other class creation I am trying to build a simple polygonal PathGeometry from a custom list of points. I found the following code on the msdn website, and it appears to work fine, with a simple modification to loop and add LineSegments, but it seems like an awful amount of inelegant mess to do what seems to be a relatively simple task. Is there a better way?
PathFigure myPathFigure = new PathFigure();
myPathFigure.StartPoint = new Point(10, 50);

LineSegment myLineSegment = new LineSegment();
myLineSegment.Point = new Point(200, 70);

PathSegmentCollection myPathSegmentCollection = new PathSegmentCollection();
myPathSegmentCollection.Add(myLineSegment);

myPathFigure.Segments = myPathSegmentCollection;

PathFigureCollection myPathFigureCollection = new PathFigureCollection();
myPathFigureCollection.Add(myPathFigure);

PathGeometry myPathGeometry = new PathGeometry();
myPathGeometry.Figures = myPathFigureCollection;

Path myPath = new Path();
myPath.Stroke = Brushes.Black;
myPath.StrokeThickness = 1;
myPath.Data = myPathGeometry;

A: You can wrap it in a function, and you can also consolidate some statements.
Path makePath(params Point[] points)
{
    Path path = new Path()
    {
        Stroke = Brushes.Black,
        StrokeThickness = 1
    };
    if (points.Length == 0)
        return path;

    PathSegmentCollection pathSegments = new PathSegmentCollection();
    for (int i = 1; i < points.Length; i++)
        pathSegments.Add(new LineSegment(points[i], true));

    path.Data = new PathGeometry()
    {
        Figures = new PathFigureCollection()
        {
            new PathFigure()
            {
                StartPoint = points[0],
                Segments = pathSegments
            }
        }
    };
    return path;
}

Then you can call it like this:
Path myPath = makePath(new Point(10, 50), new Point(200, 70));


text:
Q: Calling a java script function with php on click Ok so i have paid a coder to code me a walk around map script were users can press up and down on the keyboard and walk aroud a map using jquery. But now im trying to make it so i have a up and down image and then on click it will call the up and down function. So the suer can use the up and down keys plus clicking the images.
Here is the up function im using for when the user presses the up key on the keyboard. But now some how i need to call the same function when a image is clicked..
function move(d)
{
    if(d == "UP")
    {
        var top = (parseInt(document.getElementById('move').style.top) - 10);
        var left = parseInt(document.getElementById('move').style.left);
        if(canMove(new xy(left,top)))
        {
            document.getElementById('move').style.top = (parseInt(document.getElementById('move').style.top) - 10) + 'px';
            document.player.src = "maps/sprites/playerUp.png";
            //if(lastStep != "UP") clearTimeouts();
            //setTimeout('document.player.src="playerUp.png"', 500);
            //lastStep = "UP";
            reloadF();
        }
    }

How would i do about doing that ??
Im guessing i just need to call function move(d) and set it to up some how ?? On click of image ?

A: var keynum = 0;

if(window.event) { keynum = e.keyCode; }  // for IE
else if(e.which) { keynum = e.which; }    // for others browsers

if(keynum === 38) { // up
    //if KEY UP
}

if(keynum === 40) { // down
    //if KEY DOWN
}

I hope this help...


text:
Q: Python Pandas spit to series groupBy I have a dataframe which I can run split on a specific column and get a series - but how do I then add my other columns back into this dataframe? or do I somehow specify in the split that there's column a which is the groupBy then split on columnb ?
input:
ixd   _id     systemA         systemB
0   abc123  1703.0|1144.0   2172.0|735.0

output:
pandas series data (not expanded) for systemA and B split on '|' groupedBy _id

A: It sounds like a regular .groupby will achieve what you are after:
for specific_value, subset_df in df.groupby(column_of_interest):
   ...

The subset_df will be a pandas dataframe containing only rows for which column_of_interest contains specific_value.


text:
Q: NestJS @Sse: Return values from a third party API using @nestjs/axios I am learning Nestjs and got an eye on the SSE section of the docs.
I wanted to expand a little bit and return data from a third party API which in this case is not relevant. I am using the HttpModule provided by @nestjs/axios for requesting the data.
Thing is that I am getting confused a lot with the RXJS stuff as I am learning and don't know what to do next.
The method of the service that I am using to request data from the API looks like this:
get() {

    return this.httpService.get(url)
}

And the SSE method inside the controller is like this:
  @Sse('sse')
  sse(): Observable<MessageEvent> {

    return interval(1000).pipe(
      map((_) => ({ data: { ...this.sseService.get() } } as MessageEvent))
    );

  }

And of course I get nothing. I know there is some stuff I have to add but honestly have no idea what it is.


text:
Q: Prove every finite field is of cardinality $p^n$ I realise that this question has been asked multiple times before, but I would like to ask about a specific detail in my proof.
Let F be a finite field.
I begin by showing that the characteristic of any finite integral domain must be a prime, say p.
This gives us that: $$ker(\phi) = pZ$$ where $\phi:Z \rightarrow F$ is a homomorphism.
By first isomorphism theorem,
$$Z/pZ \cong Im(\phi) \subset F$$
Now the problem is prompting me to show that this means we can assume that $Z/pZ \subset F$.
From here it is easy to show that F is a field over $Z/pZ$ (which is also a field) and finish the proof.
From what I understand, we aren't really showing that $F$ is a field over $Z/pZ$, but rather over an isomorphic subfield of $F$. But the prompt explicitly asks us to show that F is a field over $Z/pZ$. This is where my confusion is coming from.
Any help would be appreciated

A: Well, if $F$ is a finite field of characteristic $p$, then $F$ contains a copy of ${\Bbb Z}_p$ given by the multiples of the unit element $1$. But each field extension $F$ of a field $K$ is a vector space over $K$. So $F$ is finite dimensional vector space over ${\Bbb Z}_p$. Let $\{b_1,\ldots,b_n\}$ be a basis of $F$ over ${\Bbb Z}_p$. Then each element $a$ of $F$ can be uniquely written as a linear combination $a= \sum_i k_i b_i$, where $k_i\in {\Bbb Z}_p$. Thus the field $F$ has $p^n$ elements, as required.
As a remark, the mapping ${\Bbb Z}_p \rightarrow F:a\mapsto a\cdot 1$ is a ring monomorphism, where $a\cdot 1 = 1+\ldots +1$, $a$ times. So as said, $F$ contains an isomorphic copy of ${\Bbb Z}_p$.

A: This is a common coercion of types.  Note that $\phi(0) = 0$, $\phi(1) = 1$, $\phi(\underbrace{1 + \dots + 1}_{n \text{ times}}) = \underbrace{1 + \dots + 1}_{n \text{ times}}$.  Yes, these arguments to $\phi$ are elements of $\mathbb{Z}/p\mathbb{Z}$ and the outputs of $\phi$ are elements of $\mathbb{F}_{p^n}$.  But, once you have $0$ and $1$ in a structure with addition, you can always see how much of $\mathbb{Z}$ you get by iterated addition.


text:
Q: replace @ operator in python2? Trying to learn python, and came over the @ operator.
the @ infix operator that is designated to be used for matrix multiplication in python 3.
But im using python 2.
def spaceship_cockpit_coordinates(self):
"""Calculates and returns the position of the 'cockpit' when
the spaceship rotates"""
rot_mat = np.array([[np.cos(self.angle), -1*np.sin(self.angle)],
[np.sin(self.angle), np.cos(self.angle)]])
pos = np.array([(self.width/2), 0])
rot = pos@rot_mat
cent = [self.x + self.width/2, self.y + self.height/2]

return (np.array(cent) + rot).tolist()

how can the rot = pos@rot_mat be replaced so it works in python 2?

A: You can try matrix multiplication in Numpy itself.
For matrix multiplication, you can use
np.matmul(pos,rot_mat)


text:
Q: How to use an already built Caffe when running py-faster-rcnn? I'm trying to build and run py-faster-rcnn model on my Ubuntu 16.04.
However, when I run ./tools/demo.py (as stated in the installation guide), I get the following error:
➜  py-faster-rcnn git:(master) ✗ ./tools/demo.py
Traceback (most recent call last):
  File "./tools/demo.py", line 18, in <module>
    from fast_rcnn.test import im_detect
  File "/home/denis/WEB/DeepLearning/py-faster-rcnn/tools/../lib/fast_rcnn/test.py", line 16, in <module>
    import caffe
  File "/home/denis/WEB/DeepLearning/py-faster-rcnn/tools/../caffe-fast-rcnn/python/caffe/__init__.py", line 1, in <module>
    from .pycaffe import Net, SGDSolver, NesterovSolver, AdaGradSolver, RMSPropSolver, AdaDeltaSolver, AdamSolver
  File "/home/denis/WEB/DeepLearning/py-faster-rcnn/tools/../caffe-fast-rcnn/python/caffe/pycaffe.py", line 13, in <module>
    from ._caffe import Net, SGDSolver, NesterovSolver, AdaGradSolver, \
ImportError: No module named _caffe

Before attempting to install py-faster-rcnn, I've installed Caffe in my ~/code/caffe folder and it seems to work fine:
➜  ~ python
Python 2.7.12 (default, Nov 19 2016, 06:48:10)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import caffe
>>> print caffe.__version__
1.0.0-rc3

So, if I can import caffe module in python environment, I assume I've installed it successfully.
Here're the commands I've used (from the official guide):
sudo make all
sudo make test
sudo make runtest
sudo make pycaffe
sudo make distribute

Then I've cloned the py-faster-rcnn repository in my ~/WEB/DeepLearning folder.
After that I've followed the installation instructions from the repo:

*

*Clone the repo

*cd $FRCN_ROOT/lib && make

*cd $FRCN_ROOT/caffe-fast-rcnn

*make -j8 && make pycaffe   (I didn't run this)

*cd $FRCN_ROOT && ./data/scripts/fetch_faster_rcnn_models.sh

*cd $FRCN_ROOT && ./tools/demo.py
So, step 4 in the installation guide says I have to build caffe and pycaffe in $FRCN_ROOT/caffe-fast-rcnn folder. The contents of caffe-fast-rcnn folder seem to be identical with the original caffe repository from which I've built Caffe.
So, it seems that I don't need to build caffe again, right? When trying to run the demo, I've skipped the step of building caffe and got the error stated above.
After googling for a while, I've found out that my issue is connected with path environment variables, so below are my path variables in .bashrc:
export LD_LIBRARY_PATH=/usr/local/cuda-8.0/lib64:~/code/caffe/distribute/lib:$LD_LIBRARY_PATH

export CPLUS_INCLUDE_PATH=/usr/include/python2.7

export PYTHONPATH=~/code/caffe/python:$PYTHONPATH

Am I doing something wrong and I have to change my path variables somehow?
Or I really need to build caffe again, but in a caffe-fast-rcnn folder?
And what about this distribute folder I've generated in ~/code/caffe/distribute by running sudo make distribute? Is it of any use? If so, how should I use it? The official documentation is not very clear about it.

A simple, clear and detailed explanation on how to use an already built Caffe framework with other projects like Faster-RCNN would be really helpful.

A: I struggled with this for a while and then got it working as below.
First, check PYTHONPATH env variable. It should have python path like, for eg. based on your python version and installation
PYTHONPATH = /usr/lib/python2.7

If its empty, you can set it with python path captured in your python shell. To check python path information, open python shell and type below
>>import sys
>>for p in sys.path
...  print(p)

It will list you all python path info, for eg
...
/usr/lib/python2.7
/usr/lib/python2.7/plat-x86_64-linux-gnu
/usr/lib/python2.7/lib-tk
/usr/lib/python2.7/lib-old
/usr/lib/python2.7/lib-dynload
...

If you have installed caffe already and want it to configure to be used by python, you just need to update your PYTHONPATH env variable by adding path to your /caffe-installation-path/python folder to it, like
export PYTHONPATH = /home/mypc/caffe-master/python:$PYTHONPATH

Note:- You don't need to rebuild caffe but configure caffe and python in PYTHONPATH env variable correctly.


text:
Q: How to find the name of a window I'm working on a project in Go and I wanted to know if it was possible in C++ to use the function: FindWindow
For example:
HWND hwnd = FindWindowA(NULL, "mywindow");

A: FindWindowA is not implemented in golang's Windows package.  I don't like using this function to find processes anyways, I prefer to use CreateToolHelp32Snapshot() or EnumProcesses()
Both these functions are implemented by golang's Windows package and provide a way to loop through all the processes, once you have this list you can filter them by executable name.
Once you have located the correct process, the process id can be retrieved which you will need to pass to OpenProcess().  OpenProcess is used to get a handle to the process with the required memory permissions you desire.
The windows package does not include WriteProcessMemory or ReadProcessMemory, you will need to either call it via a syscall or find another package such as go-winapi or win


text:
Q: Is there a way to use old Print composer templates in 2.0? As the title says, the old templates do not work in 2.0.  It started with having to redraw boxes, now it causes it to crash completely.
Is there an easy fix.
Can i download templates for use??

A: Which QGIS version are you using? 2.4 included some improvements to opening old templates, including a fix for the missing item borders. If you're using 2.4 or above, can you please file a bug at http://hub.qgis.org and attach a sample which crashes?


text:
Q: Sum up several files in emacs? I have roughly a gazillion files of the same architecture. Is there a way to create a buffer which will present a summary of those files? possibly with org-mode?
Each file is formated as:
q   val    counts
1   0.05   2500
4   0.01   2500
10  0.002  2500
.
.
.
.

The files are each in their own folder:
prog
 |
 +fold1
 |  |
 |  ----file1
 +fold2
 |  |
 |  ----file1
 -fold3
    |
    ----file1

I'm not certain what should the summary conclude. I think that the first 3 lines + the averages of each file.

A: Expanding Juancho's comment, in org-mode, you can define a shell source block :
#+begin_src sh :results output raw replace
  for i in /path/to/files/; do
      head -n 3 $i
      # I let you compute the average you want using awk and whatnot
  done
#+end_src

and execute it with C-c C-c (cursor being in the block).
You may want to read the manual concerning header arguments if you want the results to be formatted in some particular fashion. (And you can do that in any language org-mode supports.)


text:
Q: How to redirect a URL from hostapd without internet access? I have configured my server with iptables rules in order to forward all traffic to a specific domain. Those are NAT rules and the redirection works fine as long as I have internet access. But when internet is off, of course the forwarding doesn't work anymore.
Is there's a way to redirect all the url to a specific domain without internet access?
From what I have observed, if I plug and internet cable and then unplug it, the redirection still works for about 10 minutes, so there must be some daemon running still performing the forwarding.
Someone said that my NAT is not redirecting because the DNS is not working anymore. But I have no idea what to do, and what could be the best tool fitted for it.
I have tried socat in order to redirect socket, but with no luck.
So do you have any strategy on how I could perform it. I know this is possible because when I unplug my Ethernet cable, I can't access to internet anymore but the URL are still forwarded for at least 10 minutes. So if there is a simple an hackish way to to it, you'll be welcome.
My intention are those: someone connect to the hostapd (without internet connection), enter any URL, and then redirected to my server.


text:
Q: Hermitian metric on conic Kaehler-Einstein setting I have a technical question :
Consider the triple $(M,D,\omega)$ where $M$ is a Fano manifold, $D$ is a smooth divisor whose Poincare dual is $\lambda c_1(M)$ and $\omega$ is a conic Kaehler -Einstein metric on $M$ with cone angle $2\pi\beta$ along $D$. Let $S$ is a difining section of $D$ . In local holomorphic coordinates $z_1,z_2,...,z_n$ , write $S=f\big(\frac{\partial}{\partial z_1}\wedge...\wedge \frac{\partial}{\partial z_n}\big)$ and $H(.,.)$ be a Hermitian metric on $K_M^{-1}$  and $\omega=i\sum g_{\alpha\bar\beta}dz_\alpha\wedge d\bar z_\beta$

then $H$ can be represented by
$$\text{det}(g_{\alpha\bar\beta})^{\frac{1}{\mu}}\mid f
 \mid^{\frac{2(1-\beta)}{\mu}}$$
for some $\mu$

This fact has been appeared in most of the papers about Kahler-Einstein metrics. But I am looking for a reason!
See this paper for details


text:
Q: How to post a collected value to a new page I am still learning PHP and am now completely stuck - any help would be so much appreciated! Scenario: HTML form for user to complete, among other things, they have to select with a radio button how many tickets they want to buy. My PHP file compiles all the values into an email and sends it off - that part works perfectly - and then redirects the browser to my "thank you for completing the form" page. I would now like to display a value collected in the form on this thank you page: the amount of tickets the user selected with the radio button. How do i call the 'tickets' value to the thank you page?
Thank you ever so much!
Here is the HTML form:
http://menusolutions.co.za/maidens2014_booking_form.html
Here is my "sendmail3.php" file that sends my mail:

$webmaster_email = "carin@menusolutions.co.za";

$feedback_page = "maidens2014.html";
$error_page = "maidens_error_message.html";
$thankyou_page = "maidens_thank_you.php";

$name = $_POST['name'] ;
$telephone = $_POST['telephone'] ;
$cell = $_POST['cell'] ;
$email_address = $_POST['email_address'] ;
$address = $_POST['address'] ;
$tickets = $_POST['tickets'] ;

$mail_body = "Name: $name \n Telephone: $telephone \n Cell: $cell \n Email: email_address \n Address: $address \n Tickets: $tickets";
mail( "$webmaster_email", "Maidens Bowled Over 2014",
  $mail_body, "From: $email_address" );
header( "Location: $thankyou_page" );
}

?>

And here is my thank you page, upon which I need to display the 'tickets' value so that people can be reminded how many tickets they bought and the amount they need to pay:
http://menusolutions.co.za/maidens_thank_you.php
Your help will be greatly appreciated! Thank you!

A: You can send ticket value inside URL or using session.
header( "Location:". $thankyou_page.'?ticket='.$tickets );

and on thanks you page add below code,
$tickets = $_GET['tickets'];
echo $tickets . ' tickets.';

A: You can use sessions to accomplish that.
An other option is redirecting and using a GET value.
On your sendmail.php page you can use header to redirect the user :
header('location: thanks_page.php?ticketValue='.$ticketValue);

Be careful that : header() must be called before any actual output is sent. (see doc.)
And then get it back in your thanks_page in $_GET['ticketValue'] and do not forget to espace the value with htmlspecialchars or an equivalent for security !

A: The easiest way would be to redirect to the "thank you"-page and add the ticket value as a get-parameter
Link
maidens_thank_you.php?tickets=$tickets

A: You could use a GET parameter for this. For example,
header('Location: ' . $thankyou_page . '?tickets=' . $tickets);

And then in your thank you page (which I assume is a PHP script), you could retrieve that value using.
$tickets = $_GET['tickets'];
echo 'Thank you! You bought ' . $tickets . ' tickets.';

A: You can set a session or pass the values in the url by  making your $thankyou page something like
$thankyoupage + "?numberoftickets=" + $numberoftickets;
header('Location:' + $thankyoupage);

and get the value back by
 $_GET['numberoftickets']

in your actual thankyoupage.
only use the session method if you need the var in other pages than the thankyoupage too. sessions make this value available in your hole application.
more information about sessions can be found here: http://www.w3schools.com/php/php_sessions.asp

A: Never use a varible in double quotes ("") it's will be string so use direct. you need to more learn php
for mail tuts :- http://php.net/manual/en/function.mail.php
mail( $webmaster_email, "Maidens Bowled Over 2014",
      $mail_body, $email_address );
    header( "Location:". $thankyou_page );


text:
Q: What is the difference between asp:label and HTML label? What is the difference between the asp:label and the html label ?
I know that the first one is rendered on the server so basically it returns a span tab, but what is its use? What are the cases in which one would want to use a HTML tag and in what would one want to use the asp:label? I know that if I put it as an ASP control I can programatically access it, but what are differences between the 2 purely in terms of designing the UI?

A: If the asp:Label has its "AssociatedControlID" attribute value set to the ID of form control on the page then it will actually be rendered as a HTML label control (with the "for" value set to the client ID of the same control) when rendered to the client.
The HTML label control is designed strictly to provide a label/caption for a form control (i.e. an input, select or textarea) which describes the purpose of the form control to the user (see https://developer.mozilla.org/en-US/docs/HTML/Element/label). The label is normally (strongly) associated with the particular input using the "for" attribute which should be the ID of the input. This is particularly useful for those with accessibility needs who are not able to interpret the relationship based solely on proximity of the text and control. Imagine a form with several textboxes but no way to know which input was required in each one. The HTML label control is not used for general text outside of this context.
If the "AssociatedControlID" attribute of the asp:Label has no value then the control will simply be rendered as a span control containing the text. Some developers like to use asp:Labels to output text onto the page, giving the control a dual purpose (unlike the HTML counterpart). I personally prefer to use asp:Literals for this purpose as it gives me more control of the containing markup.
The reason to choose the asp:Label as opposed to the native HTML label control is that you can easily interact with it using server side code, for example changing the text or CssClasses in response to server events, and you can enter the server ID as the "AssociatedControlID" value which will automatically be rendered as the client ID (e.g. shown as "ct100_MainContent_TextBox1" as opposed to "TextBox1") in the "for" value on the client.


text:
Q: Incorrect checksum for freed object - error when printing I have made a class that's supposed to make a symmetric toeplitz matrix (see here). The implementation of the class is shown here
class toeplitz{
private:
    int size;
    double* matrix;
public:
    toeplitz(const double* array, const int dim){
         size = dim;
         matrix = new double(size*size);
         for(int i = 0; i < size; i++){
             for (int j = 0; j < size; j++){
                 int index = std::abs(i - j);
                 matrix[i*size + j] = array[index];
             }
         }
    }

    ~toeplitz(){
        delete[] matrix;
    }

    void print() const{
        //loop over rows
        for (int i = 0; i < size; i++){
            //loop over colums
            for (int j = 0; j < size; j++){
                double out = matrix[i*size + j];
                std::cout << std::setw(4) << out;
            }
        //start new line for each row
        std::cout << "\n";
        }
    }

};

I can't see what's wrong with this, but when I try and use this in a simple test function, I get malloc errors. The main function I have is
int main(){
    double array[] = {0,1,1,2};
    int len = sizeof(array)/sizeof(array[0]);
    std::cout<<"length of array " << len << std::endl;
    toeplitz tp = toeplitz(array, len);
    tp.print();
}

It compiles and runs when I leave out the tp.print() line, but when I add this line I get error
test_toeplitz(8747,0x7fffdbee63c0) malloc: *** error for object 0x7fb119402788:
incorrect checksum for
freed object - object was probably modified after being freed.
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6

I cannot figure out why this is. I've looked at the other questions about this on here but I can't tell how they relate to what I've done. As I understand it has to do with either double freeing memory or trying to modify memory after it's been freed, but I can't see where my code is doing that. Any insight into what's going on would be appreciated.

A: You stumbled on the classical:
matrix = new double(size*size);

which allocates a double worth size*size when you wanted to do:
matrix = new double[size*size];

to allocate an array of the proper size. So you get undefined behaviour. Sometimes it works sometimes not depending on the memory configuration.
Since you're using C++, I suggest you use std::vector<double> or Eigen matrix template, and drop C arrays forever (no more memory leaks, no more failed allocations, possible boundary checking, only advantages)


text:
Q: Monitoring WriteToBigQuery In my pipeline I use WriteToBigQuery something like this:
| beam.io.WriteToBigQuery(
     'thijs:thijsset.thijstable',
      schema=table_schema,
      write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND,
      create_disposition=beam.io.BigQueryDisposition.CREATE_IF_NEEDED)

This returns a Dict as described in the documentation as follows:

The beam.io.WriteToBigQuery PTransform returns a dictionary whose
  BigQueryWriteFn.FAILED_ROWS entry contains a PCollection of all the
  rows that failed to be written.

How do I print this dict and turn it into a pcollection or how do I just print the FAILED_ROWS?
If I do: | "print" >> beam.Map(print)
Then I get: AttributeError: 'dict' object has no attribute 'pipeline'
I must have read a hundred pipelines but never have I seen anything after the WriteToBigQuery.
[edit]
When I finish the pipeline and store the results in a variable I have the following:
{'FailedRows': <PCollection[WriteToBigQuery/StreamInsertRows/ParDo(BigQueryWriteFn).FailedRows] at 0x7f0e0cdcfed0>}

But I do not know how to use this result in the pipeline like this:
| beam.io.WriteToBigQuery(
     'thijs:thijsset.thijstable',
      schema=table_schema,
      write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND,
      create_disposition=beam.io.BigQueryDisposition.CREATE_IF_NEEDED)
| ['FailedRows'] from previous step
| "print" >> beam.Map(print)

A: Dead letters to handle invalid inputs are a common Beam/Dataflow usage and work with both Java and Python SDKs but there are not many examples for the latter.
Imagine that we have some dummy input data with 10 good lines and a bad row that does not conform to the table schema:
schema = "index:INTEGER,event:STRING"

data = ['{0},good_line_{1}'.format(i + 1, i + 1) for i in range(10)]
data.append('this is a bad row')

Then, what I do is name the write result (events in this case):
events = (p
    | "Create data" >> beam.Create(data)
    | "CSV to dict" >> beam.ParDo(CsvToDictFn())
    | "Write to BigQuery" >> beam.io.gcp.bigquery.WriteToBigQuery(
        "{0}:dataflow_test.good_lines".format(PROJECT),
        schema=schema,
    )
 )

and then access the FAILED_ROWS side output:
(events[beam.io.gcp.bigquery.BigQueryWriteFn.FAILED_ROWS]
    | "Bad lines" >> beam.io.textio.WriteToText("error_log.txt"))

This works well with the DirectRunner and writes the good lines to BigQuery:

and the bad one to a local file:
$ cat error_log.txt-00000-of-00001
('PROJECT_ID:dataflow_test.good_lines', {'index': 'this is a bad row'})

If you run it with the DataflowRunner you'll need some additional flags. If you face the TypeError: 'PDone' object has no attribute '__getitem__' error you'll need to add --experiments=use_beam_bq_sink to use the new BigQuery sink.
If you get a KeyError: 'FailedRows' it's because the new sink will default to load BigQuery jobs for batch pipelines:

STREAMING_INSERTS, FILE_LOADS, or DEFAULT. An introduction on loading
  data to BigQuery: https://cloud.google.com/bigquery/docs/loading-data.
  DEFAULT will use STREAMING_INSERTS on Streaming pipelines and
  FILE_LOADS on Batch pipelines.

You can override the behavior by specifying method='STREAMING_INSERTS' in WriteToBigQuery:

Full code for both DirectRunner and DataflowRunner here.


text:
Q: Can't we include windows.h while using native client toolchain? While compiling code using Native client toolchain -Nacl64 (using visual studio-10), i am getting the folowing error:
logger.cpp(46,21): warning : windows.h: No such file or directory

Can't we include windows.h while using native client toolchain??

A: As you've probably figured out, no. Native Client is designed to produce binaries that can run on multiple host operating systems. Including an OS-specific header wouldn't take your code in that direction.
If you are relying on something portable that happens to be defined in a non-portable header, redefine it in a header of your own.

A: NaCl's toolchain is POSIX-based, so it provides POSIX headers such as fcntl.h, unistd.h and pthread.h.  It does not provide a windows.h header.
In principle, Wine could be ported to NaCl so that you could use the Windows APIs defined in windows.h.  But you would only be able to use interfaces that can be made to work inside NaCl's sandbox.  You wouldn't be able to access devices and files outside the sandbox.  Also, no-one has created such a port yet.


text:
Q: SSL connection using Java standalone app I have created a standalone executable JAR program that needs to send private information over a SSL connection.
I was not able to establish the SSL connection using certificates. Was getting this:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path `building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target`

So I found some code somewhere that creates a trust manager that does not validate certificate chains:
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{
            new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
                public void checkClientTrusted(
                    java.security.cert.X509Certificate[] certs, String authType) {
                }
                public void checkServerTrusted(
                    java.security.cert.X509Certificate[] certs, String authType) {
                }
            }
        };

That did the trick and I was able to establish SSL connection without any certificates.
My concern is if the data will still be encrypted when exchanging private information.
This is an execute JAR file that clients will be downloading to their computers.
So is a certificate really necessary for this case?

A: It's still encrypted BUT not trustworthy. Best to fix the certificate validation issues instead.
Essentially, SSL provides both encryption and a trust mechanism. You're bypassing the trust part, so the message will still be encrypted, but prone to interception or snooping, using, e.g., a man-in-the-middle attack. A MITM could intercept the request, and complete the SSL handshake using a completely different certificate. They could optionally forward your message to the intended server & back, so you'd never know the message was intercepted.
You should look at downloading the server certificate and putting it into a truststore, which can be loaded at runtime.
See keytool.
The keytool executable comes bundled with the JDK, and you can use this command-line tool to create a 'keystore' (in this case, known as a 'truststore'), and import a certificate into it.
There are many ways to tell Java to use a keystore, and your choice depends on what libraries etc you're using to make the SSL connection.
One method is to use startup options, e.g.:
-Djavax.net.ssl.trustStore=mySrvKeystore -Djavax.net.ssl.trustStorePassword=123456
Best to google for "keystore java" plus your library name (if you're using one)
HTH

A: With such a trust manager (or with anonymous cipher suites), the connection will still be encrypted (assuming you're not enabling a cipher suite that use a null cipher, which should never be enabled by default).
However, the client won't know with which entity it is exchanging secret information: it could be a Man-In-The-Middle attacker.
Encryption isn't enough: you need to know who you're talking to. The client needs to verify that:

*

*it trusts the server certificate to be genuine (that's the purpose of the trust manager, but not this particular implementation since it never rejects anything),

*this certificate is valid for the host name the client intended to contact.


text:
Q: Solving quadratic diophantine equations in two variables I've looked at the recommended questions, but none of them seem to match my question.
Consider the equation $2015 = \frac{(x+y)(x+y-1)}{2} - y + 1$.
This can trivially be simplified to $4030 = x^2 + 2xy - x + y^2 - 3y +2$.
According to Wolfram Alpha, the integer solutions of this equation can be represented as:
$x = -\frac{n^2}{2} + \frac{5n}{2} + 2012,\:y = \frac{n^2}{2} - \frac{3n}{2} - 2013,\:n \in \mathbb{Z}$.
Can someone explain how this set of solutions is derived?

A: The equation is
$$x^2 + 2xy + y^2 - x -3y - 4028 = 0.$$
This can be modified to
$$(x+y)^2 - (x+y) - (2y+4028) = 0.$$
Let's denote $u = x+y$ so we have
$$u^2 - u = 2(y+2014)$$
Solving for $y$, we have
$$y = \frac{u^2-u}{2}-2014.$$
Then, remembering that $u=x+y$, we can solve for $x$:
$$x = u-y = u-\frac{u^2-u}{2}+2014 = \frac{-u^2+3u}{2}+2014.$$
Then we set $n=u-1$ (just a shift (to make the solution look the same)) and get the solution
$$x = \frac{-n^2+5n}{2}+2012$$
$$y = \frac{n^2-3n}{2}-2013$$


text:
Q: C# - SerialPort Encoding help needed I need help with my program with which I want to read codes from several microcontrollers simultaneously and translate them into plain text. There is only one serial interface where all codes are collected. The translation of the codes works, but I have the problem that the codes are not read correctly. He makes pauses again and again where there are no gaps and where there are gaps (500 micro sec. ) He doesn't always recognize them correctly.
Here's part of the code:
public byte[] block = new byte[4096];
        public int posBlock = 0;

        public void Read(object sender, SerialDataReceivedEventArgs e)
        {
            console_.WriteLine("--------------------------------------------------");
            console_.WriteLine("Void: Read(object sender, SerialDataReceivedEventArgs e)");
            int offset = 0, count = serialPort.BytesToRead, i = 0;
            byte[] rd = new byte[count];

            serialPort.Read(rd, offset, count);

            for (int buffer = 0; buffer < count; buffer++) { block[posBlock + buffer] = rd[buffer]; i = buffer; }
            i++;
            posBlock += i;
            string rcpausgabe = null;
            for (int i2 = 0; i2 < posBlock; i2++) { rcpausgabe += " " + (int)(block[i2]); }
            //WriteProtocol(global_.variables.protocol_other, rcpausgabe, true);
            console_.WriteLine("ReadCode: " + rcpausgabe);
            if (IsDecode == false) { Zersetzten(); } else { console_.WriteLine("Add but not Zersetzen()"); }
            IsDecode = false;
            console_.WriteLine("--------------------------------------------------");
        }

        bool IsDecode = true;
        public int ib = 0;
        public string bs = null;

        private void Zersetzten()
        {
            IsDecode = true;
            console_.WriteLine("--------------------------------------------------");
            console_.WriteLine("Void: Zersetzten()");

            byte[] b = new byte[4096];

            while (!(ib >= posBlock))
            {
                for (int i7 = 0; i7 < b[1] + 3; i7++)
                {
                    string rcpausgabe1 = null;
                    b[i7] = block[ib];
                    ib++;;
                    if (i7+1 == (b[1] + 3))
                    {
                        Thread.Sleep(500);
                        console_.WriteLine("Decoding b");
                        for (int i2 = 0; i2 < b[1]+3; i2++) { rcpausgabe1 += " " + (int)(b[i2]); }
                        console_.WriteLine("Decoding Code: " + rcpausgabe1);
                        bs = rcpausgabe1;
                        Decoding(b);
                    }
                }
            }
            IsDecode = false;
            block = new byte[4096];
            posBlock = 0;
            ib = posBlock;
            console_.WriteLine("--------------------------------------------------");
        }

I have programmed my own console (console_) to help me with this, which allows me to track all processes in real time.
I also thank everyone for their answers in advance.
(I translated this text with Pons translator because my english is not so good)

A: I can't comment, so I have to use post to help you clarify your question.
I'll edit my answer if you could provide more detail.

*

*Make your question clearer.
What result do you expect and what kind of phenomena do you observe.

*Make minimal, reproducible example
Apparently Read(object sender, SerialDataReceivedEventArgs e) is not called inside of your post.
While your problem is reading is "paused", which piece of code is calling Read could be essential.

*What is "pause" and what is "Gap".

He makes pauses again and again where there are no gaps and where there are gaps (500 micro sec.

I could only guess your program will "pause" when there is a gap, but having no idea about what "gap" and "pause" are.

*What does for (int i7 = 0; i7 < b[1] + 3; i7++) and for (int i2 = 0; i2 < b[1]+3; i2++) want do achieve?
You're using b[1] for indexing and b[1] is changed while you're receiving data.
Edit: Adding How to create a Minimal, Reproducible Example.
Edit2: Point out a strange piece of code in for loop.

A: I am not sure what is wrong with you about the code you provided.
However, you could refer to [C#, need to receive data from microcontroller to receive data from microcontroller)
to know how to achieve the data from the microcontroller.


text:
Q: tikzpicture with Cumulative Distribution Function I'm trying to recreate this picture in the tikz environment.

But with the Cumulative Distribution function that I found and altered.
What I have so far

\begin{tikzpicture}[scale=2]
% define normal distribution function 'normaltwo'
\def\normaltwo{\x,{2/exp(((\x-4)^2)/2)}}
% input y parameter
\def\y{5}
% this line calculates f(y)
\def\fy{2/exp(((\y-4)^2)/2)}

% Shade orange area underneath curve.
\fill [fill=orange!60] (2.6,0) -- plot[domain=0:3.5] (\normaltwo) -- ({\y-1.45},0) -- cycle;

% Draw and label normal distribution function
\draw[color=blue,domain=1:7] plot (\normaltwo) node[right] {};

% Add dashed line dropping down from normal.
\draw[-] (2,.05)--(2,-.05) node[below] {\footnotesize ${\mu}-{2}{\sigma}$};
\draw[-] (3,.05)--(3,-.05) node[below] {\footnotesize ${{\mu}-{\sigma}}$};
\draw[-] (3.55,.005)--(3.55,-.05) node[below] {\footnotesize ${x}$};
\draw[-] (4,.05)--(4,-.05) node[below] {\footnotesize ${\mu}$};
\draw[-] (5,.05)--(5,-.05) node[below] {\footnotesize ${\mu}+{\sigma}$};
\draw[-] (6,.05)--(6,-.05) node[below] {\footnotesize ${\mu}+{2}{\sigma}$};
% Optional: Add axis labels
\draw (-.2,2.5) ;
\draw (3,-.5) ;
% Optional: Add axes
\draw[->] (0,0) -- (7.2,0) node[right] {${x}$};
\draw[->] (0,0) -- (0,2.5) node[above] {${y}$};

\draw[-,dashed] (7,-1)--(-.08,-1) node[left] {\footnotesize ${1}$};
\draw[-] (7,-3)--(-.08,-3) node[left] {\footnotesize ${0}$};
\draw[-] (-.08,-3)--(7,-3) node[right] {\footnotesize ${z}$-scale};
\draw[-] (0,-3)--(0,-.9) node[above] {\footnotesize ${\Phi}\gobble{\Phi..}({z}\gobble{\Phi..})$};
\draw[-] (0,-2)--(-.05,-2);

%\draw[-] (1,-2.95)--(1,-3.05) node[below] {\footnotesize $-{3}$};
\draw[-] (2,-2.95)--(2,-3.05) node[below] {\footnotesize ${-2}$};
\draw[-] (3,-2.95)--(3,-3.05) node[below] {\footnotesize ${-1}$};
\draw[-] (4,-2.95)--(4,-3.05) node[below] {\footnotesize ${0}$};
\draw[-] (5,-2.95)--(5,-3.05) node[below] {\footnotesize ${1}$};
\draw[-] (6,-2.95)--(6,-3.05) node[below] {\footnotesize ${2}$};
%\draw[-] (7,-2.95)--(7,-3.05) node[below] {\footnotesize ${3}$};

\draw[-,dashed] (2,-.3)--(2,-3);
\draw[-,dashed] (3,-.3)--(3,-3);
\draw[-,dashed] (4,-.3)--(4,-3);
\draw[-,dashed] (5,-.3)--(5,-3);
\draw[-,dashed] (6,-.3)--(6,-3);

\end{tikzpicture}

Now I just need to draw the function through it. I found some function but they wouldn't line up with my top graph. I tried embedding atan(x-4)/2.6+.53 into the graph but than didn't even work. Help plz

A: Probably your main problem is that you think that the atan function gives the result in radians. But:

Use:
\draw[color=blue,domain=1:7] plot (\x,{rad(atan(\x-4))/2.6+0.53});

and adjust the curve position. Notice the extra braces needed to hide the internal parenthesis to the parser.
Anyway, this kind of diagram would be much easier with pgfplots.


text:
Q: neccessary and sufficent condition for a $n \times n$ matrix over a ring $R$ to define an isomorphism from $R^n$ to itself To find a neccessary and sufficent condition for a $n \times n$ matrix over a ring $R$ to define an isomorphism from $R^n$ to itself.
Suppose $A$ be a $n \times n$ matrix satisfying $Ax=y$, where $x,y$ are $n \times 1$ vectors in $R^n$.
If $R$ is an integral domain or a field, then $A$ defines an isomorphism if $det(A) \neq 0$.
But what about the case, when the entries of $A$ are from a ring (which is not integral domain) ?
My intuition:
In case, $R$ is just a ring, the matrix $A$ will define an injective map if $det(A)$ is not a zero divisor of $R$.
But how to ensure the surjection ?


text:
Q: sending complex object from android to vb.net webservice Im trying to send a PersonalInfo object from android to vb.net using web services. I have the connection as i can send primitive types.
This is what i have so far....
This is the android activity
package com.msc.mynamespace;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import com.msc.mynamespace.db.DatabaseHelper;
import com.msc.mynamespace.model.PersonalInfo;

import android.os.AsyncTask;
import android.os.Bundle;

import android.view.View;

import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MyActivity extends DashboardActivity {

    DatabaseHelper db ;

    TextView textView1;
    EditText editText1;
    Button button1;
    String test;

    final String NAMESPACE = "http://mywebnamespace.org/";
    final String URL = "http://localhost/MyWebService.asmx";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sync);
        db = new DatabaseHelper(this);
 }

    public void CallWebservice(View v) {

        this.SyncPersonalInfo();
    }

        //starting asynchronus task
     private class SyncPersonalInfoTask extends AsyncTask<String, Void, String> {

         @Override
         protected void onPreExecute() {
              //if you want, start progress dialog here
         }

         @Override
         protected String doInBackground(String... urls) {
             String webResponse = "";
            try{

              final String SOAP_ACTION = "http://mywebnamespace.org/SyncPersonalInfo";
              final String METHOD_NAME = "SyncPatientInfo";
              PersonalInfo pi=db.RetrievePersonalInfo();//this is PersonalInfo object that i get from the database

              SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
              PropertyInfo fromProp =new PropertyInfo();
              fromProp.setName("PI");
              fromProp.setValue(pi);
              fromProp.setType(pi.getClass());
              request.addProperty(fromProp);

              SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
              envelope.dotNet = true;
              envelope.setOutputSoapObject(request);

              //envelope.addMapping(NAMESPACE, "PersonalInfo",new PersonalInfo().getClass());

              HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

              androidHttpTransport.call(SOAP_ACTION, envelope);
              SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
              webResponse = response.toString();
           }
           catch(Exception e){

              Toast.makeText(getApplicationContext(),"Cannot access the web service"+e.toString(), Toast.LENGTH_LONG).show();
            }

             return webResponse;
        }
         @Override
         protected void onPostExecute(String result) {

                 Toast.makeText(getApplicationContext(),"Completed...", Toast.LENGTH_LONG).show();
              }
     }

        public void SyncPersonalInfo(View view) {
            SyncPersonalInfoTask task = new SyncPersonalInfoTask();

               //passes values for the urls string array
               task.execute();
              }
}

This is the vb.net part
    Imports System.Web
    Imports System.Web.Services
    Imports System.Web.Services.Protocols

<WebService(Namespace:="http://mywebnamespace.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class MyWebService
    Inherits System.Web.Services.WebService

    Public Class PersonalInfo
        Public fname As String
        Public lname As String
    End Class
    <WebMethod()> _
    Public Function SyncPatientInfo(//what to put here??) As String
       //how to manipulate the parameter??
    End Function

End Class

I am lost as to how to send the PersonalInfo object and how to receive it on the .net end and then manipulate it
Please assist thanking you all in advance

A: I got through with the problem without using WCF.
Basically the complex object had to implement kvmserializable.
This stackoverflow QandA helped me.
Ksoap: Cannot Serialize exception when passing user defined class as parameter to web method
Thanks for assistance OneFineDay

A: This is what i used to pass the PersonalInfo complex object that implements kvmserializable
   private class SyncPersonalInfoTask extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            // if you want, start progress dialog here
        }

        @Override
        protected String doInBackground(String... urls) {
            String webResponse = "";
            try {

                final String SOAP_ACTION = "http://mywebnamespace.org/SyncPersonalInfo";
                final String METHOD_NAME = "SyncPersonalInfo";
                PersonalInfo pi = db.RetrievePersonalInfo();

                SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

                PropertyInfo fromProp = new PropertyInfo();
                fromProp.setName("PI");
                fromProp.setValue(pi);
                fromProp.setType(pi.getClass());
                request.addProperty(fromProp);

                SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                envelope.dotNet = true;
                envelope.setOutputSoapObject(request);

                envelope.addMapping(NAMESPACE, "PersonalInfo",new PersonalInfo().getClass());

                MarshalDouble md = new MarshalDouble();// for serializing double
                md.register(envelope);
                HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

                androidHttpTransport.call(SOAP_ACTION, envelope);
                SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
                webResponse = response.toString();
            } catch (Exception e) {
                webResponse = "Cannot access the web service" + e.toString();
            }

            return webResponse;
        }

        @Override
        protected void onPostExecute(String result) {
            Toast.makeText(getApplicationContext(), "Completed...",Toast.LENGTH_LONG).show();
        }
    }

The vb.net webservice that accepts the complex object is as follows
Public Class PersonalInfo
    Public ID As Integer
    Public FirstName As String
    Public LastName As String

End Class

     <WebMethod()> _
Public Function SyncPersonalInfo(ByVal PI As PersonalInfo) As String
   return PI.LastName

End Function

Now i want
<WebMethod()> _
Public Function SyncPersonalInfo(ByVal PersonalInfoList As List(Of PersonalInfo)) As String
  //iterate through PersonalInfoList

End Function

How do you send List to webservice??


text: Q: Virtualization for experimenting with building network infrastructure I would like to experiment with building a network infrastructure: create many hosts running different OSs, install DHCP and DNS servers, configure routing, mail, PXE loading of hosts, configure LDAP or Active Directory, configure a web stack from WAF to Application Server'a, - in general, practice so to speak (I'm a beginner). It's a pity to build all this in AWS and other clouds of money. Therefore, I need a way how all this network interaction can be efficiently implemented, with an emphasis on realism and the ability to transfer to real machines, so to speak, on my home computer. Please advise on virtualization technologies (kvm or Docker), because I'm not very good at this.


text:
Q: BeanItem not updating associated Field more than one, when changing property by hand I'm scratching my head, trying to work out why a BeanItem's property isn't updating the component Field's value - more than once :(.
class MyComponent extends CustomComponent {
    TextField firstNames
    BeanItem<MyObject> bean = new BeanItem<MyObject>(new MyObject())

    MyComponent() {
        Layout layout = new FormLayout()
        setCompositionRoot(layout)

        firstNames = new TextField("First Names")
        layout.addComponent(firstNames)

        FieldGroup binder = new FieldGroup(bean)
        binder.bindMemberFields(this)
    }

    void setFromAccount(MyObject newObject) {
        bean.getItemProperty("firstNames").setValue(newObject.firstNames)
    }
}

The first time I call setFromAccount the value of the firstNames text field is updated on screen. The second time it isn't, and the first value persists.
Does anyone know what's going on? I thought that whenever I set the value on the underlying property everything was updated through internal listeners. Why is it only happening the first time?


text:
Q: How to log a user in by getting data from an API? I am writing an API view where am accessing API to POST email and password to the address and fetch response.So i want if response is 200 or repose message is 'Success' then to login with available email and password datas, but i'm not able to do so. How to achieve such?
class ApiLoginView(TemplateView):
    template_name = 'index.html'

    def post(self,request):
        email = request.POST.get('login-email')
        print(email)

        password = request.POST.get('login-password')
        print(password)
        API_KEY = '*********************'
        API_URL = 'http://devstudio.com/rest/storeLogin'
        parameter = {
            'authToken':API_KEY,
            'email':email,
            'password':password,
        }
        r = session.post(url = API_URL, params=parameter)
        return HttpResponse(r)

A: if you are using djagno's built-in auth and user system then you can use something like this
from django.contrib.auth import authenticate, login
class ApiLoginView(TemplateView):
template_name = 'index.html'

def post(self,request):
    email = request.POST.get('login-email')
    print(email)

    password = request.POST.get('login-password')
    print(password)
    API_KEY = '*********************'
    API_URL = 'http://devstudio.com/rest/storeLogin'
    parameter = {
        'authToken':API_KEY,
        'email':email,
        'password':password,
    }
    r = session.post(url = API_URL, params=parameter)
    if r.status_code==200:
       user = authenticate(request, username=username, password=password)
       if user is not None:
          login(request, user)
          # Redirect to a success page.

       else:
         # Return an 'invalid login' error message.

    return HttpResponse(r)

for reference check this https://docs.djangoproject.com/en/2.1/topics/auth/default/#topic-authorization
hope this helps..


text:
Q: Cyclic $R$- module over a non-commutative ring $R$, two different generators can have "ideals of order" or "order of ideals" different Let $V=M_{2 \times 1}(k)$ where $k$ is a field, and consider $V$ like a module over a ring $R=M_{2 \times 2}(k)$ over adition and multiplication of matrix. Prove that $V$ is a cyclic $R$-module and that every $\begin{pmatrix}1\\ 0 \end{pmatrix}$ and $\begin{pmatrix} 0 \\ 1 \end{pmatrix}$ generate $V$ as $R$-module. Calculate the ideals order of each of these generators and compare them.
Can you guys please help me, I know that these elements generate the module, but I don't understand the meaning about order ideal or ideal order.
Thanks for the help in advance.


text:
Q: "docker run" a command located in a mounted volume Is there a way to have docker execute a command located in a mounted volume upon container creation?
I have a simple c program located in a directory I'm bind-mounting to the container that outputs the pwd and then runs until killed:
flash@dsvm1:~$ ./hello-docker-mount
Hello from /home/flash!
^C
flash@dsvm1:~$ cat hello-docker-mount.c
#include <stdio.h>
#include <unistd.h>
int main()
{
        char cwd[1024];
        getcwd(cwd, sizeof(cwd));
        printf("Hello from %s!\n", cwd);
        for(;;) { sleep(1); }
}
flash@dsvm1:~$ ls /home/flash/hello-docker-mount -al
-rwxrwxr-x 1 flash flash 8728 May 21 22:53 /home/flash/hello-docker-mount

However, when I try to "docker run" using this as the command it seems to fail as if the mount occurs after the command is executed:
flash@dsvm1:~$ docker run -it --name foo --rm -v /home/flash:/home/flash busybox /home/flash/hello-docker-mount
standard_init_linux.go:195: exec user process caused "no such file or directory"
flash@dsvm1:~$ docker run -it --name foo --rm -v /home/flash:/home/flash -w /home/flash busybox /home/flash/hello-docker-mount
standard_init_linux.go:195: exec user process caused "no such file or directory"
flash@dsvm1:~$ docker run -it --name foo --rm -v /home/flash:/home/flash -w /home/flash busybox ./hello-docker-mount
standard_init_linux.go:195: exec user process caused "no such file or directory"
flash@dsvm1:~$ docker run -it --name foo --rm -v /home/flash:/home/flash -w /home/flash busybox hello-docker-mount
docker: Error response from daemon: OCI runtime create failed: container_linux.go:296: starting container process caused "exec: \"hello-docker-mount\": executable file not found in $PATH": unknown.

I also tried with --entrypoint:
flash@dsvm1:~$ docker run -it --name foo --rm -v /home/flash:/home/flash --entrypoint /home/flash/hello-docker-mount busybox
standard_init_linux.go:195: exec user process caused "no such file or directory"
flash@dsvm1:~$ docker run -it --name foo --rm -v /home/flash:/home/flash -w /home/flash --entrypoint hello-docker-mount busybox
docker: Error response from daemon: OCI runtime create failed: container_linux.go:296: starting container process caused "exec: \"hello-docker-mount\": executable file not found in $PATH": unknown.

If I call an executable that's in the image first, I can see the file:
flash@dsvm1:~$ docker run -it --name foo --rm -v /home/flash:/home/flash -w /home/flash busybox ls -l hello-docker-mount
-rwxrwxr-x    1 1003     1003          8728 May 21 22:53 hello-docker-mount

I have no control over what users will build in their docker images, so there's no guarantee any particular shell or executable will be available. I need to be able to "docker run -d" their image and ensure it continues to run so that when the user wants to interact with it I can use "docker exec".
Is this possible?
Less desirable, but if the above is not possible - is there an alternative way of adding a file into an existing container image to achieve the expected result?

A: It has got to do with "how to execute binary in a busybox".
"docker run" mounts the volumes before executing the command.
For example, this works fine with centos:
docker run -v /home/chan:/home/chan centos /home/chan/echo.sh
hello world

To verify if you can execute the binary in busybox, you can do
docker run -it -v /Users/nnatara/Desktop:/home/chan busybox sh
/ # cd /home/chan/
/home/chan # ./echo.sh
hello world

In your case, you might encounter issues executing the binary.

*

*You need to verify if the binary is compiled for the destination
architecture.

*Check if the required libs are found in the
environment.


text:
Q: Implementation of Javascript class generic setter (modifying setter without knowing the property name) Originally my objective is when any property of the instances of class OnlyOneProp is set,
i.e. obj.what_ever_property = "value",
at last it will only modify obj.the_only_prop.
Behavior is like this:
var obj = new OnlyOneProp();
obj.what_ever_property = "value";
console.log(obj.only_property, obj.what_ever_property);
// expected output:
// >value undefined

Original Question: Is there a way to implement above behaviour?

edit:
With respect to the solution in the answer,
here are some follow up questions:
1) Is there any major flaw to the above code? (Like I had once mixed up receiver and target, which may cause infinite looping on the setter)
2) Would Proxy hinder the performance a lot?
3) Is there any way to bypass the above proxy setter? (Like defineProperty()or so)
4) It can also be an implementation of ReadOnlyObject (after removing the setting line in setter), but would there be a better implementation? (It's a bit out of topic but I also want to know, because I really want to remove the top Proxy which is just overriding the constructor)

A: If you return an object from the constructor, the new operator returns that object, not the new object it passed to the constructor as this. So a more straight forward version of OnePropertyClass might be
class OnePropertyClass{
    constructor( value) {
        var self = this;
        return new Proxy( this, {
           set: function(target, property, value) {
                    self["only_property"] = value;
                    return true;
                }
           }
        );
    }
}

This can be simplified by using an arrow function instead of the closure:

class OnePropertyClass{
    constructor() {
        return new Proxy( this, {
           set: (target, property, value) => {
                    this.only_property = value;
                    return true;
                }
           }
        );
    }
}

var obj = new OnePropertyClass();
obj.what_ever_property = "value";
console.log(obj.only_property, obj.what_ever_property);

It doesn't set up any setter loops because the setter stores the value on the actual this object of the constructor, not on the proxy object returned.
Instances of this version of OnePropertyClass inherit per usual - the constructor property returns the OnePropertyClass constructor function, and Object.prototype properties and methods are still inherited.
You may wish to freeze OnePropertyClass.prototype to prevent additions of any other inherited properties. You may also wish to provide trap functions for defineProperty and possibly setPrototype to prevent run time property additions - see MDN handler object methods for details.
Proxy implementation is probably written in C++ and I would expect most of the additional overheads will lie in calling the setter function.
I have not tested this version for extensibility and did not use the target parameter of the set handler Please experiment before use :-)

A: After digging up from MDN Proxy and inspiration from dynamic setter/getter,
I've come up with the code below:
var OnlyOneProp = new Proxy(
    // target
    class{// normal class definition
        constructor(){
            // console.log("anonymous constructor");
        }
    }, {
    construct(target, args, caller){
        // if(!new.target){}
        // console.log("proxy construct");
        return new Proxy(new target(), {
            set(target, name, value, receiver){
                target.only_property = value;
                return true; // must have according to some specification
            }
        });
    },
});

var obj = new OnlyOneProp();
obj.what_ever_property = "value";
console.log(obj.only_property, obj.what_ever_property);
// output: value undefined

It's fully functioning but as you may see there are two new Proxy() instantiation (although the first one only execute once), which I want to remove if possible.