text:
Q: C# memory address value cannot be modified? Use "OllyDbg" app in picture.
My questions: Why cannot modify value in picture of part Q1?
(any address all cannot.)
But can modify in part Q2?
My C# code:
[DllImport("kernel32.dll")]
public static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);

[DllImport("kernel32.dll", SetLastError = true)]
static extern bool WriteProcessMemory(int hProcess, int lpBaseAddress,byte[] lpBuffer, int dwSize, ref int lpNumberOfBytesWritten);

[DllImport("kernel32.dll")]
public static extern bool ReadProcessMemory(int hProcess,int lpBaseAddress, byte[] lpBuffer, int dwSize, ref int lpNumberOfBytesRead);

static void Main(string[] args)
{
    Process process = Process.GetProcessesByName("Defiance")[0];
    IntPtr processHandle = OpenProcess(0x1F0FFF, false, process.Id);
    int bytesWritten = 0;
    byte[] buffer = Encoding.Unicode.GetBytes("test");

    WriteProcessMemory((int)processHandle, 0x022AE000, buffer, buffer.Length, ref bytesWritten);

    Console.ReadLine();
}

A: Your question is why you cannot modify the data in the read-only data section.
By definition the read-only data section can only be read, not modified or executed. That's why it's called the "read-only data section", or "rdata", for short.


text:
Q: query of sqlite3 with python using '?' I have a table of three columnsid,word,essay.I want to do a query using (?). The sql sentence is sql1 = "select id,? from training_data". My code is below:
def dbConnect(db_name,sql,flag):
    conn = sqlite3.connect(db_name)
    cursor = conn.cursor()
    if (flag == "danci"):
        itm = 'word'
    elif flag == "wenzhang":
        itm = 'essay'
    n = cursor.execute(sql,(itm,))
    res1 = cursor.fetchall()
    return res1

However, when I print dbConnect("data.db",sql1,"danci")
The result I obtained is [(1,'word'),(2,'word'),(3,'word')...].What I really want to get is [(1,'the content of word column'),(2,'the content of word column')...]. What should I do ? Please give me some ideas.

A: You can't use placeholders for identifiers -- only for literal values.
I don't know what to suggest in this case, as your function takes a database nasme, an SQL string, and a flag to say how to modify that string. I think it would be better to pass just the first two, and write something like
sql = {
    "danci":    "SELECT id, word  FROM training_data",
    "wenzhang": "SELECT id, essay FROM training_data",
}

and then call it with one of
dbConnect("data.db", sql['danci'])

or
dbConnect("data.db", sql['wenzhang'])

But a lot depends on why you are asking dbConnect to decide on the columns to fetch based on a string passed in from outside; it's an unusual design.

Update - SQL Injection
The problems with SQL injection and tainted data is well documented, but here is a summary.
The principle is that, in theory, a programmer can write safe and secure programs as long as all the sources of data are under his control. As soon as they use any information from outside the program without checking its integrity, security is under threat.
Such information ranges from the obvious -- the parameters passed on the command line -- to the obscure -- if the PATH environment variable is modifiable then someone could induce a program to execute a completely different file from the intended one.
Perl provides direct help to avoid such situations with Taint Checking, but SQL Injection is the open door that is relevant here.
Suppose you take the value for a database column from an unverfied external source, and that value appears in your program as $val. Then, if you write
my $sql = "INSERT INTO logs (date) VALUES ('$val')";
$dbh->do($sql);

then it looks like it's going to be okay. For instance, if $val is set to 2014-10-27 then $sql becomes
INSERT INTO logs (date) VALUES ('2014-10-27')

and everything's fine. But now suppose that our data is being provided by someone less than scrupulous or downright malicious, and your $val, having originated elsewhere, contains this
2014-10-27'); DROP TABLE logs; SELECT COUNT(*) FROM security WHERE name != '

Now it doesn't look so good. $sql is set to this (with added newlines)
INSERT INTO logs (date) VALUES ('2014-10-27');
DROP TABLE logs;
SELECT COUNT(*) FROM security WHERE name != '')

which adds an entry to the logs table as before, end then goes ahead and drops the entire logs table and counts the number of records in the security table. That isn't what we had in mind at all, and something we must guard against.
The immediate solution is to use placeholders ? in a prepared statement, and later passing the actual values in a call to execute. This not only speeds things up, because the SQL statement can be prepared (compiled) just once, but protects the database from malicious data by quoting every supplied value appropriately for the data type, and escaping any embedded quotes so that it is impossible to close one statement and another open another.
This whole concept was humourised in Randall Munroe's excellent XKCD comic

redpajama_set_name: RedPajamaStackExchange


