input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Redis SET with option, without expiry <p>I'm writing a library that stores keys in Redis or Memcached. To keep it generic, I'd like to use <code>SET</code> for all my set operations, but I'm struggling to find an expiry value that equates to "don't expire". Is there a sentinel value I can send?</p>
<p>For example, If there's an expiry of 100, I'd like to send:</p>
<pre><code>SET myKey myValue ex 100 NX
</code></pre>
<p>but if there's no expiry, I'd prefer to do</p>
<pre><code>SET myKey myValue ex -1 NX
</code></pre>
<p>rather than</p>
<pre><code>SETNX myKey myValue
</code></pre>
<p>Interestingly, there doesn't appear to be any way to do the equivalent of a <code>SET</code> using the <code>XX</code> option without an expiry.</p>
| <p>Just send the set command <em>without</em> an EX option. </p>
<pre><code>Set key value NX
</code></pre>
|
Horizontal ViewPager inside vertical ScrollView <p>In my app I have a fragment with horizontal ViewPager and horizontal RecycleViews that sits under vertical ScrollView. My problem is that the ViewPager is blocking the parent vertical scroll. I tried to disable ViewPager vertical touch event, but it didn't help.
Here is a video that shows the problem:</p>
<p><a href="https://drive.google.com/file/d/0B9XMTJsXn0ofQnpOcWo5TW9GLWs/view?usp=sharing" rel="nofollow">https://drive.google.com/file/d/0B9XMTJsXn0ofQnpOcWo5TW9GLWs/view?usp=sharing</a></p>
<p>And here is my layout xml:</p>
<pre><code><ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateLayoutChanges="true"
android:focusableInTouchMode="true"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_gravity="top"
android:visibility="gone" />
<InkPageIndicator
android:id="@+id/page_indicator"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginEnd="@dimen/activity_horizontal_margin"
android:layout_marginStart="@dimen/activity_horizontal_margin"
android:paddingBottom="8dp"
android:visibility="gone" />
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackground"
android:clickable="true"
android:minHeight="48dp"
android:visibility="gone">
<FrameLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1.0"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:text="@string/software"
android:textColor="?android:textColorPrimary"
android:textSize="20sp" />
</FrameLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginEnd="@dimen/activity_horizontal_margin"
android:layout_marginStart="@dimen/activity_horizontal_margin"
android:text="@string/see_all"
android:textAppearance="@style/TextAppearance.Button"
android:textColor="?colorAccent" />
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="@+id/software_recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="4dp"
android:visibility="gone" />
</LinearLayout>
</code></pre>
<p></p>
| <p>You are using LinearLayout then you can set </p>
<blockquote>
<p>android:weightSum</p>
</blockquote>
<p>property for resolving this issue.</p>
|
how loop video with javasript? <p>i have some videos source. I want to play it again when the last video is over. I tried this code below,but after the last ended it wont start from the beginning.</p>
<p>Here's my code below</p>
<p><strong>HTML</strong></p>
<pre><code><video id="myVideo" width="800" height="600" controls>
Your browser does not support HTML5 video.
</video>
</code></pre>
<p><strong>JAVASCRIPT</strong></p>
<pre><code> <script>
var videoSource = new Array();
videoSource[0]='video/adsfsaf.mp4';
videoSource[1]='video/2.mp4';
videoSource[2]='video/1.mp4';
var videoCount = videoSource.length;
document.getElementById("myVideo").setAttribute("src",videoSource[0]);
function videoPlay(videoNum)
{
document.getElementById("myVideo").setAttribute("src",videoSource[videoNum]);
document.getElementById("myVideo").load();
document.getElementById("myVideo").play();
}
function videoBegin(videoNum)
{
document.getElementById("myVideo").setAttribute("src",videoSource[0]);
document.getElementById("myVideo").load();
document.getElementById("myVideo").play();
}
i = 0;
document.getElementById('myVideo').addEventListener('ended',myHandler,false);
function myHandler() {
i++;
if(i == (videoCount-1)){
// alert(i);
videoPlay(i);
}
else{
videoPlay(i);
}
}
</script
</code></pre>
<p><strong>I found the solution.</strong></p>
<pre><code> function myHandler() {
i++;
if(i >= videoCount) i =0;
videoPlay(i);
}
</code></pre>
| <p>Can't you use the "loop" attribute of the "video" element ? </p>
<p><a href="http://www.w3schools.com/tags/att_video_loop.asp" rel="nofollow">W3School loop</a></p>
|
Failure in login, but only in Samsung <p>In my app, I have a login process, once you are logged in, the app makes a call to the server to get a specific data:</p>
<pre><code>Call<JsonObject> peticion= RetrofitClient.getRetrofitClient(InicioSesionGibActivity.this).login(imei, idCliente, user, encriptedPass);
peticion.enqueue(new Callback<JsonObject>() {
@Override
public void onResponse(final Response<JsonObject> response, Retrofit retrofit) {
String respoString=response.body().toString();
if(response.isSuccess()){
settings.edit().putBoolean("logueado", true).apply();
Call<JsonPrimitive> peticion= RetrofitClient.getRetrofitClient(InicioSesionGibActivity.this).obtenerCodOrg(settings.getString("imei", ""), settings.getString("idCliente", ""));
peticion.enqueue(new Callback<JsonPrimitive>() {
@Override
public void onResponse(Response<JsonPrimitive> response2, Retrofit retrofit) {
if (response2.isSuccess()) {
codOrg = response2.body().getAsLong();
settings.edit().putLong("codorg", codOrg).apply();
dropTables();
obtenerEntidades();
}else{
//The execution gets here
Message msg=new Message();
msg.what=1;
loginHandler.sendMessage(msg);
AlertDialog.Builder aDialog=new AlertDialog.Builder(InicioSesionGibActivity.this);
aDialog.setTitle(getString(R.string.error));
aDialog.setMessage(getString(R.string.unknownerror));
aDialog.setPositiveButton(getString(R.string.si), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
aDialog.show();
}
}
@Override
public void onFailure(Throwable t) {
settings.edit().putBoolean("logueado", false).apply();
Message msg=new Message();
msg.what=1;
loginHandler.sendMessage(msg);
AlertDialog.Builder aDialog=new AlertDialog.Builder(InicioSesionGibActivity.this);
aDialog.setTitle(getString(R.string.error));
aDialog.setMessage(getString(R.string.neterror));
aDialog.setPositiveButton(getString(R.string.si), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
aDialog.show();
}
});
}else{
final AlertDialog.Builder builder=new AlertDialog.Builder(InicioSesionGibActivity.this);
builder.setTitle(getString(R.string.error));
builder.setMessage(getString(R.string.loginerror));
builder.setPositiveButton(getString(R.string.accept), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Message msg=new Message();
msg.what=1;
loginHandler.sendMessage(msg);
editTextUsuario.setText("");
editTextPassword.setText("");
}
});
builder.create().show();
}
}
@Override
public void onFailure(Throwable t) {
Message msg=new Message();
msg.what=1;
loginHandler.sendMessage(msg);
final AlertDialog.Builder builder=new AlertDialog.Builder(InicioSesionGibActivity.this);
builder.setTitle(getString(R.string.error));
builder.setMessage(getString(R.string.loginerror));
builder.setPositiveButton(getString(R.string.accept), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
});
</code></pre>
<p>The execution goes ok in all devices...except in my boss phone, a Samsung S7 (not the one that explodes). That happens if he executes it from APK. BUT, and this is the weird part, if I get the phone, and run the app from Android Studio, the execution goes perfectly, and i get the data just fine.</p>
<p>This is driving me nuts, because its hard to debug.</p>
<p>Someone has faced this problem?</p>
<p>If you need more data, or clarification, please ask.</p>
<p>Thank you. </p>
| <p>Might be because it's a fast phone. When you save data to shared preferences are you reading it back immediately? You are using apply() which will store it in an asynchronous background thread and may not be there immediately if you try to read it back right away. </p>
<p>You may want to use commit() instead, which writes its data to persistent storage immediately in the current thread and will not continue execution until it is committed.</p>
|
Conditional Validation for Serialized Array <p>How can I create a validation where <code>committed</code> presence needs to be true only if the challenge's category is <code>habit</code>?</p>
<pre><code>class Challenge < ActiveRecord::Base
CATEGORY = ['goal', 'habit']
serialize :committed, Array
validates :committed, presence: true, if: :habit # I also tried with 'habit' & 'Habit'
end
</code></pre>
| <pre><code>validates :committed, presence: true, :if => lambda { |c| c.category == 'Habit' }
</code></pre>
|
Extracting data from an android phone <p>I'm currently trying to create a program or app which extracts information from a phone, such as SMS & Contacts. </p>
<p>I've tried to find information on the net but i am unable to find any relevant help. </p>
<p>I am not looking to be spoonfed, just to be pointed in the right direction, where should i start looking? and would a
program or app be more efficient ? </p>
<p>Thanks in advance ! </p>
| <p>Start from official android docs. You can access that data with <a href="https://developer.android.com/guide/topics/providers/content-providers.html" rel="nofollow">Content Providers</a>.</p>
|
How to format/indent multiple line text constants <p>How do I use one print function to print all the text with correct code indentation on the second and subsequent lines?</p>
<pre><code> printf("Program information\nThe program reads in the number of judges and \
the score from each judge.\nThen it calculates the average score without \
regard to the lowest and\nhighest judge score. Finally it prints the \
results (the highest, the \nlowest and the final average score).\n\n");
</code></pre>
| <p>You want to avoid using <code>\[newline]</code> inside string constants.</p>
<p>The c compiler will concatenate string constants for you, so you can format it like this:</p>
<pre><code>printf("Program information\n"
"The program reads in the number of judges and the score from each judge.\n"
"Then it calculates the average score without regard to the lowest and\n"
"highest judge score. Finally it prints the results (the highest, the \n"
"lowest and the final average score).\n\n");
</code></pre>
|
saving array of UIImage to parse as one file <p>In my swift app I have an array of UIImage and I need to save it to parse in one row and one column(as one file). I can do it when it's one image by using PFFile with no problem but for UIImage Array it doesn't work. How can I do It ? Is it Possible ? if it's possible how can I retrieve it from parse ?</p>
| <p>You can save an array of NSData()</p>
<blockquote>
<p>images: [NSData()]
UIImageView.image = UIImage(data: images[0])</p>
</blockquote>
|
database to be used for log storing <p>I am starting up with a log monitoring tool which captures audit logs,firewall logs and many other logs.I Have an issue in choosing the right kind of database for this project as number of logs generated per second is at least 500 which has to be stored.</p>
<p>Let's assume that this should be able to support 1BN+ log entries per month. The two factors that will likely come into play most are ability to write quickly and also the ability display reports quickly.</p>
| <p>A common stack used for log storing is the ELK stack composed of Elastic search, Logstash, and Kibana. </p>
<ul>
<li><strong>E</strong>lastic search is used to store the documents and can execute queries. </li>
<li><strong>L</strong>ogstash monitors and parses the logs. </li>
<li><strong>K</strong>ibana is used to create reports based off of the data in elastic search.</li>
</ul>
<p>There are other options out there. Splunk is a paid solution that does all of the above. Graylog is another solution that is similar to splunk.</p>
|
Get Pixel count using RGB values in Python <p>I have to find count of pixels of RGB which is using by RGB values. So i need logic for that one.</p>
<p>Example.</p>
<p>i have image called image.jpg. That image contains width = 100 and height = 100 and Red value is 128. Green is 0 and blue is 128. so that i need to find how much RGB pixels have that image. can anyone help?</p>
| <p>As already mentioned in <a href="http://stackoverflow.com/questions/138250/how-can-i-read-the-rgb-value-of-a-given-pixel-in-python">this</a> question, by using <code>Pillow</code> you can do the following:</p>
<pre><code>from PIL import Image
im = Image.open('image.jpg', 'r')
</code></pre>
<p>If successful, this function returns an Image object. You can now use instance attributes to examine the file contents:</p>
<pre><code>width, height = im.size
pixel_values = list(im.getdata())
print(im.format, im.size, im.mode)
</code></pre>
<p>The <code>format</code> attribute identifies the source of an image. If the image was not read from a file, it is set to None. The <code>mode</code> attribute defines the number and names of the bands in the image, and also the pixel type and depth. Common modes are âLâ (luminance) for greyscale images, âRGBâ for true color images, and âCMYKâ for pre-press images.</p>
|
A href go on next page when i click on star rating input <p>On my page I have a table. In the table there is one <code>td</code>, in which I am showing average rating input. I want when I click on average rating page, the <code>href</code> goes to next page. </p>
<p>Can anyone tell me how it can be possible?</p>
<p>Here is my html, but it doesn't work.</p>
<pre><code><table>
<tr>
<td><a href='supp_view_screen.php?id=$encrypt_id'><input id='rating-input' type='number' readonly value='".$last_cal."' step='1' class='rating'/></a></td>
</tr>
</table>
</code></pre>
| <p>Use this code snippet for that : <br></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><table>
<tr>
<td><a href='supp_view_screen.php?id=$encrypt_id' target='_blank'><input id='rating-input' type='number' readonly value='".$last_cal."' step='1' class='rating'/></a></td>
</tr>
</table></code></pre>
</div>
</div>
</p>
|
Unable to maintain one to many relationship in Eloquent using laravel 5.3 <p>I am using laravel eloquent model so there are three tables tempsocials, tempusers and tempdevices. so one user can have multiple devices and multiple social acounts.
I created a models for three of above table and trying to maintain relationship in between like following</p>
<p><strong>This is my Tempuser model:</strong></p>
<pre><code>namespace App;
use Illuminate\Database\Eloquent\Model;
class Tempuser extends Model
{
public function tempsocials(){
return $this->hasMany('App\Tempsocial');
}
public function tempdevices(){
return $this->hasMany('App\Tempdevice');
}
}
</code></pre>
<p><strong>This is my Tempdevice model:</strong></p>
<pre><code> namespace App;
use Illuminate\Database\Eloquent\Model;
class Tempdevice extends Model
{
public function tempusers(){
return $this->belongsTo('App\Tempuser');
}
}
</code></pre>
<p><strong>And this one is last Tempsocial model:</strong></p>
<pre><code>namespace App;
use Illuminate\Database\Eloquent\Model;
class Tempsocial extends Model
{
public function tempusers(){
return $this->belongsTo('App\Tempuser');
}
}
</code></pre>
<p><strong>Now this is my controller where i want to retrive all the devices and social accounts of particular user</strong></p>
<pre><code> namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Collection;
use App\Http\Requests;
use App\tempLogin;
use App\Tempdevice;
use App\Tempuser;
use App\Tempsocial;
class loginController extends Controller
{
public function check_credentials(Request $request){
$count=0;
if($request->header('content-type')=='application/json'){
$temp=new Tempuser;
$devices = $temp->tempdevices();
return $devices;
}
}
}
</code></pre>
<p>But i got following error:
"Object of class Illuminate\Database\Eloquent\Relations\HasMany could not be converted to string"</p>
| <p>You're making a new <code>Tempuser()</code>, it has no id, so your relation returns nothing as expected, you will need to pass an id to the method and with that id you could do something like:</p>
<pre><code>Tempuser::find($id);
</code></pre>
<p>This will then return an actual model instead of creating a new one.</p>
<p>Also because when you call <code>->tempdevices()</code> as a function it will return a query builder, instead when you do <code>->tempdevices</code> it will return a collection, change it like this:</p>
<pre><code>$devices = $temp->tempdevices;
</code></pre>
<p>Also, if you expect a json response (if thats not the case you can ignore this part), it might be better to also state it in your return by doing:</p>
<pre><code>return response()->json($devices);
</code></pre>
|
Group by time interval including start of next? <p>I'm trying to build a query that groups my data by a timed interval (i.e. 30 minutes) and then calculate the difference between the first and last row in each group.</p>
<p><code>select (max(v) - min(v)) as x, from_unixtime(FLOOR(UNIX_TIMESTAMP(d)/(30*60))*(30*60)) as timeKey from y group by timeKey</code></p>
<p>The above correctly returns my data in 30 minute chunks however I need to somehow tweak it to include everything between <code>12:00 and 12:30</code> rather than <code>12:00 and 12:29</code>.</p>
<p>I had attempted to use the following however <code>max</code> can't be used when assigning a value.</p>
<p><code>select max(v) - @lastV, from_unixtime(FLOOR(UNIX_TIMESTAMP(d)/(30*60))*(30*60)) as timeKey, @lastv := v from `test`, (select @lastV:=0) lastV group by timeKey</code></p>
<p><a href="http://sqlfiddle.com/#!9/e8d74/4" rel="nofollow">http://sqlfiddle.com/#!9/e8d74/4</a></p>
<p>I've created the above SQL Fiddle with some data that can be used as an example.</p>
<p>Does anyone have any suggestions?</p>
| <p>A potential solution that I managed to come up with this morning:</p>
<p><code>select *, IF(@lastV, @lastV - minV, 0) as `usage`, @lastV := minV from (
select min(v) as minV, max(v) as maxV, from_unixtime(FLOOR(UNIX_TIMESTAMP(d)/(30*60))*(30*60)) as timeKey from `test` group by timeKey order by timeKey desc
) items, (select @lastV:=0) lastV</code></p>
<p><a href="http://sqlfiddle.com/#!9/e8d74/18/0" rel="nofollow">http://sqlfiddle.com/#!9/e8d74/18/0</a></p>
<p>It unfortunately only works when sorting descending and produces a redundant row (first row has nothing to compare to) however based on my tests, this row isn't required and can be ignored when reading the data.</p>
<p>Would be useful if anyone had any other solutions?</p>
|
Javascript - why its treating windows 10 pro, IE11 as mobile or tablet? <p>I do not have mobile / tablet compatible layout, so when any user comes from mobile/tablet/linux terminal, i show a page "get out". But if the user is coming from a PC browsers IE old, IE edge, Safari, Google Chrome, Firefox, Opera, Midori etc etc. Then it is allowed.</p>
<p>Why i am getting is_pc as false even the browser was PC and IE11?</p>
<pre><code>window.onload = userAgentDetect;
var is_pc = true;
function userAgentDetect() {
if(window.navigator.userAgent.match(/Mobile/i)
|| window.navigator.userAgent.match(/iPhone/i)
|| window.navigator.userAgent.match(/iPod/i)
|| window.navigator.userAgent.match(/IEMobile/i)
|| window.navigator.userAgent.match(/Windows Phone/i)
|| window.navigator.userAgent.match(/Android/i)
|| window.navigator.userAgent.match(/BlackBerry/i)
|| window.navigator.userAgent.match(/webOS/i)) {
document.body.className+=' mobile';
is_pc = false;
get_out_from_here();
}
if(window.navigator.userAgent.match(/Tablet/i)
|| window.navigator.userAgent.match(/iPad/i)
|| window.navigator.userAgent.match(/Nexus 7/i)
|| window.navigator.userAgent.match(/Nexus 10/i)
|| window.navigator.userAgent.match(/KFAPWI/i)) {
document.body.className-=' mobile';
document.body.className+=' tablet';
is_pc = false;
get_out_from_here();
}
}
</code></pre>
| <p>Working.</p>
<pre><code>window.onload = userAgentDetect;
var is_pc = true;
function userAgentDetect() {
if(window.navigator.userAgent.match(/Mobile/i)
|| window.navigator.userAgent.match(/iPhone/i)
|| window.navigator.userAgent.match(/iPod/i)
|| window.navigator.userAgent.match(/IEMobile/i)
|| window.navigator.userAgent.match(/Windows Phone/i)
|| window.navigator.userAgent.match(/Android/i)
|| window.navigator.userAgent.match(/BlackBerry/i)
|| window.navigator.userAgent.match(/webOS/i)) {
document.body.className+=' mobile';
is_pc = false;
get_out_from_here();
}
if(window.navigator.userAgent.match(/iPad/i)
|| window.navigator.userAgent.match(/Nexus 7/i)
|| window.navigator.userAgent.match(/Nexus 10/i)
|| window.navigator.userAgent.match(/KFAPWI/i)) {
document.body.className-=' mobile';
document.body.className+=' tablet';
is_pc = false;
get_out_from_here();
}
}
</code></pre>
|
ng-option preselect value for (key,value) pair when value is an array of object <p>I can't do a pre-selection in <strong>ng-options</strong> from (key,value) pair when value is a array of objects, although if I use value.property then I can do the pre-selection.</p>
<p>I wrote an example in jsfiddle and I'm able to preselect ng-option by key or value.property but in my case I need the whole array</p>
<p><strong>edit</strong>
: I edit because [key,value] is [key,Array[Object]] instead of [key,Object]. And I add a new html select code to show right selection based on given answers.</p>
<p>be aware you must pass into ng-model whole set of arrays although the tracking just check array zero. Both structure should be identical. </p>
<p><a href="http://jsfiddle.net/rafaparche/pcfLn4xg/8/" rel="nofollow">Updated JSFiddel</a></p>
<p><strong>HTML</strong></p>
<pre><code><div ng-app="myApp" ng-controller="demoCtrl">
<select name="first" ng-model="data" ng-options="key as value.templateId for (key, value) in options">
<option value="">Select template</option>
</select>
<div>Data is preselected! = {{data}}</div>
<br>
<select name="second" ng-model="data2" ng-options="value.templateId as key for (key, value) in options">
<option value="">Select template</option>
</select>
<div>Data is preselected! = {{data2}}</div>
<br>
<select name="third" ng-model="data3" ng-options="value as key for (key, value) in options">
<option value="">Select template</option>
</select>
<div>Data is NOT preselected! = {{data3}}</div> :(
<select name="forth" ng-model="data4" ng-options="key for (key, value) in
options track by value[0].templateId">
<option value="">Select template</option>
</select>
<div>Solution! = {{data4}}</div>
</code></pre>
<p></p>
<p><strong>Angular</strong></p>
<pre><code>var app = angular.module('myApp', []);
app.controller('demoCtrl', function($scope) {
$scope.data = "for offer";
$scope.data2 = "002";
$scope.data3 = '{ templateId :"001" , color : "yellow"}';
$scope.data = [
{"templateId":3,"color":"blue"},
{"templateId":4,"color":"dark blue"}
];
$scope.options = {
"for offer":
[
{"templateId":1,"color":"yellow"},
{"templateId":2,"color":"dark yellow"}
],
"no offer":
[
{"templateId":3,"color":"blue"},
{"templateId":4,"color":"dark blue"}
],
"general":
[
{"templateId":5,"color":"orange"},
{"templateId":6,"color":"dark orange"}
]
};
});
</code></pre>
| <p>When using <code>ngOptions</code> you can use <code>track by</code> to determine an unique identifier to bind value properly. Also, the value mustn't be a string, it have to be an object like so:</p>
<pre><code>$scope.data3 = { templateId :"001" , color : "yellow"};
</code></pre>
<p>And your template:</p>
<pre><code><select name="third"
ng-model="data3"
ng-options="value as key for (key, value) in options track by value.templateId">
<option value="">Select template</option>
</select>
</code></pre>
<p>Using <code>track by value.templateId</code> will tell <code>ngOptions</code> to look at the property <code>value.templateId</code> when testing the equality of the objects and determine selected value.</p>
<p>Updated your <a href="http://jsfiddle.net/pcfLn4xg/7/" rel="nofollow">fiddle</a>.</p>
|
SSL: Intermediate certificate compromised -- Can they unrevoke a certificate? <p>I am using certs from an issuer called AlphaSSL. I just recently realised that my pages shows invalid certificate error on pageload. Further investigation shows that the intermediate certificate that binds my cert to GlobalSign's root certificate has been revoked. I checked and there is a <a href="https://secure.alphassl.com/cacert/gsalphag2.crt" rel="nofollow">new intermediate certificate on their site</a> but I am not sure I should download it as their download page is secured with the same revoked certificate. </p>
<p>UPDATE:</p>
<p>I got a boilerplate email from support, they reckon clearing the CRL cache should fix the issue. I wonder though, is this really doable, can they 'unrevoke' the certificate? How can I check <strong>their</strong> revocation list and how can I force the propagation of the undo to my CRL (other than clearing the cache)?</p>
<p>UPDATE2:</p>
<p>I received another email that references <a href="https://support.globalsign.com/customer/portal/articles/2599710-ocsp-revocation-errors---troubleshooting-guide%C2%A0" rel="nofollow">this page</a>. Long story short, they are busy shoveling the sh*t back to the horse, browser ubiquity yaddda-yadda, you should change the iterim cert to a new one, but if you have AlphaSSL or CLoudSSL, then you're sheesh out of luck, no cert for you. </p>
<p>Does not say where to claim your money back. </p>
| <p>GlobalSign is currently experiencing issues which results in certificates being marked as revoked:</p>
<p><a href="https://twitter.com/globalsign/status/786505261842247680">https://twitter.com/globalsign/status/786505261842247680</a></p>
|
With notepad++, if "Find All" strings match multiple times in 1 line, output shows duplicated lines <p>I would like to know how to prevent notepad++ to output duplicated lines when I execute Find All.</p>
<p>Here is sample text file.</p>
<pre><code>aaa aaa
bbb bbb
ccc ccc
</code></pre>
<p>I put "aaa" as search strings and click "Find All in Current Document".
Then output will be like this. Line 1 appears 2 times because strings "aaa" matched 2 times in line 1.</p>
<pre><code>Search "aaa" (2 hits in 1 file)
new 2 (2 hits)
Line 1: aaa aaa
Line 1: aaa aaa
</code></pre>
<p>It is bothering to remove duplicated lines later. Is there any good method to prevent duplicated lines?
Thanks in advance!</p>
| <p>I have never heard of a way to make the "Find result" window remove "duplicate lines". They originate from the multiple hits on the same line. </p>
<p>To stop the dupes from appearing is to make sure you only find the last occurrence of the string on a line.</p>
<p>To do this, you need to use a regex in the following form:</p>
<pre><code>(\Qaa.a\E)(?!.*\1)
</code></pre>
<p>where <code><YOUR_VALUE></code> is <code>aaa</code>. The <code>\Q</code> and <code>\E</code> operators are necessary to make the regex engine treat all chars between them as literal characters. The <code>(...)</code> will capture the search string into Group 1 and the <code>(?!.*\1)</code> negative lookahead will fail all matches that are followed with the same search string on the line (as <code>.*</code> matches any 0+ chars other than linebreak symbols).</p>
<p><a href="https://i.stack.imgur.com/wY0im.png" rel="nofollow"><img src="https://i.stack.imgur.com/wY0im.png" alt="enter image description here"></a></p>
|
symfony 3 time when log in and log out <p>I'm pretty much new in symfony 3, so how I could get time when user log in and log out.. I know i should create entity for time.. that entity would have id,userID startTime, endTime.. and user should have a connection(many to many, that lot of user could have lot of log in.. ) with this entity.... I'd like to store in database this information. I tried to search on google but I found nothing in common.</p>
<p>I'd like to activate time startTime when this button is pressed
Sign
in
and code in controller </p>
<pre><code> @Route("/login", name="authentication_login")
public function loginActionAction(Request $request)
{
$authenticationUtils = $this->get('security.authentication_utils');
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('AppBundle:uzduotis:login.html.twig', array(
'last_username' => $lastUsername,
'error' => $error,
));
}
</code></pre>
<p>then for endTime </p>
<pre><code>/**
* @Route("/logout", name="logout")
* @Method({"GET"})
*/
public function logoutAction(Request $request)
{
$session = $this->$request->getSession();
$session = $this->get('session')->clear();
return $this->render('AppBundle:uzduotis:login.html.twig');
}
</code></pre>
| <p>For this answer I assume you store the users in the database. If not, please show how you do it.</p>
<p>First of all please have a look at the doctrine documentation on how to connect entities to each other. In your case this should help:
<a href="http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html#one-to-many-bidirectional" rel="nofollow">http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html#one-to-many-bidirectional</a></p>
<p>There's also a pretty good tutorial on this subject in the Symfony documentation: <a href="http://symfony.com/doc/current/doctrine/associations.html" rel="nofollow">http://symfony.com/doc/current/doctrine/associations.html</a></p>
<p>In the controller you can fetch the currently logged in user by executing <code>$user = $this->get('security.token_storage')->getToken()->getUser();</code>. That will return the database entity of the user that you can modify immediately. E.g. by adding a new record to the time table (example code):</p>
<pre><code>$time = new TimeLog();
$time->setUser($user);
$time->setType('login');
$time->setTimestamp(time());
</code></pre>
<p>In case saving does not work, try with the persist and flush methods of <code>$this->get('doctrine')->getManager()</code>. There's lots of documentation about this, too.</p>
|
Gradle: classpath dependency not resolved from nested project <p>I have a multi-project build set-up with gradle that will contain multiple android apps and libraries. </p>
<p>Sample of the project structure:</p>
<pre><code>root (Project Root)
| android
| module1 (Android Application)
| module2 (Android Library)
| ios (in the future)
</code></pre>
<p>I want to apply certain gradle plugins only to some subprojects. (Such as the android gradle plugin only to the android subproject)
Therefore I added the classpath dependency in the <code>:android -> build.gradle</code> and the plugin declaration to the two android subproject: <br><code>:android:module1 -> build.gradle -> apply plugin: 'com.android.application'</code><br>and<br><code>:android:module2 -> build.gradle -> apply plugin: 'com.android.library'</code>
The problem is that gradle cannot found the android gradle plugin:</p>
<blockquote>
<p>Error:(1, 1) A problem occurred evaluating project ':Shoppr:presentation'.
Plugin with id 'com.android.application' not found.</p>
</blockquote>
<p>Also it is not a version problem as in some other questions (Gradle Version 3.1; Android Gradle Plugin Version: 2.2.1) because when defining the classpath dependencies in <code>:root -> build.gradle</code> or <code>:android:moduleX -> build.gradle</code> all is working as expected.</p>
<p>:root -> build.gradle</p>
<pre><code>allprojects {
repositories {
mavenCentral()
jcenter()
}
}
</code></pre>
<p>:android -> build.gradle</p>
<pre><code>buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.1' <-- Should only be applied for android project
}
}
</code></pre>
<p>:android:module1 -> build.gradle</p>
<pre><code>apply plugin: 'com.android.application' --> Plugin with id 'com.android.application' not found.
</code></pre>
<p>:android:module2 -> build.gradle</p>
<pre><code>apply plugin: 'com.android.library'
</code></pre>
| <p>I have seen such folder arrangements especially with google sample projects that include and android folder and also a web folder. What you can try is to import the project using the android folder as the project folder since you may not be using gradle to build Ios and web if you have the two more folders for you project.</p>
<p>So close the project and re-import it using the android folder as the project root, i believe this way, gradle should run fine. My project folder is also like this because i have both web and android project in a single repo but during build with android studio, i use the android folder as the project root for the android.</p>
|
How to inflate the dropdown from the multidimentional array in php <p>I am trying to loop through an array for inflate the dropdown. But I am not able to do so. I have tried many methods for this. But Nothing works for me. One of the method I try below</p>
<p>Here is the array which I am trying to inflate in dropdown. There are 22 array in this single array which I am trying to inflate. </p>
<pre><code> array(22) {
[0] => array(4) {
[0] => string(26) "Black Angled Buckle Jacket"
[1] => string(6) "036890"
[2] => int(48503)
[3] => array(4) {
[0] => string(83) "http://thebestofcards.com/wp-content/uploads/2016/09/product-man-6a-uai-480x640.jpg"
[1] => int(480)
[2] => int(640)
[3] => bool(false)
}
}
...
}
</code></pre>
<p>This is the code </p>
<pre><code>$result = count($data);
var_dump($data);
for ($row = 0; $row < $result; $row++) {
//echo "<p><b>Row number $row</b></p>";
echo '<select name="productddl">';
//echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo '<option value="'.$data[$row][$col][0].'">'.$data[$row][$col][1].'</option>'
//echo "<li>".$data[$row][$col]."</li>";
}
echo '</select>';;
//echo "</ul>";
}
</code></pre>
<p>I just want to fetch the product name in the array to the dropdown. Can anybody help?</p>
<p>Thanks</p>
| <p>that's not so difficult, array isn't too nested, it is just a list of products, the only issue is that instead of using assoc and more meaningful keys, you have numbers.</p>
<pre><code>echo '<select name="productddl">';
foreach ($data as $row) {
echo '<option value="', $row[1], '">', $row[0] , '</option>';
}
echo '</select>';
</code></pre>
|
show checked text is not working when i click on new tab <p>I am trying to acheive show checked value text in one div.</p>
<p><a href="https://i.stack.imgur.com/rXfai.png" rel="nofollow"><img src="https://i.stack.imgur.com/rXfai.png" alt="enter image description here"></a></p>
<p>By default Tiffen is active so when i click on idly and puri images the text of that image is coming and showing in selected food list </p>
<p>But when i click on Lunch in leftside menu as shown in figure ; they have some food like: curd and fish, when i check them the text is not appearing but when i go to tiffen tab and do any check modification the lunch values are coming with tiffen</p>
<p>These are my codes:</p>
<p>Here is my section code:</p>
<pre><code><section>
<div class="products">
<div class="container">
<div class="col-md-3 rsidebar">
<div class="related-row">
<h4 class="text-center">Food Menu</h4>
<ul class="nav nav-pills nav-justified">
<li role="presentation" class="active"><a href="#tiffin" aria-controls="home" role="tab" data-toggle="tab"> Tiffin </a></li>
<li role="presentation"><a href="#lunch" aria-controls="home" role="tab" data-toggle="tab"> <i></i> Lunch </a></li>
<li role="presentation"><a href="#dinner" aria-controls="home" role="tab" data-toggle="tab"> Dinner </a></li>
</ul>
</div>
<div class="related-row" id="FoodSelected">
<h4 class="text-center">Food Selected</h4>
<ul class="nav nav-pills nav-justified">
<li class="active"><a id="selectedfood"></a></li>
</ul>
</div>
</div>
<form id="FoodForm">
<div class="tab-pane active" id="tiffin">
<div class="products-row">
<?php $tq=$conn->query("select * from os_dish where dish_status=1 and dish_type=1 order by id_dish ASC");
while ($tiffen = $tq->fetch_assoc()) {
?>
<div class="col-md-3">
<div class="foodmenuform row text-center">
<input type="checkbox" id="<?php echo $tiffen['dish_name'];?>" class="Foodmenu" value="<?php echo $tiffen['dish_name'];?>" name="tifeen[]" hidden>
<label for="<?php echo $tiffen['dish_name'];?>"><img src="img/dish/<?php echo $tiffen['dish_image']; ?>" class="img img-responsive" /></label>
<h3><?php echo $tiffen['dish_name'];?></h3>
</div>
</div>
<?php } ?>
</div>
</div>
<div class="tab-pane" id="lunch">
<div class="products-row">
<?php $lq=$conn->query("select * from os_dish where dish_status=1 and dish_type=2 order by id_dish ASC");
while ($lunch = $lq->fetch_assoc()) {
?>
<div class="col-md-3">
<div class="foodmenuform row text-center">
<input type="checkbox" id="<?php echo $lunch['dish_name'];?>" class="FoodMenu" value="<?php echo $lunch['dish_name'];?>" name="lunch[]" hidden>
<label for="<?php echo $lunch['dish_name'];?>"><img src="img/dish/<?php echo $lunch['dish_image']; ?>" class="img img-responsive" /></label>
<h3><?php echo $lunch['dish_name'];?></h3>
</div>
</div>
<?php } ?>
</div>
</div>
<button id="FoodSubmit" class="btn btn-primary btn-lg btn-block">Submit Food Menu</button>
</form>
</section>
</code></pre>
<p>And here is my script code:</p>
<pre><code><script type="text/javascript" language="JavaScript">
$(".Foodmenu").click(function(){
var checkedFood = $('input[type=checkbox]:checked').map(function(){
console.log($('input[type=checkbox]:checked').serialize());
return $(this).attr('value');
}).get().join("<br>");
$("#selectedfood").html(checkedFood);
});
</script>
</code></pre>
| <p>I got the solution all the code is write but fault is in class name issue i gave small FoodMenu istead Foodmenu</p>
|
Pandas groupby countif with dynamic columns <p>I have a dataframe with this structure:</p>
<pre><code>time,10.0.0.103,10.0.0.24
2016-10-12 13:40:00,157,172
2016-10-12 14:00:00,0,203
2016-10-12 14:20:00,0,0
2016-10-12 14:40:00,0,200
2016-10-12 15:00:00,185,208
</code></pre>
<p>It details the number of events per IP address for a given 20 minute period. I need a dataframe of how many 20 minute periods per miner had 0 events, from which I need to derive IP 'uptime' as a percent. The number of IP addresses is dynamic. Desired output:</p>
<pre><code>IP,noEvents,uptime
10.0.0.103,3,40
10.0.0.24,1,80
</code></pre>
<p>I have tried with groupby, agg and lambda to no avail. What is the best way of doing a 'countif' by dynamic columns?</p>
| <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sum.html" rel="nofollow"><code>sum</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mean.html" rel="nofollow"><code>mean</code></a> of boolean mask by condition <code>df == 0</code>. Last <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a> both <code>Series</code>:</p>
<pre><code>df.set_index('time', inplace=True)
mask = (df == 0)
print (mask)
10.0.0.103 10.0.0.24
time
2016-10-12 13:40:00 False False
2016-10-12 14:00:00 True False
2016-10-12 14:20:00 True True
2016-10-12 14:40:00 True False
2016-10-12 15:00:00 False False
noEvents = mask.sum()
print (noEvents)
10.0.0.103 3
10.0.0.24 1
dtype: int64
uptime = 100 * mask.mean()
print (uptime)
10.0.0.103 60.0
10.0.0.24 20.0
dtype: float64
print (pd.concat([noEvents, uptime], axis=1, keys=('noEvents','uptime'))
.reset_index()
.rename(columns={'index':'IP'}))
IP noEvents uptime
0 10.0.0.103 3 60.0
1 10.0.0.24 1 20.0
</code></pre>
|
how to handle cordinator layout in android studio? <p>please help me.</p>
<blockquote>
<p>java.lang.NoSuchFieldError: CoordinatorLayout_LayoutParams at
android.support.design.widget.CoordinatorLayout$LayoutParams.(CoordinatorLayout.java:2274)
at
android.support.design.widget.CoordinatorLayout.generateLayoutParams(CoordinatorLayout.java:1439)
at
android.support.design.widget.CoordinatorLayout.generateLayoutParams(CoordinatorLayout.java:92)
at
android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:860)
at
android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:70)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:834) at
android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
at android.view.LayoutInflater.inflate(LayoutInflater.java:518) at
android.view.LayoutInflater.inflate(LayoutInflater.java:397) at
com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:324)
at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:429)
at
com.android.ide.common.rendering.LayoutLibrary.createSession(LayoutLibrary.java:389)
at
com.android.tools.idea.rendering.RenderTask$2.compute(RenderTask.java:548)
at
com.android.tools.idea.rendering.RenderTask$2.compute(RenderTask.java:533)
at
com.intellij.openapi.application.impl.ApplicationImpl.runReadAction(ApplicationImpl.java:966)
at com.android.tools.idea.rendering.RenderTask.createRenderSession
at com.android.tools.idea.rendering.RenderTask.lambda$inflate$53 at
java.util.concurrent.FutureTask.run(FutureTask.java:266) at<br>
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at<br>
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)</p>
</blockquote>
| <p>Replace this code with your code. </p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true" >
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
/>
</android.support.design.widget.AppBarLayout>
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:src="@android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
</code></pre>
|
Remove rows based on chronological order <p>The data that I am trying to work with is in a <code>data.frame</code> that has the following format:</p>
<pre><code>Title Year
Something 2006
something2 2007
Something 2008
Something 2009
</code></pre>
<p>I'm specifically interested in being able to subset the data so that their chronological order is fewer then 2008. For example, this would give:</p>
<pre><code>Title Year
Something 2009
</code></pre>
<p>Is it acceptable to use something like this:</p>
<pre><code>df[!(df$Year <= 2008), ]
</code></pre>
| <p>If by fewer mean older (lower number) than you are looking for <code>df<-df[df$Year>2008]</code> or as you do <code>df<-df[!df$Year<=2008]</code></p>
<p>You will need to overwrite the original <code>data.frame</code>, or it will just display the subset, but not save it. You can also use <code>subset(df, Year>2008)</code> or <code>dplyr</code> package. Whaever suits you best.</p>
|
Laravel form does not assign corresponding values to the fields of a form <p>im in deep trouble.
im using ajax to submit a form in laravel. when i submit a form it does not submit correctly because each field of laravel does not have its assigned value.
first field of laravel form is method field, when i inspect my submitted data through chrome it shows mothod field is empty and request assign my mothod field value to the very next field of the form.
in the same way each field dont have its corresponding value.
i attached snapshot of chrome inspection please look into it.
here is my code for a form.</p>
<pre><code><form id="add_car_2" class="s-submit clearfix" method="POST">
{{method_field('patch')}}
<div class="row">
<div class="col-md-6 col-xs-12">
<div class="b-submit__main-element wow zoomInUp" data-wow-delay="0.3s">
<input type="checkbox" name="security_system" id="security_system" />
<label class="s-submitCheckLabel" for="security_system"><span class="fa fa-check"></span></label>
<label class="s-submitCheck" for="security_system">Security System</label>
</div>
<div class="b-submit__main-element wow zoomInUp" data-wow-delay="0.3s">
<input type="checkbox" name="air_bag" id="air_bag" />
<label class="s-submitCheckLabel" for="air_bag"><span class="fa fa-check"></span></label>
<label class="s-submitCheck" for="air_bag">Air Bag</label>
</div>
</div>
</form>
</code></pre>
<p>here is my ajax function to submit this form.</p>
<pre><code>$("#add_car_2").submit(function(event) {
event.preventDefault();
var url=/cars/ + $('#car_id').data('carid');
$.ajax({
url: url,
type: 'POST',
data: new FormData(this),
processData: false,
success: function (data, status){
console.log(data);
console.log(status);
}
});
});
</code></pre>
<p>when i submit this form through ajax it shows failed to submit because each field of form does not have its correct value<a href="https://i.stack.imgur.com/b0KX0.png" rel="nofollow"><img src="https://i.stack.imgur.com/b0KX0.png" alt="enter image description here"></a></p>
| <pre><code><form id="add_car_2" class="s-submit clearfix" method="POST">
{{csrf_field()}}
<input type="hidden" name="_method" value="patch">
<div class="row">
<div class="col-md-6 col-xs-12">
<div class="b-submit__main-element wow zoomInUp" data-wow-delay="0.3s">
<input type="checkbox" name="security_system" id="security_system" />
<label class="s-submitCheckLabel" for="security_system"><span class="fa fa-check"></span></label>
<label class="s-submitCheck" for="security_system">Security System</label>
</div>
<div class="b-submit__main-element wow zoomInUp" data-wow-delay="0.3s">
<input type="checkbox" name="air_bag" id="air_bag" />
<label class="s-submitCheckLabel" for="air_bag"><span class="fa fa-check"></span></label>
<label class="s-submitCheck" for="air_bag">Air Bag</label>
</div>
</div>
</form>
</code></pre>
|
How to enable .zip file download in a directory inside wordpress website <p>I have created a wordpress website. I have created a directory named 'my-resources' in the root directory & uploaded few zip files via FTP. Now I am trying to download the zip files by directly entering the zip file Url in a browser but it is always showing wordpress default 404 page. I tried to enable using .htaccess without any success.</p>
<p>Example URL: <a href="http://www.example.com/my-resources/sample.zip" rel="nofollow">http://www.example.com/my-resources/sample.zip</a></p>
<p>Additional Notes:
1. Its a Linux Server
2. I have configured permalinks like <a href="http://www.example.com/sample-post/" rel="nofollow">http://www.example.com/sample-post/</a>
3. I have installed 'Easy Media Download', 'Yoast SEO' plugins which I think might conflict with the file download</p>
<p>How do I enable to download zip files from a particular directory.</p>
<p>Thanks</p>
| <p>Use Chmod command and give permission 755 to that downloadable directory. You can use help of command from this link
<a href="http://linuxcommand.org/lts0070.php" rel="nofollow">http://linuxcommand.org/lts0070.php</a></p>
|
Checking if string is complety shown in popup window <p>Is there a standard way to do this? My popup window has maxsize and I would like to cut the string if it is too long.
Currently I'm doing </p>
<pre><code> if(txt.length()>320)
{
txt = txt.substring(0,320)+"...";
}
</code></pre>
<p>but this seems crude and doesn't work sometimes because of paragraphs.</p>
| <p>You can define below property to textview. </p>
<blockquote>
<p>android:ellipsize="end"</p>
</blockquote>
|
UWP Community Toolkit <p>I added the UWP Community Toolkit to a project and am getting the following error while executing.</p>
<p><a href="https://i.stack.imgur.com/44ORB.png" rel="nofollow"><img src="https://i.stack.imgur.com/44ORB.png" alt="enter image description here"></a></p>
<p>Has anyone ever experienced this?
PS: My English is rusty kkkkk</p>
| <p>The <a href="https://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.composition.dropshadow" rel="nofollow">MSDN page of DropShadow</a> shows that the calls was added in Build 14393 (V1607):</p>
<p><strong>Device family</strong>
Universal, introduced <strong>version 10.0.14393.0</strong></p>
<p>So make sure you <a href="https://blogs.msdn.microsoft.com/visualstudio/2016/08/02/universal-windows-apps-targeting-windows-10-anniversary-sdk/" rel="nofollow">target your app for Build 14393</a> and not the older 10586.</p>
<p><a href="https://i.stack.imgur.com/CsKSj.png" rel="nofollow"><img src="https://i.stack.imgur.com/CsKSj.png" alt="enter image description here"></a></p>
|
Python Sklearn validation.py:386 error while using predict SVC model <p>While using:</p>
<pre><code>grid_search.GridSearchCV(svm.SVC(), parameters).fit(x_train, y_train).predict(x)
</code></pre>
<p>I get the following error:</p>
<blockquote>
<p>C:\Anaconda3\lib\site-packages\sklearn\utils\validation.py:386: DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and willraise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample.
DeprecationWarning)</p>
</blockquote>
<p>How can i solve it?</p>
<p>Thanks</p>
| <p>What does your dataframe look like? It is probably due to the shape of x_train/x_test. </p>
|
Magento SOAP-ERROR: Parsing WSDL - by cron <p>I have an ERP using the magento SOAP API v2 (<a href="http://www.example.com/api/v2_soap/?wsdl" rel="nofollow">http://www.example.com/api/v2_soap/?wsdl</a>). Through my local server, crons access every minute the API and synchronize data.</p>
<p>Everything always worked very well until one day just stopped working, firing the error:</p>
<blockquote>
<p>Symfony\Component\Debug\Exception\FatalErrorException:
SOAP-ERROR: Parsing WSDL: Couldn't load from
'<a href="http://www.example.com/api/v2_soap/?wsdl" rel="nofollow">http://www.example.com/api/v2_soap/?wsdl</a>' : failed to load external
entity "<a href="http://www.example.com/api/v2_soap/?wsdl" rel="nofollow">http://www.example.com/api/v2_soap/?wsdl</a>"</p>
</blockquote>
<p>When worked, this error happened a few times an hour, but now it always happens.</p>
<p>My server is a ubuntu 16.04 and use the laravel framework 5.2.</p>
<p>The big problem is that if I access the api in my local server by curl for example, everything works, but with cron stopped working.</p>
<p>I know there are many questions on this subject, but none solved my problem.</p>
<p>Thanks.</p>
| <p>Ive faced this before and had to put the host name of the soap server (your Magento machine) in the /etc/hosts file because when making a soap call the server has to be able to resolve itself.</p>
|
R Shiny selectedInput inside renderDataTable cells <p>I search for solution to put selectedInputs in renderDataTable cells. I found js solutions: <a href="https://datatables.net/examples/api/form.html" rel="nofollow">https://datatables.net/examples/api/form.html</a> , however I do not know how to implement this solution in shinyjs as renderDataTable object. I would be grateful for hints / ideas / solutions how to implement editable renderDataTable in shiny.</p>
| <p>Very similar to this: <a href="http://stackoverflow.com/questions/37356625/adding-a-column-with-true-false-and-showing-that-as-a-checkbox/37356792#37356792">adding a column with TRUE/FALSE and showing that as a checkbox</a></p>
<pre><code>library(shiny)
library(DT)
runApp(list(
ui = basicPage(
h2('The mtcars data'),
DT::dataTableOutput('mytable'),
h2("Selected"),
tableOutput("checked")
),
server = function(input, output) {
# helper function for making checkbox
shinyInput = function(FUN, len, id, ...) {
inputs = character(len)
for (i in seq_len(len)) {
inputs[i] = as.character(FUN(paste0(id, i), label = NULL, ...))
}
inputs
}
# datatable with checkbox
output$mytable = DT::renderDataTable({
data.frame(mtcars,Rating=shinyInput(selectInput,nrow(mtcars),"selecter_",
choices=1:5, width="60px"))
}, selection='none',server = FALSE, escape = FALSE, options = list(
paging=TRUE,
preDrawCallback = JS('function() {
Shiny.unbindAll(this.api().table().node()); }'),
drawCallback = JS('function() {
Shiny.bindAll(this.api().table().node()); } ')
) )
# helper function for reading checkbox
shinyValue = function(id, len) {
unlist(lapply(seq_len(len), function(i) {
value = input[[paste0(id, i)]]
if (is.null(value)) NA else value
}))
}
# output read checkboxes
output$checked <- renderTable({
data.frame(selected=shinyValue("selecter_",nrow(mtcars)))
})
}
))
</code></pre>
<p>Note that if you rerender the table, the inputs won't work unless you add some extra code to unbind. </p>
<p>edit:</p>
<p>Let's say the data in the table is reactive so it changes, and the table rerenders. You will need to explicitely unbind as per @yihui here: <a href="https://groups.google.com/forum/#!msg/shiny-discuss/ZUMBGGl1sss/zfcG9c6MBAAJ" rel="nofollow">https://groups.google.com/forum/#!msg/shiny-discuss/ZUMBGGl1sss/zfcG9c6MBAAJ</a></p>
<p>So you need to add in the UI:</p>
<pre><code>tags$script(HTML("Shiny.addCustomMessageHandler('unbind-DT', function(id) {
Shiny.unbindAll($('#'+id).find('table').DataTable().table().node());
})"))
</code></pre>
<p>And then in the Server you trigger the function whenever you rerender the datatable with:</p>
<pre><code>session$sendCustomMessage('unbind-DT', 'mytable')
</code></pre>
<p>The colnames parameter is a vector of column names so when you specify a length one vector of FALSE it gives you a table with one column named FALSE. I am not sure of a straightforward way of removing column names from datatables. That would be a good SO question on its own.</p>
|
Using sqlsrv_connect() in live environment <p>I've developed a web application in php that connects to an azure sql database using <code>sqlsrv_connect()</code>. This is a function from the <strong>SQLSRV</strong> driver by Microsoft. The application runs great locally (Using the azure database). I can select, insert and delete data perfectly fine.</p>
<p>However, I now want to put the application in my live environment. When I do this I get the following <strong>error:</strong></p>
<blockquote>
<p>Fatal error: Call to undefined function sqlsrv_connect()</p>
</blockquote>
<p>Which is logical because I did not install the SQLSRV extension in my hosting environment. I can find no explanation on how to do this, this leaves me with the question is it even possible to do this? If so can you help me with that, if not what is my alternative?</p>
| <p>You have to install php_sqlsrv_xx_ts.dll ext in your server.</p>
<p>Please follow this link for correct dll file
<a href="https://msdn.microsoft.com/en-us/library/cc296170(v=sql.105).aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/cc296170(v=sql.105).aspx</a></p>
|
merge two array value in laravel <p>I want to merge two array in laravel 5.3.I have variable '$type' which return </p>
<pre><code>`Illuminate\Support\Collection Object ( [items:protected] => Array ( [1] => rinu )`
</code></pre>
<p>which is get from the query</p>
<pre><code>$type0=DB::table('users')->where('name','=',$head)->pluck('name','id');
</code></pre>
<p>I want to merge with array $type1 which returns </p>
<pre><code>Illuminate\Support\Collection Object ( [items:protected] => Array ( [2] => john ) )
Illuminate\Support\Collection Object ( [items:protected] => Array ( [3] => dinesh ) )
Illuminate\Support\Collection Object ( [items:protected] => Array ( [4] => mahesh ) )
Illuminate\Support\Collection Object ( [items:protected] => Array ( ) )
$type1=DB::table('users')->where('name','=',$head)->pluck('name','id');
</code></pre>
<p>I tried to merge and store it in $type0;</p>
<pre><code>$type0=$type0->merge($type1);
</code></pre>
<p>It return wrong value </p>
<pre><code>Illuminate\Support\Collection Object ( [items:protected] => Array ( [0] => rinu [1] => john ) )
Illuminate\Support\Collection Object ( [items:protected] => Array ( [0] => rinu [1] => john [2] => dinesh ) )
Illuminate\Support\Collection Object ( [items:protected] => Array ( [0] => rinu [1] => john [2] => dinesh [3] => mahesh ) )
Illuminate\Support\Collection Object ( [items:protected] => Array ( [0] => rinu [1] => john [2] => dinesh [3] => mahesh ) )`
enter code here
</code></pre>
| <p>You seem to have a Collection for each value. So you are probably fetching each value independently instead of in one go.</p>
<p>Your problem is probably solved by using <a href="https://laravel.com/docs/5.3/queries#where-clauses" rel="nofollow">whereIn</a> instead of a number of <code>where</code>s.</p>
<pre><code>$result = DB::table('users')
->whereIn('name', ['John', 'Dinesh', 'Mahesh'])
->get();
</code></pre>
|
Preventing the process from exiting when running a gulp task (so a server remains up) <p>I have a gulp task that starts a server:</p>
<pre><code>gulp.task('my-task', ['start-server'], function() {});
</code></pre>
<p>The gulp task <code>start-server</code> registers a listener:</p>
<pre><code>process.on('exit', function () {
server.stop();
});
</code></pre>
<p>But, I want the server to remain open. A bit like a <code>gulp-watch</code> task stays "open".</p>
<p>Currently, AFAICT, the Node.js process running the gulp task, exits upon completion of the gulp task and takes down the server with it.</p>
<p>How can I avoid the process exiting and taking the server down with it?</p>
| <p>That's what <code>gulp-nodemon</code> was meant to do: <a href="https://www.npmjs.com/package/gulp-nodemon" rel="nofollow">https://www.npmjs.com/package/gulp-nodemon</a></p>
<p>Example implementation:</p>
<pre><code>gulp.task('develop', function () {
nodemon({ script: 'server.js'
, ext: 'html js'
, ignore: ['ignored.js']
, tasks: ['lint'] })
.on('restart', function () {
console.log('restarted!')
})
})
</code></pre>
|
Restore webview scroll position? <p>I want to <strong>save the state</strong> of my <code>webView</code> with its <strong>page scroll position</strong> when user leaves the app and restore them when user opens the app again. So that, user can continue reading the restored webview content scrolled down to the restored position.</p>
<p>Here are methods I'm using:</p>
<pre><code> @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
webView = (WebView)this.findViewById(R.id.webView);
if (savedInstanceState != null) {
int positionY = Math.round(scrollPos);
webView.scrollTo(0, positionY);
} esle {
//do something
}
</code></pre>
<p>Function that calculates the position:</p>
<pre><code> private int calculateProgression(WebView content) {
int positionTopView = content.getTop();
int contentHeight = content.getContentHeight();
int currentScrollPosition = content.getScrollY();
int percentWebview = (currentScrollPosition - positionTopView) / contentHeight;
return percentWebview;
}
</code></pre>
<p>save/restore functions:</p>
<pre><code> @Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt("position", calculateProgression(webView));
super.onSaveInstanceState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
scrollPos = savedInstanceState.getFloat("position");
}
</code></pre>
| <p>You could save the position in the <a href="https://developer.android.com/reference/android/content/SharedPreferences.html" rel="nofollow">SharedPreferences</a> in the OnDestroy method and retreive it in the OnCreate method.</p>
<p><strong>EDIT</strong>: As stated <a href="https://developer.android.com/reference/android/app/Activity.html#onDestroy%28%29" rel="nofollow">here</a>, OnPause should be the place to store data, not OnDestroy.</p>
|
PortAudio Streaming and processing in real time <p>I am new to PortAudio. My intention is to continuously capture data from the line-in input on my pc and process the data in real time.</p>
<p>I am using the sample rate of 44100 and buffer size (frameCount) of 11025. I am successfully able to do this, but I am doing all of my processing inside the callback function which the portAudio engine calls. The common prototype for this callback function:</p>
<pre><code>int recordCallback(const void* inputBuffer, void* outputBuffer, unsigned long frameCount, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void* userData);
</code></pre>
<p>Is it bad to do all of my processing of the audio data inside this callback?</p>
<p>I am also loosing data because of the time taken to execute my callback function. </p>
<p>I thought about implementing a global circular buffer of a suitable size so that the callback fills this buffer continuously and sets a flag when it is ready. My main function can poll this flag and then do the processing in the main function instead. </p>
<p>My concern however is, is it possible for the callback to be writing to this ring buffer while my main function would be also reading from it at a different part.</p>
<p>Does anyone have a better solution for what i'm trying to achieve? Many thanks in advance </p>
| <blockquote>
<p>Is it bad to do all of my processing of the audio data inside this callback?</p>
<p>I am also loosing data because of the time taken to execute my callback function.</p>
</blockquote>
<p>I think you answered your own question just there.
Try pushing it to a buffer, and then have another thread do your post processing (beware - if you don't process it fast enough you'll have to dump it to disk else you'll end up running out of memory)</p>
<p>You said you were concerned about concurrency - which is reasonable, but give it a try and then post another question about that specific issue when you've given it a try.</p>
|
Delphi pointer memory and freeing <p>I'm using custom windows messages to exchange information from the worker thread to the forms in the main VCL thread. Whenever I need to send some data with the message I do this:</p>
<pre><code>type
PntStr = ^string;
</code></pre>
<p>then <strong>PostMessage()</strong></p>
<pre><code>var
pointString : PntStr;
(...)
New(pointString);
pointString^ := mystring;
PostMessage(frmDest.Handle, UM_THREADMSG, UM_MYEVENT1, LPARAM(pointString));
</code></pre>
<p>On the receiving form</p>
<pre><code>try
myStrP := PntStr(MSG.LParam);
myfunction(myStrP^);
finally
Dispose(myStrP);
end;
</code></pre>
<p>Is this the correct way to deal with the memory allocated by the pointer? Does calling <strong>Dispose()</strong> on the pointer take care of freeing the memory?</p>
| <p>Yes, your approach is correct in terms of memory management. <code>New</code> and <code>Dispose</code> correctly deal with the managed type. That's really what they exist to do. </p>
<p>Some nuances:</p>
<ul>
<li>Check the return value of <code>PostMessage</code>. If it fails then the message was not posted and the thread needs to dispose of the memory. </li>
<li>Don't use a form's handle as the recipient. There is a race condition. The form's window may be recreated simultaneously with you posting the message. Then the message will be lost. Or worse delivered to a different window if the handle is re-used. Or worse still, the window could be re-created on the wrong thread. Instead use <code>AllocateHWnd</code> to create a window handle whose life you control. </li>
<li>Your <code>try/finally</code> is wrong. The <code>try</code> should appear after the resource has been acquired. This is one of the most common mistakes we see here. In your code it is likely benign because the assignment cannot raise an exception but it is still worth being accurate. </li>
</ul>
|
counting occurrence of elements in each sequence of the list in python <p>I have a (very big) list like the small example. I want to count the number of D in each sequence in the list and divide by the length of that sequence. (occurrence of D in each sequence).</p>
<p>small example:</p>
<pre><code>l = ['MLSLLLLDLLGLG', 'MEPPQETNRPFSTLDD', 'MVDLSVSPDVPKPAVI', 'XNLMNAIMGSDDDG', 'MDRAPTEQNDDVKLSAE']
</code></pre>
<p>do you guys know how to do that?</p>
| <p>You can simply use a <em>list comprehension</em>, get the count of <code>D</code> in each sequence and divide by the length of the sequence:</p>
<pre><code>l = ['MLSLLLLDLLGLG', 'MEPPQETNRPFSTLDD', 'MVDLSVSPDVPKPAVI', 'XNLMNAIMGSDDDG', 'MDRAPTEQNDDVKLSAE']
result = [x.count('D')/len(x) for x in l]
print(result)
# [0.07692307692307693, 0.125, 0.125, 0.21428571428571427, 0.17647058823529413]
</code></pre>
<p>To handle zero length sequences and avoid <code>ZeroDivisionError</code>, you may use a <em>ternary operator</em>:</p>
<pre><code>result = [(x.count('D')/len(x) if x else 0) for x in l]
</code></pre>
|
.htaccess - .html redirect to / <p>I am really new to this forum, it's my first post but I already read a lot.
But I didn't find any solution for my problem.</p>
<p>I will do the following via my <code>htaccess</code>:</p>
<p>301 redirect from every url of my site with the ending .html to /.</p>
<p>An example:</p>
<p><code>www.xy.de/70.html</code> should be redirected to <code>www.xy.de/70/</code></p>
<p>I already tried this code:</p>
<pre><code>RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC]
RewriteRule ^ /%1 [NC,L,R]
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^ %{REQUEST_URI}.html [NC,L]
</code></pre>
<p>Thanks for your help!</p>
| <p>This should work for WordPress:</p>
<pre><code># BEGIN WordPress
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} \.html$
RewriteRule ^(.*)\.html$ $1 [R=301,L]
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# END WordPress
</code></pre>
|
How does this for loop work and end? <p>There are two initialisation and no "<code>x<y</code>" to limit the iterations. So how does this loop work?</p>
<pre class="lang-js prettyprint-override"><code>var features = [{
position: new google.maps.LatLng(-33.91721, 151.22630),
type: 'info'
}, {
position: new google.maps.LatLng(-33.91539, 151.22820),
type: 'info'
}, {
position: new google.maps.LatLng(-33.91747, 151.22912),
type: 'info'
}];
for (var i = 0, feature; feature = features[i]; i++) {
addMarker(feature);
}
</code></pre>
| <p>Access to an out-of-bound index in Javascript will yield <code>undefined</code>, which is a falsey value. Once the index has got outside of the bound, the <code>feature = features[i]</code> assignment, which evaluates to the value it assigns, will be considered <code>false</code> and the loop will exit.</p>
|
SQL Challenge/Puzzle: How to merge nested ranges? <ul>
<li>This challenge is based on a real life use-case involving IP ranges.</li>
<li>The solution I came with is based on the <a href="http://stackoverflow.com/questions/39936479/sql-challenge-puzzle-given-a-stack-trace-how-to-find-the-top-element-at-each/39941615#39941615">stack trace</a> challenge I've presented previously. Each range start is treated as a <strong>PUSH</strong> operation and each range end + 1 is treated as a <strong>POP</strong> operation.</li>
</ul>
<hr>
<h1>The Challenge</h1>
<p>We have a data set of ranges where each range has a starting point, ending point and a value.</p>
<pre><code>create table ranges
(
range_start int not null
,range_end int not null
,range_val char(1) not null
)
;
</code></pre>
<p>A range can contain another range or follow another range, but cannot be equal to another range or intersect with another range.</p>
<p>These are <strong>valid</strong> relations between ranges:</p>
<pre><code>(1) (2) (3) (4)
--------- --------- --------- -------- -----------
--- --- ---
</code></pre>
<p>These relations are <strong>not valid</strong>:</p>
<pre><code>(5) (6)
------- --------
------- --------
</code></pre>
<p>Our initial ranges, when presented graphically, might look something like this (The letter represents <strong>range_val</strong>):</p>
<pre><code>AAAAAAAA BBCCCCCCC
DDE F GGGGG
H IIII
J
</code></pre>
<p>The goal is to take the initial set of ranges and create a new set under the following rule:</p>
<p><strong>A contained range will override the corresponding sub-range of the the containing range.</strong> </p>
<p>The requested result, when presented graphically, might look something like this</p>
<pre><code>ADDHAAAF BIIJIGCCC
</code></pre>
<h1>Requirements</h1>
<ul>
<li>The solution should be a single SQL query (sub-queries are fine). </li>
<li>The use of T-SQL, PL/SQL etc. <strong>is not allowed</strong>.</li>
<li>The use of UDF (User Defined Functions) <strong>is not allowed</strong>.</li>
</ul>
<h1>Data Sample</h1>
<pre><code>AAAAAAAAAAAAAAAAAAAAAAAAAAAA BBBB CCCCCCCCCCCCCCCCCCCCCCCCC
DDDE FFFFFFFF GGGGGGGGG HHHHHHHH IIIIIII
JJ KKKLLL MM NN OOOOO
P QQ
insert into ranges (range_start,range_end,range_val) values (1 ,28 ,'A');
insert into ranges (range_start,range_end,range_val) values (31 ,34 ,'B');
insert into ranges (range_start,range_end,range_val) values (39 ,63 ,'C');
insert into ranges (range_start,range_end,range_val) values (1 ,3 ,'D');
insert into ranges (range_start,range_end,range_val) values (4 ,4 ,'E');
insert into ranges (range_start,range_end,range_val) values (7 ,14 ,'F');
insert into ranges (range_start,range_end,range_val) values (19 ,27 ,'G');
insert into ranges (range_start,range_end,range_val) values (43 ,50 ,'H');
insert into ranges (range_start,range_end,range_val) values (55 ,61 ,'I');
insert into ranges (range_start,range_end,range_val) values (1 ,2 ,'J');
insert into ranges (range_start,range_end,range_val) values (9 ,11 ,'K');
insert into ranges (range_start,range_end,range_val) values (12 ,14 ,'L');
insert into ranges (range_start,range_end,range_val) values (22 ,23 ,'M');
insert into ranges (range_start,range_end,range_val) values (25 ,26 ,'N');
insert into ranges (range_start,range_end,range_val) values (57 ,61 ,'O');
insert into ranges (range_start,range_end,range_val) values (13 ,13 ,'P');
insert into ranges (range_start,range_end,range_val) values (60 ,61 ,'Q');
</code></pre>
<h1>Requested Results</h1>
<p>(Nulls are presented here as empty spaces)</p>
<pre><code>JJDEAAFFKKKLPLAAAAGGGMMGNNGA BBBB CCCCHHHHHHHHCCCCIIOOOQQCC
range_start range_end range_val
----------- --------- ---------
1 2 J
3 3 D
4 4 E
5 6 A
7 8 F
9 11 K
12 12 L
13 13 P
14 14 L
15 18 A
19 21 G
22 23 M
24 24 G
25 26 N
27 27 G
28 28 A
29 30
31 34 B
35 38
39 42 C
43 50 H
51 54 C
55 56 I
57 59 O
60 61 Q
62 63 C
</code></pre>
<p>Optional addition final row:</p>
<pre><code>64
</code></pre>
| <p>Oracle solution:</p>
<pre><code>with l as ( select level lvl from dual connect by level < 66 ),
r as ( select range_start r1, range_end r2, range_val v,
range_end - range_start + 1 cnt
from ranges ),
t1 as (select distinct lvl,
nvl(max(v) keep (dense_rank first order by cnt)
over (partition by lvl), '*' ) m
from l left join r on lvl between r1 and r2 ),
t2 as (select lvl, m, case when lag(m) over (order by lvl) <> m then 0 else 1 end mrk
from t1),
t3 as (select lvl, m, lvl - sum(mrk) over (order by lvl) grp from t2)
select min(lvl) r1, max(lvl) r2, nullif(min(m), '*') val
from t3 group by grp order by r1
</code></pre>
<p>Output is as requested. My English is far from good, so it's hard to explain, but let's try:</p>
<ul>
<li><code>l</code> - number generator, </li>
<li><code>r</code> - data from <code>ranges</code> with counted distance,</li>
<li><code>t1</code> - finds value with minimal distance for each lvl, </li>
<li><code>t2</code> - adds markers telling if range starts, </li>
<li><code>t3</code> - adds column which we will next use for
grouping data.</li>
</ul>
|
Dojo widget id is already registered <p>I read about 10 errors like this but nowhere I found a solution. </p>
<p>I run this code in dojo:</p>
<pre><code>this.myHeader = registry.byId("banner");
// returns 'undefined'
if(!this.myHeader) {
this.myHeader = new Header({
primaryBannerType: 'thin'
}, "banner");
}
</code></pre>
<p>My config is <code>parseOnLead: true</code> but I do not parse any file widget manually so I think this is no problem.
- I check whether the widget is already loaded
- I do not parse the widget twice</p>
<p>why I get this error?</p>
<pre><code>Tried to register widget with id==banner but that id is already registered
</code></pre>
<p>thanks</p>
| <p>Make sure you have no other DOM elements with the same ID on your page.</p>
<p>I usually use the following utility script, which can spot this kind of problem very quickly and saving some time when debugging.</p>
<p>You can just copy and paste in your developer console (it is a self invoking function).</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> (function() {
var elms = document.body.querySelectorAll('*[id]'),
ids = [];
for (var i = 0, len = elms.length; i < len; i++) {
if (ids.indexOf(elms[i].id) === -1) {
ids.push(elms[i].id);
} else {
console.log('Multiple IDs #' + elms[i].id);
}
}
})();</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div id="a"></div>
<div id="b"></div>
<div id="b"></div>
<div id="b"></div>
<div id="c"></div>
<div id="c"></div></code></pre>
</div>
</div>
</p>
<p>Also on JSFiddle:
<a href="https://jsfiddle.net/gibbok/m92pdje4/" rel="nofollow">https://jsfiddle.net/gibbok/m92pdje4/</a></p>
|
How to set Docker-compose arguments in console? <p>My Docker containers will be set up through a bash script.</p>
<p>In my docker-compose.yml file (which is called through <code>docker-compose up</code> inside the bash file) I have a few arguments:</p>
<pre><code>version: "2"
services:
nginx:
build: ./Dockerfiles/wordpress-nginx
expose:
- "80"
depends_on:
- fpm
links:
- fpm
container_name: wordpress-nginx
args:
- site_title=Example
- admin_email=test@test.co
- site_url=www.testcase001.com
- admin_user=admin
- admin_pass=qwerty
- ssl_domain=www.testcase001.com
- dbname=testcase
- dbuser=testcase
- dbpass=testcase
- dbhost=testcase
fpm:
build: ./Dockerfiles/php-fpm
expose:
- "9000"
container_name: fpm
</code></pre>
<p>Now my question is this:</p>
<p><strong><em>How can I set the arguments from the command line?</em></strong></p>
<p>For example:<br>
I want to set the <code>site_title</code> argument: <code>docker-compose up --something-to-set-the-site_title-argument</code></p>
| <p>You can use environment variables in your <code>docker-compose.yaml</code> file, e.g.:</p>
<pre><code>args:
- site_title: $SITE_TITLE
</code></pre>
<p>In your Bash script, you can then set the title environment variable like this:</p>
<pre><code>#!/bin/bash
SITE_TITLE="My new title"
docker-compose up -d
</code></pre>
<p>The <code>$SITE_TITLE</code> environment variable should then be used in your compose configuration.</p>
|
@Html.DropDownList - set particular text at top to display <p>@Html.DropDownList - set particular text at top to display</p>
<h2>code:</h2>
<pre><code>@Html.DropDownList("Plant",ViewData["PlantList"] as SelectList, new {style="height: 29px;"})
</code></pre>
<p>The dropdownlist has five items from viewdata. They are one, two, three, four, five.</p>
<p>I am having another as <code>viewdata["displaytext"]</code>.
Here any 1 value from the options will be present. say for example now <code>three</code> is present in <em>this</em> <code>viewdata</code>. How to set this <code>three</code> to be <code>display text</code></p>
<p>EDIT
Adding controller method:</p>
<pre><code>public ActionResult PlantList()
{
...
...
ViewData["PlantList"] = pList;
ViewData["displaytext"] = "three";
return view();
}
</code></pre>
| <p>Create a model;</p>
<pre><code>public class MyModel
{
public int Number { get; set; }
}
</code></pre>
<p>Return model to view.</p>
<pre><code>public ActionResult Index
{
var model = new MyModel();
model.Number = "three";
return View(model);
}
</code></pre>
<p>and in you view;</p>
<pre><code> @Html.DropDownListFor(m=>m.Number,ViewData["PlantList"] as SelectList,"", new {style="height: 29px;"})
</code></pre>
<p>And the "three" option will be selected.</p>
<p>This is a simple example. Create the related code with your model.</p>
|
geopandas: how do I merge information only if point is inside a polygon? <p>I have a <code>geopandas</code> dataframe <code>A</code> with the geometry field set to a single <code>Point</code> (x,y). Then I have a second dataframe <code>B</code> with the geometry field set to some polygon and some other information. For example:</p>
<pre><code>A
geometry
(1,2)
(3,4)
...
</code></pre>
<p>and </p>
<pre><code>B
info polygon
ab <some polygon>
bc <some other polygon>
... ...
</code></pre>
<p>How do I add a new column to <code>A</code> with <code>B</code>'s <code>info</code> field only if the point in <code>A</code> is inside the polygon in <code>B</code>?</p>
<p>I would like to end up with something like</p>
<pre><code>A
geometry info
(1,2) ab
(3,4) ab
(7,9) bc
... ...
</code></pre>
| <p>Just in case someone else needs it, and assuming your geometry is well-formed, then you can do:</p>
<p><code>new_df = gpd.sjoin(A,B,how="inner", op='intersects')</code></p>
<p>this was enough.</p>
|
Is there any way to make Linearlayout having children not clickable android? <p>I have a linearyLayout having several linearlayout and some views.</p>
<p>I want to make the whole layout not clickable.</p>
<p>this is the the first part of the linearlayout</p>
<pre><code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/selector_timetable_row"
android:orientation="vertical">
</code></pre>
<p>I first did inflating</p>
<pre><code>View view = layoutInflater.inflate(~~, above layout);
</code></pre>
<p>And I did</p>
<pre><code> view.setClickable(false);
</code></pre>
<p>but it is still clickable
listener to the layout still fires when i touch the layout.</p>
| <pre><code>public void setClickable(View view) {
if (view != null) {
view.setClickable(false);
if (view instanceof ViewGroup) {
ViewGroup vg = ((ViewGroup) view);
for (int i = 0; i < vg.getChildCount(); i++) {
setClickable(vg.getChildAt(i));
}
}
}
}
</code></pre>
|
python append() and remove html tags <p>I need some help. My output seems wrong. How can I correctly append the values of dept, job_title, job_location. And there are html tags with the values of dept. how can I remove those tags. </p>
<p>my code</p>
<pre><code>response = requests.get("http://hortonworks.com/careers/open-positions/")
soup = BeautifulSoup(response.text, "html.parser")
jobs = []
div_main = soup.select("div#careers_list")
for div in div_main:
dept = div.find_all("h4", class_="department_title")
div_career = div. find_all("div", class_="career")
title = []
location = []
for dv in div_career:
job_title = dv.find("div", class_="title").get_text().strip()
title.append(job_title)
job_location = dv.find("div", class_="location").get_text().strip()
location.append(job_location)
job = {
"job_location": location,
"job_title": title,
"job_dept": dept
}
jobs.append(job)
pprint(jobs)
</code></pre>
<p>It should look like</p>
<p>{'job_dept': Consulting,</p>
<p>'job_location':'Chicago, IL'</p>
<p>'job_title': Sr. Consultant - Central'</p>
<p>1 value for each variables.</p>
| <p>The structure of your html is sequential, not hierarchical, so you have to iterate through your job list and update department title as you go:</p>
<pre><code>import requests
from bs4 import BeautifulSoup, Tag
from pprint import pprint
headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:21.0) Gecko/20130331 Firefox/21.0'}
response = requests.get("http://hortonworks.com/careers/open-positions/", headers=headers)
soup = BeautifulSoup(response.text, "html.parser")
jobs = []
div_main = soup.select("div#careers_list")
for div in div_main:
department_title = ""
for element in div:
if isinstance(element, Tag) and "class" in element.attrs:
if "department_title" in element.attrs["class"]:
department_title = element.get_text().strip()
elif "career" in element.attrs["class"]:
location = element.select("div.location")[0].get_text().strip()
title = element.select("div.title")[0].get_text().strip()
job = {
"job_location": location,
"job_title": title,
"job_dept": department_title
}
jobs.append(job)
pprint(jobs)
</code></pre>
|
Zip file not deleted in mule <p>I am reading a zip file using file inbound connector in mule. The file should be auto deleted, since auto delete is true. But it's not.
The flow I have is</p>
<p><code><file:connector name="File" writeToDirectory="D:\FileProcessed\ringmoved\" readFromDirectory="D:\FileProcessed\" autoDelete="true" streaming="true" validateConnections="true" doc:name="File"/>
<flow name="filFlow">
<file:inbound-endpoint path="D:\FileProcessed\" moveToDirectory="D:\FileProcessed\moved\" connector-ref="File" responseTimeout="10000" doc:name="File"/>
<logger message="hi" level="INFO" doc:name="Logger"/>
</flow></code></p>
| <p>It's because you are not consuming the file. Try adding a transformer such as </p>
<pre><code><object-to-string-transformer />
</code></pre>
<p>after the file endpoint.</p>
|
What is the 'right' way to form a row of elements? ul/divs? <p>I want to create a horizontal row of elements that form a panel of steps the user needs to take. These are all made out of blue rectangles that contain a title, text and an icon. See image for example.</p>
<p><a href="https://i.stack.imgur.com/ZGEZn.png" rel="nofollow"><img src="https://i.stack.imgur.com/ZGEZn.png" alt="enter image description here"></a></p>
<p>I need the items to break at either 2 or 3 items depending on the screen size. </p>
<p>This can be achieved in (afaik) 2 ways.</p>
<ul>
<li><p>A div container with 6 divs, that all have their own class to help them beak at mobile sizes.</p></li>
<li><p>an unordered horizontal list, with classes on the list items to help them break where I want.</p></li>
</ul>
<p>How do I determine what is the 'right' option here? What method do I choose? Or does it really not matter?</p>
| <p>Given the fact that you have a step-by-step template, you can easily use an ordered list as a container. <code>ol > li(1/6%) > h3 + img + p</code> </p>
|
Creating Hangman in Java using Arrays and Loops <p>Below is my code, it gets compiled in dr.java and works. I just need help to get the loop to end if they guess the word before their attempts run out and to show the letters that are typed in by the user while they are guessing the word. All help is appreciated. </p>
<pre><code>import java.util.Scanner;
import java.util.Arrays;
public class ProgramthreeTest{
public static void main(String[] args){
Scanner kybd = new Scanner(System.in);
//Ask user what word they would like the other person to guess
System.out.println("Hello Player 1, In order to begin please type in a word");
System.out.println("that you would like Player 2 to try and guess.");
String wordInput = kybd.nextLine();
//Identify number of characters in word
int wordChars = wordInput.length();
//Create an array to store the word they are guessing
char wordRay[] = new char[wordChars];
//Fill in array with the characters
for (int i = 0; i < wordRay.length; i++) {
wordRay[i] = wordInput.charAt(0+i);
}
//Create blank space
for (int j = 0; j < 50; j++) {
System.out.println();
}
//Notice of blank space
System.out.println("Hello Player 2, In order to maintain the integrity of the game");
System.out.println("please do not scroll up as you will see waht Player 1 has chosen.");
System.out.println();
System.out.println("You will now get six (6) attempts to guess each letter in the word that Player 1 chose.");
System.out.println();
System.out.println("Below is your hint. (It's how many characters are in Player 1's word).");
System.out.println("Player 1 chose " + wordChars + " characters");
//Create an array to store the word they are guessing
char guessRay[] = new char[wordChars];
//Fill array with _
for (int k = 0; k < wordRay.length; k++){
guessRay[k] = '_';
}
//Display array with _
for(int m = 0; m < guessRay.length; m++){
System.out.print(guessRay[m] + " ");
}
System.out.println();
//Game loop
//Loop Control Variable to give the use 6 tries
int attemptsLeft = 0;
//Let the user keep guessing through a loop until the attemptsLeft is more than 6
while (attemptsLeft <= 5){
//Allow user to input their guess
char trial = kybd.next().charAt(0);
//for for length of array, if the sub n = array then correct
char charVal = 'x';
for (int n = 0; n<wordRay.length; n++){
if (trial == wordRay[n]){
charVal = 'y';
wordRay[n] = trial;
}
}
//If the given char is in the array
if (charVal == 'y'){
//Tell the user that the character is right
System.out.println("Congrats, " + trial + " is in the word");
//Reloop, don't take away a try, and let them reguess
System.out.println("You still have " + (6 - attemptsLeft) + " attempts, guess again");
//Show array with filled in letter
charVal = 'x';
//Else the given char is not in the array
} else {
//Tell the user that the character is wrong
System.out.println("Sorry but " + trial + " is not in the word");
//Take away a try
attemptsLeft++;
//Read Back attempts left
System.out.println("You have " + (6 - attemptsLeft) + " attempts left now");
//Reset the charVal back to x to reinstantiate the guessing procedure
charVal = 'x';
}
//If you run out of attempts display this
if (attemptsLeft >= 6){
System.out.println("I'm sorry you did not guess the word in the given amount of attempts");
System.out.println("The word was " + wordInput);
}
}
}
}
</code></pre>
| <p>You could do something like this. In the loop where you check if the letter equals one in the word add the last line below:</p>
<pre><code>charVal = 'y';
wordRay[n] = trial;
guessRay[n] = wordRay[n]; //Change the _ value to the letter in the array.
</code></pre>
<p>Then at the end of the <code>if (charVal == 'y')</code> loop add this block:</p>
<pre><code>if(Arrays.equals(wordRay, guessRay))
{
System.out.println("You guessed it!");
break;
}
</code></pre>
<p>I don't know if you want this but I might also move this section to the beginning of the <code>while</code>. That way the user can see what letters are correct and how many letters left each guess.:</p>
<pre><code>for(int m = 0; m < guessRay.length; m++){
System.out.print(guessRay[m] + " ");
}
System.out.println();
</code></pre>
<p>One more addition you may want to make is to add a check at the beginning of the <code>while</code> to double check the user hasn't already guessed the letter and <code>continue</code> if they have.</p>
|
swift check if textview is empty <p>I wonder how I proper check if a uitextview is empty.</p>
<p>Right now I have a validation fucntion which does the check:</p>
<pre><code>if let descText = myTextView.text {
if descText.isEmpty {
descErrorLabel.isHidden = false
} else {
descErrorLabel.isHidden = true
}
}
</code></pre>
<p>It this enough to prevent the user from sending an empty textview or must I check of whitespaces also, something like:</p>
<pre><code>stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).isEmpty
</code></pre>
| <p>You could roll it all up into something like this...</p>
<pre><code>func validate(textView textView: UITextView) -> Bool {
guard let text = textView.text,
!text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty else {
// this will be reached if the text is nil (unlikely)
// or if the text only contains white spaces
// or no text at all
return false
}
return true
}
</code></pre>
<p>Then you can validate any <code>UITextView</code> like...</p>
<pre><code>if validate(textView: textView) {
// do something
} else {
// do something else
}
</code></pre>
|
How to modify the XML file using Python? <p>Actually I have got the XML string and parse the string to get the attributes from it. Now I want my XML file to change, viewing the attributes. Like I want to change the color of the stroke. Is there any way? How I will change and then again save the file.</p>
<pre><code>import requests
from xml.dom import minidom
response = requests.get('http://localhost:8080/geoserver/rest/styles/pakistan.sld',
auth=('admin', 'geoserver'))
fo=open("/home/adeel/Desktop/untitled1/yes.xml", "wb")
fo.write(response.text)
fo.close()
xmldoc = minidom.parse('yes.xml')
itemlist = xmldoc.getElementsByTagName('CssParameter')
print "Len : ", len(itemlist)
#print "Attribute Name : ", \
itemlist[0].attributes['name'].value
print "Text : ", itemlist[0].firstChild.nodeValue
for s in itemlist :
print "Attribute Name : ", s.attributes['name'].value
print "Text : ", s.firstChild.nodeValue
</code></pre>
| <p>You should probably read through the <a href="http://docs.geoserver.org/latest/en/user/styling/sld/cookbook/index.html" rel="nofollow">SLD Cook book</a> to get hints on how to change things like the colour of the lines in your SLD. Once you've changed it you need to make a <a href="http://docs.geoserver.org/latest/en/user/rest/api/styles.html" rel="nofollow"><code>PUT</code> request</a> to place the file back on the server.</p>
|
mongoose old result based on time <p>I have the following code:</p>
<pre><code> var dates = getDates();
var a = dates.now;
var tomorrow = dates.tomorrow;
console.log("{userid: " + userid + ", time: {$gte: " + a + "}, time: {$lte: " + tomorrow +"}");
tickets.find({userid: userid, time: {$gte: a}, time: {$lte: tomorrow}}).then(function (usertickets) {
console.log(usertickets[0]);
return resolve(usertickets);
});
</code></pre>
<p>console log:</p>
<pre><code> {userid: 57e0fa234f243f0710043f8f, time: {$gte: 1476309600000}, time:
{$lte: 1476396000000}
</code></pre>
<p>console log result output:</p>
<pre><code>{ userid: '57e0fa234f243f0710043f8f',
username: 1,
fromticket: 1,
amount: 1,
toticket: 2,
time: '1474362076461',
__v: 0,
_id: 57e0fadce32462ca1036274d }
</code></pre>
<p>Q: How come that time 1474362076461 is in results, while it should be results greather or equal to 1476309600000 and lower than 1476396000000 ? </p>
| <p>You have numeric value as string and when you compare numeric values in string then it works different for ex. </p>
<pre><code>console.log('2'>'11')
</code></pre>
<p>it will print true. so change your schema to Number.</p>
|
How do you inject non-presentation dependencies like a repository in a WPF application without involving the presentation layer (i.e. view model)? <p>I'm trying to apply DI to my WPF application (with MVVM). I would like to adhere to an <a href="http://jeffreypalermo.com/blog/the-onion-architecture-part-1/" rel="nofollow">onion architecture</a>, and as such, my model has an <code>IRepository</code> interface which is injected via an IoC container into the application from its composition root.</p>
<p>There are countless sources <a href="http://stackoverflow.com/a/25524753/2704659">like this SO answer</a> and <a href="http://wpftutorial.net/ReferenceArchitecture.html" rel="nofollow">this post on wpftutorial.net</a> that talk about DI with WPF but which <em>show the repository being injected into the view model</em>. Doing that doesn't seem right to me. The view model, in my mind, should not be concerned (i.e. should not know about) the repository.</p>
<p>Is there a way to design my application so it properly adheres to the onion architecture and does not involve the presentation layer in the repository dependency injection (inasmuch as that's possible, given that the composition root must be in the top-level/executable where the views reside)?</p>
| <p>One way would be to define your repository using an interface and then using unity you can interject the correct implementation of the repository interface. </p>
<p>The link here should get you started on using unity:</p>
<p><a href="https://msdn.microsoft.com/en-us/library/dn223671(v=pandp.30).aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/dn223671(v=pandp.30).aspx</a> </p>
<p><strong>Update:</strong><br>
By looking at the onion method on your link, I would suggest interjecting your repository in the Business/Application Logic layer. And make the calls to these methods form the view model as needed.</p>
|
Find max and min values in List[List[String]] comparing by the 1st element in each sub-list <p>I have a data structure like <code>List[(String, List[List[String]])]</code>. I need to find maximum and minimum value in the <code>List[List[String]]</code> comparing the 1st element in each sub-list:</p>
<p>This is how I do it:</p>
<pre><code>val timestamp_col_ind = 1
val sorted = processed.map(list => (list._1,list._2.sortWith(_.productElement(timestamp_col_ind).toString.toLong < _.productElement(timestamp_col_ind).toString.toLong)))
</code></pre>
<p>Then I access maximum and minimum elements using <code>last.apply(timestamp_col_ind).toString.toLong</code> and <code>head.apply(timestamp_col_ind).toString.toLong</code>, correspondingly.</p>
<p>But the problem is that the sub-lists do not get ordered by the 1st element. What am I doing wrong?</p>
| <p>Like Alberto mentioned, it is always good to provide a full example to avoid confusion; see <a href="http://stackoverflow.com/help/mcve">http://stackoverflow.com/help/mcve</a>. Here is a solution to what it looks like you want:</p>
<pre><code>// initialise structure
val data = List(("foo", List(List("2", "b", "b"), List("3", "c", "c"), List("1", "a", "a"))))
// sort by long value of first element of sublists
val sortedData = data.map { case (str, lst) => (str, lst.sortBy(_.head.toLong)) }
// get minimum and maximum
val min = sortedData.map { case (str, lst) => (str, lst.head) }
val max = sortedData.map { case (str, lst) => (str, lst.last) }
</code></pre>
<p>result:</p>
<pre><code>min: List[(String, List[String])] = List((foo,List(1, a, a)))
max: List[(String, List[String])] = List((foo,List(3, c, c)))
</code></pre>
<p>This assumes that the sublists are never empty, i.e. they do have a <code>head</code></p>
|
IBM Process Designer - find all Java class references <p>My team inherited a system to support and develop and it's mostly created in IBM Process Designer with some functionality coming from external Java classes.</p>
<p>Documentation is missing or incomplete (what a surprise!) so I need to make some kind of "architecture map" for further refactoring based on the existing implementation.
So the question is: what's the best way to find and list all calls to Java integration components (ideally, to all Java methods) in IBM PD? Going process by process manually is a big troublesome because solution is rather complex.</p>
| <p>Found the solution:</p>
<p>If you go to Snapshots in Process Center you can export Installation Package to local machine. Unzip it, then unzip export.twx and in Objectss folder you'll find XML representation of all objects.
Search for 'javaClassName' string and you'll get the list.</p>
<p>Unfortunately I had to use this workaround because default tab "Where is used" in PD did not provide any information.</p>
|
Remember user timezone selection, and apply timezone changes to datetime field on all pages <p>In my database I have a dateandtime field in one of the tables, which correctly displays the date and time from the database for the row I want. As I will possibly get users from many different countries I will need to allow a user to select their timezone so that the time in the time and date in the dateandtime field will be changed to their timezone across all pages of my site.</p>
<p>I am able to successfully allow the user to type in a input field the time zone such as "+3:00" and enter a date such as "24/07/2017" into another input field, and when the user clicks the Search button the timezone conversion will be successful. This is not ideal though as it means everytime the user goes to another page on the site and goes back to the search by date page they have to input the timezone e.g. "+3:00" again.</p>
<p>I was thinking that a session could be used to achieve what I need but when I tried using a session to remember the timezone value when I went back to the page the time would no longer be in the timezone I had previously inputted.</p>
<p>To summarise, what I am trying to achieve is that I would like the user to be able to select their timezone and for any dates and times displayed on the webpages from the database will be changed to the users selected timezone, and if the user was to go off the page then their timezone will be remembered if they were to go back to the previous page.</p>
<p>An example site that shows what I am trying to achieve successfully is below</p>
<p><a href="http://liveonsat.com/los_soc_int_UEFA_CL.php" rel="nofollow">A site which has the functionality with timezones I am attempting to achieve</a></p>
<p>As you can see on that site if I select timezone, it successfully changes the timezone, and if I was to select another section of the site it would remember the users timezone and update the date and time to reflect the timezone changes. It seems after inspection that that site uses a cookie to remember the timezone value, would I be able to use cookies to achieve this type of functionality on my site?</p>
<p>Below is the code I have that successfully changes the timezone when the user inputs a timezone value e.g. "+3:00" and date into the corresponding input fields but will not remember timezone option.</p>
<pre><code><?php
include './config.php';
include './header.php';
$timezone = trim($_GET["timezone"]);
$keyword = trim($_GET["keyword"]);
if ($keyword <> "" && $timezone <> "" ) {
$sql = "SELECT f.hometeam, f.awayteam, f.sport, f.competition,
DATE_FORMAT(CONVERT_TZ(f.dateandtime, '+00:00','$timezone'), '%M %e, %Y %r') AS dateandtime,
Group_concat(s.name SEPARATOR ',') name,
Group_concat(x.channelid_fc SEPARATOR ',') channelid_fc
FROM footballfixtures f
LEFT JOIN fixturechannels x
ON x.matchid_fc=f.matchid
LEFT JOIN satellite s
ON x.channelid_fc=s.channelid
WHERE DATE(dateandtime) = STR_TO_DATE('$keyword', '%d/%m/%Y')
GROUP BY f.hometeam, f.awayteam, f.sport, f.competition, f.dateandtime
ORDER BY f.dateandtime ";
$stmt = $DB->prepare($sql);
$stmt->bindValue(":keyword", $keyword."%");
$stmt->bindValue(":timezone", $timezone." %");
$stmt->execute();
} else {
$sql = "SELECT 1 from dual";
$stmt = $DB->prepare($sql);
}
$stmt->execute();
?>
<html>
<head>
</head>
<body>
<div class="container mainbody">
<div class="mainpagetitle">
<h11>Sports Schedule</h11> <br> <br>
<p>We aim to provide you with sports schedule in an easy to view format</p> <br> <br> <br> <br> <br>
<form class="form-inline">
</div>
<div class="clearfix"></div>
<div class="col-xs-12">
<img src="css/calendar.png" class="img-responsive" />
<div id=class="container-fluid">
<div class="row">
<h2>Search by Date</h2> <br>
<p> Please Enter Date </p>
</div>
</div>
</div>
<div class="searchform">
<form action="bydate.php" method="get" >
<label class="col-xs-12" for="timezone";>
<select name="timezone" id="timezone">
<option value="+1:00">+1:00</option>
<option value="+2:00">+2:00</option>
<option value="+3:00">+3:00</option>
<option value="+4:00">+4:00</option>
</select>
</label>
<div class="searchform">
<form action="bydate.php" method="get" >
<label class="col-xs-12" for="keyword";>
<input type="text" value="<?php echo htmlspecialchars($_GET["keyword"]); ?>" placeholder="Enter Team Name" id="" class="form-control" name="keyword">
</label>
<button class="btn btn-info">search</button>
</form>
</div>
</div>
<div class="clearfix"></div>
<div class="container">
<div class="row">
<div class="tables">
<div class="col-xs-12">
<table class="table table-hover footable">
<thead>
<tr>
<th>Home Team</th>
<th> vs </th>
<th>Away Team</th>
<th data-hide="phone, tablet">Sport</th>
<th data-hide="phone, tablet">Competition</th>
<th data-hide="phone, tablet">Date and Time</th>
<th data-hide="phone, tablet">Channels</th>
</tr>
</thead>
<?php
if($stmt->rowCount() >0) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$hometeam = $row['hometeam'];
$versus= $row['versus'];
$awayteam= $row['awayteam'];
$sport= $row['sport'];
$competition = $row['competition'];
$dateandtime=$row['dateandtime'];
$name=explode(',', $row['name']);
$channelid=explode(',', $row['channelid_fc']);
?>
<tbody>
<tr>
<td> <?php echo $row[hometeam] ; ?> </td>
<td> <?php echo $row[versus] ; ?> </td>
<td> <?php echo $row[awayteam] ; ?> </td>
<td> <?php echo $row[sport] ; ?> </td>
<td> <?php echo $row[competition] ; ?> </td>
<td> <?php echo $row[dateandtime] ; ?> </td>
<td>
<?php for ($i = 0; $i < count($channelid) && $i < count($name); ++$i) {
$achannelid = $channelid[$i];
$aname = $name[$i];
echo "<a href='http://sportschedule.xyz/view_channels.php?channelid=" .$achannelid."'> ".$aname." </br> </a> ";
}
?>
</tbody>
</td>
</tr>
<?php } ?>
<?php } else { ?>
<p>No matches found for the team you searched. Please try again</p>
<?php } ?>
</table>
</div>
</div>
</div>
</div>
<script>
$('.footable').footable({ addRowToggle: false });
$('.footable').footable({
calculateWidthOverride: function() {
return { width: $(window).width() };
}
});
$(document).ready(function(){ if ($.trim($(".footable tbody").text()).length == 0) { $('.footable').hide(); } });
</script>
</body>
</html>
</code></pre>
<p>Many Thanks to anyone who reads, and/or suggests how I could achieve a solution or steers me in the right direction for assistance</p>
| <p>I think that the most correct approach on this issue is the following:
- save the timezone on each user in database or in cookie (if you dont have authenticated users)
- create a global variable in php and javascript which you'll use all over your website called user_date
- at the start of the page make that user_date equal to the DateTime + timezone
You have to have a variable and everytime you make a date calculation use that timezone.</p>
<hr>
<p>Also i will leave here my other answer, related to how you can achieve this directly in your browser, without php and database relation.</p>
<p>I think you can do this automatically using javascript. stackoverflow.com/questions/1091372/⦠You can get the browser timezone which is basically the timezone of the user computer and you can use that. Another useful library for this : momentjs.com/timezone</p>
|
Can CIDetector returns more than one CIFeature of type CIDetectorTypeRectangle? <p>I also found this question <a href="https://forums.developer.apple.com/thread/56394" rel="nofollow">on Apple Dev Forum</a>.</p>
<p>Is it possible for a <code>CIDetector</code> set with <code>CIDetectorTypeRectangle</code> to return more than just one rectangle?</p>
<p>At the moment, this code always return a <code>feature.count</code> of <code>0</code> or <code>1</code>, even if the picture is full of rectangles.</p>
<pre><code>let context = CIContext()
let opts = [CIDetectorAccuracy : CIDetectorAccuracyHigh]
let detector = CIDetector(ofType: CIDetectorTypeRectangle, context: context, options: opts)
let image = CIImage(image: self.photoTaken)
let features = detector.features(in: image)
print(features.count) // never more than 1
</code></pre>
| <p>According to this talk in WWDC (<a href="http://asciiwwdc.com/2014/sessions/514" rel="nofollow">http://asciiwwdc.com/2014/sessions/514</a>), it is limited to only one rectangle.</p>
<p>Here is a quote for that:</p>
<blockquote>
<p>So we've created a generic rectangle detector object and it takes one
option parameter which is the aspect ratio that we want to search for.</p>
<p>And again, you can ask the detector to return the features array.</p>
<p>Now right now, it just returns one rectangle but that may change in
the future.</p>
</blockquote>
|
How to automate compile less css without less js <p>I am a newbie in lesscss. </p>
<pre><code>using JavaScript is discouraged at the production stage as it will badly affect the website performance
</code></pre>
<blockquote>
<p>In future, I will deploy PHP code on <code>apache server</code>.</p>
<p>How to compile less css without node.js. Is there any alternative to
compile lesscss before hand.</p>
</blockquote>
<p>Case:</p>
<p>After changes in lesscss, I will <code>automate compile my all less css files</code> instead to go for manual because It will become tough for me to compile each less css file.</p>
<p>For automation what should I do?</p>
| <p>The simplest setup for compiling LESS beforehand is covered in the official <a href="http://lesscss.org/#using-less" rel="nofollow">"Using Less" documentation</a> ("Installation" and "Command Line Usage" sections). Basically you'll do</p>
<pre><code>$ npm install -g less
$ lessc inputfilename.less outputfilename.css
</code></pre>
<p>If you make a main LESS file that imports the rest, you'll only have to run one <code>lessc</code> command. for example, main.less (the name could be anything) might look like</p>
<pre><code>@import 'myfirstfile';
@import 'somedirectory/anotherfile';
@import 'somedirectory/yetanother';
</code></pre>
<p>and you'd just run <code>lessc main.less main.css</code></p>
|
NullPointerException when launching Camera view activity, which kills it instantly <p>I get fatal exception every time launching the tutorial app, clearly installed on phone JIAYU J3, from the activity listed below. All needed permissions and api key are added. Gradle builds finish without visionable failures. The issue goes that way: the app launches the main(camera) activity, holds it for about 1 second and crashes.</p>
<p>The trace:</p>
<pre><code>10-13 15:44:55.881 10891-10891/es.esy.kkaun.procrastinant E/dalvikvm: Could not find class 'android.os.UserManager', referenced from method com.google.android.gms.common.l.k
10-13 15:44:55.927 10891-10891/es.esy.kkaun.procrastinant E/dalvikvm: Could not find class 'android.app.AppOpsManager', referenced from method com.google.android.gms.c.aw.a
10-13 15:44:57.240 10891-10891/es.esy.kkaun.procrastinant E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at android.support.v4.a.a.a(Unknown Source)
at es.esy.kkaun.procrastinant.c.a(Unknown Source)
at com.google.android.gms.common.internal.r.a(Unknown Source)
at com.google.android.gms.c.x.a(Unknown Source)
at com.google.android.gms.c.v.g(Unknown Source)
at com.google.android.gms.c.v.a(Unknown Source)
at com.google.android.gms.c.z.a(Unknown Source)
at com.google.android.gms.c.r.a(Unknown Source)
at com.google.android.gms.common.internal.q$1.a(Unknown Source)
at com.google.android.gms.common.internal.j$j.a(Unknown Source)
at com.google.android.gms.common.internal.j$a.a(Unknown Source)
at com.google.android.gms.common.internal.j$a.a(Unknown Source)
at com.google.android.gms.common.internal.j$e.c(Unknown Source)
at com.google.android.gms.common.internal.j$d.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:4624)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
at dalvik.system.NativeStart.main(Native Method)
</code></pre>
<p>Layout.xml:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<SurfaceView
android:id="@+id/cameraview"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<ImageView
android:id="@+id/icon"
android:layout_width="96dp"
android:layout_height="96dp"
android:src="@drawable/obj1"
android:visibility="invisible"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<TextView
android:id="@+id/cameraTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Map"
android:id="@+id/btnMap"
android:layout_marginBottom="23dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="224dp"
android:layout_height="224dp"
android:id="@+id/imageView"
android:src="@drawable/reticle"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
</code></pre>
<p>Manifest file:
</p>
<pre><code><uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@android:style/Theme.NoTitleBar"
android:name="android.support.multidex.MultiDexApplication">
<activity
android:name="es.esy.kkaun.procrastinant.CameraViewActivity"
android:label="@string/activity_camera_view">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="es.esy.kkaun.procrastinant.MapsActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="es.esy.kkaun.procrastinant.CameraViewActivity" />
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="***api key added***" />
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version"/>
</application>
</code></pre>
<p></p>
<p>Butched activity lifecycle code:</p>
<pre><code>@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout. activity_camera_view);
setRequestedOrientation(ActivityInfo. SCREEN_ORIENTATION_PORTRAIT);
setupListeners();
setupLayout();
setAugmentedRealityPoint();
}
@Override
protected void onResume() {
super.onResume();
myCurrentAzimuth.start();
myCurrentLocation.start();
}
@Override
protected void onStop() {
myCurrentAzimuth.stop();
myCurrentLocation.stop();
super.onStop();
}
</code></pre>
<p>And finally full activity code:</p>
<pre><code>public class CameraViewActivity extends Activity implements
SurfaceHolder.Callback, OnLocationChangedListener, OnAzimuthChangedListener, View.OnClickListener {
private Camera mCamera;
private SurfaceHolder mSurfaceHolder;
private boolean isCameraviewOn = false ;
private MObject mPoi;
private double mAzimuthReal = 0 ;
private double mAzimuthTeoretical = 0 ;
private static final double DISTANCE_ACCURACY = 20 ;
private static final double AZIMUTH_ACCURACY = 10 ;
private double mMyLatitude = 0 ;
private double mMyLongitude = 0 ;
public static final double TARGET_LATITUDE = 27.590377 ;
public static final double TARGET_LONGITUDE = 14.425153 ;
private MyCurrentAzimuth myCurrentAzimuth;
private MyCurrentLocation myCurrentLocation;
TextView descriptionTextView;
ImageView pointerIcon;
Button btnMap;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout. activity_camera_view);
setRequestedOrientation(ActivityInfo. SCREEN_ORIENTATION_PORTRAIT);
setupListeners();
setupLayout();
setAugmentedRealityPoint();
}
private void setAugmentedRealityPoint() {
mPoi = new MObject(
getString(R.string. p_name ),
TARGET_LATITUDE, TARGET_LONGITUDE
);
}
public double calculateDistance() {
double dX = mPoi .getPoiLatitude() - mMyLatitude;
double dY = mPoi .getPoiLongtitude() - mMyLongitude;
double distance = (Math. sqrt(Math.pow (dX, 2 ) + Math.pow(dY, 2 )) * 100000 );
return distance;
}
public double calculateTeoreticalAzimuth() {
double dX = mPoi .getPoiLatitude() - mMyLatitude;
double dY = mPoi .getPoiLongtitude() - mMyLongitude ;
double phiAngle;
double tanPhi;
double azimuth = 0;
tanPhi = Math.abs (dY / dX);
phiAngle = Math.atan (tanPhi);
phiAngle = Math.toDegrees (phiAngle);
if (dX > 0 && dY > 0) { // I quater
return azimuth = phiAngle;
} else if (dX < 0 && dY > 0) { // II
return azimuth = 180 - phiAngle;
} else if (dX < 0 && dY < 0) { // III
return azimuth = 180 + phiAngle;
} else if (dX > 0 && dY < 0) { // IV
return azimuth = 360 - phiAngle;
}
return phiAngle;
}
private List<Double> calculateAzimuthAccuracy( double azimuth) {
double minAngle = azimuth - AZIMUTH_ACCURACY ;
double maxAngle = azimuth + AZIMUTH_ACCURACY ;
List<Double> minMax = new ArrayList<Double>();
if (minAngle < 0)
minAngle += 360;
if (maxAngle >= 360)
maxAngle -= 360;
minMax.clear();
minMax.add(minAngle);
minMax.add(maxAngle);
return minMax;
}
private boolean isBetween( double minAngle, double maxAngle, double azimuth) {
if (minAngle > maxAngle) {
if (isBetween( 0, maxAngle, azimuth) && isBetween(minAngle, 360 , azimuth))
return true ;
} else {
if (azimuth > minAngle && azimuth < maxAngle)
return true ;
}
return false;
}
private void updateDescription() {
long distance = ( long ) calculateDistance();
int tAzimut = ( int ) mAzimuthTeoretical ;
int rAzimut = ( int ) mAzimuthReal ;
String text = mPoi.getPoiName()
+ " location:"
+ "\n latitude: " + TARGET_LATITUDE + " longitude: " + TARGET_LONGITUDE
+ "\n Current location:"
+ "\n Latitude: " + mMyLatitude + " Longitude: " + mMyLongitude
+ "\n "
+ "\n Target azimuth: " + tAzimut
+ " \n Current azimuth: " + rAzimut
+ " \n Distance: " + distance;
descriptionTextView.setText(text);
}
public void onAzimuthChanged( float azimuthChangedFrom, float azimuthChangedTo) {
mAzimuthReal = azimuthChangedTo;
mAzimuthTeoretical = calculateTeoreticalAzimuth();
int distance = ( int ) calculateDistance();
pointerIcon = (ImageView) findViewById(R.id. icon );
Drawable myDrawable = getResources().getDrawable(R.drawable.obj1);
pointerIcon.setImageDrawable(myDrawable);
double minAngle = calculateAzimuthAccuracy(mAzimuthTeoretical ).get( 0);
double maxAngle = calculateAzimuthAccuracy(mAzimuthTeoretical ).get( 1);
if ((isBetween(minAngle, maxAngle, mAzimuthReal )) && distance <= DISTANCE_ACCURACY ) {
pointerIcon.setVisibility(View. VISIBLE );
} else {
pointerIcon.setVisibility(View. INVISIBLE );
}
updateDescription();
}
@Override
public void onLocationChanged(Location location) {
mMyLatitude = location.getLatitude();
mMyLongitude = location.getLongitude();
mAzimuthTeoretical = calculateTeoreticalAzimuth();
Toast.makeText (this , "latitude: "+location.getLatitude()+ " longitude: "+location.getLongitude(), Toast. LENGTH_SHORT ).show();
int distance = (int) calculateDistance();
if (mAzimuthReal == 0){
if ( distance <= DISTANCE_ACCURACY) {
pointerIcon.setVisibility(View.VISIBLE);
} else {
pointerIcon.setVisibility(View.INVISIBLE);
}
}
updateDescription();
}
@Override
protected void onResume() {
super.onResume();
myCurrentAzimuth.start();
myCurrentLocation.start();
}
@Override
protected void onStop() {
myCurrentAzimuth.stop();
myCurrentLocation.stop();
super.onStop();
}
private void setupListeners() {
myCurrentLocation = new MyCurrentLocation( this);
myCurrentLocation.buildGoogleApiClient( this );
myCurrentLocation.start();
myCurrentAzimuth = new MyCurrentAzimuth( this, this);
myCurrentAzimuth.start();
}
private void setupLayout() {
descriptionTextView = (TextView) findViewById(R.id.cameraTextView );
btnMap = (Button) findViewById(R.id. btnMap );
btnMap.setVisibility(View. VISIBLE );
btnMap.setOnClickListener( this );
getWindow().setFormat(PixelFormat. UNKNOWN);
SurfaceView surfaceView = (SurfaceView) findViewById(R.id.cameraview );
mSurfaceHolder = surfaceView.getHolder();
mSurfaceHolder.addCallback( this );
mSurfaceHolder.setType(SurfaceHolder. SURFACE_TYPE_PUSH_BUFFERS );
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
if ( isCameraviewOn ) {
mCamera.stopPreview();
isCameraviewOn = false ;
}
if ( mCamera != null ) {
try {
mCamera .setPreviewDisplay( mSurfaceHolder);
mCamera .startPreview();
isCameraviewOn = true ;
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
mCamera = Camera. open();
mCamera.setDisplayOrientation( 90);
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
mCamera.stopPreview();
mCamera.release();
mCamera = null ;
isCameraviewOn = false ;
}
@Override
public void onClick(View v) {
Intent intent = new Intent( this , MapsActivity. class);
startActivity(intent);
}
}
</code></pre>
| <p>Problem solved: seems from the jump it was caused by taking unsuitable target SDK, appcompat and play-services versions.</p>
|
Can I use Websphere application server V8.0.0.10 (network deployment) for mobilefirst 7.1 clustering? <p>I have done Websphere application server V8.5 (network deployment) clustering for mobilefirst 7.1 using this link. </p>
<p><a href="http://www.ibm.com/support/knowledgecenter/SSHS8R_7.1.0/com.ibm.worklight.installconfig.doc/admin/t_setting_up_WL_WAS_ND_8_cluster_env.html" rel="nofollow">http://www.ibm.com/support/knowledgecenter/SSHS8R_7.1.0/com.ibm.worklight.installconfig.doc/admin/t_setting_up_WL_WAS_ND_8_cluster_env.html</a></p>
<p>Everything is working fine.
But for this I used WAS ND V8.5.</p>
<p>Is similar clustering possible with WAD ND V8.0.0.10? I know that mobilefirst 7.1 is compatible with WAS ND V8.0.0.10 but not sure about clustering.</p>
<p>Can't find it any of document related this.</p>
| <p>Support is available from WAS ND 8.0.0.<strong>10</strong> onwards.<br>
You cannot use WAS ND 8.0.0.3.</p>
<p>See here: <a href="http://www-969.ibm.com/software/reports/compatibility/clarity-reports/report/html/softwareReqsForProduct?deliverableId=46183B706BEA11E48038141DE954FC88&osPlatforms=AIX%7CLinux%7CMac%20OS%7CMobile%20OS%7CSolaris%7CWindows&duComponentIds=S001#sw-0" rel="nofollow">http://www-969.ibm.com/software/reports/compatibility/clarity-reports/report/html/softwareReqsForProduct?deliverableId=46183B706BEA11E48038141DE954FC88&osPlatforms=AIX%7CLinux%7CMac%20OS%7CMobile%20OS%7CSolaris%7CWindows&duComponentIds=S001#sw-0</a></p>
<p>Under "Supported Software -> Application Servers".</p>
|
Imitate click of different div <p>Currently using contactable and triggering the following:</p>
<pre class="lang-js prettyprint-override"><code>$('#my-contact-div').contactable({
subject: 'feedback URL:'+location.href,
header: '',
url: 'mail.php',
name: 'Name',
email: 'Email',
message : 'Message',
submit : 'SEND',
recievedMsg : 'Thank you for your message',
notRecievedMsg : 'Sorry but your message could not be sent, try again later',
footer: 'Please feel free to get in touch, we value your feedback',
hideOnSubmit: true
});
</code></pre>
<p>However I'd like to be able to slide this form area open when clicking a different div. As the .contactable script runs attached to <code>#my-contact-div</code>, would I need to simulate a click on that <code>div</code>?</p>
<p>For example on another <code>div</code> called <code>.linkClick</code> so that when this is clicked, it registers as <code>#my-contact-div</code> being clicked.</p>
| <p>Sorted it by changing the js file with the following:</p>
<pre><code>jQuery('#contactable-inner').toggleClick(function() {
jQuery('#contactable-overlay').css({display: 'block'});
jQuery(this).animate({"marginRight": "-=5px"}, "2000");
jQuery('#contactable-contactForm').animate({"marginRight": "-=0px"}, "2000");
jQuery(this).animate({"marginRight": "+=387px"}, "4000");
jQuery('#contactable-contactForm').animate({"marginRight": "+=390px"}, "4000");
}
</code></pre>
<p>to</p>
<pre><code>jQuery('#contactable-inner,.formLink').toggleClick(function() {
jQuery('#contactable-overlay').css({display: 'block'});
jQuery('#contactable-inner').animate({"marginRight": "-=5px"}, "2000");
jQuery('#contactable-contactForm').animate({"marginRight": "-=0px"}, "2000");
jQuery('#contactable-inner').animate({"marginRight": "+=387px"}, "4000");
jQuery('#contactable-contactForm').animate({"marginRight": "+=390px"}, "4000");
}
</code></pre>
|
Delete the row with the highest id in mysql, using php <p>I'm working on a really simple minichat program (<code>php/mysql</code>) which displays the last 10 messages. </p>
<p>I wanted to add a button to delete the last message (using a form, leading to a <code>php</code> file like the one under). </p>
<p>I'm really a beginner with <code>php</code> and <code>mysql</code> so, I don't understand why it doesn't work.</p>
<p>Follows my code:</p>
<pre><code><?php
// Create connection
$cn = new mysqli("localhost","root","","test");
// Check connection
if($cn->connect_error)
{
echo "Connection failed : " . $cn->connect_error;
}
$sql = "DELETE FROM `minichat` WHERE `minichat`.`id` = ('SELECT MAX(`id`) FROM `minichat`')";
if($cn->query($sql) === TRUE){
echo "Deleted succesfully";
}
else
{
echo "Error deleting record: " . $cn->error;
}
//header('Location: connexion.php');
?>
</code></pre>
| <p>According to the manual on <a href="http://dev.mysql.com/doc/refman/5.7/en/delete.html" rel="nofollow">DELETE Syntax</a>:</p>
<blockquote>
<p>Subqueries</p>
<p>You cannot delete from a table and select from the same table in a
subquery.</p>
</blockquote>
<p>So instead you should do something like:</p>
<pre><code>DELETE FROM minichat ORDER BY id DESC LIMIT 1
</code></pre>
<p>And you probably want a condition to make sure a user can only delete his / her own comment..</p>
|
View XML-Data as Table <p>I hope anyone can help me with my problem...</p>
<p>I have a Table (DAT_Detail) in SQL Server 2008R2 with a XML-Column. In the XML-Column are my detailinformations for some tests... (I cannot change the table to another design, it hast to stay as xml).
My table has 2 columns: DAT_Detail_ID (uniqueidentifier) and XMLDetaildata (XML).</p>
<p>This is the script to add my testdata:</p>
<pre><code>INSERT INTO DAT_Detail (DAT_Detail_ID, XMLDetaildata) VALUES ('629E4F85-098D-418B-BF2E-63648DCF60ED', '<NewDataSet><DetailTest_A10><TestValue1>1321</TestValue1><TestValue2>142</TestValue2><TestValue3>153</TestValue3><TestValue4>1645</TestValue4><TestValue5>1123</TestValue5><TestValue6>114</TestValue6><TestValue7>1253</TestValue7></DetailTest_A10></NewDataSet>');
INSERT INTO DAT_Detail (DAT_Detail_ID, XMLDetaildata) VALUES ('9B30DDAF-0733-4D0D-BCBD-54DA3B56C8F9', '<NewDataSet><DetailTest_A10><TestValue1>2321</TestValue1><TestValue2>242</TestValue2><TestValue3>253</TestValue3><TestValue4>2645</TestValue4><TestValue5>2123</TestValue5><TestValue6>214</TestValue6><TestValue7>2253</TestValue7></DetailTest_A10></NewDataSet>');
INSERT INTO DAT_Detail (DAT_Detail_ID, XMLDetaildata) VALUES ('E647B9FB-7B96-440A-ADCB-300F8DEA4BF1', '<NewDataSet><DetailTest_A10><TestValue1>3321</TestValue1><TestValue2>342</TestValue2><TestValue3>353</TestValue3><TestValue4>3645</TestValue4><TestValue5>3123</TestValue5><TestValue6>314</TestValue6><TestValue7>3253</TestValue7></DetailTest_A10></NewDataSet>');
INSERT INTO DAT_Detail (DAT_Detail_ID, XMLDetaildata) VALUES ('50041AE4-BE73-4281-A36E-7448F6F35E03', '<NewDataSet><DetailTest_A10><TestValue1>4321</TestValue1><TestValue2>442</TestValue2><TestValue3>453</TestValue3><TestValue4>4645</TestValue4><TestValue5>4123</TestValue5><TestValue6>414</TestValue6><TestValue7>4253</TestValue7></DetailTest_A10></NewDataSet>');
INSERT INTO DAT_Detail (DAT_Detail_ID, XMLDetaildata) VALUES ('87AE23BA-41DE-4C1E-BA4E-37E7C3419FE3', '<NewDataSet><DetailTest_A10><TestValue1>5321</TestValue1><TestValue2>542</TestValue2><TestValue3>553</TestValue3><TestValue4>5645</TestValue4><TestValue5>5123</TestValue5><TestValue6>514</TestValue6><TestValue7>5253</TestValue7></DetailTest_A10></NewDataSet>');
INSERT INTO DAT_Detail (DAT_Detail_ID, XMLDetaildata) VALUES ('9AAEA106-35C9-40B8-B0D5-7CA7F59E5D90', '<NewDataSet><DetailTest_A10><TestValue1>6321</TestValue1><TestValue2>642</TestValue2><TestValue3>653</TestValue3><TestValue4>6645</TestValue4><TestValue5>6123</TestValue5><TestValue6>614</TestValue6><TestValue7>6253</TestValue7></DetailTest_A10></NewDataSet>');
</code></pre>
<p>What I want is to select 2 or more rows and convert the XML to a table-format to show the values in a report in a SQLReportServer.</p>
<p>I have a query for translate XML to table but i can only use 1 row for this. As soon as I try to take more rows, only the last row is translated to a table.</p>
<p>My Script:</p>
<pre><code>DECLARE @XML AS XML
DECLARE @hDoc AS INT
SELECT @XML = XMLDetaildata FROM DAT_Detail WHERE DAT_Detail_ID = '9B30DDAF-0733-4D0D-BCBD-54DA3B56C8F9'
EXEC sp_xml_preparedocument @hDoc OUTPUT, @XML
SELECT *
FROM OPENXML(@hDoc, 'NewDataSet/DetailTest_A10')
WITH
(
TestValue1 [int] 'TestValue1',
TestValue2 [int] 'TestValue2',
TestValue3 [int] 'TestValue3',
TestValue4 [int] 'TestValue4',
TestValue5 [int] 'TestValue5',
TestValue6 [int] 'TestValue6',
TestValue7 [int] 'TestValue7'
)
EXEC sp_xml_removedocument @hDoc
</code></pre>
<p>What I get is a table:</p>
<pre><code>TestValue1 TestValue2 TestValue3 TestValue4 TestValue5 TestValue6 TestValue7
2321 242 253 2645 2123 214 2253
</code></pre>
<p>I tried to change my script to:</p>
<pre><code>SELECT @XML = XMLDetaildata FROM DAT_Detail WHERE DAT_Detail_ID IN ( '9B30DDAF-0733-4D0D-BCBD-54DA3B56C8F9', '50041AE4-BE73-4281-A36E-7448F6F35E03')
</code></pre>
<p>to get this:</p>
<pre><code>TestValue1 TestValue2 TestValue3 TestValue4 TestValue5 TestValue6 TestValue7
2321 242 253 2645 2123 214 2253
4321 442 453 4645 4123 414 4253
</code></pre>
<p>but it failed... has anyone another idea to get me in the right direction?</p>
| <p>You can use this kind of solution:</p>
<pre><code>SELECT TestValue1,
TestValue2,
TestValue3,
TestValue4,
TestValue5,
TestValue6,
TestValue7
FROM (
SELECT dd.DAT_Detail_ID,
CAST(t.c.query('local-name(.)') as nvarchar(max)) as [Columns],
t.c.value('.','nvarchar(max)') as [Values]
FROM DAT_Detail dd
CROSS APPLY XMLDetaildata.nodes('/NewDataSet/DetailTest_A10/*') as t(c)
WHERE dd.DAT_Detail_ID IN (
'9B30DDAF-0733-4D0D-BCBD-54DA3B56C8F9',
'50041AE4-BE73-4281-A36E-7448F6F35E03')
) t
PIVOT (
MAX([Values]) FOR [Columns] IN (TestValue1,TestValue2,TestValue3,TestValue4,TestValue5,TestValue6,TestValue7)
) as pvt
</code></pre>
<p>Output:</p>
<pre><code>TestValue1 TestValue2 TestValue3 TestValue4 TestValue5 TestValue6 TestValue7
4321 442 453 4645 4123 414 4253
2321 242 253 2645 2123 214 2253
</code></pre>
<p>Or:</p>
<pre><code>SELECT t.c.value('(*)[1]','nvarchar(max)') as TestValue1,
t.c.value('(*)[2]','nvarchar(max)') as TestValue2,
t.c.value('(*)[3]','nvarchar(max)') as TestValue3,
t.c.value('(*)[4]','nvarchar(max)') as TestValue4,
t.c.value('(*)[5]','nvarchar(max)') as TestValue5,
t.c.value('(*)[6]','nvarchar(max)') as TestValue6,
t.c.value('(*)[7]','nvarchar(max)') as TestValue7
FROM DAT_Detail dd
CROSS APPLY XMLDetaildata.nodes('/NewDataSet/DetailTest_A10') as t(c)
WHERE dd.DAT_Detail_ID IN (
'9B30DDAF-0733-4D0D-BCBD-54DA3B56C8F9',
'50041AE4-BE73-4281-A36E-7448F6F35E03')
</code></pre>
|
Wordpress Permalink Redirect <p>On the google search console i have thousands of 404 error with permalink structured like this </p>
<p><a href="http://www.example.com/2016/01/11/victory-for-wenger-as-arsenal-top-premier-league-money-table/meky2xs@gmail.com" rel="nofollow">http://www.example.com/2016/01/11/victory-for-wenger-as-arsenal-top-premier-league-money-table/meky2xs@gmail.com</a> </p>
<p>and my current permalink structure is </p>
<p><a href="http://www.example.com/2016/01/victory-for-wenger-as-arsenal-top-premier-league-money-table" rel="nofollow">http://www.example.com/2016/01/victory-for-wenger-as-arsenal-top-premier-league-money-table</a></p>
<p>how do i redirect all thousand of links to this new structure via .htaccess?</p>
<p>and also links like <code>http://www.example.com/2016/07/explosion-rocks-german-immigrââation-centre-nurembeâârg/@authorname</code> to this link <code>http://www.example.com/2016/07/explosion-rocks-german-immigrââation-centre-nurembeâârg</code> in htaccess? just removing the author's name and any other link after the postname?</p>
| <p>you can try this </p>
<pre><code>Redirect 301 /http://www.example.com/2016/01/11/victory-for-wenger-as-arsenal-top-premier-league-money-table/meky2xs@gmail.com http://www.example.com/2016/01/victory-for-wenger-as-arsenal-top-premier-league-money-table
</code></pre>
|
Certain Unix commands fail with "... not found", when executed through Java using JSch <p>I have a piece of code which connects to a Unix server and executes commands.</p>
<p>I have been trying with simple commands and they work fine.</p>
<p>I am able to login and get the output of the commands.</p>
<p>I need to run an Ab-initio graph through Java.</p>
<p>I am using the <code>air sandbox run graph</code> command for this.</p>
<p>It runs fine, when I login using SSH client and run the command. I am able to run the graph. However, when I try to run the command through Java it gives me a <em>"air not found"</em> error.</p>
<p>Is there any kind of limit on what kind of Unix commands JSch supports?</p>
<p>Any idea why I'm not able to run the command through my Java code?</p>
<p>Here's the code:</p>
<pre><code>public static void connect(){
try{
JSch jsch=new JSch();
String host="*****";
String user="*****";
String config =
"Host foo\n"+
" User "+user+"\n"+
" Hostname "+host+"\n";
ConfigRepository configRepository =
com.jcraft.jsch.OpenSSHConfig.parse(config);
jsch.setConfigRepository(configRepository);
Session session=jsch.getSession("foo");
String passwd ="*****";
session.setPassword(passwd);
UserInfo ui = new MyUserInfo(){
public boolean promptYesNo(String message){
int foo = 0;
return foo==0;
}
};
session.setUserInfo(ui);
session.connect();
String command="air sandbox run <graph-path>";
Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);
InputStream in=channel.getInputStream();
channel.connect();
byte[] tmp=new byte[1024];
while(true){
while(in.available()>0){
int i=in.read(tmp, 0, 1024);
if(i<0)break;
page_message=new String(tmp, 0, i);
System.out.print(page_message);
}
if(channel.isClosed()){
if(in.available()>0) continue;
System.out.println("exit-status: "+channel.getExitStatus());
break;
}
try{Thread.sleep(1000);}catch(Exception ee){}
}
channel.disconnect();
session.disconnect();
}
catch(Exception e){
System.out.println(e);
}
}
public static void main(String arg[]){
connect();
}
public String return_message(){
String ret_message=page_message;
return ret_message;
}
public static abstract class MyUserInfo
implements UserInfo, UIKeyboardInteractive{
public String getPassword(){ return null; }
public boolean promptYesNo(String str){ return false; }
public String getPassphrase(){ return null; }
public boolean promptPassphrase(String message){ return false; }
public boolean promptPassword(String message){ return false; }
public void showMessage(String message){ }
public String[] promptKeyboardInteractive(String destination,
String name,
String instruction,
String[] prompt,
boolean[] echo){
return null;
}
}
</code></pre>
| <p>The "exec" channel in the JSch (rightfully) does not allocate a pseudo terminal (PTY) for the session. As a consequence a different set of startup scripts is (might be) sourced. And/or different branches in the scripts are taken, based on absence/presence of the <code>TERM</code> environment variable. So the environment might differ from the interactive session you use with your SSH client.</p>
<p>So in your case, the <code>PATH</code> is probably set differently and consequently the <code>air</code> executable cannot be found.</p>
<p>You should fix your startup scripts to set the <code>PATH</code> same for both interactive and non-interactive sessions.</p>
<p>To verify that this is the root cause, disable the pseudo terminal allocation in your SSH client. For example in PuTTY, it's <em>Connection > SSH > TTY > Don't allocate a pseudo terminal</em>. Then go to <em>Connection > SSH > Remote command</em> and ether your <code>air ...</code> command. Check <em>Session > Close window on exit > Never</em> and open the session. You should get the same <em>"air not found"</em> error.</p>
<hr>
<p>You can of course work this around by using a full path to the <code>air</code>.</p>
<hr>
<p>Another (not recommended) approach is to force the pseudo terminal allocation for the "exec" channel using the <code>.setPty</code> method:</p>
<pre><code>Channel channel=session.openChannel("exec");
((ChannelExec)channel).setPty(true);
</code></pre>
<p>Using the pseudo terminal to automate a command execution can bring you nasty side effects. See for example <a href="http://stackoverflow.com/q/33291631/850848">Is there a simple way to get rid of junk values that come when you SSH using Python's Paramiko library and fetch output from CLI of a remote machine?</a></p>
|
A more efficient / less-amateur way to do something based on selected option instead of a massive if-tree? <p>This has been bugging me for a while but I'm not sure if there's anyway to improve this... Basically in this project I have a list compiled of cards that I want to add to a final text output. I iterate through the list and every iteration I go through many if statements, checking for a card name and if the card name is recognizable then I add a block of code to a string that is specific to that card. Here are some things that might help / restrict solutions:</p>
<ul>
<li><p>The blocks of code that get added to the string that I'm compiling are stored in the resources file of my project. You will see in the code below they're referred to as m1735xxxx. Maybe there's a way to do a search through these strings in my resource file much like a list?</p></li>
<li><p>all of the possible items on the list being read in are known and have a block of code that goes with them stored in my resources.</p></li>
</ul>
<p>Code:</p>
<pre><code>int numCards = moduleList.Count;
while (moduleList.Any())
{
SplashScreen.SetProgress((int)((numCards - moduleList.Count) * 100.00 / numCards));
if (moduleList[0].name.Contains("1756"))
{
etrCount++;
string newCard = Cards.m1756EN2T.Replace("@SLOT@", etrCount.ToString());
newCard = newCard.Replace("@ETHERNUM@", etrCount.ToString());
finalOutput = finalOutput + newCard;
finalOutput += Environment.NewLine;
finalOutput += Environment.NewLine;
moduleList.RemoveAt(0);
modSlotCount = 0;
}
else if (moduleList[0].name.Contains("AENTR"))
{
aentrCount++;
modSlotCount = 0;
string newCard = Cards.m1734AENTR.Replace("@SLOT@", modSlotCount.ToString());
newCard = newCard.Replace("@SIZE@", numMods[aentrCount].ToString());
newCard = newCard.Replace("@AENTRNUM@", aentrCount.ToString());
newCard = newCard.Replace("@ETHERNUM@", etrCount.ToString());
finalOutput = finalOutput + newCard;
finalOutput += Environment.NewLine;
finalOutput += Environment.NewLine;
moduleList.RemoveAt(0);
modSlotCount++;
}
while (moduleList.Any() && !moduleList[0].name.Contains("AENTR") && !moduleList[0].name.Contains("1756"))
{
if (moduleList[0].name == "1734-IB8S")
{
string newCard = Cards.m1734IB8S.Replace("@SLOT@", modSlotCount.ToString());
newCard = newCard.Replace("@AENTRNUM@", aentrCount.ToString());
finalOutput = finalOutput + newCard;
finalOutput += Environment.NewLine;
finalOutput += Environment.NewLine;
moduleList.RemoveAt(0);
modSlotCount++;
}
else if (moduleList[0].name == "1734-OB8S")
{
string newCard = Cards.m1734OB8S.Replace("@SLOT@", modSlotCount.ToString());
newCard = newCard.Replace("@AENTRNUM@", aentrCount.ToString());
finalOutput = finalOutput + newCard;
finalOutput += Environment.NewLine;
finalOutput += Environment.NewLine;
moduleList.RemoveAt(0);
modSlotCount++;
}
else if (moduleList[0].name == "1734-IB4D")
{
string newCard = Cards.m1734IB4D.Replace("@SLOT@", modSlotCount.ToString());
newCard = newCard.Replace("@AENTRNUM@", aentrCount.ToString());
finalOutput = finalOutput + newCard;
finalOutput += Environment.NewLine;
finalOutput += Environment.NewLine;
moduleList.RemoveAt(0);
modSlotCount++;
}
else if (moduleList[0].name == "1734-OB4E")
{
string newCard = Cards.m1734OB4E.Replace("@SLOT@", modSlotCount.ToString());
newCard = newCard.Replace("@AENTRNUM@", aentrCount.ToString());
finalOutput = finalOutput + newCard;
finalOutput += Environment.NewLine;
finalOutput += Environment.NewLine;
moduleList.RemoveAt(0);
modSlotCount++;
}
else if (moduleList[0].name == "1734-IE2C")
{
string newCard = Cards.m1734IE2C.Replace("@SLOT@", modSlotCount.ToString());
newCard = newCard.Replace("@AENTRNUM@", aentrCount.ToString());
finalOutput = finalOutput + newCard;
finalOutput += Environment.NewLine;
finalOutput += Environment.NewLine;
moduleList.RemoveAt(0);
modSlotCount++;
}
else if (moduleList[0].name == "1734-OE2C")
{
string newCard = Cards.m1734OE2C.Replace("@SLOT@", modSlotCount.ToString());
newCard = newCard.Replace("@AENTRNUM@", aentrCount.ToString());
finalOutput = finalOutput + newCard;
finalOutput += Environment.NewLine;
finalOutput += Environment.NewLine;
moduleList.RemoveAt(0);
modSlotCount++;
}
else if (moduleList[0].name == "1734-IR2")
{
string newCard = Cards.m1734IR2.Replace("@SLOT@", modSlotCount.ToString());
newCard = newCard.Replace("@AENTRNUM@", aentrCount.ToString());
finalOutput = finalOutput + newCard;
finalOutput += Environment.NewLine;
finalOutput += Environment.NewLine;
moduleList.RemoveAt(0);
modSlotCount++;
}
}
}
</code></pre>
<p>See what I mean by amateur style? This works it's just really ugly to look at.</p>
| <p>You could create a dictionary which maps your strings to the resource field names and lookup the card via the resource manager:</p>
<pre><code>var mappings = new Dictionarx<string, string> { { "1734-IB8S", "m1734IB8S" }, { "1734-OB8S", "m1734OB8S" } /* ... */ }
var resourceManager = new ResourceManager("yourresourcefilename", typeof(Cards).Assembly);
while (moduleList.Any() && !moduleList[0].name.Contains("AENTR") && !moduleList[0].name.Contains("1756"))
{
string resourceName;
if (!mappings.TryGetValue(moduleList[0].name, out resourceName))
{
continue;
}
var field = resourceManager.GetString(resourceName);
string newCard = field.Replace("@SLOT@", modSlotCount.ToString());
newCard = newCard.Replace("@AENTRNUM@", aentrCount.ToString());
finalOutput = finalOutput + newCard;
finalOutput += Environment.NewLine;
finalOutput += Environment.NewLine;
moduleList.RemoveAt(0);
modSlotCount++;
}
</code></pre>
|
How to make a loading screen for a website hold for a certain number of seconds <p>I'm creating a website using the Salient theme in wordpress and I have a fairly large video file on the home page. So i set up a small gif to play as a loading image but sometimes the website loads too fast to even really see the gif.</p>
<p>Is there a piece of code that will force the website to hold of the loading screen for around 3-4 seconds by default?</p>
<p><a href="http://www.ryanlrobinson.com" rel="nofollow">http://www.ryanlrobinson.com</a> is the website where you can see the issue for yourself</p>
| <p>Well, what you want is a <code>setTimeout</code>, but what you should do is preload the video.</p>
<pre><code>setTimeout(function(){
// Hide loading
}, 3000); // Time is in milliseconds
</code></pre>
<p><strong>Example</strong></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>setTimeout(function(){
document.getElementById("loading").style.display = 'none';
}, 3000);</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.video {
width: 320px;
height: 240px;
position: relative;
}
#loading {
width: 100%;
height: 100%;
background: red;
position: absolute;
z-index: 1;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="video">
<div id="loading">Loading...</div>
<video width="320" height="240" autoplay>
<source src="http://ryanlrobinson.com/wp-content/uploads/2016/10/Home-Video.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
</div></code></pre>
</div>
</div>
</p>
<hr>
<p><strong>Update</strong> Based of comments.</p>
<p>Try this.</p>
<ol>
<li>Go to <strong>Plugins > Add new</strong>.</li>
<li>Search for a plugin that allows you to add custom Javascript. For example, Custom JS.</li>
<li>Active the plugin.</li>
<li>Go to <strong>Custom JS</strong></li>
<li>Copy & paste the following code in the <strong>Add JS in Footer</strong>.</li>
</ol>
<hr>
<pre><code>var loading = document.createElement('div');
loading.className = 'loading';
document.getElementsByClassName('swiper-wrapper')[0].appendChild(loading);
setTimeout(function(){
loading.style.display = 'none';
}, 3000);
</code></pre>
<hr>
<ol start="6">
<li>Now go to <strong>CSS/Script Releted</strong> section and paste the following code on <strong>Custom CSS Code</strong></li>
</ol>
<hr>
<pre><code>.loading {
width: 100%;
height: 100%;
background: #000 url('data:image/gif;base64,R0lGODlhQABAAKUAAAQCBISChMTCxDQ2NOzq7KyqrExOTBweHJSSlNTW1PT29FxaXLS2tCwqLAwKDIyKjMzKzERCRPTy9FRWVCQmJJyanNze3Pz+/GRiZLy+vExKTAQGBISGhMTGxOzu7KyurFRSVCQiJJSWlNza3Pz6/FxeXLy6vCwuLAwODIyOjMzOzERGRAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQICAAAACwAAAAAQABAAAAG/kCWcEgsGo/IpHLJbDqf0CgRtXg8FiipdjshXL4XwmRLdk7A6Mu4zD6ivOkvIduuCzFxNMbOHCwWA0opeWApfEkgI2gWIEgPhF8Ph0cBhAFHJZAXe0gHHBkmHAdaZ5BrUx6EHnRGGhJoChpRABaaFgBGpXELna9pEqNPA5pfgUYLcHKnRg8keZJPeMScRiglViWsRwKEAlDSmtRkGd1Qw8TGZY/PULS2uGwHvmjAUbp5vHUaCrCyUpV5LvE58EBAhgfBSNUCY2HZpDoDSpRI97CixYsYM2pkgoICBW0bo0Rg4OwCCQYRQkLZIIJQBXgql1TQhCDmkhXELqwIeaCA/gcJBRIOIUcsw8YGyS54CEHEQUlNJBxo/BDnA5ETOb+c0DgPjAQiDbJe2Jqx65evQ5zmjDq1ahGimoxqRIrGA4UiEXKm3NhTAlChQ2ZCqmlTyQbBcSpsKMwkgomSJEzsZdzEAYUGUilr3sw5yYkUCSR4SJCCbGciLJ+CISFi8WkWG+DmyeC6c0tiIk43UE2IRAM+FJhKuZ0zd5sQEL5AEP4kgdgEdZKDgRCFNyQSx+PcfWK9dxsK2qE4zwq9jXTlUYjjrhNCxRcVzJ2c6J7GN/DfWhBDqpBkgwEDmWXkADeQCFBbEQ64d4EKAWLEEiGtIYJGIyE1gEBoEoyAAH4SG4JB4WtGbCAdBAeCSAQABoAAk4kstujii00EAQAh+QQICAAAACwAAAAAQABAAIUEAgSEgoTEwsREQkSsrqwcGhzk5uRsamyUkpT09vQMDgxcWlwkJiR0dnTMysxMSky8urycmpwMCgyMiowkIiTs7ux0cnT8/vwEBgTExsRERkS0trQcHhzs6uxsbmyUlpT8+vwUFhQsLix8fnzMzsxMTky8vrycnpyMjowAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAG/sCUcEgsGo/IpHLJbDqf0Kh0Sl0uMheQY1HtOj+XsPjjLSMX4vSFa24LHWqxw90GgOJhEICeFE02GxMiSQAJeFl7fEUAE3dpE4lGcHhzikUThxNnh2xIEiMZGSMSUyKHYYNHCHERSgokaSQKUpinmmeTW0sBcQFSEKcXEG1YapVQwKfDZpNpx08owShtvGq+UaanqWWvsbNS0XjTbhIBGQ4BpFMA4WkokZZdIigQGyjb8fn6+/z9/v8AAxLB8MCDhwcYBD7x0CFNhQMKmZw4dCJikgPBPASkwMBThWAV1PHjkIuCkRLBwmjw1+zCMyEWUl5o0I9CnI5EYqakyY/B/s0iKFM+YOnMiISPp0L64wDrAgmTRjwEgwiQAU4kE/FUtJjEAtIwFSxwXSKhoIUHIseqXcu2bRIFVr+5JTJggyMQGwbMTYEBDJ4I8NRGCIagrQaZK9eakGnCTYgGFkJIkeAoGIi0AylQSMikgIEwBgpgk4nKyAMIdyGUWDIizYjRpPFJIHCIgFwjrcW8hkJZ5uUhGAQEE8DZSIGGFzqIjrI4ZeMhtYLdOvK4wfIoA2TqFRKi8qkEki0NPlV4CEbSVBVhGM+qeAr2KbfGG4A6D4TtRGiTJsBPQlwk8AUjn0XnyZSeRQV4dwgI4Y0V3SnjqCVBMYc4gBlXCugXh217CZVgwl0mrOZGEAAh+QQICAAAACwAAAAAQABAAIUEAgSEgoREQkTEwsQkIiSkoqRsamzk4uT08vQUFhRUVlQ0MjS0srSUlpR0dnQMCgxMSkzU0tSsqqzs6uz8+vw8OjzMyswsLix0cnQcHhxcXly8vrycnpwEBgSEhoRERkTExsQkJiSkpqRsbmzk5uT09vQcGhxcWlw0NjS0trScmpx8fnwMDgxMTkysrqzs7uz8/vw8PjwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAG/kCZcEgsGo/IpHLJbDqf0Kh0Sq1ar8lLilJKXbBg5AUBK8MQ37BamDKbU2s1gOIuUwBxZYdA6CwBJXUwd3lHDwETZS8BD0ptdXCFRR0bght+SAtkZmhNHXhVAYJlAUpaFBQpC0wsHAglHCxTHYmjE5hgIm4iUyGjZiFhD3RmFLhPvr8wwWAdxHbHTrS/t2oSbhJUHr8eaywFrwWyswOCA9FgAKBVDx4vZQiMkmEAIX3z+Pn6+/z9/v8AA06p0AAECBUVBDLpwEEQB3QKhzQcxSHikRjKYMTwl8ABhgRIJv6qyM8EiTIkTByxkNFCvxVuVqxs+TLmEZEU+5moNUGl/hGMyjb26+jA55ECvwpYPNIBaZ0CEJfKiKHCoAqhUrNq3cq1q8IKATgUCJCwSgcII0ZAiEoFBcs6FlBMGVFLkYEwCp7VKXEiCk43JK2g0CuIglwnBjKOsAIgQsYyEdYpefBO2YtGVAQ8NiOgSYvNH6ps2wyjGxMMmx0gAYDixAkUkodcI53tdGojAAwccEPCQGxdtD1vhjDJxS8Xx0ZvNr2EcsbLRVRkbEDkA2kYnZuMyHiXyALCglYJabw58pO/ZgIPkf5YBZEK4N1QKPsEQ2V4i404fhyhSN5fFPQlxQNoYbAWErs9doARbgkSFz77ZdQfbjF4UEABHsQQWx4NKWzmnlQobHaYVOi58WFWHTDwCwNsCZTbSWZM4JtXMgBQgQYaVLDhFUEAACH5BAgIAAAALAAAAABAAEAAhQQCBISChDw6PMTGxOTm5CQiJFRWVKSipNTW1CwuLAwODJSWlERGRGxqbMzOzPT29LS2tNze3AwKDERCRCwqLGRiZDQ2NJyenPz+/AQGBISGhDw+PMzKzCQmJFxaXKyqrNza3DQyNBQWFJyanExKTGxubNTS1Pz6/Ly6vOTi5AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAb+QJVwSCwaj8ikcslsOp/QqHRKrVqvS0oHy10WHBiMqdAtF03hsMPM7qTTFHaZ8g7H5UqRyIlOm/BJJH0IJEwFfWOARwx1GAxNFHdNEgYeElYIjQhsEpkYCJdTIo1he2UVbxVUo6SmXahpqlQgjSBsCp4gClWMdYWcHpZXJLQYIL+KXHrJzM3Oz9DR0tPUzgIBFwcBAtVMFhyNHBZJEiEhGdEGJ6QYDx5GGRoPYQ8a6M0C8+wYJ+NDCn3eONiVDEDAfSYADFnAbgGzCfvqTBCiQF+jBwQBaYj4RoOQEBH9AfrAMc0HIRZCJiNZEsNJFQrWkToRSmNLDB6FMCTlMFn+r5ITKR4MYyIjIIMlExKJJ/OEPWsy2Z3gZkSChRA1namT+q7bkW/hRHo1AmCDhgMHNGxQOLat27djJVSAAAIBhAb3pghYMGDACKpdLKRolEKskwwXGl3IayUfuweAnSQmdQGLhMH7UjBesiHihisNSjZ4MpldZSsoSqJ4Am4fhysRSkZgHfE1kgQBPqRNgCQ2x9mSI54uImHnmxGbVaTmuNpJ532fiwBY3ggF2yElSpaAcoDdgSOh940mIoFAxBRGmWToXudAchW+2QEnMsFinalTNozoOyK6kQIlkVGEAJi9kUJkcoDEkWFCSNAAXSCgUEFWeADIkYBuxUdKCnAgqRAeO+O9lQF1dVjXoQqINYLciUOEoMEHH2gQAovQBAEAIfkECAgAAAAsAAAAAEAAQACFBAIEhIKEREJExMbEJCIk5ObkbGpsrKqsFBIUNDI09Pb03NrcVFJUdHZ0tLa0DAoMlJKULCos7O7sHBocPDo8zM7MtLK0/P785OLkXFpcfH58BAYEhIaETEpMzMrMJCYk7OrsbG5srK6sFBYUNDY0/Pr83N7cVFZUfHp8vLq8DA4MlJaULC4s9PL0HB4cPD48AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABv5AmHBILBqPyKRyyWw6n9CodEqtWq/YbHaiCUy0YCNBcrlICEwAi8FgAcJMTbkcUG5QhfmlgNrAkwF6GkkjA3p6AyN/R2NlZ0gbHoeHA35SGwIvD04TAV5JDSWTh4NRCSZlJglZAHmjeiBvTw+ocwWbVwmvkyRQL5MvWBm7hxm+wMLEesazrmW3WLrKZb1Qp6mrWBsg0yCWUA8CArhZDdOli1GRxB7f6VCFr4nvVHfccyB99FYACWwJsvYJHEiwoMEwDww4WLDAgQF3B5WQqKUHQ7UjAD58CDjwhahRCigcOYGhDIYTBGkRwwDxxCSUAg1MM0Ck1SQMHNOlmJaCyP6HVx8EUtxlwidQgSWVFR1i81CBnIt2KutJxGWxgTKVhTCSIenJlM5GYVCBMUIEqPQ8viohMqISCkkrtnVrRyHDFA/p6t3Lt69fOA/MkqvyIEECiFk+HFBQpsSBoFM2cGB8QQEHxFU6tJjUooMUFRUmVSCLJcJmkBGirHi1IssBYgegqPg4SQFpwrRHlRi8RNqri1RYTGPxhAQx4Ece8C4iXBlxJ7PXLhfyoMGCMgv0GXmQe9JuKKtHtT6CwNAhDwiOvN4VW3boQxXSHxHxysKRD6c5p47ygMPHEhxMB4NvoyAnhGaceUbFAyQkIKAQcuyCThERiPCfCPvRAwExEC8o8QALLDwIBwrEoPCXEMbtYiBfFtR34hAIvKdHfC8O8QAKtZiAgoh+qcBjjYsEAQAh+QQICAAAACwAAAAAQABAAIUEAgSMioxEQkTMysxkYmTk5uQkIiSsqqxUUlT09vSUlpTc2tx0cnQcGhwsLiwMCgxMSkzU0tRsamzs7uxcWlyUkpQsKiy0trT8/vycnpwEBgSMjoxERkTMzsxkZmTs6uwkJiSsrqxUVlT8+vycmpzk4uR8enw0MjQMDgxMTkzU1tRsbmz08vRcXlwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAG/kCXcEgsGo8ayCYU2kAAx6h0Sp1yVJisdiGoer9fz0hLxowk4LR6yBmXy921nKrBvssqzXx/TN3vCHyCQxV/bxWDgxeGZRdHBisKFSsGiVOLjFqORA8kblkjGQ+WR4WZWYhDDwN/A6OkRAinWYFDCowZcycBGydRAHaMC1BCBp93I5VqDglZCQ5RbZlxQgynDGu3WgpSYn9nRSSnuWqmWdxSAgtvXEYZ42sObiPQUwBKTBVPR9aZ2GsnNvQiZYzRCBCwBL0zRC7hngcd/nR45XAPioVkMqComMgAAwUkGCjjSLKkyZMoU6o0+cCCBYorwYA40MzMAYQxvUBg8YYF/gQpKCBA2KjSAs87CSwcETAhywRqJw8wOmAERVMtE4iyrPkNpgs/ZVKgdHCq3hCwZMSePFG2iFUyWVE+OPZmhFcXAo6ygGpSqiGqR4IOXWn0DwulOafs7PkzMRULIeaFQOy4ygMHDu5W3sy5s+fPoCuioBAgAAWtcwCAAEEMlogPZD6I2COiRJYSs0mJ+JNbze4yvQWhgH3nA2ovAAq8KdGaDwFGBNSA+INT0AZGG6RTTxSAUQA1yd8UaG4EAAcTJjiQJ/LcUHTfbyhMARGBTATKbq++ibuGgm0MuE3RgHJlFNBAFL/FtwcALq1XhDZvoHMEBcRlIRtKBIo3BQoELpTWwnEcacCIHqFVWMYHoQkBYRkSgjbgGx8cmKILFgSDgQr4pWgeevvM6CNnQQAAIfkECAgAAAAsAAAAAEAAQACFBAIEhIaEREJExMbEJCIkZGJktLK07OrsnJqcVFZUDA4MNDI0/Pr8jI6M5OLkdHZ0TEpMzM7MLCosvL689PL0XF5cFBYUBAYEjIqMzMrMJCYkZGZk7O7snJ6cXFpcFBIUNDY0/P78lJKUfHp8TE5MxMLEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABv5Ak3BILBqPyKRyyWyaPo/BwTF4KJzYrBJyCHm/B4h2PIYwvugQQ0xuLxWcdJrzcduPI7l8dGcSAhkOBwMBBEcDemkDfUkAAWdpDBgARXGJXxSMRxcGlyEGlEMUnl6ZRgAFE1MTBRdaAaQhGESIpItFFrVoAxZYGpCeDBpDeaR8RAC6iq5NDbFeDUMflol0RQWeG04RzyERRGaXbEQlnhNOo8+mQwLUXxzjRO5yHE7zl+vSI1IHGSNXR9JV29btm5tyl841EdEtmpsN2Zz8isVAgh0AGRJlCNUEQ6xZdyxkTJOhFxZOngwwuwNgQ4kDB0ps4IgFAAZgXyTR1NRHQ/6ACDAjYDDEs6jRo0iTKl3KtKlTIQo8YMDgAeBTLQm6gElwNUuCRFyRgOiAAERXBVrlHLBKZEG6ilexXSpwBAGaDledXXJYpMPdqx4vgSyyABKDBVcreKJ7REKHDoivwqnGtmuSr3o8WHbiIW2IA2E3N1FQYGqFOqJTq17NurXr17Bj90kwgAGFAaHbKIAAoTIjhmlEuGnnhYOAopjl5MYy+Z1vNyPl3NJCQg4JTQBwomGws0n1NNcZARAYqTuT5sWft4muqI2AdBSOM1kwYoRZJcnTLM+yuzcTAH590YF5QwCHhnBOPSDHA0t4UBsDA2j2lANyOCCbEAAkQiBrFBqmYeGFJiiYBoMgAnjXhq6BUN99ILboYmxBAAAh+QQICAAAACwAAAAAQABAAIUEAgSMiozExsRUUlQkIiSkpqTk5uQUEhQ0MjS0srT09vScmpx8enwMCgw8Ojzk4uRcWlwsKiysrqz08vQcHhy8urz8/vykoqQEBgSUkpTMzsxUVlQkJiSsqqzs6uwUFhQ0NjS0trT8+vycnpx8fnwMDgw8PjwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAG/sCTcEgsGo/IpHLJbA4PINDBSa02ESGRxSIKIazg8Gmj3ZpFG7GaiVCY39zIen4MweEhuhNDoWCSB2V3WyJTekkOEm4WChIORw6DcI+HRgABkgEARSCSb5RHBAMDHGKYngFFB55mhkUEFW8VBFYmrFsmRXaeFUcUBnceFFUJtxZ5RAiCcCJyRrGDvXuLrAp/RBDLhGlGHKylTd7GFuDJFWUiFV9HG6zcTOLG5aogDq5HA+572oMi12IEvlEpdisBHWh3pDmxdSvXHAIegtGqcirToQ8SZE2scinTpkqiSK1JhC4BqEooMRDwg7Kly5cnMHyEqcfBCGAWDIw4SdNK/oMCkgo06GmlhAZWGu4RXdLBWIelQjYIEKFAwDshkcbxfFnRTAYiQMcVIApB0jucxgwQFSBJwJBxZobCBMCP0Ee4W+S+BECN2ceI4zysbTskrLGxPcsOepfV2FaXGe58BesU6gkIU0UIgGDEKFK9lpWUaDqoA+jQSxxceLDlwYXHqJlg+Be7tu3buHPr3s3bSYQsCkI4UwNixAIQLiNMeDNhOJg2hJzr2fUGWZgFb0agpHtHxEwrI7Jv72tXjDJC6ypRN2M9TIQLI9JXUs5cOtEBBToMaPJbRBf7PTHwBgO9HVHCMiKUUGARCNwh34IHvpHggkUIaAYJFBoxQAf6CWXo4YcghmhEEAA7T0VxOVNBb3d0UUNIclB6d2x3QWFCSUttamRzTW5mRkh2N1dwSTUrSzJpdjIvb3EzcmF6MnVuZ1E2YlNjNnprYw==') center center no-repeat;
position: absolute;
z-index: 1;
}
</code></pre>
|
Pivot/Transpose in SQL Query in Oracle <p>I didn't know if my problem is related to Pivoting or Transposing so that's why I wrote both in the title.</p>
<p>Below is my query (using it in an Oracle APEX Report)</p>
<pre><code>SELECT QUESTION_ID,
RESPONDENT,
ANSWER
FROM SURVEY
</code></pre>
<p>Here is the result : </p>
<pre><code>Question_ID Respondent Answer
1 A test1
2 A test2
3 A test3
1 B test4
2 B test5
3 B test6
</code></pre>
<p>The result I want is this :</p>
<pre><code> Question
Respondant 1 2 3
A test1 test2 test3
B test4 test5 test6
</code></pre>
<p>How can this be achieved? </p>
| <pre><code>select *
from table_name
pivot ( min(answer) for question_id in (1 as q1, 2 as q2, 3 as q3));
</code></pre>
|
Find element by tag name within element by tag name (Selenium) <p>I want to print all the href(links) from a website. All these hrefs are stored in an 'a' tag, and these a tags are stored in a 'li' tag. Now, I know how to select all the li's. I need a way to select all the a's within the li's to get the 'href' attribute. Tried the following but doesn't really work.</p>
<pre><code>li = driver.find_elements_by_tag_name('li')
for link in li:
a_childrens = link.find_element_by_tag_name('a')
for a in a_children
(print a.get_attribute('href'))
</code></pre>
<p>Thanks in advance.</p>
| <p>I recommend css_selector instead of tag_name</p>
<pre><code>aTagsInLi = driver.find_elements_by_css_selector('li a')
for a in aTagsInLi:
(print a.get_attribute('href'))
</code></pre>
|
How can I print only the division that i want on html? <p>Hi guys I want that on the print section only the this division will be shown,
what would be the script to this? And by the way this is a modal of every tenant on a table. This print will serve as a receipt of every tenant.</p>
<pre><code> <div class="modal-body">
<form class="form-horizontal" enctype = "multipart/form-data">
<div class="form-group">
<strong>
<div>
<h3 class="modal-title text-center" id="myModalLabel">
<strong>Republic of the Philippines<br>Province of Negros Occidental</strong></h3>
<h4 class ="text-center"><em>City of Victorias</em></h4>
<h4 class="text-center">
<strong>OFFICE OF THE MARKET SUPERVISOR</strong>
</h4>
<br>
<div class="form-group">
<input type = "hidden" class="form-control" name= "id" placeholder="First Name" value = "<?php echo $value['rate_id'];?>">
<label class="col-sm-2 control-label">Name </label>: <?php echo $value['tenant_fname']." ".$value['tenant_mname']." ".$value['tenant_lname'];?>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Location </label>: Stall No. <?php echo $value['stall_number']." (".$value['stall_floor'];?>)
</div>
<div class="form-group">
<label class="col-sm-2 control-label">SUBJECT </label> :
FOR PAYMENT OF ELECTRICAL CONSUMPTION FOR THE &nbsp;&nbsp;&nbsp;PERIOD FROM
<input class = "datepick custom-input1"></input>
,TO
<input class = "datepick custom-input1"></input>
</div>
<div class="form-group">
<label class="col-sm-4 control-label">METER NO. </label>: <input type="text" name="" class = "custom-input"></input>
</div>
<div class="form-group">
<label class="col-sm-4 control-label">ELECTRIC RATE </label>: <input class = "custom-input" value="<?php echo $value['elec_rate']?> per kWh" id= "rate" readonly ></input>
</div>
<div class="form-group">
<label class="col-sm-4 control-label">PRESENT </label>: <input class = "custom-input" id="current" name="current"></input>
</div>
<div class="form-group">
<label class="col-sm-4 control-label">PREVIOUS </label>: <input class = "custom-input" value ="<?php echo $value['charges']?> kWh" id = "previous" readonly> </input>
</div>
<div class="form-group">
<label class="col-sm-4 control-label">TOTAL CONSUMPTION</label>:
<input type="text" class = "custom-input" type="" id="result1" readonly>
</div>
<div class="form-group">
<label class="col-sm-4 control-label">AMOUNT </label>:
<input type="text" class = "custom-input" type="" id="result" readonly>
</div><br>
</strong>
</div>
</div>
</code></pre>
| <p>If I am not wrong, then the code below will do what you want. For more information, refer to the <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/@media" rel="nofollow">MDN documentation about @media</a>.</p>
<pre><code>@media print {
body * {
visibility: hidden;
}
.modal-body* {
visibility: visible;
}
.modal-body{
display: block!important;
position: absolute;
top: 40px;
left: 30px;
}
}
</code></pre>
|
Getting error: Type argument cannot be infered from usage when using LINQ to count nested foreach loop <p>I am trying to create a LINQ query for a nested foreach loop.</p>
<p>The loop is as below:</p>
<pre><code>var c = 0;
foreach(var e in elements)
{
foreach(var a in e.Attributes)
{
if(a.Name=="City" && a.GetValue().ToString() == "Oakland")
c += 1;
}
}
</code></pre>
<p>I am trying to find a count.</p>
<p>I have tried using a LINQ query</p>
<pre><code>int d = elements.SelectMany(e => e.Attributes)
.Count(a => a.Name == "City" &&
a.GetValue().ToString() == "Oakland");
</code></pre>
<p>but I am getting the error:</p>
<blockquote>
<p>The type argument for method Enumerable.SelectMany cannot be inferred from the usage. Try specifying the type argument explicitly.</p>
</blockquote>
<p>I tried replacing <code>SelectMany</code> by <code>Select</code> but then I get an error:</p>
<blockquote>
<p>does not contain a definition for Name and no extension method ...</p>
</blockquote>
<p>Any suggestions?</p>
| <p>The type of <code>Attributes</code> is probably <code>dynamic</code> (or boxed as <code>object</code>) and thus the compiler does not know that it is a collection. Explicitly specify that it is an <code>IEnumerable<T></code>:</p>
<pre><code>int d = elements.SelectMany(e => (IEnumerable<dynamic>)e.Attributes)
.Count(a => a.Name == "City" &&
a.GetValue().ToString() == "Oakland");
</code></pre>
<p>Here is the scenario I describe (explicitly specifying the type):
<a href="https://i.stack.imgur.com/GUzI4.png" rel="nofollow"><img src="https://i.stack.imgur.com/GUzI4.png" alt="enter image description here"></a></p>
|
Date parsing not failing with invalid format <p>The below piece of code should throw a parsing exception as per my understanding but it does not. Looked at the documentation but couldn't figure it out. </p>
<pre><code>DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd", Locale.US);
dateFormat.setLenient(false);
dateFormat.parse("20160821_$folder$");
</code></pre>
| <p>This is what the <a href="http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html#parse(java.lang.String)" rel="nofollow">javadoc</a> says:</p>
<blockquote>
<p>Parses text from the beginning of the given string to produce a date. The method may not use the entire text of the given string.</p>
</blockquote>
<p>As long as it finds the match, it stops scanning further which seems to be the case here.</p>
<p>If you want strict checking, you can add <code>RegEx</code> mathing on top of this, to prevent such strings from getting parsed.</p>
|
Reading JSON Data with inconsistent data index extJS <p>I am currently trying to read data from an endpoint on my Chef Server using the JSON proxy reader in extJS in order to display it on a grid. Usually, the JSON response looks something like this:</p>
<pre><code>{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optioreprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},
{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
}
</code></pre>
<p>However, the response I am receiving from the endpoint, specifically, the <strong>organizations/(organization-name)/cookbooks</strong> endpoint, comes in like this:</p>
<pre><code>{"my_cookbook_1":{"url":"company.com","versions":[{"version":"0.1.0","url":"company.com"}]},
"my_cookbook_2":{"url":"company.com","versions":[{"version":"0.2.0","url":"company.com"}]}
</code></pre>
<p>With the former response, I can specify the <strong>dataIndex</strong> attribute on the grid as 'name' and get the respective information. </p>
<pre><code>var optionalCookbooksGrid = Ext.create('Ext.grid.Panel', {
store: optionalCookbooksStore,
width: '100%',
height: 200,
title: 'Optional Cookbooks',
columns: [
{
text: 'Role',
width: 100,
sortable: false,
hideable: false,
dataIndex: 'userID'
}
]
});
</code></pre>
<p>Because my response from the Chef Server does not have a consistent dataIndex, how would I display the content to my grid?</p>
<p>Thank you</p>
| <p>I know nothing of extJS so this isn't really a direct answer, but then again this isn't really a Chef question either. Basically the Chef REST API is not built for direct consumption by simple clients. Notably the list endpoint you showed there only gives the name (and URL but that's pretty useless) for each cookbook. From there you need to do N more queries to grab the list of versions for each and then possibly N*M to grab the details for each version. You would normally do this all before feeding the resulting massive data blob in to a UI framework.</p>
|
Use hdf5 as caffe input, error: HDF5Data does not transform data <p>I used hdf5 file as caffe input data, and the error occured:</p>
<blockquote>
<pre><code>hdf5_data_layer.cpp:75] Check failed: !this->layer_param_.has_transform_param() HDF5Data does not transform data.
</code></pre>
</blockquote>
<p>This is my defination:</p>
<pre><code>layer {
name: "weight28"
type: "HDF5Data"
include { phase : TRAIN }
transform_param { scale: 0.00392156862745098 }
hdf5_data_param {
source: "/home/zhangyu/codes/unsupervised/data/weight28.h5"
batch_size: 8
}
top: "weight28"
}
</code></pre>
<p>Here is some information of my h5 file:</p>
<pre><code>HDF5 weight28.h5
Group '/'
Dataset 'data'
Size: 2555000x28
MaxSize: Infx28
Datatype: H5T_IEEE_F64LE (double)
ChunkSize: 28x28
Filters: none
FillValue: 0.000000
</code></pre>
<p>I find a <a href="http://stackoverflow.com/a/31634295/1714410">similar question</a> and the answer said <i> You cannot use transform param in the hdf5data layer. </i><br>
What dose data transform in caffe do? Can I just cancel it?</p>
| <ol>
<li><p>As you already spotted yourself, you cannot have <code>transformation_param</code> in a <code>"HDF5Data"</code> layer - caffe does not support this.</p></li>
<li><p>As for the transformation parameters themselves, look at <a href="https://github.com/BVLC/caffe/blob/master/src/caffe/proto/caffe.proto#L408-L429" rel="nofollow"><code>caffe.proto</code></a>:</p></li>
</ol>
<blockquote>
<pre><code>// For data pre-processing, we can do simple scaling and subtracting the
// data mean, if provided. Note that the mean subtraction is always carried
// out before scaling.
optional float scale = 1 [default = 1];
</code></pre>
</blockquote>
<p>Having <code>transform_param { scale: 0.00392156862745098 }</code> means your net expects your input to be scaled by <code>0.0039..</code> (1/254).<br>
You can (and probably should) scale the data by 1/254 when you create the hdf5 data files for training and then remove the <code>transform_param</code> from the <code>"HDF5Data"</code> layer.</p>
|
Inserting an Event in Google Calendar with VB.Net <p>I am trying to add a Google Calendar event using the code below:</p>
<pre><code> Sub UpdateCalendar()
Dim CalendarEvent As New Data.Event
Dim StartDateTime As New Data.EventDateTime
Dim A As Date
A = "15-OCT-2016 12:00"
StartDateTime.DateTime = A
Dim b As Date
b = A.AddDays(2)
Dim EndDateTime As New Data.EventDateTime
EndDateTime.DateTime = b
CalendarEvent.Start = StartDateTime
CalendarEvent.End = EndDateTime
CalendarEvent.Id = System.Guid.NewGuid.ToString
CalendarEvent.Description = "Test"
service.Events.Insert(CalendarEvent, "primary").Execute()
End Sub
</code></pre>
<p>But I am getting the following error in the last line:</p>
<pre><code>Invalid resource id value. [400]
</code></pre>
<p>What am I doing wrong?</p>
<p>Edit: The suggested "duplicate" does not address the problem since it is for Java and it suggests switching the parameters, which did not solve the problem.</p>
| <p>Apparently commenting the following line solved the problem:</p>
<pre><code>CalendarEvent.Id = System.Guid.NewGuid.ToString
</code></pre>
|
Attempted relative import beyond toplevel package <p>Here is my folder structure:</p>
<pre><code>Mopy/ # no init.py !
bash/
__init__.py
bash.py # <--- Edit: yep there is such a module too
bass.py
bosh/
__init__.py # contains from .. import bass
bsa_files.py
...
test_bash\
__init__.py # code below
test_bosh\
__init__.py
test_bsa_files.py
</code></pre>
<p>In <code>test_bash\__init__.py</code> I have:</p>
<pre><code>import sys
from os.path import dirname, abspath, join, sep
mopy = dirname(dirname(abspath(__file__)))
assert mopy.split(sep)[-1].lower() == 'mopy'
sys.path.append(mopy)
print 'Mopy folder appended to path: ', mopy
</code></pre>
<p>while in <code>test_bsa_files.py</code>:</p>
<pre><code>import unittest
from unittest import TestCase
import bosh
class TestBSAHeader(TestCase):
def test_read_header(self):
bosh.bsa_files.Header.read_header()
if __name__ == '__main__':
unittest.main()
</code></pre>
<p>Now when I issue:</p>
<pre><code>python.exe "C:\_\JetBrains\PyCharm 2016.2.2\helpers\pycharm\utrunner.py" C:\path\to\Mopy\test_bash\test_bosh\test_bar.py true
</code></pre>
<p>I get:</p>
<pre><code>Traceback (most recent call last):
File "C:\_\JetBrains\PyCharm 2016.2.2\helpers\pycharm\utrunner.py", line 124, in <module>
modules = [loadSource(a[0])]
File "C:\_\JetBrains\PyCharm 2016.2.2\helpers\pycharm\utrunner.py", line 43, in loadSource
module = imp.load_source(moduleName, fileName)
File "C:\Dropbox\eclipse_workspaces\python\wrye-bash\Mopy\test_bash\test_bosh\test_bsa_files.py", line 4, in <module>
import bosh
File "C:\Dropbox\eclipse_workspaces\python\wrye-bash\Mopy\bash\bosh\__init__.py", line 50, in <module>
from .. import bass
ValueError: Attempted relative import beyond toplevel package
</code></pre>
<p>Since 'Mopy" is in the sys.path and <code>bosh\__init__.py</code> is correctly resolved why it complains about relative import above the top level package ? <em>Which is the top level package</em> ?</p>
<p>Incidentally this is my attempt to add tests to a legacy project - had asked in <a href="http://stackoverflow.com/q/34694437/281545">Python test package layout</a> but was closed as a duplicate of <a href="http://stackoverflow.com/q/61151/281545">Where do the Python unit tests go?</a>. Any comments on my current test package layout is much appreciated !</p>
<hr>
<p>Well the <a href="http://stackoverflow.com/a/40022629/281545">answer below</a> does not work in my case:</p>
<p>The <em>module</em> bash.py is the entry point to the application containing:</p>
<pre><code>if __name__ == '__main__':
main()
</code></pre>
<p>When I use <code>import bash.bosh</code> or <code>from Bash import bosh</code> I get:</p>
<pre><code>C:\_\Python27\python.exe "C:\_\JetBrains\PyCharm 2016.2.2\helpers\pycharm\utrunner.py" C:\Dropbox\eclipse_workspaces\python\wrye-bash\Mopy\test_bash\test_bosh\test_bsa_files.py true
Testing started at 3:45 PM ...
usage: utrunner.py [-h] [-o OBLIVIONPATH] [-p PERSONALPATH] [-u USERPATH]
[-l LOCALAPPDATAPATH] [-b] [-r] [-f FILENAME] [-q] [-i]
[-I] [-g GAMENAME] [-d] [-C] [-P] [--no-uac] [--uac]
[--bashmon] [-L LANGUAGE]
utrunner.py: error: unrecognized arguments: C:\Dropbox\eclipse_workspaces\python\wrye-bash\Mopy\test_bash\test_bosh\test_bsa_files.py true
Process finished with exit code 2
</code></pre>
<p>This usage messgae is from the main() in bash. No comments...</p>
| <p>TLDR: Do</p>
<pre><code>import bash.bosh
</code></pre>
<p>or</p>
<pre><code>from bash import bosh
</code></pre>
<p>If you also just happen to have a construct like <code>bash.bash</code>, you have to make sure your package takes precedence over its contents. Instead of appending, add it to the front of the search order:</p>
<pre><code># test_bash\__init__.py
sys.path.insert(0, mopy)
</code></pre>
<hr>
<p>When you do</p>
<pre><code>import bosh
</code></pre>
<p>it will import the <em>module</em> <code>bosh</code>. This means <code>Mopy/bash</code> is in your <code>sys.path</code>, python finds the file <code>bosh</code> there, and imports it. The module is now globally known by the name <code>bosh</code>. Whether <code>bosh</code> is itself a module or package doesn't matter for this, it only changes whether <code>bosh.py</code> or <code>bosh/__init__.py</code> is used.</p>
<p>Now, when <code>bosh</code> tries to do</p>
<pre><code>from .. import bass
</code></pre>
<p>this is <em>not</em> a file system operation ("one directory up, file bass") but a module name operation. It means "one package level up, module bass". <code>bosh</code> wasn't imported from its package, but on its own, though. So going up one package is not possible - you end up at the package <code>''</code>, which is not valid.</p>
<p>Let's look at what happens when you do</p>
<pre><code>import bash.bosh
</code></pre>
<p>instead. First, the <em>package</em> <code>bash</code> is imported. Then, <code>bosh</code> is imported as a module <em>of that package</em> - it is globally know as <code>bash.bosh</code>, even if you used <code>from bash import bosh</code>.</p>
<p>When <code>bosh</code> does</p>
<pre><code>from .. import bass
</code></pre>
<p>that one works now: going one level up from <code>bash.bosh</code> gets you to <code>bash</code>. From there, <code>bass</code> is imported as <code>bash.bass</code>.</p>
<p>See also <a href="http://stackoverflow.com/a/39932711/5349916">this related answer</a>.</p>
|
Hide tabs within a tabbed control in Access <p>I have two tabs in my tabbed control and want to hide the tabs / tab names at the top of it as I want users to access the each tab using dedicated sidebar buttons (which I have created and which work).</p>
<p>Is it possible to hide the tabs at the top of the form?</p>
| <p>The default Format > Style = "Tabs". If you set this to "None" the tabs row will not appear.</p>
<p><a href="https://i.stack.imgur.com/CQFtC.png" rel="nofollow"><img src="https://i.stack.imgur.com/CQFtC.png" alt="enter image description here"></a></p>
<p>Alternatively, have oyu considered using a Navigation form?</p>
<p><a href="https://i.stack.imgur.com/QWu0N.png" rel="nofollow"><img src="https://i.stack.imgur.com/QWu0N.png" alt="enter image description here"></a></p>
|
Purpose of dbo.Policies table in SSRS <p>What is the purpose of the <code>[dbo].][Policies]</code> table in SSRS <strong>ReportServerDB</strong> database?</p>
<p>I see two columns, <code>PolicyID</code> and <code>PolicyFlag</code> and I don't get any clue about purpose of this table. Is it possible to add anew row into that table and what represents those data, i.e. rows?</p>
| <p>Each row of <code>Policies</code> table declares via <code>PolicyFlag</code> column if that policy is defined for system roles.</p>
<p>A policy can be related only with created user defined objects, <code>UserType = 1</code> in <code>User</code> table. System defined objects like <code>NT AUTHORITY\SYSTEM</code> and Local Server Administrator aren't mapped with policies.</p>
<p>If you run this query:</p>
<pre><code>SELECT b.username,
c.policyflag,
d.rolename,
b.usertype,
c.policyid
FROM policyuserrole a
INNER JOIN users b
ON a.userid = b.userid
INNER JOIN policies c
ON a.policyid = c.policyid
INNER JOIN roles d
ON a.roleid = d.roleid
</code></pre>
<p><a href="https://i.stack.imgur.com/z5EVx.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/z5EVx.jpg" alt="enter image description here"></a></p>
<p>By default you will have two rows in Policies table.</p>
<p><a href="http://sornanara.blogspot.com.co/2011/07/ssrs-reportserver-database-tables_10.html" rel="nofollow">REFERENCE</a></p>
<p>Let me know if this helps.</p>
|
Can't populate RecylcerView Android <p>I tried to follow how to build a recyclerview for my class project, but for some reason, I can't do it. I'm not sure of what I am missing. Ideas?</p>
<p>EDIT: I went ahead and added more code upon reuqest</p>
<p>The code that is relevant:</p>
<pre><code>String selectedVenue;
String id;
String currentuser;
String venueType;
boolean canComment;
ArrayList<Comments> commentList = new ArrayList<>();
ParseGeoPoint venueLocation;
ParseGeoPoint userLocation;
Button commentButton;
RecyclerView commentRecView;
SwipeRefreshLayout mySwipeRefreshLayout;
CommentDetailAlt commentDetailAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_user_feed_alt);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
try{
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
catch (Exception e){
e.printStackTrace();
}
currentuser = ParseUser.getCurrentUser().getUsername();
mySwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefreshAlt);
mySwipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
mySwipeRefreshLayout.setRefreshing(true);
commentList.clear();
GetFeed download = new GetFeed();
download.execute();
}
}
);
commentRecView = (RecyclerView) findViewById(R.id.comment_list);
commentRecView.setLayoutManager(new LinearLayoutManager(this));
commentDetailAdapter = new CommentDetailAlt(commentList, this);
commentRecView.setAdapter(commentDetailAdapter);
UserFeedAlt.GetFeed download = new GetFeed();
download.execute();
}
public class GetFeed extends AsyncTask<String, Void, Void> {
ArrayList<Comments> temp = new ArrayList<>();
@Override
protected Void doInBackground(String... strings) {
ParseQuery<ParseObject> contentFeed = new ParseQuery<>("UserCommentary");
ParseQuery<ParseObject> drinks = new ParseQuery<>("venueDrinks");
if(venueType.equals("House Parties")){
//Query for Bars
drinks.whereEqualTo("venueName",selectedVenue);
drinks.whereEqualTo("venueID",id);
drinks.addDescendingOrder("createdAt");
drinks.setLimit(2);
try{
List<ParseObject>qReply = drinks.find();
if(qReply.size()>0){
for(ParseObject item : qReply){
String drinkName = item.getString("venueDrinkName");
float drinkPrice = (float) item.getInt("venuePriceDrink");
boolean isImage = item.getBoolean("isImage");
Bitmap bmp;
Comments drink = new Comments(String.valueOf(drinkPrice),selectedVenue,id,drinkName,0,true);
if(isImage){
ParseFile dataPhoto = item.getParseFile("imgFile");
byte[] data = dataPhoto.getData();
bmp = BitmapFactory.decodeByteArray(data, 0 ,data.length);
drink.photoFile = bmp;
}
temp.add(drink);
}
}
else{
String comment = "Nothing Here";
String owner = "Mr. Smith";
int count = 0;
String id = "Test";
String venueName = "Smith's Mayback's";
Comments newComment = new Comments(comment,venueName,id,owner,count,false);
temp.add(newComment);
}
}
catch (Exception e){
e.printStackTrace();
}
contentFeed.whereEqualTo("venueName",selectedVenue);
contentFeed.whereEqualTo("venueID",id);
contentFeed.addDescendingOrder("createdAt");
try{
List<ParseObject>qReply = contentFeed.find();
if(qReply.size()>0){
for(ParseObject item : qReply){
String commentOwner = item.getString("owner");
String commentContent = item.getString("comment");
boolean isImage = item.getBoolean("image");
Bitmap bmp;
Comments comment = new Comments(commentContent,selectedVenue,id,commentOwner,0,false);
if(isImage){
ParseFile dataPhoto = item.getParseFile("imgFile");
byte[] data = dataPhoto.getData();
bmp = BitmapFactory.decodeByteArray(data, 0 ,data.length);
comment.photoFile = bmp;
}
temp.add(comment);
}
}
}
catch (Exception e){
e.printStackTrace();
}
}
else if(venueType.equals("Bars")){
//Query for HouseParties
contentFeed.whereWithinMiles("Location",userLocation,0.00284091);
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
commentList = temp;
Log.i("AppInfo", String.valueOf(commentList.size()));
commentDetailAdapter.notifyDataSetChanged();
mySwipeRefreshLayout.setRefreshing(false);
}
}
</code></pre>
| <p>add the onPostExecute function to AsyncTask and notify the adapter</p>
<pre><code>protected void onPostExecute(String result) {
commentDetailAdapter.notifyDataSetChanged();
}
</code></pre>
<p>onPostExecute calls after the background process completed (coz array might be empty before that), and onPostExecute can access the main thread.</p>
|
Android Status Bar Color <p>I am having problem with status bar color when I use <code>android:fitsSystemWindows="false"</code></p>
<p>It becomes transparent. I dont want that to happen. I want to it have <code>colorPrimaryDark</code> as its color.</p>
<p>I have to set this as <code>false</code> because I am using a <code>FrameLayout</code> in main layout so that I can inflate a overlay fragment, When <code>android:fitsSystemWindows="false"</code> is set <code>true</code> the overlay occupies whole screen, I dont want that to happen with overlay fragment. </p>
<p>my activity_main looks like this.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:background="@drawable/layout_bg_white"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="false"
tools:openDrawer="start"
tools:context="com.example.tabstrial2.MainActivity">
<RelativeLayout
android:id="@+id/main_layout_of_app"
android:layout_width="match_parent"
android:layout_height="match_parent">
</RelativeLayout>
<FrameLayout
android:id="@+id/overlay_fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="56dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="119dp" />
</android.support.v4.widget.DrawerLayout>
</code></pre>
<p>style.xml looks like this.</p>
<pre><code><resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#500347</item>
<item name="colorPrimaryDark">#862b7b</item>
<item name="colorAccent">#1a2fcf</item>
<item name="android:textColor">#ffffff</item>
<item name="colorControlHighlight">#fff</item>
<item name="colorControlActivated">@android:color/holo_green_dark</item>
<item name="colorControlNormal">#fff</item> <!-- normal border color change as you wish -->
<item name="colorButtonNormal">#500347</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
<style name="AppTheme.Picker" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:textColorPrimary">@android:color/white</item>
</style>
<!--<style name="AppTheme.CheckBox" parent="Theme.AppCompat.Light.NoActionBar">-->
<!--<item name="android:colorAccent">@android:color/white</item>-->
<!--</style>-->
<style name="MyCheckBox" parent="Theme.AppCompat.NoActionBar">
<item name="colorControlNormal">#fff
</item> <!-- normal border color change as you wish -->
<item name="colorControlActivated">#fff</item> <!-- activated color change as you wish -->
<item name="android:textColor">#FFFF3F3C</item> <!-- checkbox text color -->
</style>
</code></pre>
<p></p>
| <p>In your Activity below the setcontentview(...) </p>
<pre><code>Window window = getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
// finally change the color
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.setStatusBarColor(Color.parseColor("#c2212a"));
}
</code></pre>
|
.readlines() shouldn't return an array? <p>I have a problem with <code>.readlines()</code>.
it used to only return the line specified, i.e. if I ran</p>
<pre><code>f1 = open('C:\file.txt','r')
filedata = f1.readlines(2)
f1.close()
print filedata
</code></pre>
<p>it should print the second line of <strong>file.txt.</strong>
However now when I run that same code, it returns the entire contents of the file in an array, with each line in the file as a separate object in the array. I am using the same PC and am running the same version of <code>python (2.7).</code></p>
<p>Does anyone know of a way to fix this?</p>
| <p>Don't use <code>readlines</code>; it reads the entire file into memory, <em>then</em> selects the desired line. Instead, just read the first <code>n</code> lines, then break.</p>
<pre><code>n = 2
with open('C:\file.txt','r') as f1:
for i, filedata in enumerate(f1, 1):
if i == n:
break
print filedata.strip()
</code></pre>
<p>The <a href="https://docs.python.org/2/library/itertools.html" rel="nofollow"><code>itertools</code> documentation</a> also provides a recipe for consuming the first <em>n</em> items of an sequence:</p>
<pre><code>def consume(iterator, n):
"Advance the iterator n-steps ahead. If n is none, consume entirely."
# Use functions that consume iterators at C speed.
if n is None:
# feed the entire iterator into a zero-length deque
collections.deque(iterator, maxlen=0)
else:
# advance to the empty slice starting at position n
next(islice(iterator, n, n), None)
</code></pre>
<p>You might use it like this:</p>
<pre><code>n = 2
with open('C:\file.txt','r') as f1:
consume(f1, n-1)
filedata = next(f1)
print filedata.strip()
</code></pre>
|
First non empty value in Column of data frame in R <p>I have one data frame which has column header but position of coulmn header is not fixed so can i read non empty value in 1st column to get the index of header to process the file.</p>
<p>mydata.txt</p>
<pre><code> test 34 45
rt 45 56
tet3 67 56
Col1 Col2 Col3 Col4 Col5
45 45 23 56 12
34 45 67 65 32
45 67 78 90 54
56 43 32 12 45
mydata = read.table("mydata.txt")
mydata[,1] #how to find first non blank value in first column?
</code></pre>
<p>In order simplify the about pblm: </p>
<p>df<-c("","","",34,23,45)</p>
<p>how to find fiest non blank value in df </p>
| <p>Ok, for example </p>
<pre><code>writeLines(tf <- tempfile(fileext = ".txt"), text = "
test 34 45
rt 45 56
tet3 67 56
Col1 Col2 Col3 Col4 Col5
45 45 23 56 12
34 45 67 65 32
45 67 78 90 54
56 43 32 12 45")
mydata = read.table(tf, fill = TRUE, stringsAsFactors = FALSE)
idx <- which.min(mydata[,4]=="")
df <- mydata[-(1:idx), ]
df <- as.data.frame(lapply(df, type.convert))
names(df) <- unlist(mydata[idx, ],F,F)
</code></pre>
<p>gives you </p>
<pre><code>str(df)
# 'data.frame': 4 obs. of 5 variables:
# $ Col1: int 45 34 45 56
# $ Col2: int 45 45 67 43
# $ Col3: int 23 67 78 32
# $ Col4: int 56 65 90 12
# $ Col5: int 12 32 54 45
</code></pre>
|
Button is not clicked unless I click on it twice in Firefox, using selenium webdriver and C# <p>I have a button in a web application which I want to click. I am using Selenium WebDriver, C# and Firefox version 47.0.1.</p>
<p>I tried using explicit wait and also tried using Actions class. But nothing works. </p>
<p>It only works for firefox when I add the below code (click twice)
_NextButton.Click();
_NextButton.Click();</p>
<p>However, it works fine in Chrome browser with : _NextButton.Click();
and fails in chrome for the code used for executing on Firefox.</p>
<p>Kindly help me resolve this issue.</p>
<p></p>
| <p>Sometimes their is some problems with IE11 and chrome in selenium is not able to work as expected. so I use double click instead of click in certain scenarios.</p>
<p>Actions action = new Actions(driver); action.moveToElement(driver.findElement(By...path..."))).doubleClick().perform();</p>
|
Duplicate Boolean fields in JSON <p>I have boolean field as</p>
<pre><code>private boolean isCustom;
</code></pre>
<p>having getter and setters as </p>
<pre><code>public boolean isCustom() {
return isCustom;
}
public void setCustom(boolean isCustom) {
this.isCustom = isCustom;
}
</code></pre>
<p>And in this case my JSON will be <code>{"custom":false}</code></p>
<p>but i want JSON to be <code>{"isCustom":false}</code></p>
<p>so I added <em>@JsonProperty</em> :</p>
<pre><code>@JsonProperty
private boolean isCustom;
</code></pre>
<p>But now there is another problem as my JSON is <strong><code>{"isCustom":false,"custom":false}</code></strong></p>
<p><strong>Q : How can i eliminate unwanted/duplicate field in this case ?</strong></p>
<p>Note: I am using <strong><em>jackson-all-1.9.11.jar</em></strong></p>
| <p>The annotation accepts a parameter. And it should be placed on the field, getter, <strong>and</strong> setter to prevent the duplicate </p>
<pre><code>@JsonProperty("isCustom")
</code></pre>
|
android gms big method count. How to avoid it? <p>I do - as many developers, have issues with the infamous android 65000 methods limit. I'm already multi-dexing my app but I'd really like to make it lighter somehow.</p>
<p>This is the graph of my app's methods (taken with dexcount plugin: <a href="https://github.com/KeepSafe/dexcount-gradle-plugin" rel="nofollow">https://github.com/KeepSafe/dexcount-gradle-plugin</a>).</p>
<p><a href="https://i.stack.imgur.com/jU44O.png" rel="nofollow"><img src="https://i.stack.imgur.com/jU44O.png" alt="enter image description here"></a></p>
<p>As you can see, most of the methods come from the com.google.android.gms package. This is the list of dependencies from build.gradle file:</p>
<pre><code>dependencies {
compile fileTree(dir: 'libs', include: ['*.jar', '*.aar'])
compile project(':libs:cip-library:cip-library')
compile project(':libs:android-times-square')
compile files('../libs/mobile.connect-android-1.7.6.jar')
compile files('../libs/dtapl-2.1.1.jar')
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.android.support:cardview-v7:24.2.1'
compile 'com.android.support:multidex:1.0.1'
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.3'
compile 'com.nhaarman.listviewanimations:lib-core:3.1.0@aar'
compile 'com.nhaarman.listviewanimations:lib-manipulation:3.1.0@aar'
compile 'com.nhaarman.listviewanimations:lib-core-slh:3.1.0@aar'
compile 'com.nineoldandroids:library:2.4.0'
compile 'com.google.code.gson:gson:2.4'
compile 'de.greenrobot:greendao:2.0.0'
compile 'com.pnikosis:materialish-progress:1.5'
compile 'org.adw.library:discrete-seekbar:1.0.0'
compile 'com.android.support:design:24.2.1'
compile 'net.fredericosilva:showTipsView:1.0.4'
compile 'com.google.maps.android:android-maps-utils:0.4.4'
compile 'com.robohorse.gpversionchecker:gpversionchecker:1.0.8'
compile 'net.danlew:android.joda:2.9.4.1'
compile 'com.android.support:support-annotations:24.2.1'
compile('com.crashlytics.sdk.android:crashlytics:2.6.2@aar') {
transitive = true;
}
compile('com.mikepenz:aboutlibraries:5.7.1@aar') {
transitive = true
}
}
</code></pre>
<p>Now, I know these dependencies are not a few, but what I don't understand is specifically which one - and how - is triggering the dependency on packages like com.google.android.gms.internal.games, while my app is not a game, com.google.android.gms.internal.cast or com.google.android.gms.internal.fitness. And - most of all - how could I ever get rid of those dependencies?</p>
<p>Thank you very much
Marco</p>
| <p>To understand where certain dependencies come from, run the <code>dependencies</code> Gradle task on your app's module. Suppose your app's module is called <code>app</code>, then the command will look like:</p>
<pre><code>./gradlew -q :app:dependencies
</code></pre>
<p>The output should contain all transitive dependencies, and it should be easy to see which libraries are dragging the stuff that you want to get rid of.</p>
|
T-SQL sort integer values <p>id like to create a procedure wich later will have 5 integer parameters as an input. Within these procedure i want to sort those integer values in ascending order and later update a table. I did it with case whens so that i dont loose the information of each parameter (Background: Additional to this, each parameter is connected to a string wich i need so sort in the same order. But sorting those integer first is faster.)</p>
<p>Somehow i cant get the sorting for the middle part. Min and Max Value works fine:</p>
<pre><code>DECLARE @tableX TABLE(c1 INT, c2 INT, c3 INT, c4 INT, c5 INT);
INSERT @tableX(c1,c2,c3,c4,c5)
SELECT 2,1,3,0,1
UNION ALL SELECT 3,4,5,2,2
UNION ALL SELECT 5,4,3,1,1
UNION ALL SELECT 3,1,2,0,10;
SELECT
--int1
c1 = CASE
WHEN c1 >= c2 AND c1 >= c3 AND c1 >= c4 AND c1 >= c5 THEN c1
WHEN c2 >= c1 AND c2 >= c3 AND c2 >= c4 AND c2 >= c5 THEN c2
WHEN c3 >= c1 AND c3 >= c2 AND c3 >= c4 AND c3 >= c5 THEN c3
WHEN c4 >= c1 AND c4 >= c2 AND c4 >= c3 AND c4 >= c5 THEN c4
ELSE c5 END,
--int2
--c2 = CASE
-- WHEN c1 >= c2 AND c1 >= c3 AND c1 >= c4 AND c1 >= c5 THEN
-- CASE WHEN c2 >= c3 AND c2 >= c4 AND c2 >= c5 THEN c2 ELSE
-- CASE WHEN c3 >= c2 AND c3 >= c5 THEN
-- CASE WHEN c4 >= c5 THEN
-- WHEN c2 >= c3 AND c2 >= c4 AND c2 >= c5 THEN
-- CASE WHEN c2 >= c3 AND c2 >= c4 AND c2 >= c5 THEN c2 END
--ELSE
--CASE WHEN c3 >= c2 AND c3 >= c4 AND c3 >= c5 THEN c3 ELSE
--CASE WHEN c4 >= c5 THEN c4 ELSE c5 END END END END,
--int3
c3 = NULL,
--in4
c4 = NULL,
--in5
c5 = CASE
WHEN c1 <= c2 AND c1 <= c3 AND c1 <= c4 AND c1 <= c5 THEN c1
WHEN c2 <= c1 AND c2 <= c3 AND c2 <= c4 AND c2 <= c5 THEN c2
WHEN c3 <= c1 AND c3 <= c2 AND c3 <= c4 AND c3 <= c5 THEN c3
WHEN c4 <= c1 AND c4 <= c2 AND c4 <= c3 AND c4 <= c5 THEN c4
ELSE c5 END
FROM @tableX;
</code></pre>
<p>Can someone give a hint for the middle part?
Thanks in advance. </p>
| <p>I don't know exactly how you want to use the sorted integers, but why not let SQL do the sorting for you? the below, creates a temp table (<code>@s</code>), with the five integers (passed in as parameters?) in it and sorts them. </p>
<pre><code>declare @ip1 int = 2
declare @ip2 int = 1
declare @ip3 int = 3
declare @ip4 int = 0
declare @ip5 int = 1
declare @s table (v int)
INSERT @s(v)
values((@ip1)), ((@ip2)), ((@ip3)), ((@ip4)), ((@ip5))
insert
select v from @s order by v
</code></pre>
<p>What you do in the stored proc with this sorted list is another question... </p>
<p>Ok, here's a script to try and work through. It is T-SQL. Please run it and look at the output. the first part creates a dummy table To represent your table and populates it with some data. It assumes that your table has an integer Primary Key. </p>
<pre><code> CREATE TABLE dbo.sortTbl
( id int IDENTITY(1,1) Primary Key NOT NULL,
i1 int NOT NULL, i2 int NOT NULL, i3 int NOT NULL,
i4 int NOT NULL, i5 int NOT NULL,
s1 varchar(20) NULL, s2 varchar(20) NULL, s3 varchar(20) NULL,
s4 varchar(20) NULL, s5 varchar(20) NULL)
insert sortTbl(i1, i2, i3, i4, i5, s1, s2, s3, s4, s5)
Values ((3), (1), (0), (5), (7), ('fog'), ('snap'), ('dead'), ('yellow'), ('lox')),
((6), (2), (12), (1), (8),('tree'), ('saw'), ('earn'), ('ran'), ('que')),
((5), (6), (0), (2), (3),('like'), ('car'), ('hood'), ('wash'), ('man'))
</code></pre>
<p>The next part is the script that generates the extra ten columns from the data in this sample table (`sortTbl'). It works even if the original values are not only 1 through 5, but within each row there should not be duplicates. </p>
<pre><code> declare @T table (id int primary key not null,
ni1 int null, ni2 int null, ni3 int null,
ni4 int null, ni5 int null,
ns1 varchar(20) null, ns2 varchar(20) null,
ns3 varchar(20) null, ns4 varchar(20) null,
ns5 varchar(20) null)
insert @t(id) select id from sortTbl
declare @d table (id int, val int, strVal varchar(20))
declare @id int = 0
declare @S table (rn int primary key identity not null,
id int, colOrder int null, val int, strVal varchar(20))
While exists (Select * from @t
Where id > @id) Begin
select @id = Min(id)
from sortTbl where id > @id
insert @d(id, val, strVal)
Select @id, i1, s1 From sortTbl where id = @id union
Select @id, i2, s2 From sortTbl where id = @id union
Select @id, i3, s3 From sortTbl where id = @id union
Select @id, i4, s4 From sortTbl where id = @id union
Select @id, i5, s5 From sortTbl where id = @id
-- -------------------------------------------
Insert @s(id, val, strVal)
Select id, val, strVal from @d
order by val
Delete @d
end
Update s set colOrder =
(Select Count(*) from @s
Where id = s.id
and rn <= s.rn)
From @s s
Select a.Id,
c1.Val, c1.strVal,
c2.Val, c2.strVal,
c3.Val, c3.strVal,
c4.Val, c4.strVal,
c5.Val, c5.strVal
From sortTbl a
left join @s c1 on c1.id = a.id and c1.colOrder = 1
left join @s c2 on c2.id = a.id and c2.colOrder = 2
left join @s c3 on c3.id = a.id and c3.colOrder = 3
left join @s c4 on c4.id = a.id and c4.colOrder = 4
left join @s c5 on c5.id = a.id and c5.colOrder = 5
</code></pre>
|
What is the path for a font symfony <p>I am trying to do some text and convert it into an image. </p>
<p>I got some code from the php manual.</p>
<p>Im working on it in symfony 3.1</p>
<p>The only problem that I have is how do you set the path for the font.</p>
<p>The roboto-regular.ttf is in my <strong>/web</strong> directory.</p>
<p>My code:</p>
<pre><code> //setting the content type
header('Content-Type: image/png');
// Create the image
$im = imagecreatetruecolor(400,30);
// Create Some colors
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 399, 29, $white);
// The text to draw
$text = 'Testing';
// Replace path by your font path
$font = 'Roboto-Regular.ttf';
// Add some shadow to the text
imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);
// Add the text
imagettftext($im, 20, 0, 10, 20, $black, $font, $text);
// Using imagepng() resulst in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
</code></pre>
| <p>There's actually no direct way to get path to webdir in Symfony2 as the framework is completely independent of the webdir.
But you can use <code>getRootDir()</code>:</p>
<pre><code>$path = $this->get('kernel')->getRootDir() . '/../web';
</code></pre>
|
Git Commit message structure <p>I am starting a new repository from scratch and I want to ensure I start off correctly. I am talking over from a previous developer who used github terribly and I want to fix it before I continue developing on to of their code. </p>
<p>I have done a lot of reading on github and I will be putting the repository together tomorrow. I was hoping to get your opinions on the format of the git commit message I will be using and if I am doing anything incorrect (format, too detailed etc) All my commits will be following the same format so I want to get it right.</p>
<p>Here's and example of one of my commit messages, thanks in advance.</p>
<p>"Add WIFI reconnect </p>
<p>Added code to force WIFI module to save and reboot if it has been over 45 seconds since a packet has been sent successfully.</p>
<p>This was added to fix an issue where the WIFI module lost connection to itâs network. Once disconnected it would only try to reconnect a limited number of times.</p>
<p>Now if the WIFI module disconnects or data has not been sent correctly for 45 seconds, a reboot will be forced and the module will try to connect and transmit on wakeup."</p>
| <p>Writing a good commit message is important, and it's fantastic you're putting so much thought into it. In general, the rule of thumb is to write in present tense and to write short, descriptive messages.</p>
<p>Maybe more importantly, commits should hold small and logical units of work. It appears in your example that the code encompassed in that commit could be <em>a lot</em> of code, maybe too much. Your example looks like a great merge commit, or merge/squash commit message.</p>
<p>So, smaller commits, present tense short messages, only use the extended description when necessary. </p>
|
Using a variable and an id inside a querySelector <p>I want to get value from the input column using querySelector. I need to use two id to get the correct column. The second id is stored in a variable and its an integer value. I have tried different things but I am not getting anything. Currently it gives me null. </p>
<pre><code> checkDescriptionField = document.querySelector('#methodProperties input#'+'descriptionFieldId');
if(typeof checkDescriptionField !== 'undefined' && checkDescriptionField !== null)
{
descriptionFieldValue = document.querySelector('#methodProperties input#'+'descriptionFieldId').textContent;
}
</code></pre>
<p>The outer id is methodProperties and the inner is input id="0eca409e-e2f7-467d-bd5e-dff9b63e3715" and I want to get its value ="Customers" </p>
<pre><code><div id="methodProperties">
<td role="gridcell">
<input id="0eca409e-e2f7-467d-bd5e-dff9b63e3715" class="k-textbox gridTable propertiesField" value="Customers" readonly="" data-role="droptarget" type="text">
<span class="errorTooltip" style="display: none;">
<span class="deleteTooltip" style="padding: 5px; display: inline;" title="Delete Value" data-role="tooltip">
</td>
</code></pre>
<p>I tried this but I get invalid error</p>
<pre><code>checkDescriptionField = document.querySelector('#methodProperties input#'+descriptionFieldId);
if(typeof checkDescriptionField !== 'undefined' && checkDescriptionField !== null)
{
descriptionFieldValue = document.querySelector('#methodProperties input#'+descriptionFieldId).textContent;
}
</code></pre>
| <blockquote>
<p>The outer id is methodProperties and the inner is input
id="0eca409e-e2f7-467d-bd5e-dff9b63e3715" and I want to get its value
="Customers"</p>
</blockquote>
<p>Try this</p>
<pre><code>descriptionFieldValue = document.querySelector( '#' + descriptionFieldId ).value;
</code></pre>
<p>or since there is only one input in a <code>methodProperties</code> </p>
<pre><code>descriptionFieldValue = document.querySelector( '#methodProperties input' ).value;
</code></pre>
<p>If you want to repeat the id, then use data-id attribute instead</p>
<pre><code><div data-id="methodProperties">
<td role="gridcell">
<input value="customers">
</td>
</div>
</code></pre>
<p>and js as</p>
<pre><code>descriptionFieldValue = document.querySelector( 'div[data-id="methodProperties"] input' ).value; //this will take the value from first methodProperties
</code></pre>
|
Deploy meteor server using development mongodb <p>I'm currently trying to deploy a Meteor server from scratch using the command <code>meteor build</code>, there is no big issue but a question that may be very dumb.</p>
<p>In development environment, a mongodb instance is automatically started when I start my Meteor server with <code>meteor</code>. My question is, why can't I use this feature in production ?</p>
<p>The bundle created with <code>meteor build</code> contains "only" the node server and the client application.</p>
| <p>You need to set the environment variable like:</p>
<pre><code>export PORT=3000;
export MONGO_URL=mongodb://localhost:27017/my-app
</code></pre>
<p>Then you can run the main.js file using node.</p>
<pre><code>node main.js
</code></pre>
<blockquote>
<p>Note: When you build a meteor app. It converts the meteor app into a
simple node app. As node doest not provide any MongoDB instance, So
you have to run a separate MongoDB server to perform DB operation.</p>
</blockquote>
|
ASP.net AjaxToolKit LineChart Drawing Series <p>I have the following SqlServer Data Table :<br/><br/>
Years | Sales(A) | Sales(B)<br/>
------------------------------<br/>
2000 | 38000 | 55000<br/>
2001 | 18000 | 47000<br/>
2002 | 70000 | 16000<br/>
2003 | 21000 | 55000<br/>
2004 | 77000 | 50000<br/>
2005 | 16000 | 64000<br/>
2006 | 82000 | 61000<br/>
2007 | 37000 | 16000<br/></p>
<p>and I need to compare these to columns by using AjaxToolKit LineChart
in ASP Page I have the following :</p>
<p>**</p>
<blockquote>
<p>ASPX</p>
</blockquote>
<p>**</p>
<pre><code><%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<div style="width: 100%; height: 50px">
<h1>Ajax Database Multiline Chart Tutorial </h1>
</div>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Generate Chart" />
<br />
<br />
<div style="width: 100%; height: 500px">
<ajaxToolkit:LineChart ID="LineChart1" runat="server" ChartType="Stacked" ChartWidth="720" Width="800px" ChartTitle="Arabian Food Supplies Annual Sales">
</ajaxToolkit:LineChart>
</div>
</asp:Content>
</code></pre>
<p>**</p>
<blockquote>
<p>VB Code</p>
</blockquote>
<p>**</p>
<pre><code> Imports System.Data.SqlClient
Public Class AjaxLineChartDatabase
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub Compare(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt As DataTable = GetData("SELECT Years,A FROM LineChart")
Dim x As String() = New String(dt.Rows.Count - 1) {}
Dim y As Decimal() = New Decimal(dt.Rows.Count - 1) {}
For i As Integer = 0 To dt.Rows.Count - 1
x(i) = dt.Rows(i)(0).ToString()
y(i) = Convert.ToInt32(dt.Rows(i)(1))
Next
LineChart1.Series.Add(New AjaxControlToolkit.LineChartSeries() With {
.Name = "Series 1",
.Data = y
})
dt = GetData("SELECT Years,B FROM LineChart")
y = New Decimal(dt.Rows.Count - 1) {}
For i As Integer = 0 To dt.Rows.Count - 1
x(i) = dt.Rows(i)(0).ToString()
y(i) = Convert.ToInt32(dt.Rows(i)(1))
Next
LineChart1.Series.Add(New AjaxControlToolkit.LineChartSeries() With {
.Name = "Series 2",
.Data = y
})
LineChart1.CategoriesAxis = String.Join(",", x)
LineChart1.ChartTitle = String.Format("{0} and {1} Distribution", "S-1", "S-2")
LineChart1.Visible = True
End Sub
Private Shared Function GetData(query As String) As DataTable
Dim dt As New DataTable()
Dim constr As String = ConfigurationManager.ConnectionStrings("ChartsConnectionString").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand(query)
Using sda As New SqlDataAdapter()
cmd.CommandType = CommandType.Text
cmd.Connection = con
sda.SelectCommand = cmd
sda.Fill(dt)
End Using
End Using
Return dt
End Using
End Function
End Class
</code></pre>
<p>The problem when I draw the chart, the first series(A) appears OK but the 2nd Series(B) values appear as A+B</p>
<p>Sample :
<a href="https://i.stack.imgur.com/plrYk.png" rel="nofollow"><img src="https://i.stack.imgur.com/plrYk.png" alt="enter image description here"></a>
Why I get it like this ?</p>
| <p>My theory, is the array is just getting appended. *Note, we may need separate arrays as it's getting rendered after the code.</p>
<p>Try this,</p>
<pre><code> dt = GetData("SELECT Years,A, B FROM LineChart")
y = New Decimal(dt.Rows.Count - 1) {}
y2 = New Decimal(dt.Rows.Count - 1) {}
For i As Integer = 0 To dt.Rows.Count - 1
x(i) = dt.Rows(i)(0).ToString()
y(i) = Convert.ToInt32(dt.Rows(i)(1))
y2(i) = Convert.ToInt32(dt.Rows(i)(2))
Next
LineChart1.Series.Add(New AjaxControlToolkit.LineChartSeries() With {
.Name = "Series 2",
.Data = y
})
LineChart1.Series.Add(New AjaxControlToolkit.LineChartSeries() With {
.Name = "Series 2",
.Data = y2
})
LineChart1.CategoriesAxis = String.Join(",", x)
LineChart1.ChartTitle = String.Format("{0} and {1} Distribution", "S-1", "S-2")
LineChart1.Visible = True
</code></pre>
|
Ionic Sign-up and Login with Firebase <p>I have just started learning ionic. I was wondering if anyone could guide me how to implement Login and Sign-up functionality using Firebase in Ionic?
Any help would be appreciated.</p>
| <p>I created a guide detailing that exact process <a href="https://javebratt.com/firebase-3-email-auth/" rel="nofollow">here</a>.</p>
<p>But if you're just learning Ionic I do suggest you go through Ionic's documentation or invest in <a href="https://www.joshmorony.com/building-mobile-apps-with-ionic-2/" rel="nofollow">Joshua Morony's Book</a>. It's what I used to learn Ionic 2 before jumping into Firebase :)</p>
|
Linq Left Join where right is null <p>relatively new to linq, coming from SQL. So, I'm trying to figure out left joins for the following:</p>
<pre><code>SELECT * from MASTER m
LEFT JOIN CHILD C
ON m.ID=C.MASTER_ID
WHERE C.MASTER_ID is null
</code></pre>
<p>So, normally this would return all of the records from Master that do not have a child. I've discovered the .DefualtIfEmpty() but that doesn't eliminate the master records that have children.</p>
<p>I started along the lines of:</p>
<pre><code>var recs=from m in MASTER
from c in child
.where (mapping=>mapping.MasterId == m.Id)
.DefaultIfEmpty()
select new { MasterId = m.Id};
</code></pre>
<p>But that's as far as I got and got stuck. I'm assuming the .DefaultIfEmpty() isn't what I'm looking for.
Note: The master table has a few million rows in it. The children are close to the same count. I only mention because it won't be efficient to pull back all of the records, etc. Ideally, the SQL generated will look like the SQL I posted.</p>
<p>Thanks All.</p>
| <p>If you are using EF, then you can get the masters which don't have children using the navigation property that represent the children:</p>
<pre><code>var result= from m in MASTER
where m.Children.Count()==0// or m.Any()
select m;
</code></pre>
<p>If you want to do it using an explicit join in linq you can try this:</p>
<pre><code>var recs=from m in MASTER
join c in child on m.Id equals C.MasterId into gj
where gj.Count()==0 // or gj.Any()
select m;
</code></pre>
|
Getting lookup field value without specifying the name for onChange field event <p>I have a form, that could have <code>Contact</code> lookup field, or <code>User</code> lookup field, depending on the type of the person User wants to add. Only one of the fields is visible.</p>
<p>There is also <code>Name</code> text field, which I want to populate using name from lookup.</p>
<p>I want to add <code>onChange</code> function on lookup field to get the name and insert it in the <code>Name</code> field.</p>
<p>I know i can get field value like this:</p>
<pre><code>Xrm.Page.getAttribute("ad_user").getValue();
</code></pre>
<p>But this way I would need to make separate functions for each field.
Is there a way for field with <code>onChange</code> event to get its own value without quoting that fields name? Something like this:</p>
<pre><code>this.getValue();
</code></pre>
<p>That way I could use the same function for both fields.</p>
| <p>When registering the onChange event handler pass <a href="https://msdn.microsoft.com/en-us/library/gg328130.aspx" rel="nofollow">ExecutionContext</a> as the first parameter. You can then get the input value like so:</p>
<p>Event handler registration:</p>
<p><a href="https://i.stack.imgur.com/2Ka0s.png" rel="nofollow"><img src="https://i.stack.imgur.com/2Ka0s.png" alt="enter image description here"></a></p>
<p>Handler:</p>
<pre><code>function foo_onChange(executionContext) {
var inputValue = executionContext.getEventSource().getValue();
}
</code></pre>
|
wordpress visual editor not generating html p tags for the paragraphs <p>wordpress visual editor not generating html <code><p></code> tags for the paragraphs and thus non formatted content gets saved in the database. It results in showing all paragraphs together on frontend.</p>
| <p>You can use this plug-in: <a href="https://wordpress.org/plugins/tinymce-advanced/" rel="nofollow">https://wordpress.org/plugins/tinymce-advanced/</a></p>
<p>After activation goto <strong>Settings</strong> > <strong>TinyMCE Advanced</strong></p>
<p>Under <strong>Advanced Options</strong> check '<strong>Keep paragraph tags</strong>'</p>
|
How to get current date and time with respect to Time Zone in Codeigniter <p>When I run the following code in codeigniter, it returns incorrect time and date for the India location. Please let me the solution. </p>
<pre><code>'date_default_timezone_set('Asia/Kolkata');
$date = date('Y-m-d H:i:s', time());
echo $date;'
</code></pre>
| <p>try this</p>
<pre><code>$now = new DateTime();
$now->setTimezone(new DateTimezone('Asia/Kolkata'));
echo $now->format('Y-m-d H:i:s');
</code></pre>
|
How To Qt Creator Embedded use PSQL <p>I'm trying to use connection to postgres with Qt Creator for embedded device with the Raspberry Pi 3, however the driver is not loaded. The same application on the desktop is ok.</p>
<p>My example is quite simple.</p>
<p>I have a console project with a main class and in it a log with </p>
<pre><code>QSqlDatabase::drivers();
</code></pre>
<p>In raspberry list only QSQLITE, and desktop list QSQLITE, QPSQL, QMYSQL among others.</p>
<p>I am using oQt Creator Enterprise, connecting to the device with Boot2Qt, that comes with Qt Creator, compilation and execution is everything correctly, however is not listed PSQL driver in device.</p>
| <p>QSqlDatabase::drivers() lists only the drivers that can be loaded on that particular platform, in many cases to have a working driver you need the Qt driver and a specific client library.</p>
<p>Probably there is a postgresql client library for raspberry with your specific linux version somewhere but Boot2Qt does not load it automatically to your board.</p>
<p>You have to find the client library for your specific version of linux (maybe you will have to compile it) then manually copy the postgresql Qt driver onto the board and the QSqlDatabase::drivers() should show you the postgresql driver available. </p>
|
ComboBox writing Words in a TXT <p>Let me show you what I have in my code : </p>
<pre><code>public List<String> listQuality = new List<string>();
public int qualityChoose;
InitializeComponent();
listQuality.Add("Fastest");
listQuality.Add("Fast");
listQuality.Add("Simple");
listQuality.Add("Good");
listQuality.Add("Beautiful");
listQuality.Add("Fantastic");
foreach (String item in listQuality)
{
listQualityy.Items.Add(item);
}
string textWriteQuality;
textWriteQuality = "-screen-quality " + qualityChoose + Environment.NewLine;
File.AppendAllText(@"./arguments.txt", textWriteQuality);
</code></pre>
<p>But ofc it doesn't work, I think the problem is the "init" but i'm not sure i'm noob at coding it's my first program (Yeah i repeat it again xd)</p>
<p>I have skipped some other code that are useless for the question - I think -</p>
| <p>your question isn't very understandable, by the way you can do something like this example</p>
<p>xaml:</p>
<pre><code><Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<ComboBox Grid.Row="0" ItemsSource="{Binding listQuality}" SelectedItem="{Binding qualityChoose}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Item2}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<Button Grid.Row="1" Content="Save" Click="Button_Click"/>
</Grid>
</code></pre>
<p>codebehind:</p>
<pre><code>public List<Tuple<int, String>> listQuality { get; set; }
public Tuple<int, String> qualityChoose { get; set; }
public MainWindow()
{
InitializeComponent();
listQuality = new List<Tuple<int, string>>();
listQuality.Add(new Tuple<int, string>(0, "Fastest"));
listQuality.Add(new Tuple<int, string>(1, "Fast"));
listQuality.Add(new Tuple<int, string>(2, "Simple"));
listQuality.Add(new Tuple<int, string>(3, "Good"));
listQuality.Add(new Tuple<int, string>(4, "Beautiful"));
listQuality.Add(new Tuple<int, string>(5, "Fantastic"));
this.DataContext = this;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
int quality = qualityChoose.Item1;
}
</code></pre>
<p>when you click the button "Save" in <em>qualityChoose.Item1</em> there's your value</p>
<p><strong>EDIT</strong></p>
<p>instead using a tuple you can use a List< string > like in your question, modify xaml like this:</p>
<pre><code>...
<ComboBox Grid.Row="0" ItemsSource="{Binding listQuality}" SelectedIndex="{Binding selIndex}">
...
</code></pre>
<p>and in codebehind add "selIndex" property:</p>
<pre><code>public int selIndex { get; set; }
</code></pre>
<p>in this property there's the index of the selected string.
this is easier but you can't decide the value of qualities.</p>
|
$q doesn't work asynchronously <p>I am using <code>promise</code> and <code>$q</code> to make an asynchronous call. But it doesn't work.</p>
<p>eventData.js</p>
<pre><code>angular.module('eventsApp').factory('eventData' , function($http ,$q, $log) {
return {
getEvent : function() {
var deferred = $q.defer()
$http({method: 'GET', url: 'http://localhost:8080/springhibernateangularjs/service/events'}).
then(
function(response){
deferred.resolve(response.data);
console.log("succccccc");
},
function(error){
console.log("faiiiiiiil");
deferred.reject(status);
});
return deferred.promise ;
}
};
});
</code></pre>
<p>EventContrller.js</p>
<pre><code>$scope.event = eventData.getEvent();
</code></pre>
<p>But <code>$scope.event</code> is not loading correctly!</p>
| <p>This is how you get the data since you are returning a promise not the results:</p>
<pre><code>eventData.getEvets().then(function(result){
$scope.event = result;
})
</code></pre>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.