text:
Q: How to properly build a dictionary when .txt file has the key and values on pairs of consecutive lines? Code:
trans_file = open("textabbv.txt", "r")
def text_translate(user_input):
    user_input = input("Please enter your text: ")
    textdict = {}
    for line in trans_file:
        readline(line)
        line = line.split(":")
        line = line.strip('\n')

Contents of textabbv.txt:

r:
  are
  y:
  why
  u:
  you
  ttyl:
  talk to you later
  l8:
  late
  brb:
  be right back
  lol:
  laughing out loud
  bbl:
  be back later
  tl;dr:
  too long; didn't read
  rofl:
  rolling on floor laughing
  gtg:
  got to go
  cya:
  see you
  cuzz:
  because
  bff:
  best friend forever
  bffs:
  best friends forever
  idk:
  I don't know
  sup:
  what's up?
  omg:
  oh my gosh
  nbd:
  no big deal
  tisnf:
  this is not fair
  nw:
  no way!
  rus:
  are you serious?
  myob:
  mind your own business
  njoy:
  enjoy
  nter:
  enter
  1ce:
  once
  aka:
  also known as
  afk:
  away from keyboard
  jk:
  just kidding
  asap:
  as soon as possible
  app:
  application
  atm:
  at the moment
  b4:
  before
  fyi:
  for your information
  bday:
  birthday
  k:
  okay
  msg:
  message
  np:
  no problem
  pic:
  picture
  plz:
  please
  sry: sorry
  dunno:
  don't know
  @:
  at
  wut:
  what
  wuts:
  what's

A: You can try this:
abbvs = []
with open("textabbv.txt") as file:
    for line in file:
        line = line.strip().strip(":")
        abbvs.append(line)

pairs = dict([tuple(abbvs[i:i+2]) for i in range(0, len(abbvs), 2)])

print(pairs)

Output:
{'l8': 'late', 'r': 'are', 'ttyl': 'talk to you later', 'u': 'you', 'y': 'why'}

If you don't want to use with, just do this:
abbvs = []
for line in open("textabbv.txt").readlines():
    line = line.strip().strip(":")
    abbvs.append(line)

pairs = dict([tuple(abbvs[i:i+2]) for i in range(0, len(abbvs), 2)])
print(pairs)

Can even do this to handle uneven lines in files:
try:
    abbvs = []
    with open("textabbv.txt") as file:
        for line in file:
            line = line.strip().strip(":")
            abbvs.append(line)

    pairs = dict([tuple(abbvs[i:i+2]) for i in range(0, len(abbvs), 2)])

    print(pairs)

except ValueError:
    print("Uneven number of lines in txt file found")

A: Here you have a quick oneliner:
>>> f = open(r"c:/tests/test.txt", "r")
>>> xlines = iter(f.readlines())
>>> {k.rstrip("\n").rstrip(":"):v.strip("\n") for k, v in zip(xlines,xlines)}
{'pic': 'picture', 'np': 'no problem', 'aka': 'also known as', 'k': 'okay', 'nw': 'no way!', 'sry: sorry': 'dunno:', 'myob': 'mind your own business', 'bffs': 'best friends forever', 'afk': 'away from keyboard', 'tisnf': 'this is not fair', '1ce': 'once', 'jk': 'just kidding', 'tl;dr': "too long; didn't read", 'ttyl': 'talk to you later', 'bff': 'best friend forever', 'asap': 'as soon as possible', 'njoy': 'enjoy', 'nter': 'enter', 'r': 'are', 'atm': 'at the moment', 'what': 'wuts:', 'gtg': 'got to go', 'cuzz': 'because', 'cya': 'see you', 'rofl': 'rolling on floor laughing', 'app': 'application', 'u': 'you', 'y': 'why', 'lol': 'laughing out loud', 'nbd': 'no big deal', 'brb': 'be right back', 'bbl': 'be back later', 'b4': 'before', 'omg': 'oh my gosh', 'fyi': 'for your information', 'at': 'wut:', 'rus': 'are you serious?', 'l8': 'late', 'msg': 'message', 'sup': "what's up?", "don't know": '@:', 'plz': 'please', 'idk': "I don't know", 'bday': 'birthday'}

A: Your problem basically boils down to reading two lines at a time, which has been answered here. So the solution for your file is:
import pprint

def text_translate():
    result = {}
    with open('textabbv.txt', 'r') as f:
        for line in f:
            key = line.strip().strip(':')
            value = f.next().strip()
            result[key] = value
    return result

abbrvs = text_translate()
pprint.pprint(abbrvs)

with next(f) instead of next for Python 3.
Note that if there is odd number of lines in the file, f.next() will raise a StopIteration exception, which should be handled explicitly in this case.


text:
Q: How to add calendar event in react-native? What is the best way to add a calendar event in React native? Is there an api out of the box or I need to use a third party npm packages.
I have looked into the api docs of react-native on following link but could not find anything about calendar.
https://reactnative.dev/docs/accessibilityinfo

redpajama_set_name: RedPajamaStackExchange


text:
Q: How are local variables referenced in closures? I am reading an article (JavaScript Closures for Dummies) and one of the examples is as follows.
function buildList(list) {
  var result = [];
  for (var i = 0; i < list.length; i++) {
    var item = 'item' + list[i];
    result.push( function() {alert(item + ' ' + list[i])} );
  }
  return result;
}

function testList() {
  var fnlist = buildList([1,2,3]);
  // using j only to help prevent confusion - could use i
  for (var j = 0; j < fnlist.length; j++) {
    fnlist[j]();
  }
}

testList();

When testList is called, an alert box that says "item3 undefined".  The article has this explanation:

When the anonymous functions are called on the line fnlist[j](); they all use the same single closure, and they use the current value for i and item within that one closure (where i has a value of 3 because the loop had completed, and item has a value of 'item3').

Why does item have a value of 'item3'?  Doesn't the for loop end when i becomes 3?  If it ends shouldn't item still be 'item2'?  Or is the variable item created again when testList calls the functions?

A: You're close...

Why does item have a value of 'item3'? Doesn't the for loop end when i becomes 3?

Yes.

If it ends shouldn't item still be
  'item2'?

Nope. This example is a little tricky. During the last iteration of the loop, i is 2, but it references the 3rd element of the list array, which is 3. In other words, item == 'item' + list[2] == 'item3'

Or is the variable item created again when testList calls the functions?

No, you were almost right the first time.  I think you just missed that item[2] has the value of 3.

A: The for loop within buildList completes before you do the following:
for (var j = 0; j < fnlist.length; j++) {
  fnlist[j]();
}

... therefore, by that time (when you call each function), the variable item will be whatever was last assigned to it (i.e. "item3"), and i will be 3 (as a result of the last i++ operation), and list[3] is undefined.
It's all to do with the fact that the loop completes before you call the closure'd function. To prevent this, you could create a new closure, like so:
function buildList(list) {
  var result = [];
  for (var i = 0; i < list.length; i++) {
    var item = 'item' + list[i];
    result.push(
        (function(item, i){
            // Now we have our own "local" copies of `item` and `i`
            return function() {
                console.log(item + ' ' + list[i])
            };
        })(item, i)
    );
  }
  return result;
}

A: The list variable is stored in closure as you say.
Actually you can access the list variable, but you are trying to access list[3]. After all, the i variable is also stored as a closure and it's value is 3 when the console.log function is called.

A: I think the point you are missing is that list[i] is underfined because i is 3, and list is only defined for 0..2.

A: The loop ends when i becomes 3, but the "item" variable stored in the closure, and displayed by alert, is set to
var item = 'item' + list[i];

the text 'item' + the value at list[2]. The third list item is 3, so the text is item3


text:
Q: Using find_all in BeautifulSoup I am trying to extract more than one URL and description from a website to download pictures from it, and i was able to get it to output the first link and description, but i am confused where i should go from here to get the rest of the sets. My code to get the first link is below.
import requests
from bs4 import BeautifulSoup
import urllib
import csv
import time

URL = 'https://www.baps.org/vicharan'
content = requests.get(URL)

soup=BeautifulSoup(content.text, 'html.parser')

f = csv.writer(open('crawler.csv' , 'w'))
f.writerow(['description' , 'full_link'])

panelrow = soup.find('div' , {'class' : 'panelrow'})

main_class =  panelrow.find_all('div' , {'class' : 'col-xl-3 col-lg-3 col-md-3 col-sm-12 col-xs-12 padding5'})

individual_classes = panelrow.find('a' , {'class' : 'highslidooo'})

for link in individual_classes.find_all('img'):
    links=link.get('src')
    full_link = 'https://www.baps.org' + links
    description = link.get('alt')
    f.writerow([description , full_link])

print('--------------------')
print(full_link)
print(description)

A: I think your issue is that you are not using find_all and find correctly.  Take a look at the documentation for them and some examples.
find finds the FIRST match only.  So your individual_classes variable will only have one link in it
find_all gets a container of ALL of the matches, which you can iterate.
So one recommendation is to look at the length of your results to see how they are doing along the way.  try:
len(panelrow)
len(main_class)
# etc...

and see how it is going.  sometimes a good pattern is to find a collection of outer containers with find_all and then use find within that to get the first result or such....  In a nested fashion.  something like this will probably work for you:
groups = soup.find_all(...)
for group in groups:
    link = group.find(...)


text:
Q: Strange behavior with string interning in Java There is code as following:
String s = new String("1");
s.intern();
String s2 = "1";
System.out.println(s == s2);

String s3 = new String("1")+new String("1");
s3.intern();
String s4 = "11";
System.out.println(s3 == s4);

Output of the code above is:
false
true

I know that s and s2 are different objects, so the result evaluates to  false, but the second result evaluates to true. Can anyone tell me the difference?

A: Here's what's happening:

Example 1
String s1 = new String("1");
s1.intern();
String s2 = "1";

*

*The string literal "1" (passed into the String constructor) is interned at address A.
String s1 is created at address B because it is not a literal or constant expression.

*The call to intern() has no effect. String "1" is already interned, and the result of the operation is not assigned back to s1.

*String s2 with value "1" is retrieved from the string pool, so points to address A.

Result: Strings s1 and s2 point to different addresses.

Example 2
String s3 = new String("1") + new String("1");
s3.intern();
String s4 = "11";

*

*String s3 is created at address C.

*The call to intern() adds the string with value "11" at address C to the string pool.

*String s4 with value "11" is retrieved from the string pool, so points to address C.

Result: Strings s3 and s4 point to the same address.