text:
Q: making a mass texting app with keywords I'm on a youtube channel trying to follow a 200 lesson series on Android development when all I want to know first is if my app idea is possible.
I want to make an app for mass texting to a small group probably under 100 people at any given time.
I don't need any of that short code stuff, actually I'd like to use my GV# since that's a free long code.
Right now what I do is I use GV & the Gmail workaround (if you don't know what that is you can ask me or google it) but it is a long and tedious process due to the fluctuation of subscribers.
My question is:
I need the keywords capability too, which GV does not provide which
led me to think about making an app. I would also like to have people
added to the list automatically via keyword. I will be sending out
10-20 or so bursts a month from my AT&T Samsung Galaxy S II.
I'm obviously getting pretty desperate... any help, questions, or advice?

A:   SmsManager sm = SmsManager.getDefault();
  String number = "8001234567";
  sm.sendTextMessage(number, null, "Enter text message here", null, null);

and remember to set your permissions in the manifest to
  android:name="android.permission.SEND_SMS"

that should get you started in the correct direction.

A: You don't necessarily need an Android app to send SMS. You can use some web based APIs too.
There are some companies like Twilio, Tropo and MediaBurst that provide web based APIs that you could call from a web service or from an Android app.
There are also some operators offering web based APIs for sending SMS through their network using a web based API including Bluevia (see https://bluevia.com).
So equally you could just write a web service if that is easier for you.

A: There is an app on the market called SMS KeyWords. Sounds like what your looking for.


text:
Q: How to delete software installed with third party repository? I struggled getting VirtualBox to work in Ubuntu, so I removed it and installed it using a third party repository. I ran these commands:
wget -q -O - http://download.virtualbox.org/virtualbox/debian/oracle_vbox_2016.asc | sudo apt-key add -

sudo sh -c 'echo "deb http://download.virtualbox.org/virtualbox/debian focal non-free contrib" >> /etc/apt/sources.list.d/virtualbox.org.list'

I reconsidered and decided to remove VirtualBbox completely, however, I now can't remove it using:
sudo apt-get remove --purge virtualbox

This gives the output:
Package 'virtualbox' is not installed, so not removed

I can still open VirtualBox and am unsure how to remove it. Also, I'm a complete newbie to Ubuntu, so I might have some fundemental misunderstanding of what repositories actually are or something similar.


text:
Q: Draw Rectangle for scattered points I have some scattered points for which I need to draw a rectangle / circle / polygon as a background. I have only coordinates (x,y) of selected points.what will be the maths formula to this? These points are inside canvas and I need to draw the outer shape for selected points in canvas itself. Tried with canvas rect .
Attaching one more image:


text:
Q: ActiveRecord vs SQL raw queries? What is the difference between ActiveRecord and writing raw queries.??
 In  which situation one should adopt writing raw queries in rails app .

A: The key difference is that ActiveRecord lets you be more productive by using a higher level abstraction which lets you write less code.
It also makes your code more portable by abstracting away some of the differences between DBMS:es.
This abstraction comes at a cost and can lead to performance problems if you don't pay attention to the queries that ActiveRecord generates.

In which situation one should adopt writing raw queries in rails app?

When needed to accomplish the job at hand. This could for example be to use the Postgres extension ILIKE:
# case insensitive search:
@user = User.where('users.name ILIKE ?', params[:name])

Or when you need to execute a complicated join or another performance critical operation. Like this example which fetches a number of associated records per parent. It sounds simple but is extremely difficult to do in ActiveRecord.
class Observation < ActiveRecord::Base
  belongs_to :station

  # ...

  def self.pluck_from_each_station(limit = 1)
    ActiveRecord::Base.connection.execute(%Q{
      SELECT o.id
      FROM   stations s
      JOIN LATERAL (
         SELECT id, created_at
         FROM   observations
         WHERE  station_id = s.id  -- lateral reference
         ORDER  BY created_at DESC
         LIMIT  #{limit}
      ) o ON TRUE
      ORDER BY s.id, o.created_at DESC;
    }).field_values('id')
  end
end

And lastly if you don't know how to perform an operation with ActiveRecord it is often better to write a bit of SQL with a test backing it and go back and refactor later.
@users = User.where("occupation NOT IN(?)", params[:blacklist])) # @todo fix

You can then refactor this to:
@users.where.not(occupation: params[:blacklist])

A: ActiveRecord will serve you well most of the time, but there are a few situations where you will need to write raw sql. It is worth noting that ActiveRecord queries can also be written in a sql-like way. For example, you could write:
User.where(name: "Person A")

Or you could write it with a slightly more SQL-like syntax:
User.where("name = ?", "Person A")
User.where("name LIKE ?", "%Person A%")

One of the reasons that you may want to write raw SQL is when you are trying to access something that cannot be accessed through ActiveRecord methods, like the join table in a has_and_belongs_to_many association.


text:
Q: Trouble migrating from v1 to v2 of AzureRM using for network interface security group, it fails to apply I'm migrating my config from azurerm 1.44 to 2.3.0 and need to use the new config item azurerm_network_interface_security_group_association
When I do my plan all seems good:
Terraform will perform the following actions:
  # module.web-msg.azurerm_network_interface_security_group_association.main[0] will be created
  + resource "azurerm_network_interface_security_group_association" "main" {
      + id                        = (known after apply)
      + network_interface_id      = "/subscriptions/xxxx/resourceGroups/vm-0/providers/Microsoft.Network/networkInterfaces/vm-0-nic"
      + network_security_group_id = "/subscriptions/xxxx/resourceGroups/vm-0/providers/Microsoft.Network/networkSecurityGroups/MsgHubNetworkSecurityGroup"
    }

  # module.web-msg.azurerm_network_interface_security_group_association.main[1] will be created
  + resource "azurerm_network_interface_security_group_association" "main" {
      + id                        = (known after apply)
      + network_interface_id      = "/subscriptions/xxxx/resourceGroups/vm-1/providers/Microsoft.Network/networkInterfaces/vm-1-nic"
      + network_security_group_id = "/subscriptions/xxxx/resourceGroups/vm-1/providers/Microsoft.Network/networkSecurityGroups/MsgHubNetworkSecurityGroup"
    }

But when I come to apply I get this which doesn't make sense as the resource "vm-0" is being managed by terraform.
terraform apply .\the.plan
module.web-msg.azurerm_network_interface_security_group_association.main[0]: Creating...
module.web-msg.azurerm_network_interface_security_group_association.main[1]: Creating...

Error: A resource with the ID "vm-0" already exists - to be managed via Terraform this resource needs to be imported into the State. Please see the resource documentation for "azurerm_network_interface_security_group_association" for more information.

  on ..\..\..\infra\terraform\global\msghub\main.tf line 52, in resource "azurerm_network_interface_security_group_association" "main":
  52: resource "azurerm_network_interface_security_group_association" "main" {

Error: A resource with the ID "vm-1" already exists - to be managed via Terraform this resource needs to be imported into the State. Please see the resource documentation for "azurerm_network_interface_security_group_association" for more information.

  on ..\..\..\infra\terraform\global\msghub\main.tf line 52, in resource "azurerm_network_interface_security_group_association" "main":
  52: resource "azurerm_network_interface_security_group_association" "main" {


text:
Q: For laravel application add cron jobs in linux server Hi
In laravel I have done scheduling the commands, I Have doubt on this step.
*** * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1**.
path means which path(laravel application path)?.
*** * * * * php /var/www/html/laravel/artisan schedule:run >> /dev/null 2>&1**.
is this right?

A: The full path to where your artisan file is. If you look in your Laravel root directory, you should find that it is there - so, simply put, the path to that directory as a whole. If your Laravel installation, in your case, resides in /var/www/html/laravel, then the path is correct.


text:
Q: To push objects to table component in angular Scenario: I have 2 api's called customers and workers, I am displaying all my customers and their assigned workers using  table in an component called customersas in below image:

When i click on edit button of particular customer, I am injecting that particular customer object(Ex Customer 1) values to an another component called edit(dialog component),where i am displaying injected customer properties(name,email) and the assigned worker properties(name,email,phone) into the table. as in below image:

As shown in the second image i have placed an another component(workers-list)inside the edit component which will show all workers in the dropdown:

Expected Result:

*

*Now i want push those selected workers from workers-list component to table present in the edit component like this:

Ex pic: Worker 2 selected from the dropdown and gets added to table in edit component by clicking Add button.

*

*It should not add duplicates.

I am receiving emitted workers in edit component, but i am unable verify duplicates and i am unable push the new workers to table.

Since components are many, I am giving stackblitz link.

A: Please take a look.
To rerender table you need to create a new array like that:
this.customerWorkers = [...this.customerWorkers, ...value];

To skip empty values (and not add them to table), you can use filter on subject like:
this.dataService.onSelectWokers.pipe(
     filter(x => x)
   )

Also you need to map workers before pushing them to service, example:
const workersMap = this.addForm.value.workerIds;
const workersArray = Object.keys(workersMap).map(x => workersMap[x]);

Hope that helps.


text:
Q: Zend Framework 3 filter / validate array of contents I've searched internet and there is no official documentation for applying input filters to arrays in ZF3.
I have seen answers for ZF2, Zend Framework 2 filter / validate array of contents
Can anyone help out how to apply input filters to array of input.
This is my form class
class ContactForm extends Form
{
 public function __construct($name = null)
{
    // we want to ignore the name passed
    parent::__construct("contactForm");
    $this->addInputFilters();
}

public function init()
{
    $this->add([
        "name"                       => "Type[]",
        "type"                       => "text",
        "attributes"                 => [
            "class"                  => "form-control",
        ],
    ]);
}
private function addInputFilters() {
    $inputFilter->add([
        "name"                       => "Type[]",
        "required"                   => true,
        "filters"                    => [],
        "validators"                 => [
            [
                "name"               => "StringLength",
                "options"            => [
                    "min"            => 3,
                    "max"            => 100,
                ],
            ],
        ],
    ]);
}

A: This page has the answer for you https://olegkrivtsov.github.io/using-zend-framework-3-book/html/en/Collecting_User_Input_with_Forms/Adding_Form_Filtering_and_Validation_Rules.html .
The first difference I can see is the method name that is not addInputFilters but addInputFilter, without 's'.
Also within addInputFilter you did not get the form input filter with

$inputFilter = $this->getInputFilter();

infact in you example you are calling 'add' to an undefined variable actually, but perhaps your posted example is not the ful code.
Also, if you want to validate collection ( wich kind of data is going to validate 'Type[]'? ), use Collection input filter, and assign to it an input filter to validate each entry.


text:
Q: highcharts is not working in django I write an small piece of javascript code to display a barchart in django framework using highcharts.
my home.html contains
{% extends "base.html" %}
{% block main_content %}
{% load staticfiles %}

<button class="btn btn-primary" type="button" id="btn_day_of_week">Day of week</button>

{% endblock %}

static/js/day_of_week.js contains
$(document).ready(function(){
       $('#btn_day_of_week').click(function(){

            //alert("day_of_week is clicked");

            $('#container').highcharts({
                chart: {
                    type: 'column'
                },
                title: {
                    text: 'Call Patterns in Week of Day'
                },

                xAxis: {
                    categories: [
                        'Sunday',
                        'Monday',
                        'Tuesday',
                        'Wednesday',
                        'Thursady',
                        'Friday',
                        'Saturday',
                    ]
                },
                yAxis: {
                    min: 0,
                    title: {
                        text: 'call duration(sec)'
                    }
                },
                tooltip: {
                    headerFormat: '{point.key}
',
                    pointFormat: '
{series.name}: 	' +
                        '{point.y:.1f} mm
',
                    footerFormat: '
',
                    shared: true,
                    useHTML: true
                },
                plotOptions: {
                    column: {
                        pointPadding: 0.2,
                        borderWidth: 0
                    }
                },
                series: [{
                    name: 'Tokyo',
                    data: [49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6]

                }, {
                    name: 'New York',
                    data: [83.6, 78.8, 98.5, 93.4, 106.0, 84.5, 105.0]

                }, {
                    name: 'London',
                    data: [48.9, 38.8, 39.3, 41.4, 47.0, 48.3, 59.0

                }, {
                    name: 'Berlin',
                    data: [42.4, 33.2, 34.5, 39.7, 52.6, 75.5, 57.4]

                }]
            });

       });

     });

The alert("day_of_week is clicked"); is working well but the graph is not displaying. How to make it display ?

A: You have two errors in your code:

*

*data: [48.9, 38.8, 39.3, 41.4, 47.0, 48.3, 59.0 <-- missing ]

*'Saturday', <-- trailling comma

After fixing this two small bugs, it works like a charm: http://jsfiddle.net/Yrygy/50/


text:
Q: Can't import Orekit - 'DLL load failed' I try to run Orekit library through python. I use Anaconda, as proposed in official tutorial. Unfortunately, I come across following error as soon as I try to import orekit in python 2.7 console:
In [1]: import orekit
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-1-307c30f2343b> in <module>()
----> 1 import orekit

C:\Anaconda2\lib\site-packages\orekit\__init__.py in <module>()
      2 os.environ["PATH"] = r"C:/Anaconda2\Library\jre\bin\server" + os.pathsep + os.environ["PATH"]
      3
----> 4 import os, _orekit
      5
      6 __dir__ = os.path.abspath(os.path.dirname(__file__))

ImportError: DLL load failed: Nie mo┐na odnalečŠ okreťlonego modu│u.

I've already added required 2 environmental paths and installed JDK which is located in C:\Program Files\Java\jdk1.8.0_102. I've also installed JCC and Orekit through Anaconda. I use Windows 10 64 bit and python 2.7.
Do you have any suggestions what might gone wrong? How to run it properly?

A: The solution was to install jdk through Anaconda by:
conda install -c cyclus java-jdk

I found it in official mailing list thread.


text:
Q: Moduli space of (all) vector bundles on $\mathbb{P}^1$ It is well known that, by a theorem of Grothendieck, every vector bundle (always assumed coherent in this question; and everything is over the complex numbers) splits as a direct sum of line bundles.
This is not true in families, though, not even locally on the base of the family, as it is possible to construct flat $1$-parameter families of VB that have generically the same splitting type and "jump" to a different splitting type at the special fiber. This prevents the moduli stack $\mathfrak{M}$ of all VB on $\mathbb{P}^1$ (or the corresponding functor $F$ of isomorphism classes) to be separated (in the sense of valuative criteria). Here we took the notion of isomorphism of families to mean, as usual: the families $\mathscr{E}$ and $\mathscr{E}'$ of VB on $X$ parametrized by $T$ are isomorphic if there is a line bundle $L$ on $T$ such that $\mathscr{E}\simeq\mathscr{E}'\otimes L$.
For a smooth projective curve $X$, the moduli functor $F^s$ of stable bundles is representable by a smooth separated scheme $M^s$, and the stack $\mathfrak{M}^s$ of stable bundles is a gerbe over the latter. The moduli functor $F^{ss}$ of isomorphism classes of semistable bundles has a non separated coarse moduli space with proper connected components, and collapsing $S$-equivalence classes in the sense of Seshadri fixes this: now the functor $F'^{ss}$ of such $S$-equivalence classes of semistable bundles has a coarse moduli space (each connected component of) which is a projective variety (in particular separated).
By Grothendieck's theorem, the relation of S-equivalence on $\mathbb{P}^1$ coincides with the relation of isomorphism, so we can avoid talking of $S$-equivalence in this case. Also, there are no stable VB on $\mathbb{P}^1$ (of rank $>1$).
In what follows the curve $X$ is $\mathbb{P}^1$.
Since every VB is uniquely determined by its splitting type, and there is a countable set of choices for the possible line bundles occurring as summands, each connected component of $M^{ss}$, which is a variety, has to be a reduced point $\mathrm{Spec}(\mathbb{C})$.
Recall we let $\mathfrak{M}$ be the stack in groupoids of all VB on $\mathbb{P}^1$, with isomorphisms of families as $1$-arrows, and $F$ the corresponding functor of isomorphism classes.

Q.1: How does $\mathfrak{M}$ look like?
Q.2: Does $F$ have a coarse moduli space $M$? If yes, how does it look like?

It seems possible to me that an answer to question 1 or 2 has something to do with the partial order structure on the set $\boldsymbol{\mathrm{HNP}}$ of "Harder-Narasimhan polygons" (see Shatz, The decomposition and specialization of algebraic families of vector bundles). Maybe the specialization order on (field-valued) points of $M$ (or of $F$, or of $\mathfrak{M}$) reflects somehow the structure of the lattice $\boldsymbol{\mathrm{HNP}}$?

A: Well, it is not clear to me what exactly you mean by Q.1 but here is some kind of an answer. Let's even work with $G$-bundles for any reductive group $G$ (you can take $G=GL(n)$ if you want, but that's not necessary). Consider the quotient $G((t))/G[t^{-1}]$. It has a natural scheme structure of infinite type. This scheme is isomorphic to the scheme of $G$-bundles on $\mathbb P^1$ endowed with a trivialization at the formal neighborhood of $\infty$. It is also called the thick affine Grassmannian of $G$, so we'll denote it by $Gr_G$. Now the stack of $G$-bundles on $\mathbb P^1$ is obviously the quotient $G[[t]]\backslash Gr_G$.
The isomorphism classes of $G$-bundles correspond to $G[[t]]$-orbits on $Gr_G$ which are in one-to-one correspondence with dominant coweights of $G$ (this is the analog of Grothendieck's theorem for any $G$). So, for any such coweight $\lambda$ there is a stratum $\mathcal M^{\lambda}$ in $\mathcal M$ and we have
$\mathcal M^{\mu}\subset \overline{\mathcal M^{\lambda}}$ iff $\lambda\leq \mu$ with respect to the standard partial order on coweights ($\lambda\leq \mu$ means that $\mu-\lambda$ is a sum of positive coroots). The geometry of $\overline{\mathcal M^{\lambda}}$ is pretty complicated (for example, it is quite singular). In fact, the closures of $G[[t]]$-orbits on $Gr_G$ are special examples of affine Schubert varieties.

A: The stack $\mathfrak{M}$ was discussed in section 7 of On the motivic class of the stack of bundles by Behrend and Dhillon, where the same stratification as discussed by Alexander Braverman was described.  Moreover, the various strata are identified with classifying stacks (for the automorphism groups of the corresponding bundles).


text:
Q: Could not find an existing managed instance for this object I have a Xamarin iOS app, it was working properly, but I don't know what I've touched so it started raising this exception when I click on button to move to another view in storyboard:
System.Exception: Failed to marshal the Objective-C object 0x7ffa72c19570 (type: PropertyListViewController). Could not find an existing managed instance for this object, nor was it possible to create a new managed instance (because the type 'Rental.iOS.PropertyListViewController' does not have a constructor that takes one IntPtr argument).
  at at (wrapper managed-to-native) ObjCRuntime.Messaging:void_objc_msgSendSuper_bool_bool (intptr,intptr,bool,bool)
  at UIKit.UIViewController.BeginAppearanceTransition (System.Boolean isAppearing, System.Boolean animated) [0x0002c] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/src/build/ios/native/UIKit/UIViewController.g.cs:168
  at XLPagerTabStrip.PagerTabStripViewController.UpdateContent () [0x001c3] in /Users/abd/Programming/Gits/Rental/Rental/Rental/Rental.iOS/XLPagerTabStrip/PagerTabStripViewController.cs:271
  at XLPagerTabStrip.PagerTabStripViewController.Scrolled (UIKit.UIScrollView scrollView) [0x0000e] in /Users/abd/Programming/Gits/Rental/Rental/Rental/Rental.iOS/XLPagerTabStrip/PagerTabStripViewController.cs:339
  at at (wrapper managed-to-native) ObjCRuntime.Messaging:void_objc_msgSend_CGPoint (intptr,intptr,CoreGraphics.CGPoint)
  at UIKit.UIScrollView.set_ContentOffset (CoreGraphics.CGPoint value) [0x00010] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/src/build/ios/native/UIKit/UIScrollView.g.cs:387
  at XLPagerTabStrip.PagerTabStripViewController.UpdateContent () [0x00068] in /Users/abd/Programming/Gits/Rental/Rental/Rental/Rental.iOS/XLPagerTabStrip/PagerTabStripViewController.cs:247
  at XLPagerTabStrip.PagerTabStripViewController.Scrolled (UIKit.UIScrollView scrollView) [0x0000e] in /Users/abd/Programming/Gits/Rental/Rental/Rental/Rental.iOS/XLPagerTabStrip/PagerTabStripViewController.cs:339
  at at (wrapper managed-to-native) UIKit.UIApplication:UIApplicationMain (int,string[],intptr,intptr)
  at UIKit.UIApplication.Main (System.String[] args, System.IntPtr principal, System.IntPtr delegate) [0x00005] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/src/UIKit/UIApplication.cs:79
  at UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x00038] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/src/UIKit/UIApplication.cs:63
  at Rental.iOS.Application.Main (System.String[] args) [0x00008] in /Users/abd/Programming/Gits/Rental/Rental/Rental/Rental.iOS/Main.cs:17

What can I check in Interface Designer to make sure I am not doing anything wrong?
I added thhis constructor:
public partial class PropertyListViewController : UIViewController
{
    protected PropertyListViewController(IntPtr handle) : base(handle)
    {
        // Note: this .ctor should not contain any initialization logic.
    }
    ~~~~
}

But now I receive this error :
Foundation.MonoTouchException: Objective-C exception thrown.  Name: NSInternalInconsistencyException Reason: -[UIViewController _loadViewFromNibNamed:bundle:] loaded the "PropertyListViewController" nib but the view outlet was not set.
Native stack trace:
    0   CoreFoundation                      0x000000010c73ad4b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x000000011713a21e objc_exception_throw + 48
    2   CoreFoundation                      0x000000010c7a42b5 +[NSException raise:format:] + 197
    3   UIKit                               0x00000001101b6aea -[UIViewController _loadViewFromNibNamed:bundle:] + 679
    4   UIKit                               0x00000001101b72e7 -[UIViewController loadView] + 177
    5   UIKit                               0x00000001101b761c -[UIViewController loadViewIfRequired] + 201
    6   UIKit                               0x00000001101be062 -[UIViewController __viewWillAppear:] + 118
    7   Rental.iOS                          0x000000010c0c6f9c xamarin_dyn_objc_msgSendSuper + 220
    8   ???                                 0x0000000130fb7405 0x0 + 5116752901

  at at (wrapper managed-to-native) ObjCRuntime.Messaging:void_objc_msgSendSuper_bool_bool (intptr,intptr,bool,bool)
  at UIKit.UIViewController.BeginAppearanceTransition (System.Boolean isAppearing, System.Boolean animated) [0x0002c] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/src/build/ios/native/UIKit/UIViewController.g.cs:168
  at XLPagerTabStrip.PagerTabStripViewController.UpdateContent () [0x001c3] in /Users/abd/Programming/Gits/Rental/Rental/Rental/Rental.iOS/XLPagerTabStrip/PagerTabStripViewController.cs:271
  at XLPagerTabStrip.PagerTabStripViewController.Scrolled (UIKit.UIScrollView scrollView) [0x0000e] in /Users/abd/Programming/Gits/Rental/Rental/Rental/Rental.iOS/XLPagerTabStrip/PagerTabStripViewController.cs:339
  at at (wrapper managed-to-native) ObjCRuntime.Messaging:void_objc_msgSend_CGPoint (intptr,intptr,CoreGraphics.CGPoint)
  at UIKit.UIScrollView.set_ContentOffset (CoreGraphics.CGPoint value) [0x00010] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/src/build/ios/native/UIKit/UIScrollView.g.cs:387
  at XLPagerTabStrip.PagerTabStripViewController.UpdateContent () [0x00068] in /Users/abd/Programming/Gits/Rental/Rental/Rental/Rental.iOS/XLPagerTabStrip/PagerTabStripViewController.cs:247
  at XLPagerTabStrip.PagerTabStripViewController.Scrolled (UIKit.UIScrollView scrollView) [0x0000e] in /Users/abd/Programming/Gits/Rental/Rental/Rental/Rental.iOS/XLPagerTabStrip/PagerTabStripViewController.cs:339
  at at (wrapper managed-to-native) UIKit.UIApplication:UIApplicationMain (int,string[],intptr,intptr)
  at UIKit.UIApplication.Main (System.String[] args, System.IntPtr principal, System.IntPtr delegate) [0x00005] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/src/UIKit/UIApplication.cs:79
  at UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x00038] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/src/UIKit/UIApplication.cs:63
  at Rental.iOS.Application.Main (System.String[] args) [0x00008] in /Users/abd/Programming/Gits/Rental/Rental/Rental/Rental.iOS/Main.cs:17

A:
PropertyListViewController does not have a constructor that takes one IntPtr argument.

In your UIViewController subclass, add an .ctor like so:
public partial class PropertyListViewController : UIViewController
{
    protected PropertyListViewController(IntPtr handle) : base(handle)
    {
        // Note: this .ctor should not contain any initialization logic.
    }
    ~~~~
}


text:
Q: how to share my computer using ftp,i need to access it from anywhere assuming static ip? I need to access my PC using ftp , how to do that?
there is FILE Z  but i can't configure it right
any ideas , not necessarily FILE Z
I tried shiftedit but i have no clue what is that
windows7 basic home

A: I would forget FTP and think about using SCP/SSH. It's secure, as easy to install as FTP, or even more depending on the software you choose, and you can find a lot of reliable tools: WinSCP, Putty, OpenSSH, etc...
As your need is related to file transfer, you could combine:
1 - http://mobassh.mobatek.net/ as the server
2 - https://winscp.net/eng/download.php as the client.
They both combine well:
http://mobassh.mobatek.net/documentation.html#4
WinSCP has a straight installation procedure, it is just a client, you'll only need to configure your connections like in any other FTP client. In fact WinSCP also supports plain FTP.
In regards to the SSH server, follow the creator instructions here:
http://mobassh.mobatek.net/documentation.html#1a


text:
Q: Computed key, as interface key, from enum member I am trying to set up an object property by selecting its key using a computed key, through an enum, like in the following snippet of code.
For some reason, solution 1, and 2 don't work. Those are the solutions I'd like to use in my code, since I need to assign a value to a key that's dynamically obtained from an API call.
What's weird, in my ignorance, is that solutions 4 and 5 are working, demonstrating that, actually, also solutions 1 and 2 could "potentially" work, by reassigning property values with the dynamic key, following hard-coded property key.
That's of course because TypeScript, as long as you provide matching interface properties, accepts an arbitrary number of additional properties, but, still, I don't understand why duplicated, dynamic properties, are working in 4 and 5.
That said, why solution 1 and 2 are not working? What am I doing wrong?
Thanks for your help.

interface Cat {
    tail: boolean;
    legs: Quadruped;
}

interface Quadruped {
    totalNumber: number;
}

enum BodyParts {
    TAIL = 'tail',
    TOTAL_NUMBER = 'totalNumber'
}

let brokenArgo: Cat = { tail: true, legs: { totalNumber: 4 } };
let argo: Cat = { tail: true, legs: { totalNumber: 4 } };

argo.legs = null;

let TN = 'TOTAL_NUMBER';
let tn: BodyParts = BodyParts[TN];

// solution 1 = broken
brokenArgo.legs = { [tn]: 6 }
// solution 2 = broken
brokenArgo.legs = { [BodyParts[TN]]: 6 };
// solution 3 = working
argo.legs = { [BodyParts['TOTAL_NUMBER']]: 6 };
// solution 4 = working
argo.legs = {
    totalNumber: 0,
    [tn]: 6
};
// solution 5 = working
argo.legs = {
    totalNumber: 0,
    [BodyParts[TN]]: 6
};

You can see the above script running in Typescript playground here

A: After some TypeScript unofficial documentation, I realized that since the interfaces declared are expecting a specific property (I.E. the interface is not optionial), I need to let TypeScript know that I am actually using a computed key "as" the expected property.
I.E. I am sure (I expect) to get from backend exactly that property.
The above (very bad example, I am sorry) can be fixed like so:
(see live code here)
interface Cat {
    tail: boolean;
    legs: Quadruped;
}

interface Quadruped {
    totalNumber: number;
}

enum BodyParts {
    TAIL = 'tail',
    TOTAL_NUMBER = 'totalNumber'
}

let brokenArgo: Cat = { tail: true, legs: { totalNumber: 4 } };
let argo: Cat = { tail: true, legs: { totalNumber: 4 } };

argo.legs = null;

let TN = 'TOTAL_NUMBER';
let tn: BodyParts.TOTAL_NUMBER = BodyParts[TN];

// solution 1 = broken
brokenArgo.legs = { [tn]: 6 }
// solution 2 = broken
brokenArgo.legs = { [BodyParts[TN as 'TOTAL_NUMBER']]: 6 };
// solution 3 = working
argo.legs = { [BodyParts['TOTAL_NUMBER']]: 6 };
// solution 4 = working
argo.legs = {
    // totalNumber: 0, // No more needed
    [tn]: 6
};
// solution 5 = working
argo.legs = {
    totalNumber: 0,
    [BodyParts[TN]]: 6
};

So, if you don't know, in advance, if you'll receive propertyA or propertyB from backend (which was my original problem), and you'd like to use a computed key then, you probably need or to set key in interface declaration as optional, or to set it up to an alias type (or an enum) like type myType = 'propertyA' | 'propertyB' and, then, using it as the key of the property in your interface like:
interface MyInterface {
    myType: number
}


text:
Q: Definition of sober: does it necessarily include drugs other than alcohol? Which ones? When I say sober it means "not intoxicated." And intoxicated would be under the influence of alcohol or any controlled or illegal substance.
Is someone sober if they are alcohol free but, let's say, "barred out" on Xanax as they say? or what about nodding out on Oxy? tripping balls on LSD?
I know this will have many opinions but logically Xanax is a GABA receptor agonist with a slightly different chemical structure than ethyl alcohol, so right there "sober" must pertain to more than strictly alcohol in my opinion. Thoughts?

A: Depending on the context, the word can be used to indicate that one's capacities (that are relevant to the context) are not diminished by the effects of any intoxicating substance, or that they are not diminished by the effects of the intoxicating substance that is indicated by the context. The primary meaning of the word, however, is not being under the influence of alcohol: that's what most people will will first think of upon hearing the word outside a context that clearly points to another interpretation.
So, if one wants to use the word in the ways that are suggested in the question, one can, but only if the context makes it clear that this is what is intended.

A: Sober refers to any intoxicating substance.

abstaining from drinking alcohol or taking intoxicating drugs : refraining from the use of addictive substances (see SUBSTANCE sense 3c)

MW
Intoxication can be limited to

the condition of having physical or mental control markedly diminished by the effects of alcohol or drugs

MW
What constitutes "markedly diminished" is likely to be vary somewhat by opinion.


text:
Q: how to import multiple folders containing images ,in matlab? I want to select just folders instead of selecting each images individually.
for example I have 8 folders and each of then including 72 dicom images. my purpose is to just select 8 folders and  save each folder images in one row of array. I have written this code but it only read multiple images in one folder. please help me to solve my problem.
function cell=readfromfile()
[filename, pathname] = uigetfile('*.*', 'Pick folder','Multiselect','on');
img_dir =pathname;
filename(1);
    N =length(filename);
strfile =filename{1};
img = dicomread(fullfile(img_dir, strfile));
siz_img = size(img);
% create result matrix:
% load all the remaining images and put them in the matrix
for ii=2:N
    strfile =filename{ii};
    I{ii}=dicomread( fullfile(pathname, filename{ii}) );
end

A: Neither uigetfile or uigetdir allow you to select multiple folders, so I would probably just use uigetdir to get the path of the selected folder. If you know you have 8 folders you can just call this in a loop 8 times (making sure not to overwrite you data). If you don't know how many folders you have you may need to so something cunning, but I haven't really thought about it.
I would then use dir to get a list of the files in your folders. You may need to use something like dir('*.png'); if you have any subfolders or other files you don't want to read in the folder.
Your reading of the images looks fine from there.


text:
Q: Encryption used in Multipeer Connectivity framework? Hey I am using a multi peer Connectivity framework in ios for a chat application . Does this framework support any encryption .I want to know about the encryption used in this framework like AES OR RSA encryption systems?
My findings or research:
1. https://datatheorem.github.io/documents/BH_MultipeerConnectivity.pdf
2. https://nabla-c0d3.github.io/blog/2014/08/20/multipeer-connectivity-follow-up/
Please post ur suggestions

A: Yes, there is an encryption option in MCSession.h class
 // Encryption preference.
typedef NS_ENUM (NSInteger, MCEncryptionPreference) {
MCEncryptionOptional = 0,                   // session preferred encryption but will accept unencrypted connections
MCEncryptionRequired = 1,                   // session requires encryption
MCEncryptionNone = 2,                       // session should not be encrypted
} NS_ENUM_AVAILABLE (10_10, 7_0);

call this method:
- (instancetype)initWithPeer:(MCPeerID *)myPeerID
        securityIdentity:(nullable NSArray *)identity
    encryptionPreference:(MCEncryptionPreference)encryptionPreference NS_DESIGNATED_INITIALIZER;

A: To answer your second question, MCSession uses DTLS to encrypt it's data. DTLS is based on TLS (which is the replacement of SSL), and offers the same level of security.
So just uses
MCSession *session = [[MCSession alloc] initWithPeer:localPeerID
                                securityIdentity:nil
                            encryptionPreference:MCEncryptionRequired];

to make your communications secure.


text:
Q: How to find maven entries for any project Is there a standard way for finding maven entries for any project? For eg if I talk about Spring MVC. Do I need to go the Spring website and find a section there or is there some other standard procedure using which I can find the entries I need to make ?

A: No, You can find them in the ordinary maven repositories:

*

*http://mvnrepository.com/

*http://search.maven.org/
You search for the artificat you want, and get the pom info to include in your dependencies

A: I just google "maven" and the package name. Some artifacts are only made public in company repos.

A: I search com.x.y.z maven coordinates on google and almost every time I get the results.


text:
Q: Save name for screenshots and with mobile time and date I want to give name to different screenshots that is with the name of mobile calender and time
Please help ..
Thanks in advance. i am adding my manifest file please have a look. and please add further help
What i am doing wrong
 public class MainActivity extends Activity implements Listener {

//  private static final int CAMERA_REQUEST=0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
     Button btn=(Button)findViewById(R.id.button1);
     btn.setOnClickListener(new OnClickListener() {

   @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub

     if (v.getId() == R.id.button1) {

              Bitmap bitmap = takeScreenshot();

            ImageView imageView = (ImageView)findViewById(R.id.imageView);
            imageView.setImageBitmap(bitmap);

              saveBitmap(bitmap);

          }

      }
     });}

      public Bitmap takeScreenshot() {
          View rootView = findViewById(android.R.id.content).getRootView();
          rootView.setDrawingCacheEnabled(true);
          return rootView.getDrawingCache();
      }
      public void saveBitmap(Bitmap bitmap) {

          try {

              ByteArrayOutputStream bytes = new ByteArrayOutputStream();
              bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);

              Calendar cal=Calendar.getInstance();
             File f = new File(Environment.getExternalStorageDirectory()
                    // (cal.getTimeInMillis()+"jpg"));
                      + File.separator+ (cal.getTimeInMillis()+"jpg") );

              f.createNewFile();
              FileOutputStream fo = new FileOutputStream(f);
              fo.write(bytes.toByteArray());
              fo.close();
          } catch (FileNotFoundException e) {
              Log.e("GREC", e.getMessage(), e);
          } catch (IOException e) {
              Log.e("GREC", e.getMessage(), e);
          }

      }

public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public void onGpsStatusChanged(int event) {
    // TODO Auto-generated method stub

}}

