title
stringlengths 15
150
| body
stringlengths 38
32.9k
| label
int64 0
3
|
---|---|---|
Replace "Refresh Icon" of SwipeRefreshLayout with text | <p>It is possible with SwipeRefreshLayout to replace the "Refresh icon" with text?
Just like Twitter does:
<a href="https://i.stack.imgur.com/SQRIR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SQRIR.png" alt="enter image description here"></a></p>
<p>Or it is possible to remove the icon? When the user swipes down, the "Refresh icon" i want to be invisible.</p> | 2 |
java ternary conditions strange null pointer exception | <p>Can someone explain me why in the first case null pointer was detected, but no on the other ?</p>
<p>Maybe he always looks on the first type, but why he does so only if the condition is false..</p>
<pre><code>@Test
public void test1() {
final Integer a = null;
final Integer b = false ? 0 : a;
//===> NULL POINTER EXCEPTION
}
@Test
public void test2() {
final Integer b = false ? 0 : null;
//===>NOT NULL POINTER EXCEPTION
}
@Test
public void test3() {
final Integer a = null;
final Integer b = true ? 0 : a;
//===>NOT NULL POINTER EXCEPTION
}
@Test
public void test4() {
final Integer a = null;
final Integer b = false ? new Integer(0) : a;
//===> NOT NULL POINTER EXCEPTION
}
@Test
public void test5() {
final Integer a = null;
final Integer b = false ? a : 0;
//===>NOT NULL POINTER EXCEPTION
}
</code></pre> | 2 |
xmpp openfire push notification and logging | <p>I am building the java backend for an app (android & ios) which has a messenger function integrated. </p>
<p>I was playing around with openfire and ejabberd the last days and was wondering how i can solve my problem - I want to catch all messages from and to Server for </p>
<ol>
<li>log messages to custom history file</li>
<li>send push notifications to android & ios client when offline.</li>
</ol>
<p>Has anyone implemented something like this yet? I have read something about a xmpp proxy doing that work but i really dont know how to start.</p>
<p>thanks in advance.
- bob</p> | 2 |
Running C code using FastCGI & NGINX | <p>I am trying to run C code using FastCGI and NGINX. Right now, after following all the steps in this website: <a href="http://chriswu.me/blog/writing-hello-world-in-fcgi-with-c-plus-plus/" rel="nofollow">http://chriswu.me/blog/writing-hello-world-in-fcgi-with-c-plus-plus/</a> </p>
<p>I am at the step where I am about to spawn-fcgi. However, the system that I must use is a 32 bit system where commands such as sudo apt-get install are not supported. I tried copying over the spawn-fcgi binary from my 64 bit system and tried using that like this: <code>./spawn-fcgi -p 8000 -n hello_world</code> command but it is giving me an error saying it cannot execute the binary file (I'm assuming it is because I am for sure on a 32 bit system when trying to use it). In fact, when I executed <code>file spawn-fcgi</code> it told me that it was a 64-bit LSB executable, and as I am running it on a 32-bit system, that's why the "Cannot execute binary file" error is there.</p>
<p>What I'm wondering is if there is anyway I could run a C script using FASTCGI without calling on <code>spawn-fcgi</code> or <code>cgi-fcgi</code> or if there is anyway I could use somehow get these binaries in 32-bit. I tried searching online for 32-bit downloads of FASTCGI but it seems like fastcgi.com is broken as I am unable to access the website. </p>
<p>Please let me know if I've left out any crucial information and I'll be glad to provide it. Thanks!</p> | 2 |
Removing stopwords using NLTK in python | <p>i am using NLTK to remove stopwords from a list element.
Here is my code snippet</p>
<pre><code>dict1 = {}
for ctr,row in enumerate(cur.fetchall()):
list1 = [row[0],row[1],row[2],row[3],row[4]]
dict1[row[0]] = list1
print ctr+1,"\n",dict1[row[0]][2]
list2 = [w for w in dict1[row[0]][3] if not w in stopwords.words('english')]
print list2
</code></pre>
<p>the problem is, this not only removing the stopwords but also it is removing characters from other words e.g. from the word 'orientation' 'i' and more stopwords will be removed and further it is storing characters instead of words in the list2.
i.e. ['O', 'r', 'e', 'n', 'n', ' ', 'f', ' ', '3', ' ', 'r', 'e', 'r', 'e', ' ', 'p', 'n', '\n', '\n', '\n', 'O', 'r', 'e', 'n', 'n', ' ', 'f', ' ', 'n', ' ', 'r', 'e', 'r', 'e', ' ', 'r', 'p', 'l'.......................
while i want to store it as ['Orientation','.................... </p> | 2 |
using find sort and wc -l in the one command | <p>This is how find files using find and show the number of lines in each file</p>
<pre><code>$ find ./ -type f -name "data*.csv" -exec wc -l {} +
380723 ./data_2016-07-07-10-41-13.csv
369869 ./data_2016-07-11-10-42-01.csv
363941 ./data_2016-07-08-10-41-50.csv
378981 ./data_2016-07-12-10-41-28.csv
1493514 total
</code></pre>
<p><strong>how do I sort the results by file name?</strong> Below is my attempt, but it is not working. </p>
<pre><code>$ find ./ -type f -name "data*.csv" -exec wc -l {} + | sort
1493514 total
363941 ./data_2016-07-08-10-41-50.csv
369869 ./data_2016-07-11-10-42-01.csv
378981 ./data_2016-07-12-10-41-28.csv
380723 ./data_2016-07-07-10-41-13.csv
$ find ./ -type f -name "data*.csv" | sort -exec wc -l {} +
sort: invalid option -- 'e'
Try `sort --help' for more information.
$ find ./ -type f -name "data*.csv" -exec sort | wc -l {} +
find: wc: {}missing argument to `-exec'
: No such file or directory
wc: +: No such file or directory
0 total
$
</code></pre>
<p><strong>Can someone offer a solution and correct me so I understand it better?</strong></p>
<h2>EDIT1</h2>
<p>from <code>man sort</code></p>
<pre><code> -k, --key=POS1[,POS2]
start a key at POS1 (origin 1), end it at POS2 (default end of line). See POS syntax below
POS is F[.C][OPTS], where F is the field number and C the character position in the field; both are origin 1. If neither -t nor -b is in effect, characters in a field are counted from the begin‐
ning of the preceding whitespace. OPTS is one or more single-letter ordering options, which override global ordering options for that key. If no key is given, use the entire line as the key.
</code></pre> | 2 |
set config params from database in yii 1 | <p>I have created CRUD for global configuration parameters. I want to apply this parameters value as main config params (main.php).
I have found some way like add value of these parameters to any .inc file and perform read/write operation. Can anybody help me how can I achieve this? I am beginner in yii.</p>
<p>I have created table structure : </p>
<pre><code>global_config :
Field | Value
pageSize | 20
admin_email| [email protected]
</code></pre>
<p>main.php file as below :</p>
<pre><code>.
.
{
'params' = array(
'pageSize' => 10,
'admin_email' => '[email protected]',
);
}
</code></pre>
<p>.
.</p>
<p>I am using config file as show above, I want to change it dynamically that it should get value from database.</p>
<p>So that I can make changes in config file from front-end side. I don't need to perform open/write action on main.php</p> | 2 |
Error: cannot access java.lang.Object | <p>I am using Visual studio 2015 in which I install xamarin plugin.
I create a cross plateform project and I just want to display a message on the screen of android .However,I get the following error when I try to build: </p>
<p>Error: cannot access java.lang.Object</p> | 2 |
Fatal error: Call to undefined method User_m::get_by() in C:\xampp\htdocs\cms\application\controllers\admin\user.php on line 10 | <p><strong>I have a problem when i was login i got a error like this "Fatal error: Call to undefined method User_m::get_by() in C:\xampp\htdocs\cms\application\controllers\admin\user.php on line 10"</strong> </p>
<p><em>this is my user_m.php modal file</em>
<pre><code>class User_m extends CI_Model{
protected $_table_name = 'users';
protected $_order_by = 'name';
public $rules = array(
'email' => array(
'field' => 'email',
'label' => 'Email',
'rules' => 'trim|required|valid_email|xss_clean'
),
'password' => array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required'
)
);
public function __construct()
{
parent::__construct();
}
public function login()
{
$user = $this->get_by(array(
'email' => $this->input->post('email'),
'password' =>$this->hash($this->input->post('password'))
), TRUE);
if (count($user)) {
$data = array(
'name' => $user->name,
'email' => $user->email,
'id' => $user->id,
'loggedin' => TRUE,
);
$this->session->set_userdata($data);
}
}
public function logout()
{
$this->session->sess_destroy();
}
public function loggedin()
{
return (bool) $this->session->userdata('loggedin');
}
public function hash($string)
{
return hash('sha512', $string . config_item('encryption_key'));
}
}
</code></pre>
<p><strong>this is my view file login.php</strong></p>
<pre><code><div class="modal-header">
<h3>Log in</h3>
<p>Please log in using your credentials</p>
</div>
<div class="modal-body">
<?php echo validation_errors(); ?>
<?php echo form_open(); ?>
<table class="table">
<tr>
<td>Email</td>
<td><?php echo form_input('email'); ?></td>
</tr>
<tr>
<td>Password</td>
<td><?php echo form_password('password'); ?></td>
</tr>
<tr>
<td></td>
<td><?php echo form_submit('submit', 'Log in', 'class="btn btn-primary"'); ?></td>
</tr>
</table>
<?php echo form_close(); ?>
</div>
</code></pre>
<p><strong>this is my controller user.php</strong></p>
<pre><code> <?php
class User extends Admin_Controller{
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->data['users'] = $this->user_m->get_by();
$this->data['subview'] = 'admin/user/index';
$this->load->view('admin/_layout_main');
}
public function edit($id=NULL)
{
}
public function delete($id)
{
}
public function login()
{
$dashboard = 'admin/dashboard';
$this->user_m->loggedin() == FALSE || redirect($dashboard);
$rules = $this->user_m->rules;
$this->form_validation->set_rules($rules);
if ($this->form_validation->run()==true) {
if ($this->user_m->login() == TRUE) {
redirect($dashboard);
}else{
$this->session->set_flashdata('error', 'That email and password combination does not exit');
redirect('admin/user/login', 'refresh');
}
}
$this->data['subview'] = 'admin/user/login';
$this->load->view('admin/_layout_modal', $this->data);
}
}
</code></pre> | 2 |
Google test on bare-metal stm32 MCU | <p>I use Google test on almost all parts of my project except MCU (STM32F1) firmware. Now I want to use it for tests directly on MCU to ensure I didn't make any machine-dependent bugs, which may pass tests on x64, but fail on the MCU. Google test requires libpthread, which is obviously not present on the MCU. I use sophisticated gcc 5.2.1 toolchain, so it's <code>g++</code> should be able to build google test. System calls are also properly defined, so tests output should be successfully compiled and printed to serial console.</p>
<p>Is it possible to disable libpthread in Google test and build it for a bare-metal microcontroller? Does anyone have any experience in using unit-tests this way?</p> | 2 |
Nightwatch.js how to use the expect API to verify the page title | <p>I am trying to use only the <a href="http://nightwatchjs.org/api#expect-api" rel="noreferrer">expect API</a> of <a href="http://nightwatchjs.org/" rel="noreferrer">nightwatch.js</a> to verify an html page title, but I can't get the command right.<br>
My guess would be to either check the inner text of the 'title' element, or maybe its value, but It's not working how I would expect it.</p>
<p>If I run the following mocha test:</p>
<pre><code>describe('Open Google', function () {
var expectedTitle = 'Google';
var uri = 'https://www.google.de';
it('should assert the page title', function (browser) {
browser.url(uri);
browser.expect.element('title').to.be.present.before(2000);
browser.assert.title(expectedTitle);
});
it('should verify title.text', function (browser) {
browser.url(uri);
browser.expect.element('title').to.be.present.before(2000);
browser.expect.element('title').text.to.equal(expectedTitle);
});
it('should verify title.value', function (browser) {
browser.url(uri);
browser.expect.element('title').to.be.present.before(2000);
browser.expect.element('title').value.to.equal(expectedTitle);
});
});
</code></pre>
<p>The assert statement works as expected, but with both ways of using expect, I don't receive the page title.</p>
<p>Output is this:</p>
<pre><code>Open Google
√ should assert the page title (4787ms)
1) should verify title.text
2) should verify title.value
1 passing (12s)
2 failing
1) Open Google should verify title.text:
Expected element <title> text to equal: "Google" - Expected "equal 'Google'" but got: ""
at Context.<anonymous> (C:\temp\nightwatch-test\test\google.js:14:18)
2) Open Google should title.value:
Expected element <title> to have value equal: "Google" - Expected "equal 'Google'" but got: "null"
at Context.<anonymous> (C:\temp\nightwatch-test\test\google.js:20:18)
</code></pre> | 2 |
Opening a file based on user's input python | <p>How to open a file from the list of given files based on the user's input which is an integer </p>
<pre><code>print("Enter 1.tp.txt\n2.c17testpat.pat\n3.c432testpat.pat\n4.c499testpat.pat\n5.c1335testpat.pat\n6.c6228testpat.pat")
user = input("Enter a number")
if user == 1:
filename = "tp.txt"
elif user == 2:
filename = "c17testpat.pat"
elif user == 3:
filename = "c432testpat"
elif user == 4:
filename = "c499testpat.pat"
elif user == 5:
filename = "c1355testpat.pat"
elif user == 6:
filename = "c6288testpat.pat"
fp = open(filename)
</code></pre>
<p>is there any other way to do it in python </p>
<p>this caused NameError: name 'filename' is not defined</p> | 2 |
logstash grok pattern to parse mysql queries | <p>I have mysql slowlogs in logstash and I'm wondering if anyone has had any luck parsing the query section to try and categorize statements. I'm stuck right now trying to split up the query by words in capital letters. I'm thinking that I can at least separate the initial statement. The specific question is this: how can I filter a message like this one so that I can at least deal with each section of the query split by words in capital letters? </p>
<p>So this:</p>
<pre><code>SELECT column_one, column_two, COUNT(DISTINCT IF(column_three > 0, CONCAT('m_', column_three), CONCAT('r_', column_one))) AS tally FROM column_four WHERE ...
</code></pre>
<p>would parse into this:</p>
<pre><code>field1: SELECT column_one, column_two,
field2: COUNT(DISTINCT IF(column_three > 0,
field3: CONCAT('m_', column_three),
field4: AS tally
... etc
</code></pre>
<p>Or something similar that would allow me to further clean the query and make it indexable.</p> | 2 |
GitHub repository folder icon is black and not click-able | <p>I am new to GitHub and finding it incredibly hard to learn. I am following the instructions <a href="http://kbroman.org/github_tutorial/" rel="nofollow noreferrer">here</a> to create new repositories from an existing directory containing the project and typing <code>git init</code> ... etc. </p>
<p>However I created a repository in the wrong place and then deleted it by going into Settings at github.com. Then, when I tried to re-push the files the way I wanted it, one of the subfolders is now black (the one I had just deleted the repository for) and now not clickable - i.e. does not appear to be there. See <code>statistics_project1</code> in screenshot below.</p>
<p>It's very hard to troubleshoot a problem like this. There is no error message or explanatory text when you hover over the black sub-folder.</p>
<p>This post seems similar but I don't know. The solution looks complicated.
<a href="https://stackoverflow.com/questions/21381530/cannot-remove-submodule-from-git-repo">Cannot remove submodule from Git repo</a></p>
<p>Could someone please tell me what a black 'unclickable' folder means in a github repository?<a href="https://i.stack.imgur.com/sf7rP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sf7rP.png" alt="enter image description here"></a></p> | 2 |
Checking if there is any data entered into a range of cells using VBA in Excel | <p>I'm trying to call a Sub (New_Row) when the first empty row (minus the last column) is filled. I'm having trouble with how to reference a range of cells in the If statement toward the end. </p>
<pre><code>Sub Data_Added()
'Check if anything has been entered into the first empty row in "Data"
Dim sht As Worksheet
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range
Sheets("Data").Select
Set sht = Worksheets("Data")
Set StartCell = Range("A1").End(xlDown).Select
Worksheets("Data").UsedRange
LastRow = StartCell.SpecialCells(xlCellTypeLastCell).Row
LastColumn = StartCell.SpecialCells(xlCellTypeLastCell).Column
Set InputRange = sht.Range(StartCell, sht.Cells(LastRow + 1, LastColumn - 1))
If InputRange Is Not Nothing Then
Call New_Row
End If
End Sub
</code></pre>
<p>I've seen people using the Application.Intersect method, but I'm not sure if an intersect makes sense for just one row of cells. Totally new to VBA, though, so I don't know. Right now I'm getting an "Invalid use of Object" error pointing at the "Nothing" in the If statement.</p> | 2 |
Can a combining character be used alone in Unicode? | <p>Let's take <a href="http://www.fileformat.info/info/unicode/char/0301/index.htm" rel="nofollow noreferrer">COMBINING ACUTE ACCENT</a>, for example. Its <a href="http://www.fileformat.info/info/unicode/char/0301/browsertest.htm" rel="nofollow noreferrer">browser test page</a> does include it alone in the page, but it reacts in a strange way: I can't select it with my mouse, and if I try to interact with it in the DOM inspector, it feels like it's not part of the text at all (there's no <em>before</em> and <em>after</em> this character):</p>
<p><a href="https://i.stack.imgur.com/qgPbb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qgPbb.png" alt="Combining character"></a></p>
<p><strong>Is a combining character, used alone, still a valid Unicode string?</strong></p>
<p>Or does it have to follow another character?</p> | 2 |
Android dependencies inconsitant | <p>I am using firebase database and have updated my dependencies.</p>
<pre><code>dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.0.0'
compile 'com.android.support:support-v4:24.0.0'
compile 'com.firebase:firebase-client-android:2.3.1'}
</code></pre>
<p>I keep getting the following error:</p>
<blockquote>
<p>A/FirebaseApp: Firebase API initialization failure.
java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.google.firebase.FirebaseApp.zza(Unknown Source)
at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
at com.google.firebase.FirebaseApp.zzbu(Unknown Source)
at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown Source)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1696)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1671)
at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
at android.app.ActivityThread.installProvider(ActivityThread.java:5045)
at android.app.ActivityThread.installContentProviders(ActivityThread.java:4630)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4570)
at de.robv.android.xposed.XposedBridge.invokeOriginalMethodNative(Native Method)
at de.robv.android.xposed.XposedBridge.handleHookedMethod(XposedBridge.java:729)
at android.app.ActivityThread.handleBindApplication()
at android.app.ActivityThread.access$1600(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1383)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5300)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:133)
Caused by: java.lang.IncompatibleClassChangeError: The method 'java.io.File android.support.v4.content.ContextCompat.getNoBackupFilesDir(android.content.Context)' was expected to be of type virtual but instead was found to be of type direct (declaration of 'java.lang.reflect.ArtMethod' appears in /system/framework/core-libart.jar)
at com.google.firebase.iid.zzg.zzeC(Unknown Source)
at com.google.firebase.iid.zzg.(Unknown Source)
at com.google.firebase.iid.zzg.(Unknown Source)
at com.google.firebase.iid.zzd.zzb(Unknown Source)
at com.google.firebase.iid.FirebaseInstanceId.getInstance(Unknown Source)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.google.firebase.FirebaseApp.zza(Unknown Source)
at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
at com.google.firebase.FirebaseApp.zzbu(Unknown Source)
at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown Source)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1696)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1671)
at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
at android.app.ActivityThread.installProvider(ActivityThread.java:5045)
at android.app.ActivityThread.installContentProviders(ActivityThread.java:4630)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4570)
at de.robv.android.xposed.XposedBridge.invokeOriginalMethodNative(Native Method)
at de.robv.android.xposed.XposedBridge.handleHookedMethod(XposedBridge.java:729)
at android.app.ActivityThread.handleBindApplication()
at android.app.ActivityThread.access$1600(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1383)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5300)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:133) </p>
<p>E/FA: Task exception on worker thread: java.lang.IncompatibleClassChangeError: The method 'java.io.File android.support.v4.content.ContextCompat.getNoBackupFilesDir(android.content.Context)' was expected to be of type virtual but instead was found to be of type direct (declaration of 'java.lang.reflect.ArtMethod' appears in /system/framework/core-libart.jar): com.google.android.gms.measurement.internal.zzt.zzEd(Unknown Source)</p>
</blockquote>
<p>But if I change these dependencies back to version 23 instead of 24 and run after rebuilding gradle:</p>
<pre><code>dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.0.0'
compile 'com.android.support:support-v4:23.0.0'
compile 'com.firebase:firebase-client-android:2.3.1'}
</code></pre>
<p>I dont get the above error but still get:</p>
<p>D/FirebaseInstanceId: background sync failed: SERVICE_NOT_AVAILABLE</p>
<p>Everything was working fine untill I updated android studio</p>
<p>The complete build, gradle looks like the following:</p>
<pre><code>apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
android {
compileSdkVersion 23
buildToolsVersion "24.0.0"
defaultConfig {
applicationId "pvn.com.locanews"
minSdkVersion 19
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
packagingOptions {
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE-FIREBASE.txt'
exclude 'META-INF/NOTICE'
}}dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.0.0'
compile 'com.android.support:support-v4:24.0.0'
compile 'com.firebase:firebase-client-android:2.3.1'}
</code></pre>
<p>Stuck..............</p> | 2 |
Flask SqlAlchemy MySQL connection timed out due to QueuePool overflow limit | <p>Please I need help with the following error which I get on the 16th database connection. None of the other answers on Stackoverflow seem to work:</p>
<pre><code>QueuePool limit of size 5 overflow 10 reached, connection timed out, timeout 30
</code></pre>
<p>Backend configuration:</p>
<ul>
<li>Python 2.6.9 </li>
<li>Flask 0.10.1 </li>
<li>Flask-SQLAlchemy 2.1</li>
<li>Mysql-connector-python 1.0.12 </li>
<li>Mysql 5.6.27</li>
</ul>
<p>Database Setup:</p>
<pre><code>connection_str = 'mysql+mysqlconnector://%s:%s@%s:%s/%s' % (config["DATABASE_USER"], config["DATABASE_PASSWORD"], \
config["DATABASE_HOST"], config["DATABASE_PORT"], \
config["DATABASE_SCHEMA1"])
engine = create_engine(connection_str, convert_unicode=True, pool_recycle=config["DATABASE_POOL_RECYCLE"])
db_session = scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()
import application_package.models
Base.metadata.create_all(bind=engine)
@app.teardown_appcontext
def shutdown_session(exception=None):
db_session.remove()
</code></pre> | 2 |
Spatial merge in R returns "non-unique matches detected" even though data has unique value | <p>I am trying to merge a SpatialPolygonsDataFrame with a normal data frame.</p>
<p>The SpatialPolygonDataFrame looks as follows:</p>
<pre><code> check1 LargeSpatialDataFrame
......@data:'data.frame' : 206 obs
$latitude : num
$longitude: num
$name1 : int
</code></pre>
<p>The normal dataframe looks as follows:</p>
<pre><code> Val1 name1
18262 662
55484 532
20859 525
</code></pre>
<p>The DataFrame has 210 unique "name1" value and the SpatialPolygonsDataFrame has 206 unique "name1" value.</p>
<p>When I run the below command I get the following "Error in .local(x, y, ...) : non-unique matches detected"</p>
<pre><code> sp::merge(check1,groupdma,by.x="dma",by.y="dma_number",all=TRUE,duplicateGeoms=FALSE)
</code></pre>
<p>How do I fix this error? My main aim is to create a SpatialPolygonsDataFrame that I can pass to the leaflet function to create a chloropeth map. I have tried the link <a href="http://zevross.com/blog/2015/10/14/manipulating-and-mapping-us-census-data-in-r-using-the-acs-tigris-and-leaflet-packages-3/" rel="nofollow">here</a>, but the area of my polygons always came out to be 0. Hence I am trying to use sp::merge in order to avoid the steps given in the link.</p>
<p>The dataframe and the spatialdataframe, both do not have duplicate id values.</p> | 2 |
How can I strip symbols from my iOS framework? | <p>I have built an iOS framework (release) but when I 'nm'/'otool' it, I see symbols I don't want to be exposed. And that are local symbols (no need to have them exported).</p>
<p>As an example:
I extract the arm64 part using lipo.
And I see what symbols are exported in the binary using "nm -G myLibrary".
I get a lot of:
_kMyLibraryPrivateKey
_MyLibrarySecretThing</p>
<p>I tried to use "strip -x MyLibrary -o MyLibraryStripped", I get no error but the binary is still the same size and I get the same result with the 'nm' command.</p>
<p>Why is not doing anything? how can I remove all these symbols from my framework and only keep the one that are needed by apps using it?</p>
<p>Any help welcome!! Thanks!</p> | 2 |
Why is XPath unclean constructed? Why is text() not needed in predicate? | <p>Assume I have:</p>
<pre><code><A>
<B>C</B>
<D>E</D>
</A>
</code></pre>
<p>Then I can output the B-element (including tags) with:</p>
<pre><code>//B
</code></pre>
<p>Which will return </p>
<pre><code><B>C</B>
</code></pre>
<p><strong>But why is text() not needed in a predicate?</strong> The following 2 lines give the same output:</p>
<pre><code>/A[B = 'C']/D
/A[B/text() = 'C']/D
</code></pre>
<p>If XPATH was cleanly constructed I would expect it would be (or in some kind of other element structure):</p>
<pre><code>/A[B = <B>C></B>]/D
</code></pre>
<p>and:</p>
<pre><code>/A[B/text()='C']/D
</code></pre>
<p><strong>Can someone give me a rationale why text() is needed for output, but it is not needed for predicates?</strong> </p> | 2 |
How to display SELECT query results to a textbox in vb.net | <p>I want to allow the user to query the database for a specific <code>customer_id</code>
and to use this to populate <code>textboxes(tbFName, tbLName, tbPhoneNum, etc)</code> with the users relevant information from the table which can then be edited on another button press update the database. Below are a copy of my current code and an image of the form i'm trying to create. </p>
<pre><code>Public Class searchcustomers
Dim sql As New sqlcontrol
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
If sql.HasConnection = True Then
sql.RunQuery("SELECT order_id, date_ordered, order_total, collection_method, staff_id FROM orders WHERE customer_id=" & tbSearchID.Text & " ORDER BY date_ordered")
If sql.sqldataset.Tables.Count > 0 Then
dgvPOrders.DataSource = sql.sqldataset.Tables(0)
End If
End If
'queries database to search for customer id to then display relevant data in data grid view'
End Sub
Private Sub searchcustomers_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub btnSearchName_Click(sender As Object, e As EventArgs) Handles btnSearchName.Click
If sql.HasConnection = True Then
sql.RunQuery("SELECT customers.customer_id, order_id, date_ordered, order_total, collection_method, staff_id FROM (customers INNER JOIN orders on orders.customer_id=customers.customer_id) WHERE customers.first_name=" & tbSearchFName.Text & "")
If sql.sqldataset.Tables.Count > 0 Then
dgvPOrders.DataSource = sql.sqldataset.Tables(0)
End If
End If
'queries database to search for customer name to then display relevant data in data grid view'
End Sub
End Class
</code></pre>
<p><br><strong>FYI I've already managed to get the previous orders section working correctly.</strong></p>
<p><a href="http://i.stack.imgur.com/TXo36.png" rel="nofollow">image of form</a></p> | 2 |
C Programming - Allow / determine / check "space ( )" input in integer | <p>First, sorry for my bad english, okay go to this question above. I was surfing a lot for reference about this question on many websites, but i didn't find the right answer yet.</p>
<p>I'm trying to make a C program which this program can determine if the user input an integer or not, if user didn't input an integer then the program retry prompt to user for input an integer and so on. Everything is ok when i use scanf() return value on conditional statement, but the problem is, when user input 'whitespace/blankspace/space' (on ascii code as &#32) and press 'enter', my program just stay running to wait for user input some characters or integer. </p>
<p>I just wish that if the input is 'whitespace/blackspace/space', the program will repeat prompt to user to input an integer or the program just stop.</p>
<p>Here is the case code :</p>
<pre><code>#include <stdio.h>
int main() {
int number, isInt;
printf("Input a number : ");
do {
if ((isInt = scanf("%d", &number)) == 0) {
printf("retry : ");
scanf("%*s");
} else if (number < 0) {
printf("retry : ");
}
} while (isInt == 0 || number < 0);
printf("%d\n", number);
return 0;
}
</code></pre>
<p>I am a newbie in C, and curious about this. I know if i use %[^\n] <-- code format for scanf() string and convert it to integer, the program that i mean will run correctly. Is there another way to solve this using %d code format? or using scanf() ?</p>
<p>Please help me to break my curiosity, Regards :D</p> | 2 |
Viewpager with SwipeRefreshLayout when refresh the icon doesn't go away | <p>My question is exactly like this one. </p>
<p><a href="https://stackoverflow.com/questions/36087295/frozen-snapshot-of-list-rendered-with-swiperefreshlayout-in-viewpager">Frozen snapshot of list rendered with SwipeRefreshLayout in ViewPager</a></p>
<p>But in short, I refresh the list and the spinning thing still keeps going after the list has been refreshed. </p>
<p>I tried the following solution he gave of wrapping the SwipeRefreshLayout with a FrameLayout and i had no success. </p>
<p>Here are screenshots of what I have right now, and the code where I implement this. </p>
<p><a href="https://i.stack.imgur.com/qrhE2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qrhE2.png" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/IVBZL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IVBZL.png" alt="enter image description here"></a></p>
<p>In my Fragment Class and parts of my Asynctask, </p>
<pre><code>private LocationUtil loc;
private static final String ARG_SORT_TYPE = "sortType";
String sortType = null;
private ArrayList<Facility> results;
private SwipeRefreshLayout mPtrListView;
private ListView waitTimesListView;
SummaryAdapter adapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_wait_times_viewpager_fragment,container,false);
mPtrListView = (SwipeRefreshLayout) view.findViewById(R.id.wait_times_pull_refresh_list);
waitTimesListView = (ListView) view.findViewById(R.id.wait_times_listview);
waitTimesListView.setOnItemClickListener(this);
mPtrListView.setOnRefreshListener(this);
WaitTimesTask task = new WaitTimesTask(getActivity());
task.execute(sortType, longitudeLocation, latitudeLocation);
return view;
}
@Override
public void onRefresh() {
WaitTimesTask task = new WaitTimesTask(getActivity());
task.execute("name", longitudeLocation, latitudeLocation);
}
public void setLocation(){
if(loc.useSmartLocation()){
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
Log.v("Check Location frag" + sortType + " " , " " + location.getLongitude() + " " + location.getLatitude());
latitudeLocation = Double.toString(location.getLatitude());
longitudeLocation = Double.toString(location.getLongitude());
} else {
Log.v("Check waitTimesActivity" , " is null");
}
}
else {
loc.determineLocation();
latitudeLocation = Double.toString(loc.getLatitude());
longitudeLocation = Double.toString(loc.getLongitude());
}
}
@Override
protected void onPreExecute() {
dialog = AsyncProgressDialog.show(mContext, "", "");
setLocation();
}
@Override
protected void onPostExecute(String string) {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
if(string != null){
Log.v("result on post & type: " + Sort, string);
NovantFacilityXmlParser parser = new NovantFacilityXmlParser();
string = string.replace("&", "&amp;");
try {
results = parser.parse(new ByteArrayInputStream(string.getBytes()));
} catch (IOException | XmlPullParserException ex) {
Log.e("Parsing error:", ex.getMessage());
}
Log.v("SetUp "," of List");
if(!results.isEmpty()) {
adapter = new SummaryAdapter(mContext, R.layout.row_wait_time, results.toArray(new Facility[results.size()]));
waitTimesListView.setAdapter(adapter);
}
}
else{
Toast.makeText(getActivity(), "No data available", Toast.LENGTH_LONG).show();
}
}
</code></pre>
<p>My xml, both fragment and main activity. </p>
<p>Activity xml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
android:background="@color/aubergine">
<android.support.design.widget.TabLayout
android:id="@+id/wait_times_tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabIndicatorHeight="3dp"
app:tabIndicatorColor="#ffffff"
app:tabSelectedTextColor="#ffffff"
app:tabMode="fixed"
android:background="#333333"/>
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/wait_times_ViewPager">
</android.support.v4.view.ViewPager>
</LinearLayout>
</code></pre>
<p>Fragment xml</p>
<pre><code><FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/base_color">
<!--tools:context=".WaitTimesFragment">-->
<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/wait_times_pull_refresh_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/wait_times_listview"/>
</android.support.v4.widget.SwipeRefreshLayout>
<include layout="@layout/novant_menu_layout" />
</code></pre>
<p></p>
<p>In my OnpostExecute, I get the string from the doinBackground and parse the xml feed and make an arraylist that i use for my adapter that i custom made.</p>
<p>Any help would greatly be appreciated.
Thanks.</p> | 2 |
Xamarin.Forms.Xaml.XamlParseException: Position 16:13. No Property of name Cliked found | <p>I'm following a tutorial to make an app that receives and sends data to a web service.
But the time to create a button on the MainPage to bring the registration screen of the Visual Studio this error</p>
<pre><code> Xamarin.Forms.Xaml.XamlParseException:. Position 16:13 In the Property of name Cliked found
</code></pre>
<p>and I lost because my this code like the tutorial.</p> | 2 |
How to get OUT parameter by executing stored procedure in CMD @echo , ORALCE-PL/SQL? | <blockquote>
<p>Procedure structure :: Package.Procedure(In a,Out b)</p>
</blockquote>
<hr>
<blockquote>
<p>@echo execute Package.Procedure('%a%',<strong>?XX?</strong>) | sqlplus
%USER_ID%/%PASSWORD%@%SID%</p>
</blockquote>
<hr>
<p>I can execute procedure with IN parameters or without parameters.
I would like to know how can I do for OUT parameter.</p>
<p>**** ITS INSIDE CMD, NOT SQLPLUS ****</p> | 2 |
Colorizing text in Turbo C++ | <p>How can I write colored text in <strong>Turbo C++</strong>? That is, how can I write different text with different colors and also have different Background colors?</p>
<p>For example like this...</p>
<pre><code>textcolor(2);
cprintf("\n\t Hello World");
</code></pre>
<p>But I want to set a background color for the "Hello World" text, also.</p>
<p><a href="https://i.stack.imgur.com/mRTi0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mRTi0.png" alt="CLICK Too See Image.."></a></p> | 2 |
Error pip installing getch Python3.5 | <p>I'm running Fedora 24. I want to import the getch module on Python 3.5.2 (which I think is already installed, however when I run python -V, it says Python 2.7.11)</p>
<p>When I enter pip install getch I get this:</p>
<pre><code>Collecting getch
Downloading getch-1.0.tar.gz
Installing collected packages: getch
Running setup.py install for getch ... error
Complete output from command /usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-ZsVfHE/getch/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-dOzMrO-record/install-record.txt --single-version-externally-managed --compile:
running install
running build
running build_ext
building 'getch' extension
creating build
creating build/temp.linux-x86_64-2.7
gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -I/usr/local/include -I/usr/include -I/usr/include/python2.7 -c getchmodule.c -o build/temp.linux-x86_64-2.7/getchmodule.o
getchmodule.c: En la función ‘getch_getche’:
getchmodule.c:36:6: aviso: variable ‘ok’ sin usar [-Wunused-variable]
int ok = PyArg_ParseTuple(args, "");
^~
getchmodule.c: En la función ‘getch_getch’:
getchmodule.c:43:6: aviso: variable ‘ok’ sin usar [-Wunused-variable]
int ok = PyArg_ParseTuple(args, "");
^~
getchmodule.c: En el nivel principal:
getchmodule.c:54:15: error: la variable ‘getchmodule’ tiene inicializador pero de tipo de dato incompleto
static struct PyModuleDef getchmodule = {
^~~~~~~~~~~
getchmodule.c:55:4: error: ‘PyModuleDef_HEAD_INIT’ no se declaró aquí (no en una función)
PyModuleDef_HEAD_INIT,
^~~~~~~~~~~~~~~~~~~~~
getchmodule.c:55:4: aviso: exceso de elementos en el inicializador de struct
getchmodule.c:55:4: nota: (cerca de la inicialización de ‘getchmodule’)
getchmodule.c:56:4: aviso: exceso de elementos en el inicializador de struct
"getch", /* name of module */
^~~~~~~
getchmodule.c:56:4: nota: (cerca de la inicialización de ‘getchmodule’)
getchmodule.c:58:4: aviso: exceso de elementos en el inicializador de struct
-1, /* size of per-interpreter state of the module, or -1 if the module keeps state in global variables. */
^
getchmodule.c:58:4: nota: (cerca de la inicialización de ‘getchmodule’)
getchmodule.c:59:4: aviso: exceso de elementos en el inicializador de struct
GetchMethods
^~~~~~~~~~~~
getchmodule.c:59:4: nota: (cerca de la inicialización de ‘getchmodule’)
getchmodule.c: En la función ‘PyInit_getch’:
getchmodule.c:64:9: aviso: declaración implícita de la función ‘PyModule_Create’ [-Wimplicit-function-declaration]
return PyModule_Create(&getchmodule);
^~~~~~~~~~~~~~~
getchmodule.c:64:9: aviso: ‘return’ con valor, en una función que devuelve void
return PyModule_Create(&getchmodule);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
getchmodule.c:62:16: nota: se declara aquí
PyMODINIT_FUNC PyInit_getch(void)
^~~~~~~~~~~~
getchmodule.c: En el nivel principal:
getchmodule.c:54:27: error: no se conoce el tamaño de almacenamiento de ‘getchmodule’
static struct PyModuleDef getchmodule = {
^~~~~~~~~~~
error: command 'gcc' failed with exit status 1
----------------------------------------
Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-ZsVfHE/getch/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-dOzMrO-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-ZsVfHE/getch/
</code></pre>
<p>Last line is in red.</p>
<p>So, how can I make it work?</p>
<p>Thank you</p>
<hr>
<p>Update: Ok, so I managed to update pip to the latest version, but now I get the next problem (seems like a progress):</p>
<p>Ok, so I managed to get pip updated to the latest version, but now I get the following problem (seems like a progress):</p>
<pre><code>`Collecting getch
Using cached getch-1.0.tar.gz
Installing collected packages: getch
Running setup.py install for getch: started
Running setup.py install for getch: finished with status 'error'
Complete output from command /usr/bin/python3.5 -u -c "import setuptools, tokenize;__file__='/tmp/pycharm-packaging1/getch/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-a0bmz59i-record/install-record.txt --single-version-externally-managed --compile:
running install
running build
running build_ext
building 'getch' extension
creating build
creating build/temp.linux-x86_64-3.5
gcc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -I/usr/local/include -I/usr/include -I/usr/include/python3.5m -c getchmodule.c -o build/temp.linux-x86_64-3.5/getchmodule.o
getchmodule.c:1:20: error fatal: Python.h: No such file or directory
#include <Python.h>
^
compilación terminada.
error: command 'gcc' failed with exit status 1
----------------------------------------
Command "/usr/bin/python3.5 -u -c "import setuptools, tokenize;__file__='/tmp/pycharm-packaging1/getch/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-a0bmz59i-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pycharm-packaging1/getch/`
</code></pre> | 2 |
chrome debugger skipping breakpoints, extension development | <p>I'm trying to figure out how to develop extensions in chrome and started out with the obvious: adblock plus.</p>
<p>But I noticed something very unsettling: the break points get skipped.</p>
<p><a href="https://i.stack.imgur.com/uioKr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uioKr.png" alt="enter image description here"></a></p>
<p>As you can see, I set a break point on the line <code>console.log("Was here 00 " + timeStamp());</code> but the message was still printed to the screen.</p>
<p>I expect the Javascript interpreter to break on the break points. Obviously it's not happening.</p>
<p>I don't understand this. Can someone please shed some light on this mystery?</p>
<p>Thanks in advance for your kind help.</p> | 2 |
Stream live video to Facebook from iOS | <p>I’m using Live video API, i want to show privacy (Public, Friends, only me) before streaming live video on Facebook from iOS app.</p>
<p>1 Does FBSDKShareKit supports live video content ?</p>
<p>2 Can i retrieve friend list and display privacy in custom views ?</p> | 2 |
Copy a number starting with 0 in vba and paste is as such | <p>say cell A1, A2, A3 contains value "00V", cell An contains value "029"
I'm doing a comparison for consecutive cells in column A like:</p>
<p>If A1 not equal to A2 then ill copy the cell value of A2 and paste it into a new worksheet in Column A first consecutively.</p>
<p>When I compare 00V and 029 (i.e. both are unequal) ill copy 029 and paste into new sheet</p>
<p>But "029" gets pasted as "29"</p>
<p>How do I fix this in Excel vba?</p> | 2 |
Flyout menu in UWP with MVVM | <p>I'm trying to implement a Flyout menu in a Windows 10 App (using MVVM) that opens when holding down an item of a GridView. I've been looking and I haven't been able to find any examples that works for me. The Flyout menu is not opening to display options. Does anyone know how can I do it?</p>
<pre><code><GridView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<FlyoutBase.AttachedFlyout>
<MenuFlyout>
<MenuFlyoutItem Text="Delete" Command="{Binding DeleteCommand}"/>
</MenuFlyout>
</FlyoutBase.AttachedFlyout>
<Image Source="{Binding Dictionary}" Height="25"/>
<TextBlock Text="{Binding Title}" Foreground="White" Width="170"/>
</StackPanel>
</DataTemplate>
</GridView.ItemTemplate>
</code></pre>
<p><strong>Note:</strong> Solution found in <a href="https://marcominerva.wordpress.com/2013/12/17/using-a-behavior-to-open-attached-flyouts-in-winows-81-store-apps/" rel="nofollow">https://marcominerva.wordpress.com/2013/12/17/using-a-behavior-to-open-attached-flyouts-in-winows-81-store-apps/</a></p> | 2 |
why cv::cuda::createMedianFilter function is slower than cv::medianBlur? | <p>As you know, <code>Ptr<Filter> cv::cuda::createMedianFilter (int srcType, int windowSize, int partition=128)</code> function added to OpenCV3.1.0.</p>
<p>I'm trying to do a median filter on 8 bit large images (6000*6000) with custom window size(up to 21). I compare <code>cv::medianBlur</code> and <code>cv::cuda::createMedianFilter</code> and results was</p>
<pre><code>windowSize cv::medianBlur cv::cuda::createMedianFilter
3 0.071 sec 3.637 sec
5 0.285 sec 3.679 sec
11 2.641 sec 3.652 sec
19 2.566 sec 3.719 sec
</code></pre>
<p>1) why cuda::createMedianFilter is slower than cv::medianBlur?</p>
<p>2) How can i write a kernel code to implement median filter that use opencv Mat with custom kernel size?</p> | 2 |
Amazon and multi customer support in shared multi-tenant model | <p>Are there any ready services (by amazon or partners) that help you manage multi-customer aspects of a "pool" [1][2] type service - where all the multi-tenancy is handled by internal context switching, databases are shared, etc. </p>
<p>AWS tools (marketplace, billing manager) seems to be geared toward "provision new service / host by customer" while what I'm looking for is the customer and license management, user association, authentication (including federated authentication integration with multiple customer portals) and perhaps even listing and catalog services - but when a new customer purchase (or change) a license / user / configuration - I expect to get an API call to my already existing solution - in which I'll decide what to do.</p>
<p>Seems like there should be many services like that - but either they are proprietary, or I'm using the wrong keywords to find the information.</p>
<p>[1] <a href="http://www.slideshare.net/AmazonWebServices/arc340-multitenant-application-deployment-models/9" rel="nofollow">http://www.slideshare.net/AmazonWebServices/arc340-multitenant-application-deployment-models/9</a></p>
<p>[2] <a href="https://www.youtube.com/watch?v=DMP0leGZpo4" rel="nofollow">https://www.youtube.com/watch?v=DMP0leGZpo4</a></p> | 2 |
Why are iterators in forEach immutable for a struct but mutable for a class? | <p>The iterator is mutable for a class:</p>
<pre><code>var selections: [Selection] = []
class Selection {
var selected: Bool
init(selected: Bool) {
self.selected = selected
}
}
selections.forEach({ $0.selected = false }) // This works
</code></pre>
<p>but not mutable for a struct:</p>
<pre><code>var selections: [Selection] = []
struct Selection {
var selected: Bool
}
selections.forEach({ $0.selected = false }) // This doesn't work because $0 is immutable
</code></pre> | 2 |
R ggplot: stat = "identity" is not working for some reason | <p>I have a datafile which looks something like this...</p>
<pre><code>Rate <- runif(14, 0, 20)
Day <- c("Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday",
"Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday")
Grouper <- c(rep(1, 7), rep(2, 7))
df <- data.frame(Rate, Day, Grouper)
</code></pre>
<p>...and I want to make a bar chart with two bars for each day: one bar for <code>Grouper = 1</code> and one bar for <code>Grouper = 2</code>. The y-value is not a count, it's the <code>Rate</code> variable, so I need to use <code>stat = "identity"</code> to make it work...</p>
<pre><code># Set max chart height
maxlimit = max(df$Rate) * 1.1
# Actual plot code
ggplot(df, aes(Day, Rate)) +
geom_bar(stat = "identity") +
geom_bar(aes(fill = Grouper), position = "dodge") +
scale_y_continuous(limits = c(0, maxlimit)) +
theme_classic()
</code></pre>
<p>...but I am still getting the error <code>stat_count() must not be used with a y aesthetic.</code> Can someone explain to me why I am getting this error and what I can do to fix it?</p> | 2 |
Laravel 5 abort not returning error message | <p>I'm trying to throw an error from my Laravel 5.1 app to my frontend Angular app. The thrown errors are not returning the actual status message, which I need:</p>
<pre><code>if (Hash::check($updated_profile['current_password'], $user->password)) {
$user->password = Hash::make($updated_profile['new_password']);
return $user;
} else {
abort(500, 'Passwords do not match');
}
</code></pre>
<p>I've also tried <code>throw new \Exception('Passwords do not match');</code></p>
<p>For both, I get an error on the frontend, but it's missing the status message:</p>
<pre><code>Object
data: null
headers:(name)
status: 0
statusText:""
__proto__: Object
</code></pre> | 2 |
which download of activestate perl 5.24 do i need? | <p>I'm running Windows 7 Home Premium 64-bit. I need to install the perl
5.24 binary.</p>
<p>at <a href="http://www.activestate.com/activeperl/downloads" rel="nofollow noreferrer">http://www.activestate.com/activeperl/downloads</a> I get two choices:
download activeperl 5.24.0 for windows (x86)
download activeperl 5.24.0 for windows (64-bit, x64)</p>
<p>Which of those two do I need?</p>
<p>Call me dense but <em>I don't find my answer</em> at <a href="https://stackoverflow.com/questions/26168746/how-can-i-check-">How can I check whether my Perl installation is 32 or 64 bit?</a>
whether-my-perl-installation-is-32-or-64-bit, although it does tell how to
display several version-related characteristics</p>
<ul>
<li><p>perl -V:ivsize says
ivsize='8';</p></li>
<li><p>perl -V:archname says
archname='MSWin32-x86-multi-thread-64int';</p></li>
<li><p>perl -v says</p></li>
</ul>
<p>This is perl 5, version 20, subversion 1 (v5.20.1) built for MSWin32-x86-multi-thread-64int
(with 1 registered patch, see perl -V for more detail)</p>
<p>Copyright 1987-2014, Larry Wall</p>
<p>Binary build 2000 [298557] provided by ActiveState </p>
<p><a href="http://www.ActiveState.com" rel="nofollow noreferrer">http://www.ActiveState.com</a>
Built Oct 15 2014 22:10:49</p>
<p>Please help.
Phil</p> | 2 |
JQuery Datatables add new row from text box | <p>I'm creating a page that lists the stats of players in a jQuery Datatable. So far I've been able to display the data that is in the actual database, but I have not been able to add any new players. I created an add button and from for inputing the new player, but I get this error "Datatables warning: table id=test - Requested unknown parameter 'id' for row 3, column 0. For more information about this error please see, <a href="https://datatables.net/manual/tech-notes/4" rel="nofollow">https://datatables.net/manual/tech-notes/4</a> " and a blank row is added to the table after I click ok. Here is my jQuery code:</p>
<pre><code>$(document).ready(function () {
$('#test').DataTable({
"ajax":{
"url": "players.json",
"dataSrc":""
},
"columns": [
{"data": "id"},
{ "data": "playername" },
{ "data": "points" },
{ "data": "steals" },
{ "data": "blocks" },
{ "data": "assists" },
{ "data": "mpg" },
{ "data": "shootingpercentage" },
{ "data": "threepointpercentage" }
]
});
var dTable = $('#test').DataTable();
$('#addbtn').on('click', function(){
dTable.row.add([
$('#id').val(),
$('#player').val(),
$('#points').val(),
$('#steals').val(),
$('#blocks').val(),
$('#assists').val(),
$('#mpg').val(),
$('#shotpct').val(),
$('#3pct').val()
]).draw();
});
</code></pre>
<p>And the HTML for the input text boxes and table:</p>
<pre><code><body>
<div id="main" class="container">
<input type="text" name="id" id="id" placeholder="Id" />
<input type="text" name="player" id="player" placeholder="Player"/>
<input type="text" name="points" id="points" placeholder="Points" />
<input type="text" name="steals" id="steals" placeholder="Steals" />
<input type="text" name="blocks" id="blocks" placeholder="Blocks" />
<input type="text" name="assists" id="assists" placeholder="Assists" />
<input type="text" name="mpg" id="mpg" placeholder="MPG" />
<input type="text" name="shotpct" id="shotpct" placeholder="Shot %" />
<input type="text" name="3pct" id="3pct" placeholder="3 %" />
<input type="button" value="add player" id="addbtn" />
<br />
<br />
<input type="button" value="Delete selected row" id="dltbtn" />
<div id="table">
<table id="test" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Points</th>
<th>Steals</th>
<th>Blocks</th>
<th>Assists</th>
<th>MPG</th>
<th>Shot %</th>
<th>3 %</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Id</th>
<th>Name</th>
<th>Points</th>
<th>Steals</th>
<th>Blocks</th>
<th>Assists</th>
<th>MPG</th>
<th>Shot %</th>
<th>3 %</th>
</tr>
</tfoot>
</table>
</div>
</div>
</body>
</code></pre>
<p>I just need to be able to make the data I put in the text boxes show up in the datatable. </p> | 2 |
SQL Server messages system with conversation list | <p>Good morning!</p>
<p>I have developed a web application to allow people to exchange messages.</p>
<p>I use SQL Server 2008 and Classic ASP on Windows 2012 Server.</p>
<p>To simplify, suppose there are only 2 tables:</p>
<pre><code>tUsers
Id INT IDENTITY(1,1)
Username VARCHAR(20)
tMessages
Id INT IDENTITY(1,1)
UserIdFrom INT
UserIdTo INT
SentDate DATETIME
Message VARCHAR(300)
Read TINYINT
</code></pre>
<p>My question is simple, but I can't find a solution specific for MS SQL.</p>
<p>I need to write a query that returns the conversation list between me and other users I talked with.</p>
<p>The list must contain <em>UserId</em> and <em>Username</em> (not mine but of the users I talked with) and must be in reverse order by sent date/time order, and must include the message (from or to me) without answer (as Whatsapp for example).</p>
<p>I found many solutions, but for MySQL the conversion to MS SQL is not working. This is the first time I need help on SQL, but I can't find a solution by myself.</p>
<p>Can anyone give me an example of T-SQL query to solve my problem???</p>
<p>Sorry for my English, I used to speak Italian.</p>
<p>This is my second question on StackOverflow. I hope I have respected the rules.</p>
<p>Thanks in advance.</p> | 2 |
Bootstrap-confirmation not respecting options | <p>Just adding the bootstrap-confirmation extension for Bootstrap popover to some buttons on a project. I'm having issues with the options not being respected. I'm trying to get the popups to work as singletons and dismiss when the user clicks outside of them <code>singleton</code> and <code>data-popout</code> options, respectively - both set to true. I'm also not seeing any of my defined callback behavior happening.</p>
<p>I defined the options both in the HTML tags and in a function and neither works. Still getting multiple boxes and they don't dismiss as expected.</p>
<p>My JS is loaded after all other libraries and is in my <code>custom.js</code> file in my footer.</p>
<p>JS is as follows:</p>
<pre><code>$(function() {
$('body').confirmation({
selector: '[data-toggle="confirmation"]',
singleton: true,
popout: true
});
$('.confirmation-callback').confirmation({
onConfirm: function() { alert('confirm') },
onCancel: function() { alert('cancel') }
});
});
</code></pre>
<p>An example of the box implemented on a button in my HTML is the following:</p>
<pre><code><a class="btn btn-danger" data-toggle="confirmation" data-singleton="true" data-popout="true"><em class="fa fa-trash"></em></a>
</code></pre>
<p>Any pointers would be appreciated. I even changed the default options in the <code>bootstrap-confirmation.js</code> file itself to what I want and still no luck.</p> | 2 |
XmlSerializer: The type of the argument object is not primitive | <p>System.InvalidOperationException: The type of the argument object 'SI_Foodware.Model.LocalisationCollection' is not primitive.
System.InvalidOperationException: There was an error generating the XML document.</p>
<h1>LocalisationCollection.cs</h1>
<pre><code>using System.Xml.Serialization;
namespace SI_Foodware.Model
{
[XmlRoot("LocalisationCollection")]
public class LocalisationCollection
{
[XmlArray("LocalisationItems")]
[XmlArrayItem("LocalisationItem", typeof(LocalisationItem))]
public LocalisationItem[] LocalisationItem { get; set; }
}
}
</code></pre>
<h1>LocalisationItem.cs</h1>
<pre><code>using System.Xml.Serialization;
using SQLite.Net.Attributes;
namespace SI_Foodware.Model
{
public class LocalisationItem
{
[PrimaryKey, AutoIncrement]
[XmlIgnore]
public int Id { get; set; }
[XmlElement("Page")]
public string Page { get; set; }
[XmlElement("Field")]
public string Field { get; set; }
[XmlElement("Language")]
public string Language { get; set; }
[XmlElement("Value")]
public string Value { get; set; }
[XmlElement("Width")]
public string Width { get; set; }
[XmlElement("Columns")]
public string Columns { get; set; }
[XmlElement("Table")]
public string Table { get; set; }
[XmlElement("Title")]
public string Title { get; set; }
[XmlElement("Parent")]
public string Parent { get; set; }
[XmlElement("IconSource")]
public string IconSource { get; set; }
[XmlElement("TargetType")]
public string TargetType { get; set; }
}
}
</code></pre>
<h1>Function to Serialize</h1>
<pre><code> public bool Serialize(string filename)
{
var path = GetPath(filename);
var serializer = new XmlSerializer(typeof(List<LocalisationCollection>));
var writer = new FileStream(path, FileMode.Create);
var localisationItems = db.GetAllItems<LocalisationItem>();
var collection = new LocalisationCollection();
collection.LocalisationItem = localisationItems.ToArray();
try
{
serializer.Serialize(writer, collection);
writer.Close();
return true;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
</code></pre>
<p>I want somethink like this</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LocalisationCollection>
<LocalisationItems>
<LocalisationItem>
<Language>Nederlands</Language>
</LocalisationItem>
<LocalisationItem>
<Language>Engels</Language>
</LocalisationItem>
<LocalisationItem>
<Page>LoginPage</Page>
<Field>grd_grid</Field>
<Columns>2</Columns>
</LocalisationItem>
<LocalisationItem>
<Page>LoginPage</Page>
<Field>grd_grid</Field>
<Width>120</Width>
</LocalisationItem>
<LocalisationItem>
<Page>LoginPage</Page>
<Field>grd_grid</Field>
<Width>180</Width>
</LocalisationItem>
</LocalisationItems>
</LocalisationCollection>
</code></pre> | 2 |
RESTful API with either Tomcat or Node.js? | <p>I am at a decision fork where i have to pick whether to use Tomcat or Node.js in my project and need advice from experts on this.</p>
<p>Some questions that i have here are:</p>
<ol>
<li>Is Tomcat (Java) or Node.js with Typescript better suited to write a RESTful API which gets values form a Database and has to interact with a another java component?</li>
<li>Does Node.js have unit-testing support? </li>
<li>Is it possible to use websockets with Tomcat for another component of the API which pushes Data to the client? </li>
<li>Is the type system of Java better than the system of Typescript (not all dependencies are available in Typescript (or?) and therefore don’t have types?)? </li>
</ol> | 2 |
Python if function across a vector | <p>I'm new to Python and trying to work out how to do the following.</p>
<h2>I have a data array, X, which looks something like:</h2>
<pre><code>X = [ 1 2 3
4 5 6
7 8 9
10 11 12];
</code></pre>
<p>Such that the first column <code>X[0]</code> is,</p>
<pre><code>X[0] =[1
4
7
10];
</code></pre>
<p>the second column <code>X[1]</code> is,</p>
<pre><code>X[1] =[2
5
8
11];
</code></pre>
<p>and third column <code>X[2]</code> is,</p>
<pre><code>X[2] =[3
6
9
12];
</code></pre>
<p>What I want to do is generate a single random number, <code>k</code>, and if any of the values in the first column <code>X[0]</code> are greater than <code>k</code> I want to multiply the third column by a function (<code>2*X[0]</code>), and if any of the values are less than <code>k</code> I want to multiply by a different function (<code>2*k</code>).</p>
<p>So if <code>k=2</code>, the third column becomes:
and third column <code>X[2]</code> is,</p>
<pre><code>X[2] =[3*2*k
6*2*X[0,1]
9*2*X[0,2]
12*2*X[0,3] ];
</code></pre>
<p>Is there a succinct way to do this?</p> | 2 |
How to manually change the position of nodes in VisNetwork in R | <p>I have a problem with VisNetwork. I created a graph in R and each time when I click on the node and move it to other place, it comes back to where it was before. Is there any possibility to rearrange network manually? I'd like to move some nodes to the other place or to change the length of edges between some nodes, so that it would be more transparent.</p> | 2 |
How to filter Realm Results by String | <p>I want to filter the <code>RealmResult</code> with respect to the name of persons whose name is "max" This is my <code>RealmResult</code>.</p>
<pre><code>RealmResults data = realm.where(Users.class).findAll();
</code></pre>
<p>but how to select the users with name <code>"max"</code> only?</p> | 2 |
Hide and show checkbox issue in android | <p>I have a <code>Checkbox</code> in a <code>ListView</code> to select items and I have one <code>Button</code> outside the <code>ListView</code>. Initially the <code>Checkbox</code> should be hidden, when I click that <code>Button</code> the <code>Checkbox</code> should display in the <code>ListView</code> and vice versa. </p>
<p>I have one issue in that, when I press the <code>Button</code> initially it displays one <code>Checkbox</code> and again I press the <code>Button</code> it show a few checkboxes but what I want was initially it should be invisible when I press the <code>Button</code> it should be visible in <code>ListView</code> </p>
<p>Note: I have a <code>Button</code> in class and <code>Checkbox</code> in adapter </p>
<pre><code>sdel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
((datalist) mlistView.getAdapter()). toggleChecks();
((datalist)mlistView.getAdapter()).notifyDataSetChanged();
}
});
</code></pre>
<pre><code>public void toggleChecks() {
for (int i = 0;i<sms.size();i++) {
holder.cb.setVisibility(CheckBox.VISIBLE);
}
isCheckBoxVisible=!isCheckBoxVisible;
notifyDataSetChanged();
}
</code></pre> | 2 |
Can't access dropdown select using Selenium in Python | <p>I'm new to using Selenium in Python and I'm trying to access index data on Barclays Live's website. Once I login and the page loads, I'm trying to select 'Custom1' from a dropdown in the page. The select object in the HTML code associated with the list looks like this:</p>
<pre><code><select name="customViewId" class="formtext" onchange="submitFromSelect('username');return false;">
<option value="">&nbsp;</option>
<option value="Favorite Indices">Favorite Indices</option>
<option value="Custom1">Custom1</option>
<option value="CB group">CB group</option>
<option value="Kevin Favorites">Kevin Favorites</option>
<option value="LB Gov/Cdt intermediate">LB Gov/Cdt intermediate</option>
</select>
</code></pre>
<p>This is my code up until I try to access this object:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.support.select import Select
#Get chrome driver and connect to Barclays live site
browser = webdriver.Chrome("C:\Program Files (x86)\Google\Chrome\chromedriver.exe")
browser.get('https://live.barcap.com/')
#Locate username box and enter username
username = browser.find_element_by_name("user")
username.send_keys("username")
#Locate password box and send password
password = browser.find_element_by_name("password")
password.send_keys("password")
#Click login button
login = browser.find_element_by_id("submit")
login.click()
#Open page where you can select indices
browser.get("https://live.barcap.com/BC/barcaplive?menuCode=MENU_IDX_1061")
</code></pre>
<p>I've tried a number of proposed solutions that I've found, usually with the error "Unable to locate element: " followed by whatever method I tried to access the select object with. I don't seem to be able to access it by name, xpath, or by using the Select() function. I've tried putting wait time in the code in case the element hadn't loaded yet, and no luck. Some examples of things I would expect to work, but don't are:</p>
<pre><code>select_box = browser.find_element_by_name("customViewId")
select_box = browser.find_element_by_xpath("//select[option[@value='Custom1']]"
</code></pre>
<p>My background isn't in programming, go easy on me if this is a stupid question. Thanks in advance for the help. </p> | 2 |
Android (How to find list of dates with a interval of 10 days) | <p>I am developing an android application and i am getting start date and end date from the server.</p>
<p>Eg: 20-06-2016 and 20-06-2017 </p>
<p>I want to find the list of dates between these two dates with interval of 10 days. <strong>excluding saturday and sunday</strong>.</p>
<p>for example:
<strong>20-06-2016</strong> is monday so the next date should be <strong>04-07-2016</strong>(excluded saturday and sunday). and so on.</p>
<p>After that on each date(from the list of dates) i want to add event in the calendar on that particular date so that i can notify the user with some message. </p>
<p>I wrote the code that adds event in the calendar and notify the user on particular time. so now i just want the list of dates.</p>
<p>Please help me out.</p>
<p>Thank you.</p> | 2 |
Can't jnlp files in fedora open without icedtea | <p>its possible to open jnlp file without installed icedtea? I had icedtea, but it wasn't run correctly </p> | 2 |
Delete Row in Google Sheet depending on other Google Sheet cell valuie | <p>Is it possible to write a google script that will delete a row in a Google Sheet, based on cell values for a given range, in another google sheet?</p>
<p>I've done some research on how to do this all in the same google sheet, but my limited experience with writing google sheet scripts has prevented me from understanding if what I described is possible, and how. </p>
<p>This is a script I have so far. This will delete rows in a range of my active spreadsheet if a cell in Column F contains the word "id:123456". What I'd like to be able to do, is to modify this code so that if the word "id:123456" is found, it will look in another column of another Google Sheet, and delete rows that contain "id:123456". </p>
<pre><code>function onEdit() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName('Sheet1'); // change to your own
var values = s.getDataRange().getValues();
for (var row in values)
if (values[row][6] == 'id:123456')
s.deleteRow(parseInt(row)+1);
};
</code></pre> | 2 |
Angularjs promise inside a for loop | <p>I have the following code that loops through the list of reports, changes each one's name and does an updates. It works fine if there is only one report in the list, but if there are 2 reports, then only the 2nd one gets updated. </p>
<p>When I looked at the network tab, I saw that for the 1st report, there was only a GET call, but for the 2nd report, there were both GET and PATCH calls.</p>
<p>My suspicion is that in this async loop, the variable <code>thisReport</code> gets overwritten when the 2nd report's GET returns and then it goes on to update the 2nd report. The 1st report didn't get a chance to get updated.</p>
<p>My question is how should I rewrite the code so all the reports in the list can get updated. Sorry about the newbie question. All advice are appreciated!</p>
<pre><code>for (var i = 0; i < $scope.listOfReports.length; i++) {
var reportId = $scope.listOfReports[i].Id;
if (reportId > 0) {
var thisReport = reportSvc.query({ key: reportId });
thisReport.$promise.then(function (data) {
thisReport.name = newValue;
thisReport.$update({ key: reportId }).then(function () {
});
});
}}
</code></pre> | 2 |
How to view the correct client IP in Icecast stats, when Icecast works behind the proxy | <p>I have an Icecast server sitting behind the Apache proxy server, so the connection from the client to Icecast is done by that way:
<br>Client -> Apache server (reverse proxy) -> Icecast server.<br>
The reason I need the proxy, is that I need to have the urls to Icecast via HTTPS on the website, and did not find any other solution except proxying HTTPS to the port, which Icecast sitting on, via HTTP (the proposed solution is here - <a href="https://stackoverflow.com/questions/30237748/why-icecast2-does-not-want-to-give-the-stream-through-https">Why Icecast2 does not want to give the stream through https?</a> , although there they have nginx server as proxy).</p>
<p>Icecast server is showing the stats - the remote ip of the clients connecting to it - and I need that stats. The stats can be viewed via the web-interface of Icecast - base url, following (/admin/listclients.xsl?mount=/mount-point-name). But after proxying the connection, Icecast shows the wrong remote ip there (it always shows the proxy server ip).</p>
<p>Is it possible to make Icecast show the right client ip in those stats (like put there X-Forwarded-For IP instead of REMOTE_ADDR, as the client ip is supposed to be transferred in X-Forwarded-For header to Icecast server by the Apache mod_proxy)?</p>
<p>Here is the config of my Apache proxy virtual host:</p>
<pre><code><VirtualHost *:443>
ServerName my-proxy-server.name
ProxyPreserveHost On
ProxyRequests Off
ProxyPass / http://icecast-server-name:8000/
ProxyPassReverse / http://icecast-server-name:8000/
# Some other strings related to SSL-certificate
.....
</VirtualHost>
</code></pre>
<p>Apache version: 2.4.7 (on Ubuntu)<br>
Icecast version: 2.4.2</p> | 2 |
What does this line "BUILD_TARGET=${1:-none}" means in shell scripting? | <p>I just started learning shell scripting so forgive me if this is too basic to ask here. I want to run this sh script
(<a href="https://github.com/daid/Cura/blob/SteamEngine/package.sh" rel="nofollow noreferrer">https://github.com/daid/Cura/blob/SteamEngine/package.sh</a>).
But I cant understand what this line ( <strong>BUILD_TARGET=${1:-none}</strong> ) does?</p>
<p>Here is the excerpt:</p>
<pre><code>#!/usr/bin/env bash
set -e
set -u
# This script is to package the Cura package for Windows/Linux and Mac OS X
# This script should run under Linux and Mac OS X, as well as Windows with Cygwin.
#############################
# CONFIGURATION
#############################
##Select the build target
BUILD_TARGET=${1:-none}
#BUILD_TARGET=win32
#BUILD_TARGET=darwin
#BUILD_TARGET=debian_i386
#BUILD_TARGET=debian_amd64
#BUILD_TARGET=debian_armhf
#BUILD_TARGET=freebsd
##Do we need to create the final archive
ARCHIVE_FOR_DISTRIBUTION=1
##Which version name are we appending to the final archive
export BUILD_NAME=15.04.6
TARGET_DIR=Cura-${BUILD_NAME}-${BUILD_TARGET}
##Which versions of external programs to use
WIN_PORTABLE_PY_VERSION=2.7.2.1
</code></pre>
<p>When I tried to see how it works by running in Cygwin, it throws the following error,</p>
<pre><code>$ bash package.sh
package.sh: line 2: $'\r': command not found
: invalid option 3: set: -
set: usage: set [-abefhkmnptuvxBCHP] [-o option-name] [--] [arg ...]
: invalid option 4: set: -
set: usage: set [-abefhkmnptuvxBCHP] [-o option-name] [--] [arg ...]
package.sh: line 5: $'\r': command not found
package.sh: line 8: $'\r': command not found
package.sh: line 12: $'\r': command not found
package.sh: line 21: $'\r': command not found
package.sh: line 27: $'\r': command not found
package.sh: line 30: $'\r': command not found
package.sh: line 48: syntax error near unexpected token `$'{\r''
'ackage.sh: line 48: `{
</code></pre>
<p>What I am missing in Cygwin? </p>
<p><strong>Update 1</strong> : I solved 'command not found' by converting the line endings to unix compatible ones. More can be found here, <a href="https://stackoverflow.com/questions/11616835/r-command-not-found-bashrc-bash-profile">'\r': command not found - .bashrc / .bash_profile</a></p> | 2 |
Nesting ResourceDictionaries with MergedDictionaries in UWP | <p>I'm trying to split up a <code>ResourceDictionary</code> containing styles for multiple controls in our current UWP application. The file has grown to about 3000 lines and has become a living hell to manage, so I decided to split it up into smaller, more specific <code>ResourceDictionaries</code> and include them using <code>MergedDictionaries</code>.</p>
<p><code>App.xaml</code></p>
<pre><code><common:BootStrapper x:Class="Asteria.Ion.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:common="using:Template10.Common"
xmlns:styles="using:Asteria.Ion.Styles"
RequestedTheme="Dark">
<common:BootStrapper.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Styles\Custom.xaml" />
<ResourceDictionary Source="Styles\CustomControls.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</common:BootStrapper.Resources>
</common:BootStrapper>
</code></pre>
<p><code>CustomControls.xaml</code> contains references to other <code>ResourceDictionaries</code>.</p>
<pre><code><ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="using:Template10.Controls"
xmlns:behaviors="using:Template10.Behaviors"
xmlns:interactivity="using:Microsoft.Xaml.Interactivity"
xmlns:local="using:Asteria.Ion.Styles">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Shared.xaml" />
<ResourceDictionary Source="Templates.xaml" />
<ResourceDictionary Source="ComponentBlock.xaml" />
<ResourceDictionary Source="FlowAgent.xaml" />
<ResourceDictionary Source="Planning.xaml" />
<ResourceDictionary Source="ProjectDialog.xaml" />
<ResourceDictionary Source="Inspector.xaml" /-->
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</code></pre>
<p>This will always produce the following exception:
<code>Failed to assign to property 'Windows.UI.Xaml.ResourceDictionary.Source' because the type 'Windows.Foundation.String' cannot be assigned to the type 'Windows.Foundation.Uri'. [Line: 12 Position: 37]</code></p>
<p>I've tried changing the source URI numerous times, but it keeps giving this error. Only commenting out all the <code>ResourceDictionary</code> elements in <code>CustomControls.xaml</code> helps. But then I get exceptions concerning missing styles of course. </p>
<p>Some URI formats I've tried:</p>
<ul>
<li><code>/Styles/Shared.xaml</code></li>
<li><code>Styles/Shared.xaml</code></li>
<li><code>Styles\Shared.xaml</code></li>
<li><code>.\Shared.xaml</code></li>
<li><code>ms-appx:///Styles/Shared.xaml</code></li>
</ul>
<p>None of them work. </p>
<p>Any advice would be appreciated.</p> | 2 |
Allow requests only from specific domains | <p>I'm building an API with Laravel 5. </p>
<p>My app will be consumed from multiple apps (web, CRM, mobile, etc).</p>
<p>How can I allow requests from only specific domains?</p>
<p>I found this middleware, but I think this is not what I'm looking for: <a href="http://en.vedovelli.com.br/2015/web-development/Laravel-5-1-enable-CORS/" rel="nofollow">http://en.vedovelli.com.br/2015/web-development/Laravel-5-1-enable-CORS/</a></p> | 2 |
How to change text at the top of your Android-app? | <p><img src="https://i.stack.imgur.com/tOO8V.png" alt="The text NWZC 2016"></p>
<p>I wanna change like you see in the picture above the text <strong>NWZC 2016</strong> at the top of my app, it's the title of my app. I have 5 different activities, and in every activity I want some other text and not this "NWZC 2016". How can I do that? </p>
<p>I've looked in the files styles.xml and strings.xml and AndroidManifest.xml for trying things. I couldn't find anything clear on the Internet.
Can someone help me? Thanks!</p> | 2 |
Sort divs using data attributes and jQuery | <p>i'm new to Javascript and can't seem to find a solution so please forgive me if this has already been answered.</p>
<p>I have a list of divs (lets say these are products of different colored socks). I want users to be able to click buttons and sort these divs by price and popularity based on data attributes of each div without using arrays.</p>
<p>Here is my current JSFiddle: <a href="https://jsfiddle.net/4z97xffh/" rel="nofollow">https://jsfiddle.net/4z97xffh/</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var divList = $(".listing-item");
function sortPrice(){
divList.sort(function(a, b){ return $(a).data("price")-$(b).data("price")});
$("#list").html(divList);}
function sortPopularity(){
divList.sort(function(a, b){ return $(a).data("popularity")-$(b).data("popularity")});
$("#list").html(divList);}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="sortPrice()">Sort by price Low -&gt; High</button>
<button onclick="sortPopularity()">Sort by Popularity Low -&gt; High</button>
<div id="list">
<div class="listing-item" data-price="4" data-popularity="4">[Red Socks] Price: $4 | Popularity: 3</div>
<div class="listing-item" data-price="2" data-popularity="2">[Blue Socks] Price: $2 | Popularity: 1</div>
<div class="listing-item" data-price="1" data-popularity="1">[Green Socks] Price: $1 | Popularity: 2</div>
<div class="listing-item" data-price="3" data-popularity="3">[Yellow Socks] Price: $3 | Popularity: 4</div>
</div>
</code></pre>
</div>
</div>
</p> | 2 |
node - how to read correctly json from a local file? | <p>I am using node.js to serve a page (index.html) where I visualize a network graph, using <a href="http://visjs.org/" rel="nofollow">vis.js</a>. In order to draw a network graph with this library, one needs to provide a <strong>nodes</strong> and <strong>edges</strong> json arrays (<a href="http://visjs.org/examples/network/basicUsage.html" rel="nofollow">see example</a>).</p>
<pre><code>// create an array with nodes
var _nodes_ = [
{id: 1, label: 'Node 1'},
{id: 2, label: 'Node 2'},
{id: 3, label: 'Node 3'},
{id: 4, label: 'Node 4'},
{id: 5, label: 'Node 5'}
];
// create an array with edges
var _edges_ = [
{from: 1, to: 2},
{from: 1, to: 3},
{from: 2, to: 4},
{from: 2, to: 5}
];
</code></pre>
<p>The first version of my <strong>index.html</strong> file looks like:</p>
<pre><code><!doctype html>
<html>
<head>
<title>Network | Basic usage</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/vis.js"></script>
</head>
<body>
<div id="mynetwork"></div>
<script type="text/javascript" >
// create an array with nodes
var _nodes_ = [
{id: 1, label: 'Node 1'},
{id: 2, label: 'Node 2'},
{id: 3, label: 'Node 3'},
{id: 4, label: 'Node 4'},
{id: 5, label: 'Node 5'}
];
// create an array with edges
var _edges_ = [
{from: 1, to: 2},
{from: 1, to: 3},
{from: 2, to: 4},
{from: 2, to: 5}
];
console.log(_nodes_);
console.log(_edges_);
// create a network
var container = document.getElementById('mynetwork');
var data= {
nodes: _nodes_,
edges: _edges_,
};
var options = {
autoResize: true,
clickToUse: false,
width: '800px',
height: '800px'
};
var network = new vis.Network(container, data, options);
</script>
</body>
</html>
</code></pre>
<p>And it is working just fine. However, when I try to read from a local file the <strong>nodes</strong> and <strong>edges</strong> arrays, the network graph doesn't show up:</p>
<pre><code><!doctype html>
<html>
<head>
<title>Network | Basic usage</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/vis.js"></script>
</head>
<body>
<div id="mynetwork"></div>
<script type="text/javascript" >
// create an array with nodes
var _nodes_;
var _edges_;
$.getJSON('json/nodes.json', function(nodes) {
_nodes_= nodes;
});
$.getJSON('json/edges.json', function(edges) {
_edges_ = edges;
});
console.log(_nodes_);
console.log(_edges_);
// create a network
var container = document.getElementById('mynetwork');
var data= {
nodes: _nodes_,
edges: _edges_,
};
var options = {
autoResize: true,
clickToUse: false,
width: '800px',
height: '800px'
};
var network = new vis.Network(container, data, options);
</script>
</body>
</html>
</code></pre>
<p>I am using:</p>
<ul>
<li><p><strong>nodes.json</strong>:</p>
<p>[
{
"id": 1,
"label": "Node 1"
},
{
"id": 2,
"label": "Node 2"
},
{
"id": 3,
"label": "Node 3"
},
{
"id": 4,
"label": "Node 4"
}
]</p></li>
<li><p><strong>edges.json</strong>:</p>
<p>[
{
"from": 1,
"to": 2
},
{
"from": 1,
"to": 3
},
{
"from": 1,
"to": 4
}
]</p></li>
</ul>
<p>Is there a difference between creating a json inside your javascript and reading from a file? Can someone help me spot the error here please?</p>
<p>Thanks!</p> | 2 |
ARM: The easiest way to recreate everything in a resource group into another RG in the same subscription? | <p>I have created a relatively complex IaaS environment in one of my resource groups. The environment is working very well. Now I need to re-build the same environment in another RG for testing and validation.</p>
<p>What would be the easiest way to re-create the same environment in another Resource Group in the same subscription? I tried to export the resource group and downloaded it. The problem is that the file “parameters.json” includes hard coded references to the original resource group name.
Is there an easy way to copy all contents of a RG to another RG in the same environment?
Thank you,</p> | 2 |
ProGuard doesn't obfuscate when building alternative buildType from Android Studio | <p>So in a few words ProGuard doesn't obfuscate sources when I build alternative buildType from Android Studio but works when I use "Generate Signed APK..." option to create apk file.</p>
<p>And some more details here: Android Studio 2.1.1, Gradle version: 2.10, plugin version .2.1.0</p>
<p>I've 3 build types with the following configuration:</p>
<pre><code>buildTypes {
release {
minifyEnabled true
...
proguardFile 'proguard-rules.pro'
proguardFile getDefaultProguardFile('proguard-android.txt')
signingConfig signingConfigs.release
}
releaseDebug {
debuggable true
minifyEnabled true
...
proguardFile 'proguard-rules.pro'
proguardFile getDefaultProguardFile('proguard-android.txt')
signingConfig signingConfigs.release
}
debug {
debuggable true
minifyEnabled false
...
proguardFile getDefaultProguardFile('proguard-android.txt')
testProguardFile 'proguard-rules-test.pro'
signingConfig signingConfigs.release
}
}
</code></pre>
<p>I run application directly from Android Studio and have such results:</p>
<ul>
<li>release - obfuscated</li>
<li>releaseDebug - <strong>NOT</strong> obfuscated</li>
<li>debug - not obfuscated</li>
</ul>
<p>When I use "Generate Signed APK..." option:</p>
<ul>
<li>release - obfuscated</li>
<li>releaseDebug - obfuscated</li>
<li>debug - not obfuscated</li>
</ul>
<p>Is it a build system issue or I missed something?</p>
<p>P.S. Just for clarification, minifyEnabled is already enabled for releaseDebug build type and ProGuard is working but not in this particular case. This is not related to debug mode.</p> | 2 |
Adding line break to long text with resource.resx in ASP.NET MVC | <p>I have tried to separate long text to two lines, when using resource.resx file and logical texts in View.
Found that there are said many times to use shift+enter, but it adds only the line break to .resx file, but when using/rendering the text in view, its still one liner.</p>
<p>Tried even to change the visual studio settings, to keep tabs, but havent any effect.</p>
<p>Any new suggestion how to fix this?</p>
<pre><code>Resource.resx: (used shift+enter to add line break)
LongText:
Long text needed to show/
With to line in the browser
View.cshtml:
(just adds one space -> Long text needed to show/ With to line in the
browser)
@MyResources.Resource.LongText
</code></pre> | 2 |
Spring Boot serving static .webm and .mp4 files with wrong content type | <p>I've got a problem with a Spring Boot application that should serve static .webm and .mp4 files. When I put the files in the <code>static</code> folder on the classpath, the application serves them with content type <code>application/octet-stream</code> instead of <code>video/webm</code>, which makes them not work with <code><video></code> tags. I've tried customizing the resource handler, but it doesn't seem to provide any methods for setting headers. Images and other files work fine.</p>
<p>Spring Boot output:</p>
<pre><code>$ curl -s -D - localhost:8080/CmMs.webm -o /dev/null
HTTP/1.1 200
Last-Modified: Tue, 05 Jul 2016 18:08:41 GMT
Accept-Ranges: bytes
Content-Type: application/octet-stream
Content-Length: 648708
Date: Tue, 05 Jul 2016 18:22:40 GMT
</code></pre>
<p>Output as it should look</p>
<pre><code>$ curl -s -D - http://webm.land/media/CmMs.webm -o /dev/null
HTTP/1.1 200 OK
Server: nginx/1.1.19
Date: Tue, 05 Jul 2016 18:23:21 GMT
Content-Type: video/webm
Content-Length: 648708
Last-Modified: Tue, 05 Jul 2016 17:42:08 GMT
Connection: keep-alive
Accept-Ranges: bytes
</code></pre> | 2 |
CakePHP 3 : global variable to use everywhere | <p>I'm working in CakePHP 3 project and want to create global variable to store some information that can be used throughout the application.</p>
<p>I have to store Company information like Name, slogan, description etc and also some links like, I'm using a subdomain out of the main application to store media files like <code>http://media.website.com</code> and application is at <code>http://website.com</code>. Now I want to store <code>http://media.website.com</code> in a global variable so that I can use it anywhere in my application just like <code>WWW_ROOT</code>.</p>
<p>For this I tried using <code>Configure::write('mediaLink', 'http://media.website.com');</code> and tried to use it in view as <code><img src="<?= Configure::read('mediaLink') . DS . 'files' . DS . 'image.jpg'"></code> but it gives error as <code>Class Configure is not found</code>. I tried adding <code>use Cake\Core\Configure;</code> to the controller but it gives same error.</p> | 2 |
dbus-send not working in shell script | <p>I want Bluetooth tethering between my laptop (Debian 8) and my smartphone (Android).</p>
<p>At the arch linux wiki (<a href="https://wiki.archlinux.org/index.php/android_tethering#Tethering_via_Bluetooth" rel="nofollow">https://wiki.archlinux.org/index.php/android_tethering#Tethering_via_Bluetooth</a>) i found this command: <code>bus-send --system --type=method_call --dest='org.bluez' '/org/bluez/hci0/dev_C0_EE_FB_20_D7_00' org.bluez.Network1.Connect string:'nap'</code></p>
<p>When i execute it in the normal terminal everything works fine. For my purpose i need to call this command in a QT application. Because of this i created a shell script. But when executing the script nothing happens. Same result when calling the command inside a new shell (<code>sh</code>).</p>
<p>Does anybody have an idea how to get this working or another way? My normal terminal is the default Debian terminal, '<code>Root Terminal</code>'.</p>
<p>Thank you</p> | 2 |
Export a webpack bundle / prepend module.exports? Avoid empty object in node? | <p>I'm trying to require my bundle.js into my Node server, but apparently the webpack bundle is missing a <code>module.exports =</code> before all of the bundle code at the top.</p>
<p>I can manually put <code>module.exports =</code> into this bundle, but there has to a programmatic way to specify the bundle should be exportable</p> | 2 |
There is already a collection named "collection" in angular 2 + meteor | <p><code>
import {Mongo} from 'meteor/mongo';
export let Products = new Mongo.Collection('products');
</code></p>
<p>above code is that I've written in my sample project. When I try to run this sample project, It throws error</p>
<blockquote>
<p>There is already a collection named "products"</p>
</blockquote>
<p>I've tried <code>meteor reset</code>. still I am facing same issue. I googled but got no proper solution. can anyone help me out?</p> | 2 |
how to animate a gridview by column wise in android | <p>I am new to programming and I have a task to display a gridview with column wise animation. I tried like this.</p>
<p>My <strong>res/anim/animation.xml</strong> </p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="1500"
android:fromYDelta="5"
android:toYDelta="90%" />
</set>
</code></pre>
<p>part of my <strong>MainActivity.java</strong></p>
<pre><code>Animation anim = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.animation);
gridView.setAnimation(anim);
anim.start();
</code></pre>
<p>In the MainActivity.java please help me where i have to correct. By this I am getting on full gridview animation.</p> | 2 |
Could not find sprockets-3.6.2 in any of the sources (Bundler::GemNotFound) when doing docker-compose up | <p>I am new to docker. I have an existing rails app and I want to dockerize it. Please help me, how can I solve this. I ran into this problem. I have posted the error when I run this.</p>
<pre><code>redis_1 | 1:M 03 Jul 11:47:39.087 * The server is now ready to accept connections on port 6379
sidekiq_1 | /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/spec_set.rb:92:in `block in materialize': Could not find sprockets-3.6.2 in any of the sources (Bundler::GemNotFound)
sidekiq_1 | from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/spec_set.rb:85:in `map!'
sidekiq_1 | from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/spec_set.rb:85:in `materialize'
sidekiq_1 | from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/definition.rb:140:in `specs'
sidekiq_1 | from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/definition.rb:185:in `specs_for'
sidekiq_1 | from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/definition.rb:174:in `requested_specs'
sidekiq_1 | from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/environment.rb:18:in `requested_specs'
sidekiq_1 | from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/runtime.rb:13:in `setup'
sidekiq_1 | from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler.rb:127:in `setup'
sidekiq_1 | from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/setup.rb:18:in `<top (required)>'
sidekiq_1 | from /usr/local/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
sidekiq_1 | from /usr/local/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
backend_1 | /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/spec_set.rb:92:in `block in materialize': Could not find sprockets-3.6.2 in any of the sources (Bundler::GemNotFound)
backend_1 | from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/spec_set.rb:85:in `map!'
backend_1 | from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/spec_set.rb:85:in `materialize'
backend_1 | from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/definition.rb:140:in `specs'
backend_1 | from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/definition.rb:185:in `specs_for'
backend_1 | from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/definition.rb:174:in `requested_specs'
backend_1 | from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/environment.rb:18:in `requested_specs'
backend_1 | from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/runtime.rb:13:in `setup'
backend_1 | from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler.rb:127:in `setup'
backend_1 | from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/setup.rb:18:in `<top (required)>'
backend_1 | from /usr/local/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
backend_1 | from /usr/local/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
backend_sidekiq_1 exited with code 1
backend_backend_1 exited with code 1
</code></pre>
<p>This is my <code>Gemfile</code>:</p>
<pre><code>source 'https://rubygems.org'
gem 'unicorn', '~> 4.9'
gem 'pg', '~> 0.18.3'
gem 'sidekiq', '~> 4.0.1'
gem 'redis-rails', '~> 4.0.0'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.6'
# Use sqlite3 as the database for Active Record
# gem 'sqlite3'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.1.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use Unicorn as the app server
# gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug'
end
group :development do
# Access an IRB console on exception pages or by using <%= console %> in views
gem 'web-console', '~> 2.0'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
end
</code></pre>
<p>When I started the build process, <code>sprockets-3.6.2</code> was installed.</p>
<p>My <code>Dockerfile</code> :</p>
<pre><code># Use the barebones version of Ruby 2.2.3.
FROM ruby:2.2.3-slim
# Optionally set a maintainer name to let people know who made this image.
MAINTAINER Class and Objects <[email protected]>
# Install dependencies:
RUN apt-get update && apt-get install -qq -y build-essential nodejs libpq-dev postgresql-client-9.4 --fix-missing --no-install-recommends
# Set an environment variable to store where the app is installed to inside
# of the Docker image.
# CHANGE ALL INSTANCE OF 'backend' WITH YOUR PROJECT NAME
ENV INSTALL_PATH /backend
RUN mkdir -p $INSTALL_PATH
# This sets the context of where commands will be ran in and is documented
# on Docker's website extensively.
WORKDIR $INSTALL_PATH
# Ensure gems are cached and only get updated when they change. This will
# drastically increase build times when your gems do not change.
COPY Gemfile Gemfile
RUN bundle install
# Copy in the application code from your work station at the current directory
# over to the working directory.
COPY . .
# Provide dummy data to Rails so it can pre-compile assets.
RUN bundle exec rake RAILS_ENV=production DATABASE_URL=postgresql://user:[email protected]/dbname SECRET_TOKEN=pickasecuretoken
#assets:precompile
# Expose a volume so that nginx will be able to read in assets in production.
VOLUME ["$INSTALL_PATH/public"]
# The default command that gets ran will be to start the Unicorn server.
CMD bundle exec unicorn -c config/unicorn.rb
</code></pre>
<p>My <code>docker-compose.yml</code> :</p>
<pre><code>postgres:
image: postgres:9.4.5
environment:
POSTGRES_USER: backend
POSTGRES_PASSWORD: yourpassword
ports:
- '5432:5432'
volumes:
- backend-postgres:/var/lib/postgresql/data
redis:
image: redis:3.0.5
ports:
- '6379:6379'
volumes:
- backend-redis:/var/lib/redis/data
backend:
build: .
links:
- postgres
- redis
volumes:
- .:/backend
ports:
- '8000:8000'
env_file:
- .backend.env
sidekiq:
build: .
command: bundle exec sidekiq -C config/sidekiq.yml
links:
- postgres
- redis
volumes:
- .:/backend
env_file:
- .backend.env
</code></pre>
<p>my <code>sidekiq.rb</code>:</p>
<pre><code>sidekiq_config = { url: ENV['JOB_WORKER_URL'] }
Sidekiq.configure_server do |config|
config.redis = sidekiq_config
end
Sidekiq.configure_client do |config|
config.redis = sidekiq_config
end
</code></pre> | 2 |
How to create Angular2 Modal Component WITHOUT Bootstrap and WITHOUT jQuery? | <p>All searches on this topic lead to importing existing components that depend on Bootstrap.</p>
<p>I don't want to use Bootstrap. I want my own simpler HTML markup and way less class names to remember and crowd an already-complicated markup.</p>
<p>I'm fairly comfortable with components, component lifecycle, services, templates, events, observables, and other Angular2 concepts, but I am only able to build an application with nested components whose "parent page" end up in <router-outlet>.</p>
<p>I feel that there may be some lesser-known concepts of Angular2 that most tutorials and even video courses don't address, that would allow me to achieve modal popups. I think I will have to somehow "hack" the DOM to insert some html at the root of the entire webpage so that I can absolutely position the modal. I don't want to use jQuery because it might violate Angular2's inner workings and principles. If possible, I want to know an Angular2-safe way to manipulate the DOM if I have to - I prefer not to chase DOM elements from component code.</p>
<p>I do not only want alert confirmations and prompts. I want to be able to put a form-component on the modal window that would allow the user to save something to the database or choose an item from a list.</p>
<p>I know I'm asking for a lot, but specifically:</p>
<ol>
<li>What html markup and CSS should my popup component have at a minimum? Ideally, I want to put a translucent cover over the entire page, and the actual modal on top of it. to ensure that users can't click outside that modal window.</li>
<li>How, if absolutely required, would services and observables be used to pull this?</li>
<li>Can I just include this modal component's markup (as defined in its @Component({}) decorator) on a host/parent component and open it?</li>
<li>Ideally, on the host component's code, I want to be able to call something like <code>selectRecordModal.onSelected(selectedItem => { .... }).onCancelled( () => { ... });</code></li>
</ol> | 2 |
Using the Roslyn Semantic Model to Find Symbols in a Single .cs File | <p>I am using Roslyn to create an analyzer that warns users if a particular class exposes its fields in an unsynchronized manner, to help prevent race conditions.</p>
<h2>The Problem:</h2>
<p>I currently have working code that checks to make sure a field is private. I’m having trouble with the last piece of the puzzle: figuring out a way to make sure that all fields are only accessed inside a lock block, so they’re (ostensibly) synchronized.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.FindSymbols;
namespace RaceConditions
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class UnsynchronizedMemberAccess : DiagnosticAnalyzer
{
public const string DiagnosticId = "UnsynchronizedMemberAccess";
internal static readonly LocalizableString Title = "UnsynchronizedMemberAccess Title";
private static readonly LocalizableString MessageFormat = "Unsychronized fields are not thread-safe";
private static readonly LocalizableString Description = "Accessing fields without a get/set methods synchronized with each other and the constructor may lead to race conditions";
internal const string Category = "Race Conditions";
private static DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } }
//meant to stop other classes and itself from accessing members in an unsychronized fashion.
public override void Initialize(AnalysisContext analysisContext)
{
analysisContext.RegisterSemanticModelAction((context) =>
{
var model = context.SemanticModel;
var root = model.SyntaxTree.GetRoot();
var nodes = model.SyntaxTree.GetRoot().DescendantNodes();
var fields = nodes.OfType<VariableDeclaratorSyntax>()
.Where(v => v.Ancestors().OfType<FieldDeclarationSyntax>().Any());
//since (it appears) that you can't read/write to a an initialized field,
//I think it means you can only read/write inside a block
foreach (BlockSyntax b in nodes.OfType<BlockSyntax>())
{
//where I plan to put code to check references to the fields
}
});
}
}
}
</code></pre>
<p>More specifically, I’d like to be able to ensure everything highlighted by the reference highlighter (at least that’s what Microsoft seems to call it) is inside a lock block, while overloaded parameters do not have to.</p>
<pre><code>using System;
using System.Linq;
using System.Activities;
using System.Activities.Statements;
using System.Data.SqlClient;
namespace Sandbox
{
partial class Program
{
private int xe = 0, y = 0;
public Program(int xe)
{
this.xe = xe;
}
void bleh()
{
if (xe == 0)
{
xe = xe + 1;
}
}
static void Main(string[] args)
{
Program p0 = new Program(5),
p1 = new Program(p0),
p2 = new Program(p0.xe);
Console.WriteLine(p1.xe);
Console.Read();
}
}
partial class Program
{
public Program(Program p) : this(p.xe) { }
}
}
</code></pre>
<h2>The Research:</h2>
<p>Here, Josh Varty [1] suggests I use <code>SymbolFinder.FindReferencesAsync</code>, which requires a <code>Solution</code> object. Jason Malinowski [2] says that I shouldn’t use do this in an analyzer, since making a <code>MSBuildWorkspace</code> to get a <code>Solution</code> object is too slow, while this person [3] offers an incomplete/missing workaround to the slowness issue (the link to <code>ReferenceResolver</code> seems to be broken).</p>
<p>I have also looked into <code>DataFlowAnalysis</code> (<code>SemanticModel.AnalyzeDataFlow()</code>), but I can’t find any particular methods there that obviously let me guarantee that I’m referencing the field <code>xe</code>, and not the local variable <code>xe</code>.</p>
<h2>The Question:</h2>
<p>I do feel like there is something monumentally obvious I’m missing. Is there some elegant way to implement this that I’ve overlooked? It’d be preferable if the answer uses the semantic model, since I expect I have to use it in other analyzers to figure out where data/references come from, but I realize there are limitations, so any answers without the semantic model are also fine.</p>
<h2>Notes:</h2>
<ul>
<li>Apparently, this issue was also encountered at Github [4], but apparently it’s still being tracked there, and they don’t know if the analyzer should analyze on the project level or not. It still hasn’t been resolved. For the purposes of this analyzer, I will assume that the entire class contained in a single <code>.cs</code> file. Small steps first, eh?</li>
<li>I also searched through John Koerner's website [5] and Josh Varty's website [6], and couldn’t find anything relevant to both analyzers and DataFlowAnalysis.</li>
</ul> | 2 |
Error parsing parameter, amazon aws emr | <p>I'm trying to create a step by Linux console:</p>
<pre><code>aws emr add-steps --cluster-id j-XXXXXXXXXX --steps Type=CUSTOM_JAR,Name="S3DistCp step",Jar=/home/hadoop/lib/emr-s3distcp-1.0.jar,\
Args=["--s3Endpoint,s3-eu-west-1.amazonaws.com","--src,s3://folder-name/logs/j-XXXXXXXXXX/node/","--dest,hdfs:///output","--srcPattern,.*[a-zA-Z,]+"]
</code></pre>
<p>I jump the following error</p>
<blockquote>
<p>Error parsing parameter '--steps': Expected: ',', received: '+' for input</p>
</blockquote>
<p>How I can fix it?</p>
<p>I'm looking for a solution to upload multiple files to S3 and S3DistCp the Hive gather for Amazon EMR. Is there any other way?</p>
<p>I have another question:
Now I am creating an SSH tunnel to connect to Hive, how I could connect with PHP?</p>
<hr>
<p>At the moment I have solved the error by removing "src Pattern", however gives me another error, I include image below</p>
<p><a href="http://i.stack.imgur.com/1uaBO.png" rel="nofollow">Image error</a></p>
<p>This is the error that appears</p>
<pre><code>INFO Synchronously wait child process to complete : hadoop jar /var/lib/aws/emr/step-runner/hadoop-
INFO waitProcessCompletion ended with exit code 1 : hadoop jar
/var/lib/aws/emr/step-runner/hadoop-
INFO total process run time: 2 seconds
2016-07-12T14:26:48.744Z INFO Step created jobs:
2016-07-12T14:26:48.744Z WARN Step failed with exitCode 1 and took 2 seconds
</code></pre>
<p>Thx!!!</p> | 2 |
What's difference between find() and indexOf() methods for array | <p><a href="https://stackoverflow.com/questions/143847/best-way-to-find-if-an-item-is-in-a-javascript-array">Best way to find if an item is in a JavaScript array?</a></p>
<pre><code>var array = [2, 5, 9];
array.indexOf(2); // 0
array.indexOf(7); // -1
let found = array.find(x => x === 5 );
console.log(found); //5
found = array.find(x => x === 51 );
console.log(found); //undefined
</code></pre>
<p>What method use to detect value in array ?</p>
<p><code>array.indexOf(val) !== -1</code> or </p>
<pre><code>typeof array.find(x => x === val ) !== 'undefined';
</code></pre> | 2 |
Get security groups members Domain\Username | <p>I have script that get all members of security groups across domains and export to <code>CSV file</code> in this format: <code>Name, username, security group</code>. But I want to add another row for the domain so format will look like this: <code>domain\username, name, security group</code>. </p>
<p>I could get the DN but I am only interested in just <code>domain\username</code>. I search around in the internet and I couldn't find anything and I am not sure if this even possible </p>
<pre><code>$objForest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest() $DomainList = @($objForest.Domains | Select-Object Name) $Domains = $DomainList | foreach {$_.Name}
$Groups = Import-Csv C:\ad.csv
$Table = @()
$Record = @{ "Group Name" = "" "Name" = "" "Username" = "" }
Foreach ($Group in $Groups) {
$Arrayofmembers = Get-ADGroupMember -identity $Group.groupad
-recursive -Server $Domain | select name,samaccountname
foreach ($Member in $Arrayofmembers) {
$Record."Group Name" = $Group.ad
$Record."Name" = $Member.name
$Record."UserName" = $Member.samaccountname
$objRecord = New-Object PSObject -property $Record
$Table += $objrecord
}
}
$Table | export-csv "C:\SecurityGroups3.csv" -NoTypeInformation
</code></pre> | 2 |
AngularJS: angular-filter: How to the group by with 2 columns? | <p>I know I may sound a bit confusing so I request you to please let me elaborate</p>
<p><em>Note: A working POC (piece of code) has been attached to this post.</em></p>
<p>I have an array of an object having 3 properties
name</p>
<ol>
<li>name</li>
<li>team</li>
<li>team_rank</li>
</ol>
<blockquote>
<pre><code> $scope.players = [
{name: 'Gene', team: 'alpha', team_rank: 1},
{name: 'George', team: 'beta', team_rank: 2},
{name: 'Steve', team: 'gamma', team_rank: 3},
{name: 'Paula', team: 'beta', team_rank: 2},
{name: 'Scruath', team: 'gamma', team_rank: 3}
];
</code></pre>
</blockquote>
<p>I have got the result shown below in the pic by running the POC.</p>
<p><a href="https://i.stack.imgur.com/bjKaZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bjKaZ.png" alt="enter image description here"></a></p>
<p><strong>Problem</strong></p>
<p>I need to show the rank of the team with the team name. Please suggest what should I do?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.4.7/angular-filter.js"></script>
<meta name="description" content="[groupBy example]"/>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div ng-controller="MainController">
<ul ng-repeat="(key, value) in players | groupBy: 'team'">
Group name: {{ key }}
<li ng-repeat="player in value">
player: {{ player.name }}
</li>
</ul>
</div>
<footer>
<script>
angular.module('app',['angular.filter'])
.controller('MainController', function($scope) {
$scope.players = [
{name: 'Gene', team: 'alpha', team_rank: 1},
{name: 'George', team: 'beta', team_rank: 2},
{name: 'Steve', team: 'gamma', team_rank: 3},
{name: 'Paula', team: 'beta', team_rank: 2},
{name: 'Scruath', team: 'gamma', team_rank: 3}
];
});
</script>
</footer>
</body>
</html></code></pre>
</div>
</div>
</p> | 2 |
FileNotFoundException in laravel | <p>In laravel i am making an application that uploads a file and the user can download that same file.</p>
<p>But each time i click to upload i get this error. </p>
<pre><code> FileNotFoundException in File.php line 37: The file
"H:\wamp64\tmp\phpF040.tmp" does not exist
</code></pre>
<p>my view code is this:</p>
<pre><code>@extends('layouts.app')
@section('content')
@inject('Kala','App\Kala')
<div class="container">
<div class="row">
@include('common.errors')
<form action="/addkala" method="post" enctype="multipart/form-data">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="text" name="name">
<input type="text" name="details">
<input type="file" name="photo" id="photo" >
<button type="submit">submit</button>
</form>
</div>
</div>
@endsection
</code></pre>
<p>and my controller</p>
<pre><code>public function addkalapost(Request $request)
{
$rules = [
'name' => 'required|max:255',
'details' => 'required',
'photo' => 'max:1024',
];
$v = Validator::make($request->all(), $rules);
if($v->fails()){
return redirect()->back()->withErrors($v->errors())->withInput($request->except('photo'));
} else {
$file = $request->file('photo');
$fileName = time().'_'.$request->name;
$destinationPath = public_path().'/uploads';
$file->move($destinationPath, $fileName);
$kala=new Kala;
$kala->name=$request->name;
return 1;
$kala->details=$request->details;
$kala->pic_name=$fileName;
$kala->save();
return redirect()->back()->with('message', 'The post successfully inserted.');
}
}
</code></pre>
<p>and i change the upload max size in php.ini to 1000M.
plz help
im confusing</p> | 2 |
Map tiles not loading until a zoom is executed(Leaflet) | <p>Here's the code:</p>
<pre class="lang-js prettyprint-override"><code>mapLink = '<a href="http://openstreetmap.org">OpenStreetMap</a>';
var map = L.map('map').setView([25.7617,-80.18], 30);
L.tileLayer(
'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '&copy; ' + mapLink + ' Contributors',
maxZoom: 18,
}).addTo(map);
</code></pre>
<p>It gives no errors, yet it starts off as gray unless I zoom. Is there an attribute I'm missing or something? Must be a tile problem?</p> | 2 |
UIStackView not appearing in Container View | <p>Can someone please explain to me why I cannot see this StackView show up in its container? </p>
<p>This is what it looks like now:
<a href="https://i.stack.imgur.com/lLfOt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lLfOt.png" alt="enter image description here"></a></p>
<p>This is what I want it to look like, ignore the cells, I just need to figure out why the Edit button, search bar and Sort button are not showing.<br>
<a href="https://i.stack.imgur.com/iuDJU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iuDJU.png" alt="enter image description here"></a></p>
<p>Here is the code I used to setup the views and their contents:</p>
<pre><code> // Container
let barViewFrame = CGRectMake(0, 0, view.frame.width, 44)
let barViewContainer = UIView(frame: barViewFrame)
barViewContainer.backgroundColor = UIColor(red: 231/255, green: 231/255, blue: 231/255, alpha: 1.0)
tableView.tableHeaderView = barViewContainer
// Edit Button
let editButton = UIButton(type: .System)
editButton.bounds = CGRectMake(0, 0, 44, 44)
editButton.setTitle("Edit", forState: .Normal)
// Search Bar
let searchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width: 50, height: 44))
searchBar.placeholder = "Search"
searchBar.searchBarStyle = .Prominent
searchBar.barTintColor = UIColor(red: 231/255, green: 231/255, blue: 231/255, alpha: 1.0)
// Sort Button
let sortButtton = UIButton(type: .Custom)
sortButtton.bounds = CGRectMake(0, 0, 44, 44)
sortButtton.setImage(UIImage(named: "Sort"), forState: .Normal)
// Stackview
let stackViewH = UIStackView(arrangedSubviews: [editButton, searchBar, sortButtton])
stackViewH.axis = .Horizontal
stackViewH.alignment = .Center
stackViewH.spacing = 8
barViewContainer.addSubview(stackViewH)
barViewContainer.addConstraints([
stackViewH.leftAnchor.constraintEqualToAnchor(barViewContainer.leftAnchor),
stackViewH.topAnchor.constraintEqualToAnchor(barViewContainer.topAnchor),
stackViewH.rightAnchor.constraintEqualToAnchor(barViewContainer.rightAnchor),
stackViewH.bottomAnchor.constraintEqualToAnchor(barViewContainer.bottomAnchor)])
</code></pre> | 2 |
Secondary Logon service disabled, yet I can still invoke 'Run as administrator'? | <p>It's my understanding that disabling the seclogon service leads to an inability to run programs as administrator or anyone else. Yet here I am in my standard account running cmd with admin credentials, verified with Task Manager. Seclogon is verified disabled and stopped, both in Task Manager and Services.</p>
<p>Windows 10, latest updates.
1 local admin account, created on fresh windows install.
1 local standard account.</p>
<p>Is my understanding incorrect, or is something not functioning correctly?</p> | 2 |
javascript click not firing after partial view load | <p>I have a view with a javascript section. In this view I have javascript with an onclick event which fires on a tab click to load a partial view this all works perfectly.</p>
<p>Now I know javascript on a partial view wont work properly so in the main view I want to add a click event for when a print button gets clicked.</p>
<pre><code> <script type="text/javascript">
$(function () {
$('#printBtn').click(function () {
debugger;
printElement(document.getElementById("modal-body"));
window.print();
});
$('#tabStrip a').click(function (e) {
e.preventDefault()
var tabID = $(this).attr("href").substr(1);
$(".tab-pane").each(function () {
$(this).empty();
});
$("#" + tabID).empty().append("<div class='loader'><img src='/Content/img/Loader/ajax-loader.gif' alt='Loading' /></div>");
$.ajax({
url: "/Account/CustomerTab",
data: { Id: tabID },
cache: false,
type: "get",
dataType: "html",
success: function (result) {
$("#" + tabID).empty().append("<div id='replaceDiv'>" + result + "</div>");
$(document).trigger('ready');
debugger;
}
});
$(this).tab('show')
});
});
</script>
</code></pre>
<p>so the tab click works perfectly but once my partial view is loaded then the print button debugger doesn't get hit. this is the button in my partial view.</p>
<pre><code><button id="printBtn" type="button" class="btn btn-default">Print</button>
</code></pre> | 2 |
Ignore assembly .dll in same folder as executable | <p>I have a .NET application that crashes if I have the MySql.Data.dll assembly in the same folder as the executable but works fine if I move it. A different executable in the same folder is dependent on it so I need to keep it there. </p>
<p>What can I do to make the app ignore this dll?
I assume I can edit the config file but I can't seem to find anyone having had the problem of ignoring a local .dll, so I don't know what to write.</p>
<p>What makes me even more confused is the part about loaded assemblies written in the details of the exception. Mind you the file in the local folder (the one I want to ignore) is versioned 6.9.9.0 and the exception states that it wants to load 6.9.5.0 where as the loaded one (from the GAC) is 6.9.8.0.</p>
<p>This is my configuration file:</p>
<pre><code><?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="DB" connectionString="*" providerName="System.Data.EntityClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>
</code></pre>
<p>Very thankful for any help.</p>
<pre><code>************** Loaded Assemblies **************
---------------------------------------
MySql.Data
Assembly Version: 6.9.8.0
Win32 Version: 6.9.8.0
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/MySql.Data/v4.0_6.9.8.0__c5687fc88969c44d/MySql.Data.dll
----------------------------------------
</code></pre>
<hr>
<blockquote>
<p>************** Exception Text **************</p>
<p>System.IO.FileLoadException: Could not load file or assembly
'MySql.Data, Version=6.9.5.0, Culture=neutral,
PublicKeyToken=c5687fc88969c44d' or one of its dependencies. The
located assembly's manifest definition does not match the assembly
reference. (Exception from HRESULT: 0x80131040)
File name: 'MySql.Data, Version=6.9.5.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d'
at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly
locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder,
Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean
suppressSecurityChecks)
at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly
locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder,
Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean
suppressSecurityChecks)
at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName
assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly,
StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean
throwOnFileNotFound, Boolean forIntrospection, Boolean
suppressSecurityChecks)
at System.Reflection.Assembly.Load(AssemblyName assemblyRef)
at System.Data.Metadata.Edm.MetadataAssemblyHelper.SafeLoadReferencedAssembly(AssemblyName
assemblyName)
at System.Data.Metadata.Edm.MetadataAssemblyHelper.d__8.MoveNext()
at System.Data.Metadata.Edm.DefaultAssemblyResolver.GetAllDiscoverableAssemblies()
at System.Data.Metadata.Edm.DefaultAssemblyResolver.GetWildcardAssemblies()
at System.Data.Metadata.Edm.MetadataArtifactLoaderCompositeResource.LoadResources(String
assemblyName, String resourceName, ICollection<code>1 uriRegistry,
MetadataArtifactAssemblyResolver resolver)
at System.Data.Metadata.Edm.MetadataArtifactLoaderCompositeResource.CreateResourceLoader(String
path, ExtensionCheck extensionCheck, String validExtension,
ICollection</code>1 uriRegistry, MetadataArtifactAssemblyResolver resolver)
at System.Data.Metadata.Edm.MetadataArtifactLoader.Create(String path,
ExtensionCheck extensionCheck, String validExtension, ICollection<code>1
uriRegistry, MetadataArtifactAssemblyResolver resolver)
at System.Data.Metadata.Edm.MetadataCache.SplitPaths(String paths)
at System.Data.Common.Utils.Memoizer</code>2.<>c__DisplayClass4_0.b__0()
at System.Data.Common.Utils.Memoizer<code>2.Result.GetValue()
at System.Data.Common.Utils.Memoizer</code>2.Evaluate(TArg arg)
at System.Data.EntityClient.EntityConnection.GetMetadataWorkspace(Boolean
initializeAllCollections)
at System.Data.Objects.ObjectContext.RetrieveMetadataWorkspaceFromConnection()
at System.Data.Objects.ObjectContext..ctor(EntityConnection connection, Boolean isConnectionConstructor)
at Panola.Data.Models.PanolaDB..ctor()
at Panola.Data.Services.PanolaConfigurator..ctor(String Name, Boolean UseDefualtRepositories)
at Panola.Data.Services.PanolaConfigurator..ctor(String Name)
at Panola.Tools.Configurator.MainForm.connectToolStripMenuItem_Click(Object
sender, EventArgs e)
at System.Windows.Forms.ToolStripItem.RaiseEvent(Object key, EventArgs e)
at System.Windows.Forms.ToolStripMenuItem.OnClick(EventArgs e)
at System.Windows.Forms.ToolStripItem.HandleClick(EventArgs e)
at System.Windows.Forms.ToolStripItem.HandleMouseUp(MouseEventArgs e)
at System.Windows.Forms.ToolStripItem.FireEventInteractive(EventArgs e,
ToolStripItemEventType met)
at System.Windows.Forms.ToolStripItem.FireEvent(EventArgs e, ToolStripItemEventType met)
at System.Windows.Forms.ToolStrip.OnMouseUp(MouseEventArgs mea)
at System.Windows.Forms.ToolStripDropDown.OnMouseUp(MouseEventArgs mea)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.ToolStrip.WndProc(Message& m)
at System.Windows.Forms.ToolStripDropDown.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)</p>
</blockquote> | 2 |
ListBox Item layout in XAML/WPF | <p>I am struggling last days to achieve following layout:</p>
<p><a href="https://i.stack.imgur.com/z2k25.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/z2k25.jpg" alt="sketch"></a></p>
<p>I have a ListBox with template for each Item:</p>
<ul>
<li>Label always anchored on left side</li>
<li>Label always anchored on right side</li>
<li>Label (TextBlock) in middle with flexible size</li>
<li>3rd label bellow, so far this is easiest to set :)</li>
</ul>
<p>Main problem in my example is that I can't made middle text (that can be long) to adjust, but not push suffix (red) label while I am resizing ListBox.</p>
<p>I hope that this layout is possible, and that I am missing something trivial. </p>
<p>What's interesting is that 1st example (bellow) work well "outside" listbox. Do I need somehow force realign of listbox while resizing?</p>
<p>Thanks for any help.</p>
<p>I have attached bellow 2 examples I tried (beside many other):</p>
<p>XAML:</p>
<pre><code><Window x:Class="WPF_Experiments.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WPF_Experiments"
mc:Ignorable="d"
Title="MainWindow" Height="400" Width="400">
<Window.Resources>
<DataTemplate x:Key="Template1">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition Width="auto" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Foreground="Blue" Background="Aqua" Content="{Binding Prefix}" />
<Label Grid.Column="1" Content="{Binding Description}" />
<Label Grid.Column="2" Foreground="Magenta" Background="Beige" Content="{Binding Suffix}" />
</Grid>
</DataTemplate>
<DataTemplate x:Key="Template2">
<DockPanel LastChildFill="True">
<Label Grid.Column="0" Foreground="Blue" Background="Aqua" Content="{Binding Prefix}" />
<Label Grid.Column="2" DockPanel.Dock="Right" Foreground="Magenta" Background="Beige" Content="{Binding Suffix}" />
<TextBlock Grid.Column="1" Text="{Binding Description}" TextTrimming="CharacterEllipsis" />
</DockPanel>
</DataTemplate>
</Window.Resources>
<StackPanel>
<ListBox Name="MyListBox"
ItemTemplate="{DynamicResource Template2}"/>
</StackPanel>
</Window>
</code></pre>
<p>C#:</p>
<pre><code>namespace WPF_Experiments
{
class Item
{
public string Prefix { get; set; }
public string Description { get; set; }
public string Suffix { get; set; }
}
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<Item> items = new List<Item>();
items.Add(new Item() { Prefix = "001", Description = "Item 0", Suffix = "cm" });
items.Add(new Item() { Prefix = "002", Description = "This is very long item that maybe will not fit", Suffix = "in" });
items.Add(new Item() { Prefix = "003", Description = "Item 2", Suffix = "m" });
MyListBox.ItemsSource = items;
}
}
}
</code></pre>
<p>(Edit) One more try with StackPanel:</p>
<pre><code> <DataTemplate x:Key="Template3">
<StackPanel Orientation="Horizontal">
<Label Foreground="Blue" Background="Aqua" Content="{Binding Prefix}" />
<TextBlock Text="{Binding Description}" TextTrimming="CharacterEllipsis" />
<Label Foreground="Magenta" Background="Beige" Content="{Binding Suffix}" HorizontalAlignment="Right" />
</StackPanel>
</DataTemplate>
</code></pre> | 2 |
Get value from OpenCV Mat | <p>I have one channel matrix in my program, with next definition: </p>
<pre><code>matchingResult.create(result_cols, result_rows, CV_32FC1);
</code></pre>
<p>It is not a matrix of colours.<br>
I use <em>minMaxLoc</em> method to find of positions of the min and max values:</p>
<pre><code>double minValue;
double maxValue;
cv::Point minLocation;
cv::Point maxLocation;
cv::minMaxLoc(_matchingMap, &minValue, &maxValue, &minLocation, &maxLocation);
</code></pre>
<p>This method returns correct values: </p>
<blockquote>
<p>MinValue: -287909 MaxValue: 682182 MinLocation: [5, 1] MaxLocation:
[4, 2]</p>
</blockquote>
<p>If I print the matrix into <em>cout</em> I'll get same result.</p>
<p>But I can't get same value from the matrix by using the location of max value (maxLocation), or change value of the max.<br>
If I try to get value: </p>
<pre><code>double value = _matchingMap.at<double>(maxLocation);
std::cout<<"Value for "<<maxLocation << " is "<<value << std::endl;
</code></pre>
<p>I'll get something strange:</p>
<blockquote>
<p>Value for [4, 2] is -1.08215e+39</p>
</blockquote>
<p>I want to change values in matrix by using row/coll coordinates, but I do something wrong. I can't find error, may smb can show me the correct way.</p>
<p>How to iterate a matrix I've seen <a href="http://docs.opencv.org/2.4/doc/tutorials/core/how_to_scan_images/how_to_scan_images.html#performance-difference" rel="nofollow">here</a> </p> | 2 |
How to set popup after customer login | <p>I need popup with custom content after customer successfully login. </p>
<p>In content I need to set customer name, customer group and some other text.</p> | 2 |
Problems running Maven Failsafe Plugin | <p>I'm having trouble running failsafe plugin using <code>mvn verify</code></p>
<p>Basically it doesn't run the integration tests! If I run <code>mvn failsafe:integration-test</code> works ok</p>
<p>Also, do I need jetty plugin or similar for running integration tests. </p>
<p>The failsafe tasks are not bound to verify task</p>
<p>Code has been checked in to..
<a href="https://github.com/tonymurphy/builder" rel="nofollow">https://github.com/tonymurphy/builder</a></p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>junit-stuff</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jxr-plugin</artifactId>
<version>2.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-report-plugin</artifactId>
<version>2.19.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<testResources>
<testResource>
<directory>src/test/resources</directory>
</testResource>
</testResources>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19</version>
<executions>
<execution>
<id>default-test</id>
<phase>none</phase>
</execution>
<execution>
<id>unit-test</id>
<phase>test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<includes>
<include>**/*.java</include>
</includes>
<excludes>
<exclude>**/*$*</exclude>
<exclude>**/*ContractTest.java</exclude>
<exclude>**/*MvcTest.java</exclude>
<exclude>**/*_Test.java</exclude>
</excludes>
<excludedGroups>com.example.OneAtATime</excludedGroups>
</configuration>
</execution>
<execution>
<id>mvc-tests</id>
<phase>test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<includes>
<include>**/*MvcTest.java</include>
</includes>
<excludedGroups>com.example.OneAtATime</excludedGroups>
<excludes>
<exclude>**/*$*</exclude>
<exclude>**/*ContractTest.java</exclude>
<exclude>**/*_Test.java</exclude>
</excludes>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.19.1</version>
<executions>
<execution>
<id>integration-test</id>
<configuration>
<groups>com.example.OneAtATime</groups>
</configuration>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.2.2.v20140723</version>
<configuration>
<scanIntervalSeconds>10</scanIntervalSeconds>
<stopPort>8005</stopPort>
<stopKey>STOP</stopKey>
</configuration>
<executions>
<execution>
<id>start-jetty</id>
<phase>pre-integration-test</phase>
<goals>
<!-- stop any previous instance to free up the port -->
<goal>stop</goal>
<goal>start</goal>
</goals>
<configuration>
<scanIntervalSeconds>0</scanIntervalSeconds>
<daemon>true</daemon>
</configuration>
</execution>
<execution>
<id>stop-jetty</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jxr-plugin</artifactId>
<version>2.5</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-report-plugin</artifactId>
<version>2.19.1</version>
<reportSets>
<reportSet>
<id>integration-tests</id>
<reports>
<report>failsafe-report-only</report>
</reports>
</reportSet>
</reportSets>
</plugin>
</plugins>
</reporting>
</project>
</code></pre> | 2 |
How to maintain state of checkboxes of Datatable when data loaded via ajax. | <p>I am trying to load Datatable rows with server side calling. I have around 30000 data. By default I have loaded 200 data per page with pagination. Each row contains checkbox. Now the problem is that, suppose I have checked 5 checkboxes among 200 datas, next when going next page and back to previous page again the 5 checkboxes showed me unchecked. How I can now maintain the state of the checkboxes even if I travel through pages. Please help me to give a solution. Thanks. </p> | 2 |
parse a document with million words | <p>I have implemented some code to find the anagrams word in the txt <code>sample.txt</code> file and output them on the console. The txt document contains String (word) in each of line.</p>
<p>Is that the right Approach to use if I want to find the anagram words in txt.file with Million or 20 Billion of words? If not which Technologie should I use in this case?</p>
<p>I appreciate any help.</p>
<p><strong>Sample</strong></p>
<pre><code>abac
aabc
hddgfs
fjhfhr
abca
rtup
iptu
xyz
oifj
zyx
toeiut
yxz
jrgtoi
</code></pre>
<p><strong>oupt</strong></p>
<pre><code>abac aabc abca
xyz zyx yxz
</code></pre>
<p><strong>Code</strong></p>
<pre><code>package org.reader;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Test {
// To store the anagram words
static List<String> match = new ArrayList<String>();
// Flag to check whether the checkWorld1InMatch() was invoked.
static boolean flagCheckWord1InMatch;
public static void main(String[] args) {
String fileName = "G:\\test\\sample2.txt";
StringBuilder sb = new StringBuilder();
// In case of matching, this flag is used to append the first word to
// the StringBuilder once.
boolean flag = true;
BufferedReader br = null;
try {
// convert the data in the sample.txt file to list
List<String> list = Files.readAllLines(Paths.get(fileName));
for (int i = 0; i < list.size(); i++) {
flagCheckWord1InMatch = true;
String word1 = list.get(i);
for (int j = i + 1; j < list.size(); j++) {
String word2 = list.get(j);
boolean isExist = false;
if (match != null && !match.isEmpty() && flagCheckWord1InMatch) {
isExist = checkWord1InMatch(word1);
}
if (isExist) {
// A word with the same characters was checked before
// and there is no need to check it again. Therefore, we
// jump to the next word in the list.
// flagCheckWord1InMatch = true;
break;
} else {
boolean result = isAnagram(word1, word2);
if (result) {
if (flag) {
sb.append(word1 + " ");
flag = false;
}
sb.append(word2 + " ");
}
if (j == list.size() - 1 && sb != null && !sb.toString().isEmpty()) {
match.add(sb.toString().trim());
sb.setLength(0);
flag = true;
}
}
}
}
} catch (
IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
for (String item : match) {
System.out.println(item);
}
// System.out.println("Sihwail");
}
private static boolean checkWord1InMatch(String word1) {
flagCheckWord1InMatch = false;
boolean isAvailable = false;
for (String item : match) {
String[] content = item.split(" ");
for (String word : content) {
if (word1.equals(word)) {
isAvailable = true;
break;
}
}
}
return isAvailable;
}
public static boolean isAnagram(String firstWord, String secondWord) {
char[] word1 = firstWord.toCharArray();
char[] word2 = secondWord.toCharArray();
Arrays.sort(word1);
Arrays.sort(word2);
return Arrays.equals(word1, word2);
}
}
</code></pre> | 2 |
Stemming queries elasticsearch | <p>I've successfully implemented stemming for elasticsearch and thus when I search for "code" I hit upon "codes" and "coding" etc.</p>
<p>My problem arises when I try to make use of the "must_not" field in my queries. When I include "code" in the "must_not" field, it's fine and I still get my results as expected but when I search for "codes" I don't get back any results even though there are documents which have the word "codes" in them for sure.</p>
<p>My query is as follows:</p>
<pre><code>for(i = 0; i < exclude_words.length; i++)
{
must_not.push({term:{text:exclude_words[i].toLowerCase()}});
}
query = {
"filtered": {
"query": {
"dis_max": {
"queries": [
{"match": {"text": term}},
{"match": {"title": term}}
]
}
},
"filter": {
"bool": {
"must_not": must_not
}
}
}
}
</code></pre>
<p>I'm using the elasticsearch api for node.js to construct my queries and get results from elasticsearch.</p>
<p>I'm assuming I'm having this problem because of stemming and that "codes" is stored as "code" in the search index. </p>
<p>Is there a way to solve this without using an external algorithm to stem my queries as well? Or is there an elegant way to solve this issue?</p>
<p>Any help is much appreciated!</p>
<p><strong>Update</strong></p>
<p>This is my analyzer:</p>
<pre><code>{
"settings": {
"analysis": {
"analyzer": {
"stopword_analyzer": {
"type": "snowball",
"stopwords": ["a", "able", "about", "across", "after", "all", "almost", "also", "am", "among", "an", "and", "any", "are", "as", "at", "be", "because", "been", "but", "by", "can", "cannot", "could", "dear", "did", "do", "does", "either", "else", "ever","every", "for", "from", "get", "got", "had", "has", "have", "he", "her", "hers", "him", "his", "how", "however", "i", "if", "in", "into", "is", "it", "its", "just", "least", "let", "like", "may", "me", "might", "most", "must", "my", "neither", "no", "nor", "not", "of", "off", "often", "on", "only", "or", "other", "our", "own", "rather", "said", "say", "says", "she", "should", "since", "so", "some", "than", "that", "the", "their", "them", "then", "there", "these", "they", "this", "tis", "to", "too", "us", "wants", "was", "we", "were", "what", "when", "where", "which", "while", "who", "whom", "why", "will", "with", "would", "yet", "you", "your"]
}
}
}
}
</code></pre>
<p>The text field has the following mapping:</p>
<pre><code>"text": {
"type": "string",
"analyzer": "stopword_analyzer"
}
</code></pre> | 2 |
Wrap content not working | <pre><code>**item_my_message.xml**
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/transparent">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="72dp"
android:background="@drawable/my_message_style"
android:elevation="4dp"
android:padding="8dp">
<TextView
android:id="@+id/textView_mymessge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/textView_time"
android:text="asdasd"
android:textColor="@color/colorPrimaryBackgorund" />
<TextView
android:id="@+id/textView_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/textView_mymessge"
android:layout_alignParentRight="true"
android:background="@android:color/transparent"
android:text="12:00 pm"
android:paddingRight="6dp"
android:textColor="@color/colorHint"
android:textSize="12dp" />
</RelativeLayout>
</RelativeLayout>
package pruebas.integra.Activites;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;
import pruebas.integra.Adapters.MensajeAdapter;
import pruebas.integra.Models.ConversationModel;
import pruebas.integra.R;
public class ChatConversationActivity extends AppCompatActivity {
Context context;
TextView textViewNombre;
TextView textViewEstado;
ImageView imgEstado;
EditText mensaje;
MensajeAdapter mensajeAdapter;
Button btnEnviarMensaje;
ArrayList<ConversationModel> mensajeChat;
ListView listView;
Calendar c;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_conversation);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
context = this;
c = Calendar.getInstance();
imgEstado = (ImageView) findViewById(R.id.imageView_state);
String nombre = getIntent().getExtras().getString("value");
Boolean state = getIntent().getExtras().getBoolean("estado");
textViewEstado = (TextView) findViewById(R.id.textView_state);
if (state == true) {
textViewEstado.setText("Conectado");
textViewEstado.setTextColor(context.getResources().getColor(android.R.color.holo_green_light));
imgEstado.setColorFilter((context.getResources().getColor(android.R.color.holo_green_light)));
} else {
textViewEstado.setText("Desconectado");
textViewEstado.setTextColor(context.getResources().getColor(R.color.colorPrimaryBackgorund));
imgEstado.setColorFilter(R.color.colorPrimaryBackgorund);
}
final TimeZone tz = TimeZone.getDefault();
textViewNombre = (TextView) findViewById(R.id.txtchatNombre);
textViewNombre.setText(nombre);
btnEnviarMensaje = (Button) findViewById(R.id.btn_enviarmensaje);
mensajeChat = new ArrayList<ConversationModel>();
listView = (ListView) findViewById(R.id.listView_mensajes_conversacion);
mensaje = (EditText) findViewById(R.id.editText_mensaje);
mensajeAdapter = new MensajeAdapter(context, mensajeChat);
listView.setAdapter(mensajeAdapter);
btnEnviarMensaje.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mensaje.getText().toString() == null && mensaje.getText().toString() == " ") {
} else {
ConversationModel conversation = new ConversationModel();
//mensaje.getText().append("\ud83d\ude01"); //EMOJI
conversation.setMensaje(mensaje.getText().toString());
String temp = Integer.toString(c.get(Calendar.HOUR_OF_DAY)) + ":" + Integer.toString(c.get(Calendar.MINUTE));
conversation.setTime(temp);
mensajeChat.add(conversation);
mensajeAdapter.notifyDataSetChanged();
mensaje.setText("");
listView.smoothScrollToPosition(mensajeAdapter.getCount());
}
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
finish();
}
</code></pre>
<p>}</p>
<p>I've got an item which I'm using for a chat, the thing is that the wrap content is not working, the layout itself stays at a certain width not according to its content I don't seem to find why is it doing that.</p>
<p><a href="http://i.stack.imgur.com/9cbrf.png" rel="nofollow">This is how it looks, it is supposed to wrap the content</a></p> | 2 |
Bootstrap align rows of different sizes | <p>Ran into a problem when it comes to bootstrap columns being consistent in size, and the way they look on smaller devices: <a href="https://jsfiddle.net/ns9xk00r/3/" rel="nofollow noreferrer">JSFiddle</a></p>
<pre><code><div class="well info">
<div class="row row-centered">
<div class="col-sm-2 col-sm-offset-1 col-centered">
<div class="count row-centered">
Column 1
</div>
<div class="row-centered">
<a href="/checks">Text 1</a>
</div>
</div>
<div class="col-sm-2 col-centered">
<div class="count row-centered">
Column 2
</div>
<div class="row-centered">
<a href="">Text 1</a>
</div>
</div>
<div class="col-sm-2 col-centered">
<div class="count row-centered">Column 3</div>
<div class="row-centered"><a href="/checks">Text 1</a></div>
</div>
<div class="col-sm-2 col-centered">
<div class="count row-centered">Column 4</div>
<div class="row-centered"><a href="/upgrade">Text 4</a></div>
</div>
<div class="col-sm-2 col-centered">
<div class="count row-centered"><b>Column 5</b>
<br>
</div>
<div class="count row-centered">Text 1</div>
<div class="row-centered">Text 3</div>
<div class="row-centered">Text 4</div>
</div>
</div>
</div>
</div>
</div>
</code></pre>
<p>CSS</p>
<pre><code>.row-centered {
text-align:center;
}
.col-centered {
display:inline-block;
float:none;
/* reset the text-align */
text-align:left;
/* inline-block space fix */
margin-right:-4px;
}
</code></pre>
<p>Essentially, given a setup such as the one outlined, how does one go about making sure that:</p>
<ol>
<li>The row containing the elements is vertically centered depending on the size of the parent container.</li>
<li>The columns making up the row are all centered vertically to each other, despite potentially being different sizes.</li>
<li>The items in each column are aligned horizontally (centered).</li>
<li>The structure of the columns and rows on collapse (with smaller devices) isn't scrambled, and would appear with the columns displayed underneath one another.</li>
</ol>
<p>I have tried several arrangements of nested rows, columns, and divs, but seemingly cannot get the columns to be vertically aligned, despite applying the appropriate classes (in my mind).</p>
<p>Is it possible to do so using a combination of CSS + Bootstrap?</p>
<p>Any advice and help is appreciated!</p> | 2 |
"Repeating" an array of colors multiple times based on another array | <p>I'm building an application wherein the user can select a dataset which will then be shown in a Leaflet map. To distinguish between the markers, each marker will be given a color, based on a variable. The data has a matching legend.</p>
<p>For now, I just use a small dataset for testing and building, but I want my application to be able to work with larger datasets as well.</p>
<p>I set up a basic array with a couple of static colors, which is fine for a small dataset. However when I add a larger dataset, the colors "run out" of course, as you can see below. I increased the amount of colors in the right legend to show what I would like to see happen.</p>
<p><a href="https://i.stack.imgur.com/vCRe1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vCRe1.png" alt="enter image description here"></a></p>
<p>What I would like to have, is way to effectively "repeat" <code>arrayKleur</code> if <code>arrayMetKetens</code> is bigger then the array of colors.</p>
<p><code>arrayMetKetens</code> is an dynamic array, filled with unique values and changes depending on what dataset is selected.</p>
<p><strong>Array for colors:</strong></p>
<pre><code>arrayKleur = ["#b15928", "#6a3d9a", "#ff7f00", "#e31a1c", "#33a02c", "#1f78b4", "#a6cee3", "#b2df8a", "#fb9a99", "#fdbf6f"];
</code></pre>
<p><strong>Generate legend code:</strong></p>
<pre><code>function legenda(){
var HTMLlegenda = '<h4>Legenda</h4>';
// if arrayMetKetens is empty => default legenda text
if (arrayMetKetens.length == 0 ){
HTMLlegenda += '<p>Selecteer een tabel in de "Advanced selection" tab om de legenda weer te geven</p>'
$("#tab1").html(HTMLlegenda);
}
// if arrayMetKetens is filled => generate legenda
else{
$("#tab1").html(arrayMetKetens);
// stuk code om van bovenstaande data een HTML tabel te maken
for(ii = 0; ii < arrayMetKetens.length; ii++){
HTMLlegenda += '<i id="background" style="background:'+arrayKleur[ii]+'">&nbsp;&nbsp;&nbsp;&nbsp;</i>'+arrayMetKetens[ii]+'</br>'
}
$("#tab1").html(HTMLlegenda);
}
}
</code></pre>
<p><strong>getColor function:</strong></p>
<pre><code>function getArray(){
var ketens = [];
for(i=0;i < geojson_dataTable.features.length;i++){
ketens = ketens.concat(geojson_dataTable.features[i].properties[featureVoorSorteer])
}
window.arrayMetKetens = jQuery.unique( ketens );
}
function getColor(keten) {
var i = window.arrayMetKetens.indexOf(keten);
if (i !== -1) {
return arrayKleur[ i ];
}
else {
return '#999999';
}
}
</code></pre> | 2 |
how to remove openssl library dependencies | <p>when i try to execute the <code>Linux executable</code> on other fresh machine my program gives an error for dependency of <code>OpenSSL</code>. </p>
<p>For running my program smoothly it requires <code>libssl.so</code> and <code>libcrypto.so</code> preloaded.</p>
<p>How can i remove this dependency using make file or any other solution on <code>Linux</code></p> | 2 |
TCP server/client how to keep connections alive? | <p>I wrote a simple TCP echo server to handle multiple clients. It uses select() to get multiple connections. </p>
<p>Server Code:</p>
<pre><code>#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
int create_listener(uint16_t port) {
int listen_fd;
struct sockaddr_in name;
listen_fd = socket(AF_INET, SOCK_STREAM, 0);
if (listen_fd < 0) {
perror ("socket");
exit(EXIT_FAILURE);
}
bzero(&name, sizeof(name));
name.sin_family = AF_INET;
name.sin_addr.s_addr = htonl(INADDR_ANY);
name.sin_port = htons(port);
if (bind(listen_fd, (struct sockaddr *) &name, sizeof(name)) < 0) {
perror ("bind");
exit(EXIT_FAILURE);
}
return listen_fd;
}
int read_from_client(int fd) {
char buffer[100];
int nbytes;
nbytes = read(fd, buffer, 100);
if (nbytes < 0) {
perror("read");
exit(EXIT_FAILURE);
}
else if (nbytes == 0) {
return -1;
}
else {
fprintf(stderr, "Server: got message: %s\n", buffer);
write(fd, buffer, strlen(buffer) + 1);
return 0;
}
}
int main(int argc, char *argv[]) {
int listen_fd;
uint16_t port = 22000;
fd_set active_fd_set, read_fd_set;
int i;
struct sockaddr_in servaddr;
/* Create the socket and set it up to accept connections. */
listen_fd = create_listener(port);
if (listen(listen_fd, 10) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
/* Initialize the set of active sockets. */
FD_ZERO(&active_fd_set);
FD_SET(listen_fd, &active_fd_set);
while (1) {
/* Block until input arrives on one or more active sockets. */
read_fd_set = active_fd_set;
if (select(FD_SETSIZE, &read_fd_set, NULL, NULL, 0) < 0) {
perror("select");
exit(EXIT_FAILURE);
}
/* Service all the sockets with input pending. */
for (i = 0; i < FD_SETSIZE; ++i) {
if (FD_ISSET(i, &read_fd_set)) {
if (i == listen_fd) {
/* Connection request on original socket. */
int new_fd;
new_fd = accept(listen_fd, (struct sockaddr *) NULL, NULL);
if (new_fd < 0) {
perror ("accept");
exit(EXIT_FAILURE);
}
FD_SET(new_fd, &active_fd_set);
}
else {
/* Data arriving on an already-connected socket. */
if (read_from_client(i) < 0) {
close(i);
FD_CLR(i, &active_fd_set);
}
}
}
}
}
return 0;
}
</code></pre>
<p>Client code:</p>
<pre><code>#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
int sockfd, n;
char sendline[100];
char recvline[100];
struct sockaddr_in servaddr;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(22000);
inet_pton(AF_INET, "127.0.0.1", &(servaddr.sin_addr));
connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
while (1) {
bzero(sendline, 100);
bzero(recvline, 100);
fgets(sendline, 100, stdin);
write(sockfd, sendline, strlen(sendline) + 1);
read(sockfd, recvline, 100);
printf("%s", recvline);
}
return 0;
}
</code></pre>
<p>The problem is when I run server in one terminal and run two clients in another two terminals. If I use Ctrl+C to terminate one client, the server automatically terminates. I'm wondering why the server acts this way. What I'm expecting is the server runs forever. When client 1 terminates, server should still has a live connection with client 2. </p> | 2 |
Flask-Login POST requests turn into GET requests after login | <p>I'm using flask-login to handle authentication for my app, which is an API that expects HTTP Basic Authorization headers as part of each request (so the user can login and make the request without worrying about sessions, cookies, or having to do the login and requesting in separate steps).</p>
<p>My requests are working out like this:</p>
<pre><code>POST /api/group/48
GET /login?next=%2Fapi%2Fgroup%2F48
GET /api/group/48
</code></pre>
<p>That is, a POST request to <code>/api/group/48</code> is getting intercepted and redirected to the /login endpoint (as expected). What happens in /login is not interactive - it takes the Basic Authorization header and logs the user in. </p>
<p>After the login has completed, the client is redirected back to <code>/api/group/48</code> - but this time as a <strong>GET</strong> request, not a <strong>POST</strong>. And in this app, the <code>/api/group/48</code> endpoint is expecting only POST data, so it dies with a 405 (Method not allowed) error.</p>
<p>Is this the expected behavior of flask-login? How can I have it pass through the POST request as originally submitted? (or alternatively, should I be using some different architecture so that the redirect to <code>/login</code>, then back to <code>/api/group/48</code> doesn't take place and the POST data isn't lost?)</p>
<p>I haven't included code, since I don't think this is a code-specific issue. But if it turns out I'm doing something wrong, I can post some sample code.</p>
<p>Thanks to anyone who can help.</p> | 2 |
IAR window layout | <p>Is there a way to save your IAR window layout? Every time I start a debug session it fills my screen 9 different windows. I would be happy with 3 and a few tabs but I have to rearrange things every time. I don't see an obvious way to save them and Google doesn't have much to say on this either.</p> | 2 |
Ambiguous reference to member && | <p>If I wish to calculate if all <code>Bool</code>s in the list are <code>true</code> with this snippet, why won't the types be correctly inferred?</p>
<pre><code>let bools = [false, true, false, true]
let result = bools.reduce(true, combine: &&)
</code></pre> | 2 |
Reading zipped xml files in Spark | <p>I have a set of large xml files, zipped together in a singe file and many such zip files. I was using Mapreduce earlier to parse the xml using custom inputformat and recordreader setting the splittable=false and reading the zip and xml file.</p>
<p>I am new to Spark. Can someone help me how can I prevent spark from splitting the zip file and process multiple zips in parallel as I am able to do in MR.</p> | 2 |
get parent node/tag of a specific node/tag in c# | <p>I need to delete a specific xml tag using c# but the problem is, that tag may be located in different parent tags.</p>
<p>So I need to search for that specific tag and get its parent tag then delete it.</p>
<p>This is my xml file</p>
<pre><code><PublisherInfo>
<PublisherName value="1">Askquestionzero Publisher</PublisherName>
<PublisherLocation>Ph</PublisherLocation>
<PublisherImprintName>Askquestionzero</PublisherImprintName>
<PublisherLogo>
<Tada>Remove this value and its content</Tada>
</PublisherLogo>
<PublisherURL>Askquestionzero.com</PublisherURL>
</PublisherInfo>
</code></pre>
<p>and this is my code </p>
<pre><code>XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"C:\Users\user\Desktop\askquestion.xml");
XmlNode nodeToDelete = xmlDoc.SelectSingleNode("/PublisherInfo/PublisherLogo/Tada");
if (nodeToDelete != null)
{
nodeToDelete.ParentNode.RemoveChild(nodeToDelete);
}
Console.WriteLine(xmlDoc.OuterXml);
</code></pre>
<p>The code works but I need to specify its parent tag. So how loop through the xml file and if the <code>Tada</code> tag is found, get its parent tag then delete it.</p>
<p>expected output:</p>
<pre><code><PublisherInfo>
<PublisherName value="1">Askquestionzero Publisher</PublisherName>
<PublisherLocation>Ph</PublisherLocation>
<PublisherImprintName>Askquestionzero</PublisherImprintName>
<PublisherLogo>
</PublisherLogo>
<PublisherURL>Askquestionzero.com</PublisherURL>
</PublisherInfo>
</code></pre>
<p>Another question:</p>
<p>I need also to change the node of a xml file. The file is the same as above.</p>
<p>Here is the code for changing the xml node/tag name. But it keeps its attribute. What I want it to change its tag name and delete its attribute.</p>
<pre><code>XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(@"C:\Users\user\Desktop\askquestion.xml");
Console.WriteLine(xmlDocument.OuterXml);
XmlElement element = (XmlElement)xmlDocument.GetElementsByTagName("PublisherName")[0];
XmlElement renamedElement = (XmlElement)RenameNode(element, null, "new-element");
Console.WriteLine(xmlDocument.OuterXml);
public static XmlNode RenameNode(XmlNode node, string namespaceUri, string qualifiedName)
{
if (node.NodeType == XmlNodeType.Element)
{
XmlElement oldElement = (XmlElement)node;
XmlElement newElement = node.OwnerDocument.CreateElement(qualifiedName, namespaceUri);
while (oldElement.HasAttributes)
{
newElement.SetAttributeNode(oldElement.RemoveAttributeNode(oldElement.Attributes[0]));
}
while (oldElement.HasChildNodes)
{
newElement.AppendChild(oldElement.FirstChild);
}
if (oldElement.ParentNode != null)
{
oldElement.ParentNode.ReplaceChild(newElement, oldElement);
}
return newElement;
}
else
{
return null;
}
}
</code></pre>
<p>The output of the code above:</p>
<pre><code><new-element value="1">Askquestionzero Publisher</new-element>
</code></pre>
<p>Desired output:</p>
<pre><code><new-element>Askquestionzero Publisher</new-element>
</code></pre> | 2 |
R. replacing null value representation with NA | <p>I have tried all the methods that I have found on stackoverflow regarding this topic and nothing worked.</p>
<p>Here is a sample of my dataset called TEST:</p>
<pre><code>x2000 x2001 x2002
100 1200 230
200 2002 280
: 1980 :
</code></pre>
<p>":" represents a missing value. The problem is that I cannot replace this colon with R-accepted NA.</p>
<p>What I have tried:</p>
<pre><code>sum(TEST %in c(":"))
returns: [1] 0
TEST[TEST==":"] <-NA #does nothing
</code></pre>
<p>I tried to save the file as .csv, replace the values with "NA" in excel and it still does nothing. The columns are not factors. if the column contains the value of ":" then the column is "chr" otherwise it is "int". </p> | 2 |
Build EntityManagerFactory using Hibernate and JPA | <p>I'm building a web application using SpringFramework. In the data access layer I was using Hibernate to query data in MySQL, which was working fine. My <code>SessionFactory</code> is build from this method:</p>
<pre><code>public SessionFactory sessionFactory() throws HibernateException {
return new org.hibernate.cfg.Configuration()
.configure()
.buildSessionFactory();
}
</code></pre>
<p>Today I'm going to integrate my data access with JPA, which needs a <code>EntityManagerFactory</code>, IMO I only need to change the code above into the following:</p>
<pre><code>@Bean
public EntityManagerFactory entityManagerFactory() throws HibernateException {
return new org.hibernate.cfg.Configuration()
.configure()
.buildSessionFactory();
}
</code></pre>
<p>simply because <code>SessionFactory</code> extends <code>EntityManagerFactory</code>. However I got an exception</p>
<blockquote>
<p>java.lang.ClassCastException:
org.hibernate.internal.SessionFactoryImpl cannot be cast to
javax.persistence.EntityManagerFactory</p>
</blockquote>
<p>This is quite weird, because <code>SessionFactoryImpl</code> implements <code>SessionFactory</code> while <code>SessionFactory</code> extends <code>EntityManagerFactory</code>. I don't know why the cast fails.</p>
<p>My question is: 1. why the cast is invalid? 2. what's the correct way to build a <code>EntityManagerFactory</code> using Hibernate?</p>
<p><strong>EDIT</strong> Debugger says</p>
<pre><code>factory instanceof SessionFactory //true
factory instanceof EntityManagerFactory //false
</code></pre>
<p>and the source of <code>SessionFactory</code></p>
<pre><code>public interface SessionFactory extends EntityManagerFactory, HibernateEntityManagerFactory, Referenceable, Serializable, Closeable
</code></pre>
<p>I'm sure all the above <code>EntityManagerFactory</code> refers to <code>javax.persistence.EntityManagerFactory</code>.</p> | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.