Summary
String "1" is interned before the call to intern() is made, by virtue of its presence in the s1 = new String("1") constructor call.
Changing that constructor call to s1 = new String(new char[]{'1'}) will make the comparison of s1 == s2 evaluate to true because both will now refer to the string that was explicitly interned by calling s1.intern().
(I used the code from this answer to get information about the strings' memory locations.)

A: For the scenario 1:
String s = new String("1");
s.intern();
String s2 = "1";
System.out.println(s == s2);

with bytecode:
   0: new           #2                  // class java/lang/String
   3: dup
   4: ldc           #3                  // String 1
   6: invokespecial #4                  // Method java/lang/String."<init>":(Ljava/lang/String;)V
   9: astore_1
  10: aload_1
  11: invokevirtual #5                  // Method java/lang/String.intern:()Ljava/lang/String;
  14: pop
  15: ldc           #3                  // String 1

for String s = new String("1"); it will create a new String object, it will have a new address with "1" that it is already in String Pool:
ldc           #3                  // String 1
and for s2, as the bytecode:
15: ldc           #3                  // String 1
s2 is pointing to String Pool variable: "1", so s and s2 have the different address and  result is false.
For the scenario 2:
String s3 = new String("1")+new String("1");
s3.intern();
String s4 = "11";
System.out.println(s3 == s4);

with bytecode:
   0: new           #2                  // class java/lang/StringBuilder
   3: dup
   4: invokespecial #3                  // Method java/lang/StringBuilder."<init>":()V
   7: astore_1
   8: aload_1
   9: ldc           #4                  // String 1
  11: invokevirtual #5                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
  14: ldc           #4                  // String 1
  16: invokevirtual #5                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
  19: invokevirtual #6                  // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
  22: astore_2
  23: aload_2
  24: invokevirtual #7                  // Method java/lang/String.intern:()Ljava/lang/String;
  27: astore_3
  28: ldc           #8                  // String 11

As the bytecode, you can see new String("1")+new String("1"); is created by using StringBuilder
new           #2                  // class java/lang/StringBuilder
it's totally a new Object without String Pool variable.
and after s3.intern(), this method will add current s3 to the Memory String Pool and 8: aload_1.
and s4 is trying to load from
ldc           #8                  // String 11
so s3 and s4 address should equal and result is true.

A: Just for someone who use groovy, the addition info is: the behavior is different

A: s.intern() doesn't change the string s. You should have written:
    s = s.intern();


text:
Q: crash due to SocialAuth Library project I m facing problem while adding social auth library project (of google).
there are two jar files used socialauth-2.3 and socialauth-android
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.fbLogin:
        adapter = new SocialAuthAdapter(new ResponseListener()); //<----- after this it crashes
        wmbPreference = PreferenceManager.getDefaultSharedPreferences(this);
        boolean isFirstRun = wmbPreference.getBoolean("FIRSTRUN", true);
        adapter.authorize(LoginActivity.this, Provider.FACEBOOK);
        adapter.addProvider(Provider.FACEBOOK, R.drawable.apppurchase);
        break;

    case R.id.loginWithExistingAccount:
        new SignInDialog(context, typeface);
        break;
    case R.id.createNewAccount:
        new SignUpDialog(context, typeface, imeiString);
        break;

    default:
        break;
    }

}

Below is my logcat
07-15 12:05:20.498: E/AndroidRuntime(1353): FATAL EXCEPTION: main
07-15 12:05:20.498: E/AndroidRuntime(1353): Process: com.example.puzzleapplication, PID: 1353
07-15 12:05:20.498: E/AndroidRuntime(1353): android.content.res.Resources$NotFoundException: Resource ID #0x0
07-15 12:05:20.498: E/AndroidRuntime(1353):     at android.content.res.Resources.getValue(Resources.java:1123)
07-15 12:05:20.498: E/AndroidRuntime(1353):     at android.content.res.Resources.getDrawable(Resources.java:698)
07-15 12:05:20.498: E/AndroidRuntime(1353):     at org.brickred.socialauth.android.SocialAuthDialog.setUpTitle(SocialAuthDialog.java:181)
07-15 12:05:20.498: E/AndroidRuntime(1353):     at org.brickred.socialauth.android.SocialAuthDialog.onCreate(SocialAuthDialog.java:143)
07-15 12:05:20.498: E/AndroidRuntime(1353):     at android.app.Dialog.dispatchOnCreate(Dialog.java:361)
07-15 12:05:20.498: E/AndroidRuntime(1353):     at android.app.Dialog.show(Dialog.java:262)
07-15 12:05:20.498: E/AndroidRuntime(1353):     at org.brickred.socialauth.android.SocialAuthAdapter$3$1.run(SocialAuthAdapter.java:418)
07-15 12:05:20.498: E/AndroidRuntime(1353):     at android.os.Handler.handleCallback(Handler.java:733)
07-15 12:05:20.498: E/AndroidRuntime(1353):     at     android.os.Handler.dispatchMessage(Handler.java:95)
07-15 12:05:20.498: E/AndroidRuntime(1353):     at android.os.Looper.loop(Looper.java:136)
07-15 12:05:20.498: E/AndroidRuntime(1353):     at android.app.ActivityThread.main(ActivityThread.java:5017)
07-15 12:05:20.498: E/AndroidRuntime(1353):     at java.lang.reflect.Method.invokeNative(Native Method)
07-15 12:05:20.498: E/AndroidRuntime(1353):     at java.lang.reflect.Method.invoke(Method.java:515)
07-15 12:05:20.498: E/AndroidRuntime(1353):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
07-15 12:05:20.498: E/AndroidRuntime(1353):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
07-15 12:05:20.498: E/AndroidRuntime(1353):     at dalvik.system.NativeStart.main(Native Method)

Can u guys help me to tract it out
Regards

A: You have to put the name of the drawable like in the sample project:
Put:
adapter.addProvider(Provider.FACEBOOK, R.drawable.facebook);

instead of:
adapter.addProvider(Provider.FACEBOOK, R.drawable.apppurchase);

And them it will work.

A: As far as i am concert this is an error of your resource.
1.you are not properly getting view on which you are trying to set drawable that might causing
the error in next line that could be related to social auth
2.recheck your findViewbyid's first.


text:
Q: capturing a click event on Google Earth plugin Using the Google Earth Plugin in C#, I want to get clicked position on the earth; how can I do this?
using GEPlugin;

m_ge = (IGEPlugin)pluginInstance;
KmlLookAtCoClass lookAt =  m_ge.createLookAt("");
lookAt.set(35.337919, 33.321576, 0, m_ge.ALTITUDE_RELATIVE_TO_GROUND, 0, 0, 5000);

m_ge.getView().setAbstractView(lookAt);

m_ge.getLayerRoot().enableLayerById(m_ge.LAYER_ROADS, 1);

Now I want to add Click Event listener that I want to get click event.
How can this be done?

A: EDIT

The GEWebBrowser inherits from the
standard
System.Windows.Forms.WebBrowser
control class and has the same base
members, methods, properties and
events.

Because of this, you'll need to manually create bi-directional communication between this control and your C# class.
See this article for how to wire up C# to javascript events in a browser control. http://support.microsoft.com/kb/312777
Also, you may find the following C# method useful for adding javascript events to the GEWebBrowser.

Void AddEventListener(object, string,
string)
Wrapper for the the google.earth.addEventListener method
Parameters
object: The target plug-in Api object
string: The event Id
string: The name of javascript callback function to use
example: GEWebBrowser.AddEventListener(object,"click","function(event){alert(event.getType());}");

src: http://code.google.com/p/winforms-geplugin-control-library/wiki/GEWebBrowser

Not entirely sure, but perhaps one of these links will help you out.
http://fraserchapman.blogspot.com/2008/08/google-earth-plug-in-and-c.html
http://groups.google.com/group/google-earth-browser-plugin/browse_thread/thread/90dfb80960094828?pli=1
http://interactiveearth.blogspot.com/2008/01/create-your-own-google-earth.html
http://www.xtremevbtalk.com/showthread.php?t=287038

A: The problem is that the standard event handlers are part of the google.earth namespace and are not directly accessible via managed code. You need to 'relay' the events to your application via javascript and a COM visible class.
I have developed a free control library that allows you to easily embed the google earth plugin into an application.
It supports the AddEventListner and RemoveEventListner functions that you are looking for
http://code.google.com/p/winforms-geplugin-control-library/wiki/AddEventListener
It is worth noting that it does not use, as in your example, the GEPlugin Type Library - rather the dynamic type in C#4.0.  This means that it is not 'version dependent' on a particular version of the Google Earth Plugin
The main project is here
http://code.google.com/p/winforms-geplugin-control-library/


text:
Q: salesforce display data as column based series? Is there any tag like <apex:pageblockTable> but to show the rows in column order?
Ie . Currently
 Name :  Age : country

 Bharath : 25 : INDIA

 Graham  : 26 : UK

 Andrew  : 27 : US

Now the expected format is
Name :   Bharath : Graham : Andrew

Age  :     25    : 26     : 27

Country:   IND   : UK     : US

A: Though I am not aware of any component which will help you transpose your table but you can get this with some simple css and html.
Page:
<apex:page controller="TableTransposeController">

    <apex:pageBlock>

                First Name
                Last Name
                Email

            <apex:repeat value="{!allContacts}" var="c">

                    {!c.FirstName}
                    {!c.LastName}
                    {!c.Email}

            </apex:repeat>

    </apex:pageBlock>

</apex:page>
Controller:
public class TableTransposeController {

    public List getallContacts() {
        return [Select FirstNAme,LastName,Email from Contact limit 5];
    }

}
Note: I have not handled horizontal overflow of this table as I believe this kind of representation is better suited when you have many fields to show for fewer records. e.g. When you compare two cell phone features side by side.


text:
Q: Dependent column constraints Not sure if I can achieve this using a mysql constraint, but in a table like
CREATE TABLE constraint_table (
    id int PRIMARY KEY AUTOINCREMENT,
    col1 int NOT NULL,
    col2 int NOT NULL
)

is it possible to have a mysql constraint such that col2 can have duplicates for a given col1
| id | col1 | col2 |
| 1  | 1    | 1    |
| 2  | 1    | 2    |
| 3  | 1    | 1    |

but the col2 values used by a specific col1 value cannot be used by another col1 value again
| id | col1 | col2 |
| 1  | 1    | 1    |
| 2  | 1    | 2    |
| 3  | 1    | 1    |
| 4  | 2    | 1    | invalid - as 1 is included in col2 values where col1 <> 2 (need to restrict this)
| 5  | 2    | 2    | invalid - as 2 is included in col2 values where col1 <> 2 (need to restrict this)
| 6  | 2    | 4    | valid - as 4 is not included in col2 values where col1 <> 2

and the valid table should looks like
| id | col1 | col2 |
| 1  | 1    | 1    |
| 2  | 1    | 2    |
| 3  | 1    | 1    |
| 4  | 2    | 3    |
| 5  | 2    | 4    |
| 6  | 2    | 4    |