This my Manifest File :
       <xml version="1.0" encoding="utf-8"?>
       <manifest xmlns:android="http://schemas.android.com/apk/res/android"
       package="com.example.imagescreen"
       android:versionCode="1"
       android:versionName="1.0" >
       <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
       <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

       <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
         android:label="@string/app_name"
         android:theme="@style/AppTheme" >
        <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        </activity>
        </application>

        </manifest>

My logcat:
10-18 16:29:17.957: I/dalvikvm(91): Jit: resizing JitTable from 4096 to 8192

10-18 16:29:17.997: D/PermissionCache(36): checking android.permission.READ_FRAME_BUFFER         for uid=1000 => granted (20166 us)

10-18 16:29:17.997: W/WindowManager(91): Failure taking screenshot for (230x409) to layer 21005

10-18 16:29:18.027: D/AndroidRuntime(527): Shutting down VM

 10-18 16:29:18.067: D/dalvikvm(527): GC_CONCURRENT freed 98K, 77% free 480K/2048K, paused 1ms+1ms

10-18 16:29:18.077: I/AndroidRuntime(527): NOTE: attach of thread 'Binder Thread #3' failed

10-18 16:29:18.087: D/dalvikvm(538): Not late-enabling CheckJNI (already on)

10-18 16:29:18.128: I/ActivityManager(91): Start proc com.example.imagescreen for activity com.example.imagescreen/.MainActivity: pid=538 uid=10044 gids={1015}

10-18 16:29:18.377: W/NetworkManagementSocketTagger(91): setKernelCountSet(10044, 1) failed with errno -2

10-18 16:29:18.877: I/Process(91): Sending signal. PID: 538 SIG: 3

10-18 16:29:18.877: I/dalvikvm(538): threadid=3: reacting to signal 3

10-18 16:29:19.007: I/dalvikvm(538): Wrote stack traces to '/data/anr/traces.txt'

10-18 16:29:19.377: I/Process(91): Sending signal. PID: 538 SIG: 3

10-18 16:29:19.377: I/dalvikvm(538): threadid=3: reacting to signal 3

10-18 16:29:19.427: I/dalvikvm(538): Wrote stack traces to '/data/anr/traces.txt'

10-18 16:29:19.657: D/gralloc_goldfish(538): Emulator without GPU emulation detected.

10-18 16:29:19.737: I/ActivityManager(91): Displayed com.example.imagescreen/.MainActivity: +1s717ms

10-18 16:29:20.367: W/NetworkManagementSocketTagger(91): setKernelCountSet(10013, 0) failed with errno -2

10-18 16:29:20.387: W/InputManagerService(91): Starting input on non-focused client com.android.internal.view.IInputMethodClient$Stub$Proxy@412e7248 (uid=10013 pid=189)

10-18 16:29:22.233: D/ExchangeService(391): Received deviceId from Email app: androidc259148960

10-18 16:29:22.233: D/ExchangeService(391): Reconciling accounts...

10-18 16:29:36.067: D/dalvikvm(538): GC_FOR_ALLOC freed 113K, 4% free 6680K/6919K, paused 76ms

10-18 16:29:36.097: I/dalvikvm-heap(538): Grow heap (frag case) to 8.153MB for 1639696-byte allocation

10-18 16:29:36.157: D/dalvikvm(538): GC_CONCURRENT freed 3K, 4% free 8278K/8583K, paused 6ms+4ms