Sorry for the bad title, I'm not sure how to call this kind of scenario.

A: Have a fun!
CREATE TABLE ref_data (
  col1 INT NOT NULL,
  col2 INT NOT NULL,
  INDEX (col1),
  UNIQUE KEY (col2)
) ENGINE=INNODB;

CREATE TABLE constraint_table (
  id int NOT NULL auto_increment,
  col1 int NOT NULL,
  col2 int NOT NULL,
  PRIMARY KEY (id),
  CONSTRAINT cn_col FOREIGN KEY (col1,col2)
REFERENCES ref_data (col1,col2)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=INNODB;

A: I think you have the wrong data format.  You seem to want one value of col1 for each col2.  That suggests a table for this purpose:
create table2 (
    col2 int primary key,
    col1 int not null,
);

Then your table can be:
CREATE TABLE constraint_table (
    id int PRIMARY KEY AUTOINCREMENT,
    col2 int NOT NULL,
    . . . -- I assume there are other tables here
    foreign key (col2) references table2(col2)
);

col1 doesn't belong in this table, because it is strictly dependent on col2.  So, the pair goes in the first table -- with one row.


text:
Q: Truly Global Variable in python OK so the project I am working on requires* using a truly global variable (or five) and the other questions on here have to do with cross module variables (could be helpful later just not yet).
Here is my problem: I have a program that will be running an environmental simulation and I need to set some global variables to be used and modified inside some of the functions. How would one go about doing that?
*When I say require I mean that I haven't found a more efficient way to do this.

A: Yes, there is a way to use and modify global variables inside functions that are spread across several modules. Put the variables in a module and import that module into your main program:
# globals.py
klaatu = "Once in Persia reigned a king ..."

# main_program.py
import globals

def modify_klaatu():
    print globals.klaatu
    globals.klaatu = "It was the best of times, it was the worst of times."

A: A somewhat dodgy but entirely dynamic variant of @rob's approach:
import types
import sys

sys.modules['myglobals'] = types.ModuleType('myglobals')
sys.modules['myglobals'].__dict__.update({'first': 'thing', 'second': 'thing'})

import myglobals
print(myglobals.first) # prints 'thing'

Or if you've only got one global, how about this extremely dodgy approach:
import sys
sys.modules['myglobal'] = 'thing'

import myglobal
print(myglobal) # prints 'thing'


text:
Q: How to wrap each element of a list with no parameter lambda functions? Given a list A of any objects, I want to create another list B of lambda functions, where each B[i] () returns A[i]. For example,
B = [lambda: A[0], lambda: A[1], lambda: A[2], ...]

How can I do with for any arbitrary lengthed array A? Obviously, B = [lambda: element for element in A] does not work. What is a workaround for this?


text:
Q: knockout - cannot apply bindings multiple times to the same element I need to fill my trip table with data from two sources: from server using GET when the page loads (to have user's archive trips) and from observable values (when a user adds a new trip). Can I somehow merge those two scripts so that they apply bindings only once? Right now I get an error: You cannot apply bindings multiple times to the same element

Add a trip

        From
        <input type="text" class="form-control" id="from" name="from" placeholder="From" data-bind="value: from">

        To
        <input type="text" class="form-control" id="to" name="to" placeholder="To" data-bind="value: to">

    Add

Your trips

                From
                To

A: Give the relevant elements IDs and then apply the models to only those DOM elements.  For example,
Html:

And the binding:
ko.applyBindings(model, document.getElementById("add-trip"));

ko.applyBindings(new tripModel(), document.getElementById("your-trips"));

JSFiddle Example:
https://jsfiddle.net/hellobrett/49xaqj46/1/
JSFiddle example going the other direction:
https://jsfiddle.net/hellobrett/49xaqj46/2/
Reference:
http://knockoutjs.com/documentation/observables.html

In case you're wondering what the parameters to ko.applyBindings do,

*

*The first parameter says what view model object you want to use with    the declarative bindings it activates

*Optionally, you can pass a second parameter to define which part of    the document you want to search for data-bind attributes. For example, ko.applyBindings(myViewModel, document.getElementById('someElementId')). This restricts the activation to the element with ID someElementId and its descendants, which is useful if you want to have multiple view models and associate each with a different region of the page.


text:
Q: How to add locale in docker container I want to add locale into my container.
When I'm root on my container, and I do locale -a, I have this :
C
C.UTF-8
POSIX

I tried to add locale with this : locale-gen fr_FR.UTF-8. After I restarted container.
But when I do locale -a, I don't have fr_FR.uft8...
But I don't understant when I exit to container an do locale -a, I have fr_FR.utf8!
How can I add locale into my container?


text:
Q: Python sending header with request issue I'm having a small issue with sending a request with a custom header in order to use the fortnite tracker store within my discord bot.
The issue is that the url I get back tells me I haven't specified an API key when I open it, despite me passing it through as a header like is requested by the API.
I've tried quite a few variations of the code below e.g using requests.get rather than session.get and having the headers included within the 'r=' line but nothing seems to be working.
import requests
import discord

session = requests.Session()
session.headers.update({'TRN-Api-Key': 'Insert my API Key here'})
r = session.get('https://api.fortnitetracker.com/v1/store')
print(r.url)
imageURL = (r.url)
embed = discord.Embed()
embed.set_image(url=imageURL)
await client.say(embed=embed)


text:
Q: What happens if two non-adjacent corners of the feasible region gives optimal solution for a linear programming question? In a linear programming question, let's assume that the feasible region is a polygon. Now let's consider an objective function whose value we want to be minimised. What would happen if I get two non-adjacent points at the vertices of the polygon that gives me the least possible value (and hence the optimal solution)?
Would the line segment joining the 2 points give me the set of optimal solutions? Or will I have only two solutions? And what would happened if I get three points that give me the optimal solution? Would a triangle be my solution set?
Thanks in advance!


text:
Q: Jetpack Compose BottomSheetScaffold sheetGestures disabled but gestures still works when child component is scrollable I have a BottomSheetScaffold inside my android app that looks like the following:
 BottomSheetScaffold(
        sheetGesturesEnabled = false,
        sheetContent = { MyContent() },
        scaffoldState = bottomSheetScaffoldState,
    ) {
        ..
    }

With the sheetGesturesEnabled set to false, the sheet should not be swipeable. However, if MyContent() contains a scrollable component like LazyColumn, the swipe to close gesture can still be executed on the modal bottom sheet.
How is that possible? Is that a known bug? Is there any fix to this?

A: Looks like this is a known bug and can be tracked here -> https://issuetracker.google.com/issues/215403277
I also ran into this and needed to find a solve in the meantime so I ended up setting the sheetPeekHeight to the height of my LazyColumn. Please note, I am not proud of this.
  BottomSheetScaffold(
        scaffoldState = sheetState,
        sheetGesturesEnabled = false,
        sheetPeekHeight = if(isFixedHeight) 500.dp else BottomSheetScaffoldDefaults.SheetPeekHeight,
        sheetContent = {

           LazyColumn(
               state = listState,
               userScrollEnabled = true,
                modifier = Modifier
                .heightIn(max = 500.dp)
                ) { //items }
           }

In my implementation, I set the sheetPeekHeight conditionally because in only some cases would it need to be static and others it wouldn't.
Its not pretty but it works. I'm sure other workarounds exist but this one fit my use case the best. Just be sure to add a TODO to fix it once there is a fix for the bug published.


text:
Q: javafx application returning null when trying to set label text  clueless about this error..i am trying to set the text property of a label when i click on a button..it keeps giving this error  :

 Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
        at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1770)
        at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1653)
        at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
        at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
        at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
        at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
        at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
        at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
        at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
        at javafx.event.Event.fireEvent(Event.java:198)
        at javafx.scene.Node.fireEvent(Node.java:8390)
        at javafx.scene.control.Button.fire(Button.java:185)
        at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
        at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
        at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
        at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
        at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
        at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
        at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
        at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
        at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
        at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
        at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
        at javafx.event.Event.fireEvent(Event.java:198)
        at javafx.scene.Scene$MouseHandler.process(Scene.java:3758)
        at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3486)
        at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
        at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2495)
        at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:350)
        at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:275)
        at java.security.AccessController.doPrivileged(Native Method)
        at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$350(GlassViewEventHandler.java:385)
        at com.sun.javafx.tk.quantum.GlassViewEventHandler$$Lambda$136/128942111.get(Unknown Source)
        at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:404)
        at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:384)
        at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
        at com.sun.glass.ui.View.notifyMouse(View.java:927)
        at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
        at com.sun.glass.ui.win.WinApplication.lambda$null$145(WinApplication.java:101)
        at com.sun.glass.ui.win.WinApplication$$Lambda$38/636526176.run(Unknown Source)
        at java.lang.Thread.run(Thread.java:745)
    Caused by: java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
        at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
        at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1765)
        ... 50 more
    Caused by: java.lang.NullPointerException
        at classes.LoginController.output(LoginController.java:26)
        ... 60 more

this is the controller:
public class LoginController  {

    @FXML private Label labelOne;

    public void output(ActionEvent actionEvent) {
        labelOne.setText("HEY");
    }
}

this is the fxml code for the controls:
<Pane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="250.0" prefWidth="350.0" xmlns="http://javafx.com/javafx/8"
      xmlns:fx="http://javafx.com/fxml/1" fx:controller="classes.LoginController">
   <children>

      <TextField id="textField" layoutX="141.0" layoutY="113.0" prefHeight="25.0" prefWidth="169.0" />

      <PasswordField id="passwordField" layoutX="141.0" layoutY="161.0" prefHeight="25.0" prefWidth="169.0" />

      <Button id="loginButton" layoutX="244.0" layoutY="211.0" mnemonicParsing="false" prefHeight="25.0" prefWidth="66.0" text="Login" />
      <Button id="signupButton" layoutX="43.0" layoutY="211.0" mnemonicParsing="false" text="SignUp" onAction="#output" />

   </children>
</Pane>

i am certain this is a fairly basic problem but i'm stuck and clueless on this problem..also what is the best method i could use to connect a javafx application to a database...and what database would be the best option to embed within this application.....

A: use H2 database which is best embedded and also on localhost
and the second issue
add fx: to your ids
like


text:
Q: Ruby Bug - Segmentation fault at POINTER ruby 2.5.3 p105 I was working on upgrading a project from Rails 3.1 to rails 5.2
during this I updated Ruby Version from 2.0.0 to 2.5.3
after finishing a lot of upgrading steps I was able to run Rails server
now when I try to test APIs locally through insomnia (Postman Alternative)
I faced this error
any informations? or guidelines?
/Users/monier/.rvm/gems/ruby-2.5.3@programmer_app_2/gems/newrelic_rpm-6.7.0.359/lib/new_relic/local_environment.rb:52: [BUG] Segmentation fault at 0x0000000000000110
ruby 2.5.3p105 (2018-10-18 revision 65156) [x86_64-darwin18]

-- Crash Report log information --------------------------------------------
   See Crash Report log file under the one of following:
     * ~/Library/Logs/DiagnosticReports
     * /Library/Logs/DiagnosticReports
   for more details.
Don't forget to include the above Crash Report log file in bug reports.

-- Control frame information -----------------------------------------------
c:0026 p:---- s:0140 e:000139 CFUNC  :each_object
c:0025 p:0027 s:0135 e:000134 METHOD /Users/monier/.rvm/gems/ruby-2.5.3@programmer_app_2/gems/newrelic_rpm-6.7.0.359/lib/new_relic/local_environment.rb:52
c:0024 p:0065 s:0130 e:000129 METHOD /Users/monier/.rvm/gems/ruby-2.5.3@programmer_app_2/gems/newrelic_rpm-6.7.0.359/lib/new_relic/local_environment.rb:125
c:0023 p:0054 s:0125 e:000124 METHOD /Users/monier/.rvm/gems/ruby-2.5.3@programmer_app_2/gems/newrelic_rpm-6.7.0.359/lib/new_relic/local_environment.rb:80
c:0022 p:0009 s:0120 e:000119 METHOD /Users/monier/.rvm/gems/ruby-2.5.3@programmer_app_2/gems/newrelic_rpm-6.7.0.359/lib/new_relic/local_environment.rb:32
c:0021 p:0019 s:0116 e:000115 BLOCK  /Users/monier/.rvm/gems/ruby-2.5.3@programmer_app_2/gems/newrelic_rpm-6.7.0.359/lib/new_relic/agent/configuration/default_sourc [FINISH]

-- Ruby level backtrace information ----------------------------------------
/Users/monier/.rvm/gems/ruby-2.5.3@programmer_app_2/gems/newrelic_rpm-6.7.0.359/lib/new_relic/agent/threading/agent_thread.rb:14:in `block in create'
/Users/monier/.rvm/gems/ruby-2.5.3@programmer_app_2/gems/newrelic_rpm-6.7.0.359/lib/new_relic/agent/agent.rb:707:in `block in start_worker_thread'
/Users/monier/.rvm/gems/ruby-2.5.3@programmer_app_2/gems/newrelic_rpm-6.7.0.359/lib/new_relic/agent/agent.rb:680:in `deferred_work!'
/Users/monier/.rvm/gems/ruby-2.5.3@programmer_app_2/gems/newrelic_rpm-6.7.0.359/lib/new_relic/agent/agent.rb:661:in `catch_errors'
/Users/monier/.rvm/gems/ruby-2.5.3@programmer_app_2/gems/newrelic_rpm-6.7.0.359/lib/new_relic/agent/agent.rb:681:in `block in deferred_work!'
/Users/monier/.rvm/gems/ruby-2.5.3@programmer_app_2/gems/newrelic_rpm-6.7.0.359/lib/new_relic/agent.rb:506:in `disable_all_tracing'
/Users/monier/.rvm/gems/ruby-2.5.3@programmer_app_2/gems/newrelic_rpm-6.7.0.359/lib/new_relic/agent/agent.rb:682:in `block (2 levels) in deferred_work!'
/Users/monier/.rvm/gems/ruby-2.5.3@programmer_app_2/gems/newrelic_rpm-6.7.0.359/lib/new_relic/agent/agent.rb:928:in `connect'
/Users/monier/.rvm/gems/ruby-2.5.3@programmer_app_2/gems/newrelic_rpm-6.7.0.359/lib/new_relic/agent/agent.rb:809:in `connect_to_server'
/Users/monier/.rvm/gems/ruby-2.5.3@programmer_app_2/gems/newrelic_rpm-6.7.0.359/lib/new_relic/agent/connect/request_builder.rb:34:in `connect_payload'
/Users/monier/.rvm/gems/ruby-2.5.3@programmer_app_2/gems/newrelic_rpm-6.7.0.359/lib/new_relic/agent/configuration/manager.rb:218:in `to_collector_hash'
/Users/monier/.rvm/gems/ruby-2.5.3@programmer_app_2/gems/newrelic_rpm-6.7.0.359/lib/new_relic/agent/configuration/manager.rb:195:in `flattened'
/Users/monier/.rvm/gems/ruby-2.5.3@programmer_app_2/gems/newrelic_rpm-6.7.0.359/lib/new_relic/agent/configuration/manager.rb:195:in `inject'
/Users/monier/.rvm/gems/ruby-2.5.3@programmer_app_2/gems/newrelic_rpm-6.7.0.359/lib/new_relic/agent/configuration/manager.rb:195:in `each'
/Users/monier/.rvm/gems/ruby-2.5.3@programmer_app_2/gems/newrelic_rpm-6.7.0.359/lib/new_relic/agent/configuration/manager.rb:197:in `block in flattened'
/Users/monier/.rvm/gems/ruby-2.5.3@programmer_app_2/gems/newrelic_rpm-6.7.0.359/lib/new_relic/agent/configuration/manager.rb:197:in `each'
/Users/monier/.rvm/gems/ruby-2.5.3@programmer_app_2/gems/newrelic_rpm-6.7.0.359/lib/new_relic/agent/configuration/manager.rb:199:in `block (2 levels) in flattened'
/Users/monier/.rvm/gems/ruby-2.5.3@programmer_app_2/gems/newrelic_rpm-6.7.0.359/lib/new_relic/agent/configuration/manager.rb:199:in `instance_eval'
/Users/monier/.rvm/gems/ruby-2.5.3@programmer_app_2/gems/newrelic_rpm-6.7.0.359/lib/new_relic/agent/configuration/default_source.rb:131:in `block in dispatcher'
/Users/monier/.rvm/gems/ruby-2.5.3@programmer_app_2/gems/newrelic_rpm-6.7.0.359/lib/new_relic/local_environment.rb:32:in `discovered_dispatcher'
/Users/monier/.rvm/gems/ruby-2.5.3@programmer_app_2/gems/newrelic_rpm-6.7.0.359/lib/new_relic/local_environment.rb:80:in `discover_dispatcher'
/Users/monier/.rvm/gems/ruby-2.5.3@programmer_app_2/gems/newrelic_rpm-6.7.0.359/lib/new_relic/local_environment.rb:125:in `check_for_unicorn'
/Users/monier/.rvm/gems/ruby-2.5.3@programmer_app_2/gems/newrelic_rpm-6.7.0.359/lib/new_relic/local_environment.rb:52:in `find_class_in_object_space'
/Users/monier/.rvm/gems/ruby-2.5.3@programmer_app_2/gems/newrelic_rpm-6.7.0.359/lib/new_relic/local_environment.rb:52:in `each_object'

-- Machine register context ------------------------------------------------
 rax: 0x0000000000000100 rbx: 0x00007febe6f91ad0 rcx: 0x00007fff8d178a40
 rdx: 0x0000000000000000 rdi: 0x00007fff8d178a40 rsi: 0x00007febe6f91ad0
 rbp: 0x00007ffeedb47cf0 rsp: 0x00007ffeedb47ca8  r8: 0x0000000000000000
  r9: 0x00007febe6f91ad0 r10: 0x007fffffffffffff r11: 0x0000004000000000
 r12: 0x00007ffeedb47db0 r13: 0x0000002000000000 r14: 0x00007ffeedb47d50
 r15: 0x0000000000000000 rip: 0x00007fff6310644e rfl: 0x0000000000010206

-- C level backtrace information -------------------------------------------
0   libruby.2.5.dylib                   0x00000001022a4827 rb_vm_bugreport + 135
1   libruby.2.5.dylib                   0x000000010212b128 rb_bug_context + 472
2   libruby.2.5.dylib                   0x0000000102217e21 sigsegv + 81
3   libsystem_platform.dylib            0x00007fff6334db1d _sigtramp + 29
4   libdispatch.dylib                   0x00007fff6310644e _dispatch_mgr_queue_push + 41
5   libdispatch.dylib                   0x00007fff630fc50e _dispatch_client_callout + 8
6   libdispatch.dylib                   0x00007fff63108567 _dispatch_lane_barrier_sync_invoke_and_complete + 60
7   Security                            0x00007fff384d6661 _ZN8Security12KeychainCore14StorageManager14tickleKeychainEPNS0_12KeychainImplE + 485
8   Security                            0x00007fff382a9374 _ZN8Security12KeychainCore12KCCursorImpl4nextERNS0_4ItemE + 352
9   Security                            0x00007fff384786a1 _ZN8Security12KeychainCore14IdentityCursor4nextERNS_10SecPointerINS0_8IdentityEEE + 217
10  Security                            0x00007fff3849d1ef SecIdentitySearchCopyNext + 155
11  Security                            0x00007fff384a8504 _Z23SecItemCopyMatching_osxPK14__CFDictionaryPPKv + 261
12  Security                            0x00007fff384abd50 SecItemCopyMatching + 338
13  Heimdal                             0x00007fff4dd72f43 keychain_query + 531
14  Heimdal                             0x00007fff4dd70b8c hx509_certs_find + 92
15  Heimdal                             0x00007fff4dd2f592 _krb5_pk_find_cert + 466
16  GSS                                 0x00007fff2e74c98b _gsspku2u_acquire_cred + 619
17  GSS                                 0x00007fff2e731bbc gss_acquire_cred + 940
18  libpq.5.dylib                       0x00000001035176e3 pg_GSS_have_cred_cache + 54
19  libpq.5.dylib                       0x0000000103505eb0 PQconnectPoll + 6356
20  libpq.5.dylib                       0x0000000103503026 connectDBComplete + 231
21  libpq.5.dylib                       0x00000001035031ad PQconnectdb + 36
22  pg_ext.bundle                       0x00000001034c4181 gvl_PQconnectdb_skeleton + 17
23  libruby.2.5.dylib                   0x0000000102251a92 rb_thread_call_without_gvl + 82
24  pg_ext.bundle                       0x00000001034c415d gvl_PQconnectdb + 45
25  pg_ext.bundle                       0x00000001034c9289 pgconn_init + 121
26  libruby.2.5.dylib                   0x000000010229ee2d vm_call0_body + 557
27  libruby.2.5.dylib                   0x000000010229fb48 rb_call0 + 152
28  libruby.2.5.dylib                   0x000000010228b261 rb_funcallv + 49
29  libruby.2.5.dylib                   0x0000000102199059 rb_class_s_new + 41
30  libruby.2.5.dylib                   0x000000010229815b vm_call_cfunc + 283
31  libruby.2.5.dylib                   0x0000000102281cad vm_exec_core + 11805
32  libruby.2.5.dylib                   0x0000000102292a2e vm_exec + 142
33  libruby.2.5.dylib                   0x000000010229fb48 rb_call0 + 152
34  libruby.2.5.dylib                   0x000000010228b261 rb_funcallv + 49
35  libruby.2.5.dylib                   0x0000000102199059 rb_class_s_new + 41
36  libruby.2.5.dylib                   0x000000010229815b vm_call_cfunc + 283
37  libruby.2.5.dylib                   0x0000000102281cad vm_exec_core + 11805
38  libruby.2.5.dylib                   0x0000000102292a2e vm_exec + 142
39  libruby.2.5.dylib                   0x000000010229fd04 invoke_block_from_c_bh + 372
40  libruby.2.5.dylib                   0x000000010228dd3e rb_yield + 158
41  libruby.2.5.dylib                   0x000000010219899e rb_obj_tap + 14
42  libruby.2.5.dylib                   0x000000010229815b vm_call_cfunc + 283
43  libruby.2.5.dylib                   0x000000010228126d vm_exec_core + 9181
44  libruby.2.5.dylib                   0x0000000102292a2e vm_exec + 142
45  libruby.2.5.dylib                   0x000000010217ac61 rb_load_internal0 + 337
46  libruby.2.5.dylib                   0x000000010217b499 rb_require_internal + 1609
47  libruby.2.5.dylib                   0x000000010217acf8 rb_f_require + 24
48  libruby.2.5.dylib                   0x000000010229815b vm_call_cfunc + 283
49  libruby.2.5.dylib                   0x0000000102281cad vm_exec_core + 11805
50  libruby.2.5.dylib                   0x0000000102292a2e vm_exec + 142
51  libruby.2.5.dylib                   0x00000001021350a1 ruby_exec_internal + 177
52  libruby.2.5.dylib                   0x0000000102134f98 ruby_run_node + 56
53  ruby                                0x00000001020b4f2f main + 79