10-18 16:30:10.347: W/ThrottleService(91): unable to find stats for iface rmnet0

my bitmap:
public void saveBitmap(Bitmap bitmap) {
    try {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
        File f = new File(Environment.getExternalStorageDirectory()
                + File.separator + "test.jpg");
        f.createNewFile();
        FileOutputStream fo = new FileOutputStream(f);
        fo.write(bytes.toByteArray());
        fo.close();
    } catch (FileNotFoundException e) {
        Log.e("GREC", e.getMessage(), e);
    } catch (IOException e) {
        Log.e("GREC", e.getMessage(), e);
    }
}

A: try it -
 // take screenshot
 public Bitmap takeScreenshot() {
      View v1 = getWindow().getDecorView().getRootView();
     v1.setDrawingCacheEnabled(true);
     return Bitmap.createBitmap(v1.getDrawingCache());
  }

save image
File fn;
public void onSnapshotReady(Bitmap bitmap) {
   // TODO Auto-generated method stub
    bitmap
    try {
    File sampleDir = new File(Environment.getExternalStorageDirectory(), "/ScreenShots");
   // Created directory if not exist
   if(!sampleDir.exists()){
   sampleDir.mkdirs();
   }
   Date d=new Date();
  fn=new File(sampleDir+"/"+"Screenshot"+d.getTime()+".png");
  FileOutputStream out = new FileOutputStream(fn);
  bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
  Toast.makeText(getApplicationContext(), "Screenshot saved at - "+sampleDir+"!!!",Toast.LENGTH_SHORT).show();
  } catch (Exception e) {
  e.printStackTrace();
  }
}

A: public void saveBitmap(Bitmap bitmap) {

          try {

              ByteArrayOutputStream bytes = new ByteArrayOutputStream();
              bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);

              SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
              String currentDateandTime = sdf.format(new Date());
              File f = new File(Environment.getExternalStorageDirectory()
                 + File.separator+ (currentDateandTime+".jpg") );

              f.createNewFile();
              FileOutputStream fo = new FileOutputStream(f);
              fo.write(bytes.toByteArray());
              fo.close();
          } catch (FileNotFoundException e) {
              Log.e("GREC", e.getMessage(), e);
          } catch (IOException e) {
              Log.e("GREC", e.getMessage(), e);
          }


text:
Q: Python - Vectoring or Efficient way of Creating an Upper Triangular Matrix and Stack it I'd like to know if someone knows a vectoring or more efficient way (reducing time and memory consuming) of creating an upper triangular matrix, which the rows are delayed versions (shifted arrays) of the first one. I've already seen this topic but is there another way? I'll appreciate so much!
Let's introduce the problem: suppose my matrix A is like (I'm using numpy.array to create it):
[[ 5  6  7  8  9 10 11 12]
 [ 4  5  6  7  8  9 10 11]
 [ 3  4  5  6  7  8  9 10]
 [ 2  3  4  5  6  7  8  9]
 [ 1  2  3  4  5  6  7  8]]

And I want a new matrix with more R=4 columns, A_extended, like:
[[ 1  2  3  4  |  5  6  7  8  9 10 11 12]
 [ 0  1  2  3  |  4  5  6  7  8  9 10 11]
 [ 0  0  1  2  |  3  4  5  6  7  8  9 10]
 [ 0  0  0  1  |  2  3  4  5  6  7  8  9]
 [ 0  0  0  0  |  1  2  3  4  5  6  7  8]]

So, I need to create an upper triangular matrix and after to stack it to the original matrix. The stacking is not necessary the problem, but if there are another ways more efficient of stacking as well, I'll thank you.
Obs.: I'm assuming that A in the example above is R+1=5 rows of a bigger matrix, let's say: (M,Dr) = B.shape, which in real context, Dr is in the order of 10^6 and M=m(R+1) (m and R are integers), which m ranges from 32 to 128 and R from 8 to 16.
My code:
A_extended = np.hstack((np.zeros((m*(R+1), R)), B))

for i in range(m)):
    # A = B[i*(R+1):(i+1)*(R+1), :]
    temp_array = B[i*(R+1) + R, R:2*R]

    for r in range(R + 1):
        A_extended[i*(R + 1) + r, r:R] = temp_array[:R-r]


text:
Q: Hadamard theorem about embedding The following theorem is commonly attributed to Jacques Hadamard.

Assume $\Sigma$ is a smooth locally convex immersed surface in the Euclidean space. Then $\Sigma$ is embedded and bounds a convex set.

Many authors refer to Hadamard's Sur certaines propriétés des trajectoires en Dynamique (1897)
(for example, James Stoker in his Über die Gestalt der positiv... (1936)).
Likely the statement is there, but the paper is long, it is in French and often the statements are not clearly marked; I was searching for it for several days. I asked a friend and she said that it was there 20 years ago, but she could not find it; she also said that it was not easy to extract it from what is written ( = one has to think). [For sure the word immersion is not there.]
I hope someone here knows this paper and can help me.
P.S. Now I see it this way: Stoker was the first who had formulated and proved the theorem; at the beginning of his paper he attributed the theorem to Hadamard because it almost follow from item 23 in his paper. After Stoker everyone did the same.

A: I think the relevant location is item 23, page 352, but what Hadamard aims to is stated as follows:

A smooth, co-orientable surface of $\mathbb{R}^3$ with Gauss curvature bounded below by some $\kappa >0$ is simply connected. (implicitly, the surface is compact without boundary)

("Or une surface à deux côtés et sans points singuliers, à courbure partout positive (la valeur zéro et les valeurs infiniment petites étant exclues) est toujours simplement connexe.")
The goal is to use the Gauss-Bonnet Formula to deduce that when curvature is positive, any two closed geodesics must meet (otherwise they would together bound a total curvature 0 region of the surface).
What is not clear from the text of item 23 is whether the surface assumed to be immersed or embedded. He basically says that the normal map is a global diffeomorphism, because positive curvature makes it a covering of the sphere.
It seems the argument does provide the statement attributed to this paper, although it seems not explicitly stated. Second edit: Mohammad Ghomi gives an argument to that effect in comment.


text:
Q: MongoDB Multiple documents update with Positional Array index Having a collections as below:

   [{
        "_id" : ObjectId("5ee111e541050ba2728adb3f"),
        "User" : "user1",
        "applications" : ["test1", "test2","test3"]
    },
    {
        "_id" : ObjectId("5ee111e541050ba2728adb40"),
        "User" : "user2",
        "applications" : ["test1", "test3","test2"]
    }]

Expected Output:

[{
        "_id" : ObjectId("5ee111e541050ba2728adb3f"),
        "User" : "user1",
        "applications" : ["test1", "test2Updated","test3"]
    },
    {
        "_id" : ObjectId("5ee111e541050ba2728adb40"),
        "User" : "user2",
        "applications" : ["test1", "test3","test2Updated"]
    }]

Used Below Query:

db.getCollection('testUser').update({"applications":"test2"},
{$set:{"applications.$[elem]":"Test2Updated"}},
{ "arrayFilters": [{ "elem": "test2" }], "multi": true })

Not working in MongoDB 3.4
Any Solutions to make it work on MongoDB 3.4 could be helpful

A: As arrayFilters was only introduced after 3.6 you need to do it in two update operations, We can use .bulkWrite() to achieve this in one DB call.
Query :
db.collection.bulkWrite([
  /** First push `test2Updated` element to applications array where `test2` exists */
  {
    updateMany: {
      filter: { applications: "test2" },
      update: { $push: { applications: "test2Updated" } }
    }
  },
  /** Remove `test2` from applications */
  {
    updateMany: {
      filter: { applications: "test2" },
      update: { $pull: { applications: "test2" } }
    }
  }
]);

Note :
Since we can't use $set + $unset both on array field at same time we've split this into two ops.
Also if you've multiple test2 elements in same applications array use $pullAll to pull all of them out but you can't insert equivalent no.of test2Updated elements as you don't know how many test2's exist for a document in that case you need to individually read docs to code and update applications array(I guess this is not the case).
One other thing is test2Updated will not be pushed to same index at which test2 is but I guess this is not that important.


text:
Q: Wordpress setup: wp-config and content transfer Can I delete the wp-config-sample.php after I save it as wp-config.php?
Also, is there a way I can transfer all my content from my old web pages which are not in a database to Wordpress, instead of manually adding all the content page by page? Keep in mind that I'm adding Wordpress to my GoDaddy hosting account.

A: Yes you can delete the sample configuration file if you want to.
You could theoretically write a script to take the content from your pages and insert them into Wordpress, but depending on the number of pages and the diversity of the structure/content of the pages it may be more worthwhile to do it manually.

A: Yes you can delete the file. There is no harm in it as the file name says its just a sample file.
Well copying the content from your old web pages is a tiring job. And as Ghills said its not an easy task to write a script to move the content as there are lot of other jobs involved when you write a post. Example : Categories, Tags, images etc.
Also you cannot trust the script completely as you will be moving a HTML content and dont know how wordpress editor will accept it.
Its better to o it manually.

A: Of course you can delete the file, because it is a sample. Most people rename it to just wp-config.php and modify it, but if you went through the graphical interface, there is no harm.
As for transferring, since you are making a static-to-live transfer, it is recommended to do this by hand so you will not make any errors with a script.
Although this is a hassle, the next time you need to move it, there are scripts as well as setups for a WordPress-to-WordPress transfer, WordPress-to-Typepad transfer, etc.


text:
Q: Rendering Sonata Admin Twig Files Variable Form Not Found I'm working on a custom controller/function in symphony2/sonata admin panel. I want to render the file using:
return $this->render('SonataAdminBundle:CRUD:base_list.html.twig', array('entities' => $entities));

I get the error
Variable "form" does not exist in SonataAdminBundle:CRUD:base_list.html.twig

Hers the line in the twig:
{{ form_widget(form.getChild(filter.formName).getChild('type')) }}

Thanks.

A: You also have to pass the form view to render.
return $this->render('SonataAdminBundle:CRUD:base_list.html.twig', array('entities' => $entities, 'form' => $form->createView()));

A: I think you know that you need to pass the form to the view.
So I guess you haven't the form.
You need to work in the controller of the corresponding admin class (sonata) to render the Datagrid form. Otherwise, you need to rewrite the whole logic.
That includes all the form building/processing using (or not) the DatagridMapper.
You should keep in mind that forms and lists represent the main components of sonata-admin (same for every admin panel), and although they are based on symfony forms, it represent a fully customised behavior.
So, for use sonata, you need to be in a sonata context.
(In this case, of one of their CRUD actions)


text:
Q: kubectl exec vs ssh using bastion KOPS lets us create a Kubernetes cluster along with a bastion that has ssh access to the cluster nodes
With this setup is it still considered safe to use kubectl to interact with the Kubernetes API server?
kubectl can also be used to interact with shell on the pods? Does this need any restrictions?
What are the precautionary steps that need to be taken if any?
Should the Kubernetes API server also be made accessible only through the bastion?