text:
Q: Adding acra.jar to the /libs folder I am trying to use ACRA in my helloacra android applications.
I read this article .
There it is written "Add the acra-4.2.3.jar from the archive (acra-4.2.3/build) in the libs folder"
But the file is being added to the "referenced libraries" instead (acra-4.2.3.jar)
I tried to move it to the libs folder but could not.
Please advise...
TIA
Guy

A: When you add any library to the /libs folder, the newer versions of ADT automatically add it to your build path. This is why you're also seeing it in Referenced Libraries. This is perfectly normal and expected behavior.


text:
Q: Parsing floating-point number and ranges separated by two periods with ANTLR 3 I am working on a parser for a DSL that has two currently 'conflicting' features:

*

*Floating-point numbers like 123.4.

*Ranges specified like ID[2..5] (ID is defined as 'a'..'z'+ and doesn't matter much. The part '[2..5]' matters most.

The test grammar that should parse it looks as follows:
grammar DotTest;

span returns [double value]
  : ID'['e=INT'..'f=INT']' { /*some code to process the values*/ $value = (double)(Int32.Parse($e.text) + Int32.Parse($f.text)); } ;

num returns [double value]
  : DOUBLE {$value = double.Parse($DOUBLE.text); } ;

INT     : '0'..'9'+ ;
DOUBLE  : '0'..'9'+'.''0'..'9'+ ;
ID      : 'a'..'z'+ ;

WS      :   ( ' ' | '\t' | '\r' | '\n' ) {$channel=HIDDEN;} ;

The problem: the rule span cannot parse its input correctly, because it conflicts with DOUBLE token. The lexer tries to match 2..5 as a DOUBLE and fails. Here is how it looks in ANTLR Works:

What will be the correct way to solve this conflict and parse the two INTs in the span correctly?
P.S. I'm using ANTLR 3 and not ANTLR 4 as I'm going to generate a C# parser, which is not currently implemented in ANTLR 4.

A: This solution (the second grammar) works fine. After I transformed the lexer rules to the following:
NUM : (INT RNG)=> INT {$type=INT;}

    | (DOUBLE)=> DOUBLE {$type=DOUBLE;}

    | INT {$type=INT;};

fragment INT :  '0'..'9'+ ;
fragment DOUBLE :   '0'..'9'+'.''0'..'9'+ ;

RNG: '..' ;

parsing of intervals like 1..2 started working smoothly.

A: The DOUBLE rule you posted above does not conflict with the .. operator since the '0'..'9'+ following the '.' contains at least one digit. The following alternate definition of DOUBLE would in fact conflict:
DOUBLE : '0'..'9'+ '.' '0'..'9'*;

I suspect you are using the interpreter in ANTLRWorks, which is known to give incorrect results in many cases.


text:
Q: Slick index causes InvocationTargetException to be thrown I have a following Slick Table definition:
class FooRecords(tag: Tag) extends Table[Foo](tag, Foo.TableName) {
  def id = column[Int]("ID", O.PrimaryKey)
  def teamId = column[Int]("TEAM_ID")
  // ... other columns
  def * = (id, teamId, /* ... */) <> ((FooRecord.apply _).tupled, FooRecord.unapply)
  def teamIdIdx = index("team_id_idx", teamId, unique = false)
}

// ...

val fooRecords = TableQuery[FooRecords]
fooRecords.ddl.createStatements.foreach(x => info(x))

If the def teamIdIdx line is commented, it works fine (but obviously no index is created). If it is not commented I get an InvocationTargetException:
 Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at scala.slick.lifted.AbstractTable$$anonfun$indexes$2.apply(AbstractTable.scala:105)
        at scala.slick.lifted.AbstractTable$$anonfun$indexes$2.apply(AbstractTable.scala:103)
        at scala.collection.TraversableViewLike$Mapped$$anonfun$foreach$2.apply(TraversableViewLike.scala:169)
        at scala.collection.TraversableViewLike$Filtered$$anonfun$foreach$4.apply(TraversableViewLike.scala:197)
        at scala.collection.IndexedSeqOptimized$class.foreach(IndexedSeqOptimized.scala:33)
        at scala.collection.mutable.IndexedSeqLike$$anon$1.foreach(IndexedSeqLike.scala:52)
        at scala.collection.TraversableViewLike$Filtered$class.foreach(TraversableViewLike.scala:196)
        at scala.collection.mutable.IndexedSeqView$$anon$1.foreach(IndexedSeqView.scala:80)
        at scala.collection.TraversableViewLike$Mapped$class.foreach(TraversableViewLike.scala:168)
        at scala.collection.SeqViewLike$$anon$3.foreach(SeqViewLike.scala:197)
        at scala.collection.generic.Growable$class.$plus$plus$eq(Growable.scala:59)
        at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:104)
        at scala.collection.ViewMkString$class.thisSeq(TraversableViewLike.scala:22)
        at scala.collection.SeqViewLike$AbstractTransformed.thisSeq(SeqViewLike.scala:37)
        at scala.collection.SeqViewLike$$anonfun$sortBy$1.apply(SeqViewLike.scala:266)
        at scala.collection.SeqViewLike$$anonfun$sortBy$1.apply(SeqViewLike.scala:266)
        at scala.collection.SeqViewLike$$anon$1.<init>(SeqViewLike.scala:195)
        at scala.collection.SeqViewLike$class.newForced(SeqViewLike.scala:195)
        at scala.collection.SeqViewLike$AbstractTransformed.newForced(SeqViewLike.scala:37)
        at scala.collection.SeqViewLike$class.sortBy(SeqViewLike.scala:266)
        at scala.collection.SeqViewLike$AbstractTransformed.sortBy(SeqViewLike.scala:37)
        at scala.slick.lifted.AbstractTable.indexes(AbstractTable.scala:105)
        at scala.slick.driver.JdbcStatementBuilderComponent$TableDDLBuilder.<init>(JdbcStatementBuilderComponent.scala:597)
        at scala.slick.driver.SQLiteDriver$TableDDLBuilder.<init>(SQLiteDriver.scala:192)
        at scala.slick.driver.SQLiteDriver$class.createTableDDLBuilder(SQLiteDriver.scala:133)
        at scala.slick.driver.SQLiteDriver$.createTableDDLBuilder(SQLiteDriver.scala:260)
        at scala.slick.driver.SQLiteDriver$.createTableDDLBuilder(SQLiteDriver.scala:260)
        at scala.slick.driver.JdbcProfile$class.buildTableSchemaDescription(JdbcProfile.scala:39)
        at scala.slick.driver.SQLiteDriver$.buildTableSchemaDescription(SQLiteDriver.scala:260)
        at scala.slick.driver.SQLiteDriver$.buildTableSchemaDescription(SQLiteDriver.scala:260)
        at scala.slick.profile.RelationalProfile$TableQueryExtensionMethods.ddl(RelationalProfile.scala:52)

I'm at "com.typesafe.slick" %% "slick" % "2.1.0" on Android 19.

A: This was due to Proguard eliminating the index method. Adjusting build.sbt with:
proguardOptions in Android ++= Seq(
  "-keep class scala.slick.lifted.**",
  // ...
}

helped.


text:
Q: How do I get each of the entries from Guava MultiMap and their corresponding values associated with it? I am reading from a huge csv file which contains duplicate entries. I was able to read the whole csv file into a Multimap. I am also able to obtain the keyset with duplicate values and write them to a file. I want to get the value associated with each of the keys and write it to a file but unable to do so. I cant seem to find any of the options that might help me. I tried using entries() method which according to the doc

Returns a view collection of all key-value pairs contained in this multimap, as Map.Entry instances

but I am unable to get anything from it.
I am using ArrayListMultiMap implementation of MultiMap. Reason for using ArrayList is that later I need to perform a search operation which is quicker in an ArrayList.
I have pstored the keyset as a MultiSet which is why I am able to get all the duplicate keys.
Value of each of the keys is an object which I want to be written to a file corresponding to that read key.

A: If you want each key and each value associated with that key, instead of each key-value pair, then you can do that with
for (Map.Entry<String, Collection<SomeClassObject>> entry : multimap.asMap().entrySet()) {
   String key = entry.getKey();
   Collection<SomeClassObject> valuesForKey = entry.getValue();
   // do whatever
}

A: As you've discovered, there are two ways to think about Multimaps. One is as a Map<K, Collection<V>>, and the other is as a Map<K, V>, where the keys do not have to be unique. In the documentation, Google stresses that the latter approach is preferred, although if you do multimap.asMap().entries() (N.B. Not just multimap.entries()), as Louis suggested, you will have entries like the former version.
For your particular problem, I'm not sure why you can't do something like the following:
for (String key : multimap.keySet()) {
    Collection<SomeClassObject> values = multimap.get(key);
    //Do whatever with all the values for Key key...
}


text:
Q: failed to get array of data in react native I'm using react native CRNA for my apps and I'm having a trouble to load array of data from API.
This is my code:
constructor(props){
    super(props);
    this.state ={
        branches: [],
        loading: false,
    }
}

componentDidMount() {
    fetch('APIurl', {
            method: 'GET',
        })
      .then((response) => response.json())
      .then((responseJson) => {
          this.setState({
          branches: responseJson.data,
          loading: true,
          })
          console.log(responseJson);
          return responseJson;
      })
        .catch(error=>{
            console.log(error);
        });
    }
}
  render(){
    return(
       <Text style={{margin: 2, alignItems: 'stretch',
                 flex:1, fontWeight: 'bold'}}>
       {this.state.branches.name}</Text>
       <Text style={{margin: 2, justifyContent: 'space-
         around', alignItems: 'stretch', flex:2,}}>
       {this.state.branches.address}</Text>
      <Picker
       selectedValue={this.state.branches.name}
       mode="dropdown"
       style={{ height: 50, justifyContent: 'space-
       around', flex:4, alignItems: 'stretch', }}
        onValueChange={(itemValue, itemIndex)=>
      this.setState({branches: key})}>
        {this.state.branches.map((branches, key)=> (
        <Picker.Item label={branches.name} value={branches.name} key=
       {branches.branch_id}/>)
        )}
     </Picker>
      <View style={{flex: 5, flexDirection:'column', alignItems: 'stretch',justifyContent: 'space-around'}}>
          <Button
            title="GO"
            titleStyle={{ fontWeight: "700" }}
            buttonStyle={{
            backgroundColor: "#5eac1a",
            width: 250,
            height: 45,
            borderColor: "transparent",
            borderWidth: 0,
            borderRadius: 25
            }}
           />);
         }
     }

The code is not showing any error when I tried to run it. But it doesn't show anything, it was like it couldn't get any data from the API. Can anyone please help me? Thank you so much..
EDIT: it doesn't show any error but a warning instead.

Each child in an array or iterator should have a unique "key" prop.

A: Inside responsejson you can do something like this.
responsejson.forEach((item)=>{

this.state.branches.push({
 branchid:item.branch_id

})

})

*

*this branch_id is from json data type.


text:
Q: Set EditorState without the application state in Draft js I want to update the Draft js Editor with some initial content. I know we can change EditorState using component state.
import React from 'react';
import ReactDOM from 'react-dom';
import {Editor, EditorState} from 'draft-js';

class MyEditor extends React.Component {
  constructor(props) {
    super(props);
    this.state = {editorState: EditorState.createEmpty()};
    this.onChange = (editorState) => this.setState({editorState});
  }
  render() {
    return (
        <Editor editorState={this.state.editorState} onChange={this.onChange} />
    );
  }
}

Whenever I tried to change something in the Editor it's re rendering. This is causing some performance issue. Is there anyway I can set or change the Editor's state without changing the state. Something similar to this
EditorState.set(editorState); //here editorState is new editor state;

Any idea how to achieve?

A: After the two days of struggle, I found one useful wysiwyg editor built on top of Draft.js with cool features. It has all the features given by Draft.js. We can load existing content using Editor's refs.
import {EditorState, convertFromRaw} from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';

class myEditor extends Component {

   componentDidMount(){
       //I have stored rawContent in  database
       let rawContent={"blocks":[{"key":"3ge2q","text":"Hello World!;","type":"header-three","depth":0,"inlineStyleRanges":[],"entityRanges":[],"data":{}}],"entityMap":{}};
       //Convert Raw to contentState
       let content=convertFromRaw(rawContent);
       let editorState=EditorState.createWithContent(content);
       this.refs.editor.editor.update(editorState); //Update the editor with updated content.
   }

    render(){
      <Editor
         ref="editor"
         wrapperClassName="demo-wrapper"
         editorClassName="template-editor"
         spellCheck={true}
         placeholder="Type something"
         onEditorStateChange={this.onEditorStateChange.bind(this)}
     />
  }
}


text:
Q: Flex (Flash Builder 4) compilation with debug=false resulting in errors that do not occur when debug=true We have a fairly large Flex application and our QA were getting random, but reproducible, errors that the Flex developers couldn't reproduce.  Some of these errors were being thrown from the flash player debug version such as:
ReferenceError: Specified ApplicationDomain does not contain the class ::LineSeriesLegendMarker
    at org.spicefactory.lib.reflect::ClassInfo$/getClassDefinitionByName()
    at org.spicefactory.lib.reflect::ClassInfo$/getClassInfo()
    at org.spicefactory.lib.reflect::ClassInfo$/forInstance()
    at org.spicefactory.parsley.core.view.impl::DefaultViewConfigurator/getDefinitionByType()
    at org.spicefactory.parsley.core.view.impl::DefaultViewConfigurator/getDefinition()
    at org.spicefactory.parsley.core.view.handler::ViewAutowireHandler/processAutowireEvent()
    at org.spicefactory.parsley.core.view.util::ContextAwareEventHandler/handleEvent()
    at org.spicefactory.parsley.core.view.handler::ViewAutowireHandler/handleAutowireEvent()
    at flash.events::EventDispatcher/dispatchEventFunction()
    at flash.events::EventDispatcher/dispatchEvent()
    at org.spicefactory.parsley.core.view.handler::ViewAutowireHandler/prefilterView()
    at flash.display::DisplayObjectContainer/addChildAt()
    at mx.core::UIComponent/http://www.adobe.com/2006/flex/mx/internal::$addChildAt()
    at mx.core::Container/addChildAt()
    at mx.core::Container/addChild()
    at mx.charts::Legend/addLegendItem()
    at mx.charts::Legend/populateFromArray()
    at mx.charts::Legend/commitProperties()
    at mx.core::UIComponent/validateProperties()
    at mx.managers::LayoutManager/validateProperties()
    at mx.managers::LayoutManager/doPhasedInstantiation()
    at mx.managers::LayoutManager/doPhasedInstantiationCallback()

Other errors include comboboxes not being populated correctly and what seems to be just general timing issues.
I'd like to emphasize that we've narrowed this down to our our main SWF with no other variables except the mxmlc parameter -debug=true vs -debug=false.  Has anyone else encountered this or know why the builds would be resulting in different behavior?

A: You're going to have to show more code than that; mostly your parsley config.
The difference between debug=true and debug=false is that debug=true will not trace errors in the end product. Your developers should always run with debug=true and have the Flash Player Debug installed.
Also, I'm curious as to why Parsley needs to know about view components.  Are you using the Configure tag?  I recommend you do not use it and instead use FastInject with proper presenter models which is better for testability.  Configure means that Parsley have to reflect all the properties within your view which is useless and time consuming.  I guarantee if you use FastInject instead of Configure that your problem would disappear.  That is unless you're trying to inject a view into a components, which you shouldn't do.  If that's the case, you'll need to architect your application in a better way.


text:
Q: windowsformhost cant load a usercontrol from another dll So I have a dll from another project which contains many useful classes and controls for me (lets call it foo.dll). I'm making an WPF app. I need to use some of them in my app. I created my usercontrol for windows forms and referenced UserControlForMe from foo.dll. It's shown, all good. Now I want to insert my usercontrol into a wpf form. It looks like this:
<UserControl x:Class="FlatRectangular_Profile.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
          xmlns:uc="clr-namespace:FlatRectangular_Profile.UC"
          Height="2093" Width="717">
    <Grid Name="grid">
        <WindowsFormsHost>
            <uc:WindowsFormsProfManual ></uc:WindowsFormsProfManual>
        </WindowsFormsHost>
    </Grid>
</UserControl>

But here I get an error "cant load type UserControlForMe from foo.dll". No info on that error. Again, UserControlForMe loads in WindowsFormsProfManual. All these is going on in one class library. I referenced everything that foo.dll needed.
No idea how what to do next. I also tried to load it in code in usercontrol.loaded event, but it fails too, and shows stacktrace which leads to the constructor of the UserControlForMe.

A: I guess you'll have to add the assembly to your namespace import to point your application in the right direction:
xmlns:uc="clr-namespace:FlatRectangular_Profile.UC;Assembly=MyDLL"

A: I found a workaround since I cant get why it is not working. If I load a UserControlForMe from foo.dll directly  to the windowsformhost, it works. But if there is a "buffer" dll, it works in this dll, but doesnt open in futher window. Also I add a UserControlForMe programmatically to a windowsformhost.


text:
Q: GREP out n rows of text between two specific strings I want to grep out >contig_18, the rows of text that follow it, and stop before >contig_19.
I do not understand how to grep the many rows of text after >contig_18 without giving the exact number of line breaks.
Ex: Note there will normally be 1000+ rows of text between contigs.
>contig_18
GCACAGACGGCCGACTTTAGAGAATCTGAGTTTGGAGCGCTGCCGGT
GAATCCAGATGACTTAACCGGCCACGTCTCCCTATGACCTGCATTTT
GAAAGAGATCTGCTTCAGATGCGATCTCCATTAGGATATCAACTTGG
CCGATCGCATCGTCGAGAGCGGAGACACGGCAGCCAACCTTCTTGAG
AGTCCTTTTCAGCTCGCGAAGGGCTTCAAGTACTTCCGGAGAGAACG
GGTCGACAAGTGGATCAGGCAAAGTTGCGATTTCCACGCGTGTCGAT
TCTGACTCGCTCATTTGATCCCCCGTGGCATTCTGCGCGGGTTGGAG
>contig_19

thanks!

A: If you have awk in your system, you can do this:
awk '/^>contig_18/ {f=1} f; /^>contig_19/ {f=0}' file

It will get all data from line starting with >contig_18 to and inclusive lines with >contig_19

You can also use this, but I like the first better since its more custom able:
awk '/^>contig_18/,/^>contig_19/' file

Or you can use sed
sed -n '/^>contig_18/,/^>contig_19/p' file

A: If you really want to use grep, you can do this:
grep -A 9999 "^>contig_18" file | grep -B 9999 "^>contig_19"

That says to find up to 9,999 lines following contig_18 and, from those, find up to 9,999 lines preceding contig_19.


text:
Q: how to do a proof for subset in Isabelle I'm trying to do some proofs  manually in Isabelle but I'm struggling with the following proof:
lemma "(A ∩ B) ∪ C ⊆ A  ∪ C "
I'm trying to transform it Propositional Logic then prove it.
So here's what I tried:
 lemma "(A ∩ B) ∪ C ⊆ A  ∪ C "
  apply (subst subset_iff)+
  apply(rule allI)
  apply (rule impI)
 (*here normally we should try to get rid of Union and Inter*)
  apply(subst Un_iff)+
  apply(subst  (asm)  Un_iff)+
  apply(subst Inter_iff) (*not working*)

I'm stuck at the last step, could someone please help me finish this proof and explain how should one find the right theorems till the end?
I use find_theorems, but it takes a lot of time + the only useful (and understandable) ressource I found so far is this link:
https://www.inf.ed.ac.uk/teaching/courses/ar/isabelle/FormalCheatSheet.pdf
and some very few random lecture notes  containing almost the same content as the link above...
Other resources I found are 100+ pages and do not look like a place to start for a beginner...
Thanks in advance

A: First writing such kind of proofs manually is not useful as it can be solved by blast. It is mostly reserved for advanced users. The only documentation I know is the old tutorial, Section 5.
Anyway, you have the wrong intersection theorems: you want to use Int_iff. Here is the full proof:

lemma "(A ∩ B) ∪ C ⊆ A  ∪ C "
  apply (subst subset_iff)+
  apply(rule allI)
  apply (rule impI)
    (*here normally we should try to get rid of Union and Inter*)
  apply(subst Un_iff)+
  apply(subst  (asm)  Un_iff)
  apply(subst (asm) Int_iff)
  apply (elim disjE)
   apply (elim conjE)
   apply (rule disjI1)
   apply assumption
  apply (rule disjI2)
  apply assumption
  done

How did would I find such proof? I know by heart the low-level theorems on implication, conjunction, and disjunction (allI, impI, conjI, conjE, disjE, disjI1,...). There is a consistent naming convention (I: intro rule, E: elimination rule, D: destruction rule), so it is not so hard to remember.
For the rest, searching with find_theorems (or the query panel) is the way to go.
Here is the proof I would write (but the other one is nicer for teaching: conjE is way more important than IntE):
lemma "(A ∩ B) ∪ C ⊆ A  ∪ C "
  apply (rule subset_iff[THEN iffD2])
  apply(intro allI impI)
  apply (elim UnE)
   apply (elim IntE)
   apply (rule UnI1)
   apply assumption
  apply (rule UnI2)
  apply assumption
  done


text:
Q: openstack devstack installation stops with Connecting Dashboard Url I was facing the below errors in OpenStack installation. Problem in connecting the dashboard URL.
Changed the url in openrc file by removing version like below http://100.1.201.102:5000/identity.
But still facing the same below issue. please let me know where exactly the error is being thrown .
INFO keystone.cmd.cli [req-412f0ceb-6b28-0bb1-b2scc-aae69e76ff7b - - - - -] Created domain default
INFO keystone.cmd.cli [req-412f0ceb-6b28-0bb1-b2scc-aae69e76ff7b - - - - -] Created project admin
DEBUG passlib.registry [req-412f0ceb-6b28-0bb1-b2scc-aae69e76ff7b - - - - -] registered 'sha512_crypt' handler: <class 'passlib.handlers.sha2_crypt.sha512_crypt'> register_crypt_handler /usr/lib/python2.7/site-packages/passlib/registry.py:284
INFO keystone.cmd.cli [req-412f0ceb-6b28-0bb1-b2scc-aae69e76ff7b - - - - -] Created user admin
INFO keystone.cmd.cli [req-412f0ceb-6b28-4bb1-b2cc-aae69e76ff7b - - - - -] Created role admin
INFO keystone.cmd.cli [req-412f0ceb-6b28-4bb1-b2cc-aae69e76ff7b - - - - -] Granted admin on admin to user admin.
INFO keystone.cmd.cli [req-412f0ceb-6b28-4bb1-b2cc-aae69e76ff7b - - - - -] Created region RegionOne
INFO keystone.cmd.cli [req-412f0ceb-6b28-4bb1-b2cc-aae69e76ff7b - - - - -] Created admin endpoint http://100.1.201.102/identity_v2_admin
INFO keystone.cmd.cli [req-412f0ceb-6b28-4bb1-b2cc-aae69e76ff7b - - - - -] Created internal endpoint http://100.1.201.102/identity
INFO keystone.cmd.cli [req-412f0ceb-6b28-4bb1-b2cc-aae69e76ff7b - - - - -] Created public endpoint http://100.1.201.102/identity
2016-09-16 10:39:01.969 | +./stack.sh:main:1038                      cat
2016-09-16 10:39:01.998 | +./stack.sh:main:1053                      is_service_enabled tls-proxy
2016-09-16 10:39:02.055 | +functions-common:is_service_enabled:2078  return 1
2016-09-16 10:39:02.064 | +./stack.sh:main:1057                      source /devstack/userrc_early
2016-09-16 10:39:02.075 | ++userrc_early:source:4                     export OS_IDENTITY_API_VERSION=3
2016-09-16 10:39:02.087 | ++userrc_early:source:4                     OS_IDENTITY_API_VERSION=3
2016-09-16 10:39:02.098 | ++userrc_early:source:5                     export OS_AUTH_URL=http://100.1.201.102/identity_v2_admin
2016-09-16 10:39:02.109 | ++userrc_early:source:5                     OS_AUTH_URL=http://100.1.201.102/identity_v2_admin
2016-09-16 10:39:02.121 | ++userrc_early:source:6                     export OS_USERNAME=admin
2016-09-16 10:39:02.133 | ++userrc_early:source:6                     OS_USERNAME=admin
2016-09-16 10:39:02.144 | ++userrc_early:source:8                     export OS_PASSWORD=secret
2016-09-16 10:39:02.156 | ++userrc_early:source:8                     OS_PASSWORD=secret
2016-09-16 10:39:02.168 | ++userrc_early:source:9                     export OS_PROJECT_NAME=admin
2016-09-16 10:39:02.181 | ++userrc_early:source:9                     OS_PROJECT_NAME=admin
2016-09-16 10:39:02.192 | ++userrc_early:source:11                    export OS_REGION_NAME=RegionOne
2016-09-16 10:39:02.204 | ++userrc_early:source:11                    OS_REGION_NAME=RegionOne
2016-09-16 10:39:02.214 | +./stack.sh:main:1059                      create_keystone_accounts
2016-09-16 10:39:02.223 | +lib/keystone:create_keystone_accounts:384  local admin_project
2016-09-16 10:39:02.235 | ++lib/keystone:create_keystone_accounts:385  openstack project show admin -f value -c id
2016-09-16 10:40:19.898 | Discovering versions from the identity service failed when creating the password plugin. Attempting to determine version from URL.
2016-09-16 10:40:19.898 | Could not determine a suitable URL for the plugin
2016-09-16 10:40:19.981 | +lib/keystone:create_keystone_accounts:385  admin_project=
2016-09-16 10:40:19.992 | +lib/keystone:create_keystone_accounts:1   exit_trap
2016-09-16 10:40:20.003 | +./stack.sh:exit_trap:487                  local r=1
2016-09-16 10:40:20.014 | ++./stack.sh:exit_trap:488                  jobs -p
2016-09-16 10:40:20.025 | +./stack.sh:exit_trap:488                  jobs=
2016-09-16 10:40:20.036 | +./stack.sh:exit_trap:491                  [[ -n '' ]]
2016-09-16 10:40:20.047 | +./stack.sh:exit_trap:497                  kill_spinner
2016-09-16 10:40:20.059 | +./stack.sh:kill_spinner:383               '[' '!' -z '' ']'
2016-09-16 10:40:20.069 | +./stack.sh:exit_trap:499                  [[ 1 -ne 0 ]]
2016-09-16 10:40:20.080 | +./stack.sh:exit_trap:500                  echo 'Error on exit'
2016-09-16 10:40:20.080 | Error on exit
2016-09-16 10:40:20.093 | +./stack.sh:exit_trap:501                  generate-subunit 1474021993 427 fail
2016-09-16 10:40:20.697 | +./stack.sh:exit_trap:502                  [[ -z /opt/stack/logs ]]
2016-09-16 10:40:20.703 | +./stack.sh:exit_trap:505                  devstack/tools/worlddump.py -d /opt/stack/logs
2016-09-16 10:40:21.394 | +./stack.sh:exit_trap:511                  exit 1


text:
Q: Conditionally compiling UI components & logic I'm looking at producing a few versions of my app with restricted functionality, and I'd like to leave out the code that is not necessary in simpler versions. Being a WinForms app, the UI will have to change for each version - not displaying the restricted controls.
I made an attempt to annotate parts of the auto generated controls & layout code with conditional compilation statements, but I discovered VS throws out all my code as soon as I touch anything via the WinForms designer.
I would like to be able to conditionally compile some event handlers & UI controls. I could write the conditional UI code outside the designer file, but then I wouldn't be able to use the VS designer to edit my app.. Are there any suggestions to remedying this situation - i.e. conditionally compile UI controls & still have them display in the designer?
Thanks!

A: Not knowing how your UI forms look like perhaps you can create a base form that all versions share in functionality. Then subclass that with forms for the specific functionality. This way you can conditionally compile the sub forms rather than trying to turn on/off controls within the one form. However the subforms will typically extend the form downwards so weaving controls throughout the form might not work in this case.
Also if you use a presentation pattern (if you are not doing so already) such as MVC or MVP you can minimize the logic you have in the forms and push that to presenter/controller or even business classes that you can configure based on the version you are compiling against. These classes can get injected (DI) into the application based on some configuration.
Another option is not to compile out the form controls but hide them based on the version you are running but have the business classes compiled. This way the important 'intellectual' code is not in the app and you're not fighting with the winform designer.


text:
Q: PHP open_basedir I'm getting the following PHP warning:
PHP Warning: is_readable(): open_basedir restriction in effect. File(/usr/share/pear//home/domain.nl/application/views/helpers/HeadLink.php) is not within the allowed path(s): (/usr/share/php:/home/domain.nl/:/usr/share/pear:/usr/sbin:/usr/bin:/bin:/tmp:/etc/phpmyadmin:/usr/lib/php4:/usr/lib/php5:/opt/ioncube/lib) in /home/domain.nl/library/Zend/Loader.php on line 186

How come /usr/share/pear//home/domain.nl/application/views/helpers/.. is not within the allowed path /usr/share/pear?
Thanks,
Martijn

A: https://bugs.php.net/bug.php?id=37476
Says is_readable throws this warning for not existing files if php is older than 5.2.
And your path looks like a not existing one. I mean probably it should start with /home/
domain.nl, and the /usr/share/pear/ part is unintentional. (Perhaps the include_path directive prepended?)


text:
Q: Refresh ao clicar na aba (Foundation) Preciso dar um refresh no conteúdo ao clicar na aba. Esse refresh terá  de ser feito na aba Conteúdo 2. Alguém consegue me ajudar.

                    Conteúdo 1

Conteúdo 2

                    Conteudo1

                    Conteudo2

A: Você pode usar a função load do jQuery, indicando como alvo a mesma página e a div. Provavelmente irá combinar com ajax de onde irá trazer o novo conteúdo.
HTML

  Conteudo2

Javascript
$('#panel2').click(function(){
  // faca algo antes
  $('#panel2').load(document.URL +  ' #panel2'); // recarrega a div
});

Foudation usa jQuery, por isso na verdade poderá usar load.


text:
Q: Python - Function not defined In python, I'm trying to make an RPG and when I do "def townbar():" it says that it's not defined.
This code is for reference to make sure that everything is making sense:
class Player:
    def __init__(self, name):
        self.name = name
        self.health2 = 100
        self.health = self.health2
        self.attack = 10

# Game
def main():
    print("Welcome player.")
    print("1. Start")
    print("2. Load")
    print("3. Exit")
    option = input("> ")
    if option == "1":
        start()
    elif option == "2":
        pass
    elif option == "3":
        sys.exit()
    else:
        main()

def start():
    print('\n' * 80)
    print("Hello, what is your name?")
    option = input("> ")
    global PlayerIG
    PlayerIG = Player(option)
    start1()

def start1():
    print('\n' * 80)
    print("Name: %s" % PlayerIG.name)
    print("Attack: %i" % PlayerIG.attack)
    print("Health: %i/%i\n" % (PlayerIG.health, PlayerIG.health2))
    print("1. Go to nearby town")
    print("2. Stand here and do nothing")
    option = input("> ")
    if option == "1":
        town()
    if option == "2":
        print("Really? This is the guy we chose to be the hero of this story?
    *sigh* Pick again.")
        start1()
    else:
        start1()

def town():
    print('\n' * 80)
    print("You arrive at the town and you see 3 signs.\n")
    print("1. Go to the bar")
    print("2. Go to the market")
    print("3. Go to the king")
    option = input("> ")
    if option == "1":
        townbar()
    elif option == "2":
        market()
    elif option == "3":
        print("The king ignores you, as you are but a peasant\n")
        town()
    else:
        town()

This is the part that gives me problems, it says that bar is not defined (it was the old name for townbar). After I changed the name and checked that everything was fine, it still shows that error.
def townbar():
    print('\n' * 80)
    print("You see many people in the bar.")
    print("1. Talk to the bartender")
    print("2. Talk to the people in the bar")
    print("3. Exit the bar")
    option = input("> ")
    if option == "1":
        print("The bartender greets you.\n")
        bartendertalk()
    elif option == "2":
        print("The people don't care enough or are too drunk to speak to
    you.\n")
        townbar()
    elif option == "3":
        town()
    else:
        townbar()

def bartendertalk():
    print('\n' * 80)
    print("Would you like to hear of the local news? [Y/N]")
    option = input("> ")
    if option == "Y":
        print("Would you like to hear the gossip or some real news?\n")
        print("1. Gossip")
        print("2. Real news")
        option2 = input("> ")
        if option2 == "1":
            print("I've heard that Ron has been cheating on Margaret with
                  Beatrice! Very sad.\n")
            bartendertalk()
        elif option2 == "2":
            print("People talk of a destroyed castle holding centuries worth
                   of gold in there, but nobody has ever explored it.")
            bartendertalk()
    if option == "N":
        print("Then why are you talking to me?\n")
        townbar()
    else:
        bartendertalk()

main()

Error:
 File "C:\Users\Leo\Documents\Loadingscreens\PyCharm Community Edition
 2017.3.2\helpers\pydev\pydevd.py", line 1668, in <module>
    main()
  File "C:\Users\Leo\Documents\Loadingscreens\PyCharm Community Edition
2017.3.2\helpers\pydev\pydevd.py", line 1662, in main
    globals = debugger.run(setup['file'], None, None, is_module)
  File "C:\Users\Leo\Documents\Loadingscreens\PyCharm Community Edition
2017.3.2\helpers\pydev\pydevd.py", line 1072, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "C:\Users\Leo\Documents\Loadingscreens\PyCharm Community Edition
2017.3.2\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/Users/Leo/PycharmProjects/RPG Project/Game File.py", line 63, in
<module>
    main()
  File "C:/Users/Leo/PycharmProjects/RPG Project/Game File.py", line 21, in
 main
    start()
  File "C:/Users/Leo/PycharmProjects/RPG Project/Game File.py", line 35, in
start
    start1()
  File "C:/Users/Leo/PycharmProjects/RPG Project/Game File.py", line 46, in
start1
    town()
  File "C:/Users/Leo/PycharmProjects/RPG Project/Game File.py", line 57, in
town
    bar()
NameError: name 'bar' is not defined

A: This is not an answer to your question .. and hence will get some downvotes before I remove it again ;o) but if you decide on using this kind of menu all over the place you should consider packing the functionality into its on function like so:
def choicer(choices, onErrorMessage):
    '''Uses a dict of choices to present a menue.
The menuChoice with key -1 is used as flavour text before
first input occures, the onErrorMessage (or if None the -1 option
is used for consecutive inputs after illegan user choice.
It returns the key of the option choosen.'''

    def flavourTextOnInput():
        '''print flavour text if present'''
        if -1 in choices.keys(): # print flavour text if given:
            print(choices[-1])

    def printMenu():
        ''' print all choices without key -1'''
        for key in choices:
            if  key != -1:
                print(key, '. ', choices[key])

    def inputNumber():
        '''ask for input, convert to int else return None'''
        num = None
        numText = input()
        try:
            num = int(numText)
        except:
            pass

        return num

    flavourTextOnInput()
    printMenu()

    c = inputNumber()
    while(c not in choices.keys()):
        if onErrorMessage:
            print(onErrorMessage)
        else:
            flavourTextOnInput()
        c = inputNumber()

    return c

And use it like this:
retVal = choicer({-1: "Howdy - what do you like to do?",   # spezial by definition
                   1: "drink beer",
                   2: "drink whisky",
                   3: "get drunk by rum",
                   4: "hit some patron"},                  # set of choices
                  "What'cha want? Too loud - not heard correctly") # onErrorMessage
# then you can handle retVar to your liking

You supply a dictionary with choices and a error message. The dict key -1 is special, it is printed as flavour text before the first input(). The onErrorMessage  is printed every time a wrong input is done. The function returns the integer key of the option that was choosen and will repeat until a valid option is inputted.
You should do an far easier function just for Y/N answers which takes a string as qestion and loops until the answer is either Y or N. Your main program will get less complicated that way and its easier to keep track of everything that is going on - preventing errors by reusing failproof functionality.
def yesNo(text):
    '''Prints text once and repeats input until first non space character
is nN or yY - returns a True if yY else False. Ignores all other inputs
then the first non space one'''
    print(text, " [Y/N]")

    c = None
    while (c not in ['Y','N']):
        c = (input().strip()[0].upper()) # use 1st non space upper case character as input
    return c == "Y" # else False

Usage:
if yesNo("Quit now?"): # please rename the functions, naming is hackish
    print("Quitting")
else:
    print("continuing")

A: If the townbar() is a function outside the class, then put it above the caller i.e town(). This should be the reason why it is saying function not defined. The callee should be defined before the caller.


text:
Q: Is OLS the frequentist approach to linear regression? In this Wikipedia article, there is this sentence:

This is a frequentist approach

Is 'this' referring to OLS?
Is it really 'a' rather than 'the'? What are some other frequentist approaches? As far as I know, we must minimize [$\varepsilon_1, \varepsilon_2, ..., \varepsilon_n$][$\varepsilon_1, \varepsilon_2, ..., \varepsilon_n$]'.
Edit: This is in relation to my previous question. Tim mentioned 'Now, to estimate logistic regression in Bayesian way...'
So, how would one do it in a frequentist way? OLS? Recalled statistics class involving linear regression. Guess there's MLE too.

A: The text from:
"The ordinary least squares solution... and y is the column n-vector"
denotes the frequentist approach to linear regression, and is generally termed "OLS".  In Bayesian regression, there is a prior on the parameters.  The often used Normal prior on the betas also has a frequentist interpretation:  ridge regression.

A: OLS by itself does not imply what type of inference (if any) is being done.
I would say it is a mere descriptive statistic.
If you assume some generative model (sampling distribution), and try to infer on the OLS coefficients, you are then free to do frequentist inference or Bayesian.

A: In the folk parlance of statistics, OLS tends to be identified as a  frequentist approach to parameter estimation because it does not explicitly involve a prior distribution on the parameters being estimated. But strictly speaking, OLS is just a mathematical operation whose result has both frequentist and Bayesian interpretations.
From a frequentist perspective, if the usual linear model assumptions hold, the OLS parameter estimates are equal to the true parameter values plus an error of known distribution derived from the randomness of sampling. This enables us to extract information about the estimates (e.g. p-values and confidence intervals) which have theoretical guarantees that limit the chance of certain types of errors attributable to random sample variation.
From a Bayesian perspective,  if the usual linear model assumptions hold, OLS provides the maximum a posteriori (MAP) parameter estimate under a uniform prior. The posterior distribution is a multivariate Gaussian with a peak at the MAP estimate, and we can use the posterior to update our prior on the parameters, or compute credible intervals if we so desire.
In general, the frequentist/Bayesian distinction is fraught with so much folk connotation and association that most statistical methods end up feeling like one or the other to practitioners. But at bottom, if this distinction has any objective meaning, it is about how you interpret probabilities, and your choice of parameter estimation method does not necessarily say anything about how you interpret probabilities. Only your interpretation of the parameter estimates can identify what side of the distinction you are (currently) working in.


text:
Q: I'm trying to copy the data from a file into an array, but the way I used not working **
I'm using a 2D array with 5 columns to store player's name, and an array to store his number (number will be concidered a string). I want to copy data of file into an array, but I'm having a problem when it reaches the 2D array. This is the only function that I'm struggling with. The rest of functions are straight forward.
**
    typedef struct {
                int id;
                char team_name[25];
                char player_name[5][10];
                char player_number[5][2]; // the player's number will be concidered a string
            }Team;
    // File content:
    /*
        1234
        Real Madrid
        Courtois 1
        Carvajal 2
        Alaba 4
        Marcelo 12
        -------------------
        5678
        Paris Saint Germain
        Hakimi 2
        Ramos 4
        Messi 30
        Neymar 10
        */
            Team  copy_data_to_array (Team info[]) {
              FILE* ptr;
              char read_line[25];
              ptr = fopen("team_info.txt", "r");
              if (ptr!=NULL)
              {
                while (!(feof(ptr))) {
                       fscanf(ptr, "%d", &info[i].id);
                       char ch = getc(ptr);
                       fgets(info[i].team_name, 25, ptr);
                       for (int i = 0; i < 5; ++i) {
                           for (int j=0; i < 1; ++j) {
                             fscanf(ptr, "%s %s", info[i].player_name[i], info[i].player_number[i]);
                           }
                       }
                      fgets(read_line, 25, ptr); // to read the  line from file
                   }
                      fclose(ptr);
                }
                else {
                    printf("File cannot be allocated...\n");
                }
            }