A: Deploying a Kubernetes cluster with the default Kops settings isn't secure at all and shouldn't be used in production as such. There are multiple configuration settings that can be done using kops edit command. Following points should be considered after creating a Kubnertes Cluster via Kops:

*

*Cluster Nodes in Private Subnets (existing private subnets can be specified using --subnets with the latest version of kops)

*Private API LoadBalancer (--api-loadbalancer-type internal)

*Restrict API Loadbalancer to certain private IP range (--admin-access 10.xx.xx.xx/24)

*Restrict SSH access to Cluster Node to particular IP (--ssh-access xx.xx.xx.xx/32)

*Hardened Image can also be provisioned as Cluster Nodes (--image )

*Authorization level must be RBAC. With latest Kubernetes version, RBAC is enabled by default.

*The Audit logs can be enabled via configuration in Kops edit cluster.

kubeAPIServer:
auditLogMaxAge: 10
auditLogMaxBackups: 1
auditLogMaxSize: 100
auditLogPath: /var/log/kube-apiserver-audit.log
auditPolicyFile: /srv/kubernetes/audit.yaml

A: Kops provides reasonable defaults, so the simple answer is : it is reasonably safe to use kops provisioned infrastructure as is after provisioning.


text:
Q: Boolean argument error in Ruby I am working on POODR's chapter 8, Combining Objects with Composition. However, I can't seem to make the example work:
class Bicycle
  attr_reader :size, :parts

  def initialize(args = {})
    @size  = args[:size]
    @parts = args[:parts]
  end

  def spares
    parts.spares
  end
end

require 'forwardable'
class Parts
  extend Forwardable
  def_delegators :@parts, :size, :each
  include Enumerable

  def initialize(parts)
    @parts = parts
  end

  def spares
    select { |part| part.needs_spare }
  end
end

require 'ostruct'
module PartsFactory
  def self.build(config, parts_class = Parts)
    parts_class.new(
      config.collect do |part_config|
        create_part(part_config)
      end
    )
  end

  def self.create_part(part_config)
    OpenStruct.new(
      name:        part_config[0],
      description: part_config[1],
      needs_spare: part_config.fetch(2, true)
    )
  end
end

When I use road_config:
road_config =
  [['chain',        '10-speed'],
   ['tire_size',    '23'],
   ['tape_color',   'red']]

road_bike =
  Bicycle.new(
    size:  'L',
    parts: PartsFactory.build(road_config)
  )

p road_bike.spares.size

road_bike.spares.size returns 3. Which is what I expected. However, when I use mountain_config:
mountain_config =
  [['chain',        '10-speed'],
   ['tire_size',    '2.1'],
   ['front_shock',  'Manitou', false],
   ['rear_shock',   'Fox']]

mountain_bike =
  Bicycle.new(
    size:  'L',
    parts: PartsFactory.build(mountain_config)
  )

p mountain_bike.spares.size

I was expecting to see 4, not 3. If I delete false from front_shock to let it to the default value (true), mountain_bike.spares.size returns 4.
Why false makes mountain_bike.spares.size return 3? What am I missing?

A: Because it doesn't need a spare - in your parts class, you are selecting the parts that need a spare:
def spares
  select { |part| part.needs_spare }
end

That code will return the parts that need spares (i.e. needs_spare is true). The false in the config for front_shock sets this to false. Try setting other parts' needs_spare value to false to see what I mean.


text:
Q: Put quotes around string before first forward slash in line by line file read I am writing a bash script that deletes all the files whose paths are given in delete.txt. delete.txt is thousands of lines long, each line has a path that is structured like this:
Abies concolor/images/FV-GFVM-725_crop.jpg

Where there is a space in the name of the first directory.
Currently, my bash script reads each line of delete.txt, saves it to$line and deletes it.
#!/bin/bash

while IFS='' read -r line || [[ -n "$line" ]]; do
    "rm $line"
done < "$1"

However, because there is a space in the first directory name, my rm command returns:
rm Abies concolor/images/FV-GFVM-725_crop.jpg: No such file or directory

What can I do in my bash script to add a quote before the first and after the second words of each line before doing the rm command?

A: The problem is with rm invocation. Just correctly quote line variable:
#!/bin/bash

while IFS='' read -r line || [[ -n "$line" ]]; do
   rm "$line"
done < "$1"

Or, even simpler, you can use xargs and this oneliner which replaces the complete script:
cat delete.txt | xargs -I{} rm '{}'

This will run rm for each line in delete.txt, properly quoted. The trick here is to use -I <placeholder> option which will make sure the command rm '<placeholder>' is executed once per line (not word), each time substituting <placeholder> with filename from current line.


text:
Q: Cannot change input language in jTextField Why can't I switch input language in jtextfield and JOptionPane.showInputDialog()?
On my computer I can, but on other computer I can write only system locale language symbols.
Ctrl+Shift or Ctrl+Alt+Shift is not working in application, but it is working when app is not focus
Locale.setDefault(Locale.ENGLISH); //tried it
System.setProperty("user.language", "en"); // and it

private void showPasswordWindow() {

    String pass = JOptionPane.showInputDialog(null, "Enter password", "Secure", JOptionPane.WARNING_MESSAGE);
    if (pass == null)
        System.exit(0);
    if (!pass.contains("somepassword"))
        showPasswordWindow();
}

Not working (( password contain English symbols and I can't to enter password (only Russia symbols working)
JRE 8;
PS: I want to enter English symbols, but I can type only Russian symbols...NOT WORKING ONLY DIALOG TEXTFIELDS

A: You should change the Locale:
textField.getInputContext().selectInputMethod(Locale.ENGLISH);

EDIT
Maybe it's not the best option, but you can try override the default DocumentFilter for the JtextField and change the encoding:
class EnglishTextField extends JTextField {

    public EnglishTextField() {
        ((AbstractDocument)getDocument()).setDocumentFilter(new DocumentFilter(){
            @Override
            public void insertString(DocumentFilter.FilterBypass fb, int offset,
                    String text, AttributeSet attr) throws BadLocationException {
                try {
                    //TODO change to your current encoding
                    byte[] bytes = text.getBytes("ISO-8859-1");
                    fb.insertString(offset, new String(bytes, "UTF-8"), attr);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

A: There are two issues here.
The first is entering the symbols. This isn't really a Java problem, so much as an issue with installing a different language for the keyboard.
The second issue is displaying foreign language symbols. You may need to use a UTF font to display characters that otherwise don't display right

A: Finally...i did it O_O
frame.setVisible(true);

solved the problem, but i can't understand why??..
p.s. without the code on my comp app working nice


text:
Q: in Emacs, what's the best way for keyboard-escape-quit not destroy other windows? EDIT: I understand there is keyboard-quit (which is normally bound to C-g); but I'm more interested to know about how one deals with editing functions that come with Emacs (like in this case). I run into this kind of situations from time to time when I want to change just a little bit of some build-in functions.
In emacs, when you hit M-ESC ESC (or ESC three times), you can get out of a lots of situations like transient-mark, etc. But I habitually hit the escape key (I actually remap this to a single hit of the escape key) more than I intended, and that ends up killing my windows configuration, which is quite annoying. The function  keyboard-escape-quit is defined in simple.el:
(defun keyboard-escape-quit ()
  "Exit the current \"mode\" (in a generalized sense of the word).
This command can exit an interactive command such as `query-replace',
can clear out a prefix argument or a region,
can get out of the minibuffer or other recursive edit,
cancel the use of the current buffer (for special-purpose buffers),
or go back to just one window (by deleting all but the selected window)."
  (interactive)
  (cond ((eq last-command 'mode-exited) nil)
    ((> (minibuffer-depth) 0)
     (abort-recursive-edit))
    (current-prefix-arg
     nil)
    ((and transient-mark-mode mark-active)
     (deactivate-mark))
    ((> (recursion-depth) 0)
     (exit-recursive-edit))
    (buffer-quit-function
     (funcall buffer-quit-function))
    ((not (one-window-p t))
     (delete-other-windows))
    ((string-match "^ \\*" (buffer-name (current-buffer)))
     (bury-buffer))))

And I can see that I don't want the lines:
    ((not (one-window-p t))
     (delete-other-windows))

But what is the best way to modify this function? I can see only two ways: 1) modify simple.el 2) copy this function to my .emacs file and do the modifications there. Both ways are not really good; ideally I would like to see something on the line of defadvice, but I can't see how I can do it in this case.

A: I usually find that 'keyboard-quit (C-g) works to get out of all of those situations.
However, if you really want to have a variant of this function, I think that copying to your .emacs file (and renaming, I usually usa a prefix of bp) and making the edits there is probably the best option.
EDIT, in response to edit: In general, whenever I want an edited version of an emacs function, I either write it myself, or copy it to my .emacs, rename it bp-whotever and then do appropriate edits.
The downside of this is that my .emacs is HUGE, and probably extra-crufty with ancient functions that are nolonger used... the upside is that whenever I need to write something new, I've got tons of sample code to look at...

A: Here's another, simpler piece of advice that takes advantage of the fact that keyboard-escape-quit calls buffer-quit-function before closing windows:
(defadvice keyboard-escape-quit
  (around keyboard-escape-quit-dont-close-windows activate)
  (let ((buffer-quit-function (lambda () ())))
    ad-do-it))

Works with Emacs 25.1. (I originally used @scottfrazer's advice, but it's unhappy in 25.1. Haven't bothered debugging yet.)

A: You could use around advice and redefine the offending function to do what you want (i.e. one-window-p should always return t):
(defadvice keyboard-escape-quit (around my-keyboard-escape-quit activate)
  (let (orig-one-window-p)
    (fset 'orig-one-window-p (symbol-function 'one-window-p))
    (fset 'one-window-p (lambda (&optional nomini all-frames) t))
    (unwind-protect
        ad-do-it
      (fset 'one-window-p (symbol-function 'orig-one-window-p)))))

This kind of acts like a (let ...) but has to be more complicated because you need to override a function for a limited scope instead of a variable.

A: A single press of the Escape key, by default, acts as a Meta prefix key; that is, a keybinding which involves the Meta key.
Triple-pressing the Escape key will run keyboard-escape-quit, which is like keyboard-quit but with more of a "do what I mean" behaviour.
This code may help with your use case. You can use this in your Emacs init file:
;;; esc always quits
(define-key minibuffer-local-map [escape] 'minibuffer-keyboard-quit)
(define-key minibuffer-local-ns-map [escape] 'minibuffer-keyboard-quit)
(define-key minibuffer-local-completion-map [escape] 'minibuffer-keyboard-quit)
(define-key minibuffer-local-must-match-map [escape] 'minibuffer-keyboard-quit)
(define-key minibuffer-local-isearch-map [escape] 'minibuffer-keyboard-quit)
(global-set-key [escape] 'keyboard-quit)

A:
I'm more interested to know about how one deals with editing functions that come with Emacs (like in this case). I run into this kind of situations from time to time when I want to change just a little bit of some build-in functions.

This is exactly the purpose for which I created the library el-patch. You would put this in your init-file:
(el-patch-defun keyboard-escape-quit ()
  "Exit the current \"mode\" (in a generalized sense of the word).
This command can exit an interactive command such as `query-replace',
can clear out a prefix argument or a region,
can get out of the minibuffer or other recursive edit,
cancel the use of the current buffer (for special-purpose buffers),
or go back to just one window (by deleting all but the selected window)."
  (interactive)
  (cond ((eq last-command 'mode-exited) nil)
    ((> (minibuffer-depth) 0)
     (abort-recursive-edit))
    (current-prefix-arg
     nil)
    ((and transient-mark-mode mark-active)
     (deactivate-mark))
    ((> (recursion-depth) 0)
     (exit-recursive-edit))
    (buffer-quit-function
     (funcall buffer-quit-function))
    (el-patch-remove
      ((not (one-window-p t))
       (delete-other-windows)))
    ((string-match "^ \\*" (buffer-name (current-buffer)))
     (bury-buffer))))

A: Here's a new way using cl-lib instead of cl which is now deprecated:
;; Make it so keyboard-escape-quit doesn't delete-other-windows
  (defadvice keyboard-escape-quit
      (around keyboard-escape-quit-dont-delete-other-windows activate)
    (cl-letf (((symbol-function 'delete-other-windows)
               (lambda () nil)))
      ad-do-it))

You'll need to make sure prior to it you have called:
(require 'cl-lib)


text:
Q: Time consumption in comparing two text files in java? I have two different large text files z and xz each of in size MB.Comparing the z text file content with xz text file content if any content matches write it to a new text file output.
It takes lots of time time to verify and it does not write to output file.
How to write to output file?
public class CompareTwo {
    static int count1 = 0;
    static int count2 = 0;

    static String arrayLines1[] = new String[countLines("C:/Users/THAKUR SANTHOSHI/Desktop/z.txt")];
    static String arrayLines2[] = new String[countLines("C:/Users/THAKUR SANTHOSHI/Desktop/xz.txt")];

    public static void main(String args[]) {
        findDifference("C:/Users/THAKUR SANTHOSHI/Desktop/z.txt", "C:/Users/THAKUR SANTHOSHI/Desktop/xz.txt");
        try {
            displayRecords();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static int countLines(String File) {

        int lineCount = 0;
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(File));
            while ((br.readLine()) != null) {
                lineCount++;
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return lineCount;
    }

    public static void findDifference(String File1, String File2) {
        String contents1 = null;
        String contents2 = null;
        BufferedReader buf1 = null;
        BufferedReader buf2 = null;
        try {
            FileReader file1 = new FileReader(File1);
            FileReader file2 = new FileReader(File2);
            buf1 = new BufferedReader(file1);
            buf2 = new BufferedReader(file2);

            while ((contents1 = buf1.readLine()) != null) {
                arrayLines1[count1] = contents1;
                count1++;
            }

            while ((contents2 = buf2.readLine()) != null) {
                arrayLines2[count2] = contents2;
                count2++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (buf1 != null) {
                try {
                    buf1.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (buf2 != null) {
                try {
                    buf2.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    public static void displayRecords() throws IOException {
        // true = append file
        File file = new File("D:/out.txt");
        FileWriter fileWritter = new FileWriter(file.getName(), true);
        BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
        for (int i = 0; i < arrayLines1.length; i++) {
            String a = arrayLines1[i];
            for (int j = 0; j < arrayLines2.length; j++) {
                String b = arrayLines2[j];
                boolean result = a.equals(b);
                if (result == true) {
                    if (a != null && !a.trim().isEmpty()) {
                        bufferWritter.write(a);
                        bufferWritter.flush();
                        System.out.println(a + " Copied.");
                    }
                }
            }
        }
        bufferWritter.close();
    }
}


text:
Q: subspace of $L^2$ Let $(X,B(X),\mu)$ a measurable space, for a positive finite measure $\mu$, we consider $H=L^2(X,d\mu)$, Let $A$ a closed subspace of $H$, we know that $A$ is a hilbert space, can we say that it exist a positive measure $\mu'$ such that $A=L^2(X,d\mu')$ ?
For example can we say that Hardy space $\mathbb{H}^2(\mathbb{T})$ is a $L^2$ space

A: If $B$ is an orthonormal basis for the Hilbert space $A$ then $A$ is isomorphic to $L^2(\#)$, where $\#$ is counting measure on $B$. (Commonly known as $\ell^2(B)$.) So yes, every Hilbert space is an $L^2$ space.
Can we make it $L^2(\nu)$ where $\nu$ is some measure on $X$? Yes, but not in any interesting way - $X$ has a subset with the same cardinality as $B$. This is really irrelevant; the measure doesn't really have anything to do with $X$ or $\mu$.


text:
Q: Eliminate ssh login delay I would like to remove the delay that occurs with ssh when logging in from my intranet but retain the delay when logging in from the internet.
Is this possible?

A: Problem often occurs when reverse dns lookup enabled by SSDH. Try to use 'UseDNS no' in config.

A: use ssh-keys to authenticate yourself from the intranet machines.
your password-based authentication runs on the client against the keys you are using. once that is done, there will be no delay when authenticating against the server (sshd_config MaxStartups)


text:
Q: Changing a index of pandas.dataframe or pandas.series object by iterating over it i am trying to change a index of my pandas.series object.
My approach:
for i, val in freq_values.iteritems():
    if i == ' ':
        freq_values[i] = 'Empty String'

I tried also with iloc function to select the index i wanna change, but that didnt work out.
Is it even possible or do I have to append it to a new list?
Greetings


text:
Q: JTextField enable DnD, but not able to edit I want to be able to drag and drop a selection from a JList to a JTextField, however i do not want the person to be able to edit the text from the object after it has been put into the textfield.  I got the DnD to move,but only if the textfield is enabled, but if i do:
JTextField field = new JTextField(10);
field.setEnabled(false);

Then i can no longer drop the object into the textfield, also i only want one object to be in the field at a time,which is why i am not dragging into another JList.

A: One way: make the JTextField non-focusable via field.setFocusable(false);
This will allow the field to accept text but not allow the user to actually obtain its focus, preventing him from typing into the field.
Proof of concept code:
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;

import javax.swing.*;
import javax.swing.text.JTextComponent;

@SuppressWarnings("serial")
public class DragAndDropTest extends JPanel {
    private static final String[] LIST_DATA = {"One", "Two", "Three", "Four",
            "Five", "Six", "Seven", "Eight", "Nine", "Ten"};

    private JList<String> list = new JList<>(LIST_DATA);
    private JTextField textField = new JTextField(10);

    public DragAndDropTest() {
        list.setVisibleRowCount(6);
        textField.setFocusable(false); // *** here we go! ***
        textField.setTransferHandler(new MyTransferHandler());
        list.setPrototypeCellValue("abcdefghijkl");
        list.setDragEnabled(true);

        add(new JScrollPane(list));
        add(textField);
    }

    private class MyTransferHandler extends TransferHandler {
        @Override
        public int getSourceActions(JComponent c) {
            return COPY_OR_MOVE;
        }

        @Override
        public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
            if (Arrays.asList(transferFlavors).contains(DataFlavor.stringFlavor)) {
                return true;
            } else {
                return false;
            }
        }

        @Override
        public boolean importData(TransferSupport support) {
            // allow the JTextField's text to be *replaced* on drop
            try {
                String text = (String) support.getTransferable().getTransferData(DataFlavor.stringFlavor);
                ((JTextComponent) support.getComponent()).setText(text);
                return true;
            } catch (UnsupportedFlavorException | IOException e) {
                return false;
            }
        }
    }

    private static void createAndShowGui() {
        JFrame frame = new JFrame("DragAndDrop");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new DragAndDropTest());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}


text:
Q: Obtaining a non-rectangular dock area in Qt I am trying to achieve the below layout. Basically the idea is to achieve a non-rectangular dock area (in blue).
From my reading of the documentation in https://doc.qt.io/archives/qt-4.8/qmainwindow.html#details, under the arrangement of the QMainWindow, the toolbar always expands throughout the entire bottom of the QMainWindow.
Is there a way to obtain this non-rectangular layout?


text:
Q: how do I control the order of child controls when adding to my parent control? I have a panel (call it main_box) and I add about 20 more panels inside of it. Each of the child panels is placed right under the one above it. When I resize the form, the child panels change size (like I want them to), but they don't reposition themselves inside the parent box, so I need to do that manually.
I am trying:
Dim vert_pos as integer = 0
For Each o As Object In main_box.Controls
    o.location = New Point(0, vert_pos)
    vert_pos += o.height
Next

but the child boxes get positioned out of order. They do not appear in the same order that I added them to the parent box.
How can I ensure that they are repositioned in order?

A: What I ended up doing was creating an array; and each time I added a child panel to the main_box, I also added it to the array. Then I just iterate through the array instead of the main_box.controls and the order stays correct.


text:
Q: scroll animation trigger complete handler twice This scroll animation trigger the complete handler twice..
$('html,body').stop().animate({
    scrollTop : 100
}, {
    duration : 600,
    complete : function(){
        console.log('scroll complete');
    }
});

If you remove either html or body in the selector the scroll animation loose its cross browser support...

A: The animation is triggered on both elements, firing the complete handler for both elements.
You can use a promise to avoid it
$('html,body').stop()
              .animate({scrollTop : 100}, 600)
              .promise()
              .done(function() {
                  console.log('scroll complete');
              });


text:
Q: i cant parse the json data here this code was working and then suddenly after another test it didtn work and said that the json contains html elements like  and i cant make it work again i need help
<?php

include("config.php");

if(isset($_POST["email"]) && isset($_POST["username"]) && isset($_POST["password"])){
    $email = $_POST["email"];
    $username = $_POST["username"];
    $password = $_POST["password"];
}

$con = mysqli_connect(DATABASE_HOST, DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_NAME);

$response = array();

$statement = mysqli_prepare($con, "SELECT * FROM accounts WHERE email = ? OR username = ?");
mysqli_stmt_bind_param($statement, "ss", $email, $username);
$result = mysqli_stmt_execute($statement);
$rows = $result->num_rows;

if($rows > 0){
    $response["success"] = false;
    $response["message"] = "Email or Username already exists.";
}else{
    mysqli_stmt_close($statement);
    $statement2 = mysqli_prepare($con, "INSERT INTO accounts (email, username, password) VALUES (?, ?, ?)");
    mysqli_stmt_bind_param($statement2, "sss", $email, $username, $password);
    $result2 = mysqli_stmt_execute($statement2);
    $rows2 = $result2->affected_rows;

    if($rows2 > 0){
        $response["success"] = true;
        $response["message"] = "Account created successfuly.";
    }else{
        $response["success"] = false;
        $response["message"] = "Creation error.";
    }
}

echo json_encode($response);

mysqli_close($con);

?>

when i parse it in andoid it says to me that it contains a something thas is no a string .. and this is my android code for parsing the json
private void register() {
        Response.Listener<String> responselistener = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonresponse = new JSONObject(response);
                    boolean success = jsonresponse.getBoolean("success");
                    String message = jsonresponse.get("message").toString();
                    if(success){
                        Intent gotoContinueRegisterActivityIntent = new Intent(RegisterActivity.this, ContinueRegisterActivity.class);
                        startActivity(gotoContinueRegisterActivityIntent);
                    }else {
                        error.setText(message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };
        Response.ErrorListener errorListener = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error2) {
                error2.printStackTrace();
            }
        };
        RegisterRequest registerRequest = new RegisterRequest(s_email, s_username, s_password, responselistener, errorListener);
        RequestQueue requestQueue = Volley.newRequestQueue(getBaseContext());
        requestQueue.add(registerRequest);
    }

A: You're best to actually send headers to let your android app know that it's receiving json as it probably thinks it's getting the Content Type: text/html.
Try placing this header at the top of your PHP script:
<?php
header("Content-Type: application/json");


text:
Q: Returning invalid view from JSF action method shows warning in the facelet, but how could I detect it earlier? I have a JSF 2.3 application.
In my LoginBean, the username and password entered by the user are varified and then the user is redirected to the URL initially inquired: for example if the user inquires:
http://myhostname/admin/manage.jsf
then because every resource under http:///admin requires authentication, the user is first redirected to the logon view, something like
http://myhostname/login/login.jsf
and then, upon successful authentication, they are redirected to their initially inquired URL  (in this case, the first URL above)
However, if the initially inquired URL  is a view that does not exist, i.e.
http://myhostname/admin/nonExisting.jsf
after the user gets authenticated, nothing happens: He / she is neither shown an error page, nor an erroneous log entry is made in the logs. Just the user remains on the login page.
How could I solve this?!
I added  an error handling in the facelet like this:
<p:growl id="messages" autoUpdate="true" showDetail="true" />

and then, for the logon button:
<p:commandButton action="#{loginBean.login}" value="Log In" update="@form"/>

Now, when a non-existing view is returned, I do see the warning message:

but how coul I handle it earlier?


text:
Q: Weird LED laptop screen flickering after replacement I have a 3 years old Toshiba Satellite L750D. A couple of days ago it's screen started having random noisy horizontal bars on the screen (some noises for 1-2 seconds, then nothing for minutes, then noises again). After I rebooted, the screen backlight died completely. So I called a service where I got informed that LED screens don't have inverters or any other source of backlight problems, other than the backlight itself going out, and that backlight can't be replaced separate from the screen, so I would have to buy a new screen. Last week I went to the service, bought one and had them install it.
Ever since then, when I move the lid at around 90 degrees, or lift the laptop with the lid open at that position, I often (not always) get this annoying flickering (whole screen going black for a split second, sometimes 2-3 times in a row). For first I suspected cable malfunction, but I could also hear a strange, soft electric noise during these blackouts.
Yesterday I took it back to the service. Cables were OK, after a quick look they didn't know what the problem was. It seemed to them like something with the lid switch was going on which clearly wasn't, given that it's a magnetic sensor near the touchpad and has no interaction with the open lid. And now a couple of minutes ago, when I disconnected the charger cable, it went off (with noise) for like 2 seconds, then back on again, so I'm afraid it might even be a motherboard issue.
Any information/help would be appreciated.

A: when I move the lid at around 90 degrees, or lift the laptop with the lid open at that position.

I could also hear a strange, soft electric noise during these blackouts

AFAIK, It could be due to cable/connection problem only.
You can find the same answer in some other similar questions:

*

*My Laptop Screen keeps flickering

*Lenovo G530 laptop screen flicker

*Screen laptop display flickering

*Laptop Screen Blackout / Flicker issue; Works fine on External Monitor


text:
Q: Python -GTTS-Twilio - text message mp3 I am attempting to use gtts to generate an audio file of text I am passing in as a variable ( eventually I will be scraping the text to be read, but not in this script, that is why I am using a variable) and I want to text myself the .mp3 file I am generating. It is not working though - here is my code. Any idea how to text message an .mp3 file with twilio?
    import twilio
from gtts import gTTS
from twilio.rest import Client
accountSID = '********'
authToken = '****************'
twilioCli = Client(accountSID, authToken)
myTwilioNumber = '*******'
myCellPhone = '*****'
v = 'test'

#add voice
tts = gTTS(v)
y = tts.save('hello.mp3')
message = twilioCli.messages.create(body = y, from_=myTwilioNumber, to=myCellPhone)

this is the error i get, but the link it directs me to does not speak to texting mp3 audio files:
     raise self.exception(method, uri, response, 'Unable to create record')
twilio.base.exceptions.TwilioRestException:
[31m[49mHTTP Error[0m [37m[49mYour request was:[0m

[36m[49mPOST /Accounts/********/Messages.json[0m

[37m[49mTwilio returned the following information:[0m

[34m[49mUnable to create record: The requested resource /2010-04-01/Accounts/********/Messages.json was not found[0m

[37m[49mMore information may be available here:[0m

[34m[49mhttps://www.twilio.com/docs/errors/20404[0m

A: Twilio developer evangelist here.
You can't send an mp3 file as the body of a text message. If you do send a body, it should be a string.
You can deliver mp3 files as media messages in the US and Canada. In this case you need to make the mp3 file available at a URL. Then you set that URL as the media_url for the message, like this:
message = twilioCli.messages.create(
  from_=myTwilioNumber,
  to=myCellPhone,
  media_url="http://example.com/hello.mp3"
)

I recommend reading through the documentation on sending media via MMS and what happens to MIME types like mp3 in MMS.


text:
Q: Mount volume into Docker container and see changes on host system I would like changes made within a container to be visible on the host system. How do I do that?
This is the docker-compose.yml I am using right now:
version: '3'
services:
  timfoto:
    build: .
    command: bash -c "bundle exec middleman s"
    volumes:
      - .:/myapp
    ports:
      - "4567:4567"

And my Dockerfile:
FROM ruby:2.5.3
RUN apt-get update -qq && apt-get install -y build-essential nodejs
ADD Gemfile .
ADD Gemfile.lock .
RUN bundle
VOLUME ["/myapp"]
WORKDIR myapp
EXPOSE 4567

A: You seem to have what's required to share files and file-changes between the host and container. What is written in the /myapp directory inside container should be visible outside of the container, on the host.
For this to function, you need to make sure:

*

*On Windows you must share the host-folder in the Docker For Windows Settings

*At times relative paths have given me headaches when specifying the host-part of the volume directive. Consider using absolute paths here.


text:
Q: spRbind SpatialPolygonDataFrames with different fields I'm trying to append two SpatialPolygonDataFrames that have different fields. I've been using spRbind and have created unique row ids for each data frame using spChFIDs. But I still get the following error.
Error in rbind(deparse.level, ...) :
  numbers of columns of arguments do not match
An example is block-level shapefile date from NHGIS for the states of Missouri and Illinois. Missouri has 17 fields and Illinois has 18.
Missouri:
OGR data source with driver: ESRI Shapefile
Source: "../nhgis0030_shapefile_tl2010_290_block_2010", layer: "MO_block_2010"
with 343565 features
It has 17 fields
Illinois:
OGR data source with driver: ESRI Shapefile
Source: "../nhgis0030_shapefile_tl2010_170_block_2010", layer: "IL_block_2010"
with 451426 features
It has 18 fields
Integer64 fields read as strings:  ALAND10 AWATER10

A: You can use the bind method from the raster package for this
As always, first set up some example data (you should have include some in your question):
library(raster)
# example data
p <- shapefile(system.file("external/lux.shp", package="raster"))
p
#class       : SpatialPolygonsDataFrame
#features    : 12
#extent      : 5.74414, 6.528252, 49.44781, 50.18162  (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
#variables   : 5
#names       : ID_1,     NAME_1, ID_2,   NAME_2, AREA
#min values  :    1,   Diekirch,    1, Capellen,   76
#max values  :    3, Luxembourg,    9,    Wiltz,  312

p1 <- p[p$NAME_2=='Mersch', ]
p2 <- p[p$NAME_2=='Diekirch', ]
p3 <- p[p$NAME_2=='Remich', ]

# remove all fields for p1
p1 <- as(p1, 'SpatialPolygons')
# remove one field for p3
p3$NAME_1 <- NULL
# add a new field
p3$newfield <- 25

Now we have the example data, use bind to combine the three SpatialPolygon* objects:
x <- bind(p1, p2, p3)

data.frame(x)
#  ID_1   NAME_1 ID_2   NAME_2 AREA newfield
#1   NA     <NA> <NA>     <NA>   NA       NA
#2    1 Diekirch    2 Diekirch  218       NA
#3    2     <NA>    7   Remich  129       25


text:
Q: Postgres how can I merge 2 separate select queries into 1 I am using postgres 9.4 and I would like to merge 2 separate queries into one statement. I been looking at this How to merge these queries into 1 using subquery post but still can't figure out how to work it. These 2 queries do work independently. Here they are
# 1:  select * from votes v where v.user_id=32 and v.stream_id=130;

#2: select city,state,post,created_on,votes,id as Voted from streams
where latitudes >=28.0363 AND 28.9059>= latitudes  order by votes desc limit 5 ;

I would like query #2 to be limited by 5, however I don't want query #1 to be included in that limit so that up to 6 rows could be returned in total. This works like a suggestion engine where query #1 has a main thread and query #2 gives up to 5 different suggestions however they are obviously located in a different table.

A: Having no model and data I simulated this problem with dummies of both in this SQL Fiddle.
CREATE TABLE votes
(
   id smallint
   , user_id smallint
);

CREATE TABLE streams
(
   id smallint
   , foo boolean
);

INSERT INTO votes
VALUES (1, 42), (2, 32), (3, 17), (4, 37), (5, 73), (6, 69), (7, 21), (8, 18), (9, 11), (10, 15), (11, 28);

INSERT INTO streams
VALUES (1, true), (2, true), (3, true), (4, true), (5, true), (6, true), (7, false), (8, false), (9, false), (10, false), (11, false);

SELECT
  id
FROM
  (SELECT id, 1 AS sort FROM votes WHERE user_id = 32) AS query_1
  FULL JOIN (SELECT id FROM streams WHERE NOT foo) AS query_2 USING (id)
ORDER BY
  sort
LIMIT 6;

Also I have to point out, that this isn't my work entirely, but an adaptation of this answer I came across the other day. Maybe this is an approach here too.
So, what's going on? Column id stands for any column your tables and sub-queries will have in common. votes.user_id I made to have sth. to select in the one sub-query and streams.foo in the other.
As you demanded to have 6 rows at the most I used the limit clause twice. First in the sub-query just in case there is a huge amount of rows in your table you don't want to select and again in the outer query to finally restrict the number of rows. Fiddle about a little on the two limits and toggle WHERE foo and WHERE NOT foo and you see why.
In the first sub-query I added a sort column like it is done in that answer. That's because I guess you want the result of the first sub-query always on top too.