input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Styling a focused input in safari <p>I'm trying to apply custom styles to an input[type=range] and having issues applying those styles in Safari. Chrome, FF and IE are working properly (although FF and IE are not listed below in the code snippet). pe-color() are external scss functions calling stored variable colors. </p>
<pre><code>input[type=range] {
-webkit-appearance: none;
-moz-appearance: none;
border: none;
width: 12%;
outline: none;
background: none;
}
input[type=range]:focus {
outline: none;
}
input[type=range]::-webkit-slider-runnable-track {
height: $slider-track-height;
background: pe-color(hyperdrive);
}
input[type=range]::-webkit-slider-thumb {
-webkit-appearance: none;
box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.1);
border: 1px solid pe-color(hairline-gray);
height: $slider-thumb-diameter;
width: $slider-thumb-diameter;
border-radius: 50%;
background: pe-color(white);
margin-top: -8px;
}
input[type=range]:focus::-webkit-slider-thumb {
border: 1px solid pe-color(basic-blue);
box-shadow: 0px 0px 5px pe-color(basic-blue);
}
input[type=range]::-moz-focus-outer {
border: 0;
}
input[type=range]::-moz-range-track {
height: $slider-track-height;
background: pe-color(hyperdrive);
border: none;
}
input[type=range]::-moz-range-thumb {
box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.1);
border: 1px solid pe-color(hairline-gray);
height: $slider-thumb-diameter;
width: $slider-thumb-diameter;
border-radius: 50%;
background: pe-color(white);
}
input[type=range]:focus::-moz-range-thumb {
border: 1px solid pe-color(basic-blue);
box-shadow: 0px 0px 5px pe-color(basic-blue);
}
input[type=range]::-ms-track {
height: $slider-track-height;
border-color: transparent;
border-width: 11px 0;
background: transparent;
color: transparent;
}
input[type=range]::-ms-thumb {
box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.1);
border: 1px solid pe-color(hairline-gray);
height: $slider-thumb-diameter;
width: $slider-thumb-diameter;
border-radius: 50%;
background: pe-color(white);
}
input[type=range]::-ms-fill-lower {
background: pe-color(hyperdrive);
}
input[type=range]::-ms-fill-upper {
background: pe-color(hyperdrive);
}
input[type=range]:focus::-ms-thumb {
border: 1px solid pe-color(basic-blue);
box-shadow: 0px 0px 5px pe-color(basic-blue);
}
</code></pre>
<p>Through various googling I have seen things referring to styling the 'outline' but I am not having success in using that. Hoping to gain some insight if a pseudo-class style exists to target this element.</p>
| <p>Everything you're looking for is in here <a href="https://css-tricks.com/styling-cross-browser-compatible-range-inputs-css/" rel="nofollow">https://css-tricks.com/styling-cross-browser-compatible-range-inputs-css/</a></p>
<p>The reason you're not seeing any changes is because you probably haven't overwritten the default browser styling and haven't removed all outlines and images for the slider.</p>
<p>Check out this codepen and feel free to play around with it <a href="http://codepen.io/vveleva/pen/gwBbGB" rel="nofollow">http://codepen.io/vveleva/pen/gwBbGB</a></p>
<pre><code>input[type=range] {
-webkit-appearance: none; /* Hides browser default slider */
width: 100%;
background: transparent;
}
input[type=range]::-webkit-slider-thumb {
-webkit-appearance: none;
}
input[type=range]:focus {
outline: none;
}
input[type=range]:focus::-webkit-slider-thumb {
/* changes slider on click and drag */
border: 1px solid red;
box-shadow: 0px 0px 5px red;
}
input[type=range]::-ms-track {
width: 100%;
cursor: pointer;
/* Hides the slider so custom styles can be added */
background: transparent;
border-color: transparent;
color: transparent;
}
input[type=range]::-webkit-slider-thumb {
-webkit-appearance: none;
border: 1px solid #000;
height: 26px;
width: 26px;
border-radius: 3px;
background: #fff;
cursor: pointer;
margin-top: -6px;
box-shadow: 1px 1px 1px #000, 0px 0px 1px #0d0d0d;
}
input[type=range]::-webkit-slider-runnable-track {
width: 100%;
height: 16px;
cursor: pointer;
box-shadow: 1px 1px 5px black;
background: gray;
border-radius: 1.3px;
}
input[type=range]:focus::-webkit-slider-runnable-track {
background: blue;
border: 0.2px solid red;
}
</code></pre>
<p>I hope this helps!</p>
|
Node Server Does not Load HTML Page <p>I am having an issue here in my code...
I have a server on NodeJS, which compiles very well without errors.
But when I try to compile HTML files on the same root, localhost returns page not found.</p>
<p>Please check my codes below and the file tree. Correct me where I am wrong.</p>
<p>[SERVER.JS]</p>
<pre><code>var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var path = require("path");
var passport = require('passport');
var config = require('./config/database'); // get db config file
var User = require('./app/models/user'); // get the mongoose model
var port = process.env.PORT || 3000;
dbName = 'my_db_name';
dbHost = 'localhost';
var jwt = require('jwt-simple');
// get our request parameters
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// log to console
app.use(morgan('combined'));
// Use the passport package in our application
app.use(passport.initialize());
// demo Route (GET http://localhost:3000)
app.get('/', function(req, res) {
res.send('Hello! The Application is running @ http://localhost:' + port + '/api');
});
// connect to database
//mongoose.connect(config.database);
mongoose.connect('mongodb://'+dbHost+'/'+dbName);//try this if the the first does not work
// serve client side code.
app.use('/',express.static('/'));
// pass passport for configuration
require('./config/passport')(passport);
// bundle our routes
var apiRoutes = express.Router();
// connect the api routes under /api/*
app.use('/api', apiRoutes);
// Start the server
app.listen(port);
console.log('Server running @: http://localhost:' + port);
</code></pre>
<p>[HOME.HTML]</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Easytime Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/w3.css" />
</head>
<body ng-app="starter" ng-controller="AppCtrl">
<ui-view></ui-view>
<div class="w3-container w3-border" style="height:auto;" ng-app = "loginForm">
<!--- header --->
<div class="w3-container w3-teal">
<header>
<h2>Easytime Home</h2>
</header>
</div>
<div ng-view></div>
<div class="myContainer w3-left w3-content">
<h3 style="text-align:center">Welcome</h3>
</div>
<!--footer -->
<footer>
<div class="w3-container w3-teal others" style="margin-top:70px;"><h3>Copyright &copy; 2016, Eyo Eyo. All Rights Reserved!</h3></div>
</footer>
</div>
</body>
</html>
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/services.js"></script>
<script src="js/constants.js"></script>
</code></pre>
<p><a href="https://i.stack.imgur.com/9qT5c.jpg" rel="nofollow">FILE TREE ARRANGEMENT</a></p>
| <p>I have solved the problem by following each line of code one after another. I tried to compare the entire code with another server sample. I noticed that I did not include <code>app.use('/client',express.static('client'));</code> in order to serve client files.</p>
|
How to create a new object through code <p>for a class project, we have to make a family in Java. So our person class looks like this:</p>
<pre><code>public class Person
{
String firstName;
String middleName;
boolean isMale;
int age;
//Make new person with age set to 0
public Person(String firstName, String middleName, boolean isMale)
{
this.firstName = firstName.trim().toUpperCase();
this.middleName = middleName.trim().toUpperCase();
this.isMale = isMale;
this.age = 0;
}
}
</code></pre>
<p>We're trying to have another class call upon this and make a new <code>Person</code> based of inputs.</p>
<pre><code>public class Family
{
String surname;
Person husband;
Person wife;
Person child
//////
//The following is supposed to make a new Person() with the following variables set. However, I don't know how to do this.
//////
public void haveChild(String firstName, String middleName, boolean isMale)
{
Person baby;
System.out.println(firstName.trim().toUpperCase() + " is born."); //Prints Child's name
this.child = child; //Set's the created Person() object as variable Child, or at least that's what this is intended to do.
}
}
</code></pre>
<p>So that's what I have so far. I just can't seem to figure out what I need to do next. I've attempted to use <code>new Person();</code> and other variations, but it doesn't seem to work.</p>
| <pre><code>public void haveChild(String firstName, String middleName, boolean isMale)
{
System.out.println(firstName.trim().toUpperCase() + " is born."); //Prints Child's name
this.child = new Person(firstName, middleName, isMale); //Set's the created Person() object as variable Child, or at least that's what this is intended to do.
}
</code></pre>
|
"Warning: Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run)" <p>Similar question have been <a href="http://stackoverflow.com/questions/37709918/warning-do-not-place-android-context-classes-in-static-fields-this-is-a-memory">asked here</a>, <a href="http://stackoverflow.com/questions/39868001/do-not-place-android-context-classes-in-static-fields-this-is-a-memory-leak">here</a> and <a href="http://stackoverflow.com/questions/37894622/do-not-place-android-context-classes-in-static-fields-this-is-a-memory-leak-a">here</a> but the context is quite different from this and moreover the <a href="https://developer.android.com/training/volley/requestqueue.html#singleton" rel="nofollow">code that gave from this error</a> is written by the makers of Android and Android Studio.</p>
<p>This is the code:</p>
<pre><code>public class MySingleton {
private static MySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;
private MySingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
mImageLoader = new ImageLoader(mRequestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
@Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static synchronized MySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new MySingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
public ImageLoader getImageLoader() {
return mImageLoader;
}
}
</code></pre>
<p>The lines giving the warning are:</p>
<pre><code>private static MySingleton mInstance;
private static Context mCtx;
</code></pre>
<p>Now if I remove the <code>static</code> keyword, change <code>public static synchronized MySingleton getInstance(Context...</code> to <code>public synchronized MySingleton getInstance(Context...</code> the error disappers but another problem comes up.</p>
<p>I use <code>MySingleton</code> in RecyclerView. So this line </p>
<p><code>@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
ImageLoader imageLoader = MySingleton.getInstance(mContext).getImageLoader();</code> </p>
<p>tells me </p>
<blockquote>
<p>Non-static method 'getInstance(android.content.Context)' cannot be refrenced from a static context.</p>
</blockquote>
<p>Please anybody knows how to fix this?</p>
| <p>I found the solution to this in the <a href="http://stackoverflow.com/a/39841446/6181476">answer to a similar question answer by CommonsWare</a></p>
<p>I quote </p>
<blockquote>
<p>The quoted Lint warning is not complaining about creating singletons.
It is complaining about creating singletons holding a reference to an
arbitrary Context, as that could be something like an Activity.
Hopefully, by changing mContext = context to mContext =
context.getApplicationContext(), you will get rid of that warning
(though it is possible that this still breaks Instant Run â I cannot
really comment on that).</p>
<p>Creating singletons is fine, so long as you do so very carefully, to
avoid memory leaks (e.g., holding an indefinite static reference to an
Activity).</p>
</blockquote>
<p>So Google is not actually contracting itself. To fix this, if <code>this.getApplicationContext</code> is supplied as a parameter for the context, then there will be no memory leak.</p>
<p>So in essence, ignore the warning and supply <code>this.getApplicationContext</code> as a parameter for the context.</p>
|
Difference between mvn appengine:update and mvn appengine:deploy in Google App Engine <p>What is the difference between
<code>mvn appengine:update</code>
and
<code>mvn appengine:deploy</code> in Google App Engine.</p>
| <p>There is not references for <code>mvn appengine:deploy</code></p>
<p>But for <code>mvn appengine:update</code> the documentation is:</p>
<blockquote>
<p>To deploy your app with Maven, run the following command from your
project's top level directory, where the pom.xml file is located, for
example:</p>
<p>mvn appengine:update</p>
</blockquote>
<p><a href="https://cloud.google.com/appengine/docs/java/tools/uploadinganapp" rel="nofollow">The complete reference here</a></p>
|
Learning Android Development <p>I'm in my last year of university and I'm currently performing my first out of two internships which I hope will lead to a job. Ahead of me lays two android projects, we will develop two apps which will be up for sale. I personally don't have any android experience, however I do have quite a bit of Java experience, which is the main language I study at my university. I have 1 week of learning before we start our projects so coding around the clock is essential :) Now to my question:</p>
<p>Are there any good online tutorials out there that are able to deliver such quality that I will be able to pull these apps off?</p>
| <p>This question isn't really on topic for this site, but <em>Android: Programming & App Development For Beginners</em> by Samuel Shields is a good introduction in my opinion. It's not an "everything you ever wanted to know about Android development" type book (it's fairly short, but that's a feature in my opinion because you don't have to slog through hundreds of pages to learn about the basics) but it'll give you a good introduction to the "building blocks" of the platform. It's very inexpensive too, which, as I recall from my student days, is a major advantage in and of itself :)</p>
|
Python: [Errno 2] No such file or directory - weird issue <p>I'm learning with a tutorial <a href="https://hackercollider.com/articles/2016/07/05/create-your-own-shell-in-python-part-1/" rel="nofollow">Create your own shell in Python</a> and I have some weird issue. I wrote following code:</p>
<pre><code>import sys
import shlex
import os
SHELL_STATUS_RUN = 1
SHELL_STATUS_STOP = 0
def shell_loop():
status = SHELL_STATUS_RUN
while status == SHELL_STATUS_RUN:
sys.stdout.write('> ') #display a command prompt
sys.stdout.flush()
cmd = sys.stdin.readline() #read command input
cmd_tokens = tokenize(cmd) #tokenize the command input
status = execute(cmd_tokens) #execute the command and retrieve new status
def main():
shell_loop()
def tokenize(string):
return shlex.split(string)
def execute(cmd_tokens): #execute command
os.execvp(cmd_tokens[0], cmd_tokens) #return status indicating to wait for the next command in shell_loop
return SHELL_STATUS_RUN
if __name__ == "__main__":
main()
</code></pre>
<p>And now when I'm typing a "mkdir folder" command it returns error: <code>[Errno 2] No such file or directory</code>. BUT if I write previously "help" command which works correctly (displays me all available commands), command mkdir works correctly and it creating a folder. Please, guide me what's wrong with my code?
I'm writing in Notepad++ on Windows 8.1 64x</p>
| <p>Copy-paste from comments in my link (thanks for <a href="http://stackoverflow.com/users/3009212/ari-gold">Ari Gold</a>)</p>
<p>Hi tyh, it seems like you tried it on Windows. (I forgot to note that it works on Linux and Mac or Unix-like emulator like Cygwin only)</p>
<p>For the first problem, it seems like it cannot find <code>mkdir</code> command on your system environment. You might find the directory that the <code>mkdir</code> binary resides in and use execvpe() to explicitly specify environment instead</p>
<p>For the second problem, the <code>os</code> module on Windows has no fork() function.
However, I suggest you to use Cygwin on Windows to emulate Unix like environment and two problems above should be gone.</p>
<p>In Windows 10, there is Linux-Bash, which might work, but I never try.</p>
|
Type of an auto initialized list <p>In the C++ code below, what is type of <code>a</code>? <code>typeid</code> returns <code>St16initializer_listIPKcE</code></p>
<pre><code>auto a = { "lol", "life" };
</code></pre>
| <p>When you have</p>
<pre><code>auto a = { "lol", "life" };
</code></pre>
<p>The compiler will try to deduce a <code>std::initializer_list</code> where the type is what all of the elements are. In this case <code>"lol"</code> and <code>"life"</code> are both a <code>const char[]</code> so you have a <code>std::initializer_list<const char*></code>.</p>
<p>If on the other have you had something like </p>
<pre><code>auto foo = { 1, 2.0 };
</code></pre>
<p>Then you would have a compiler error since the element types are different.</p>
<p>The rules for auto deduction of intializer list are as follows with one expection</p>
<pre><code>auto x1 = { 1, 2 }; // decltype(x1) is std::initializer_list<int>
auto x2 = { 1, 2.0 }; // error: cannot deduce element type
auto x3{ 1, 2 }; // error: not a single element
auto x4 = { 3 }; // decltype(x4) is std::initializer_list<int>
</code></pre>
<p>The expection is that before C++17</p>
<pre><code>auto x5{ 3 };
</code></pre>
<p>is a <code>std::intializer_list<int></code> where in C++17 and most compilers that already adopted the rule it is deduced as a <code>int</code>.</p>
|
Resource management in F# <p>I know I need to use <code>use</code> keywork to dispose resouce:</p>
<pre><code>use db = new dbml.MobileDataContext(connectionString)
for rows in db.Item do
....
</code></pre>
<p>But I want to create the function which returns db connection:</p>
<pre><code>let getConnection(connectionString) =
use db = new dbml.MobileDataContext(connectionString)
db.ExecuteCommand(....) |> ignore
db
</code></pre>
<p>and use this function in my code:</p>
<pre><code>use db = getConnection(connectionString)
for rows in db.Item do
....
</code></pre>
<p>Do I need to use <code>use</code>-keyword in such case two times: in the function and in the function call ?</p>
| <p>You should only use <code>use</code> in the outer function. If you use it inside <code>getConnection</code>, then your context will be disposed upon returning from <code>getConnection</code>, and so it will be already disposed in the outer function when you want to use it. As a general rule, if you dispose a value in a function then you must not return it.</p>
|
git,curl,wget redirect to locahost <p>Git gives me this error:</p>
<pre class="lang-none prettyprint-override"><code>$ git clone How people build software · GitHub
Cloning into 'xxxx'... fatal: unable to access 'xxx (Michael Dungan) · GitHub': Failed to connect to 127.0.0.1 port 443: Connection refused
</code></pre>
<p><code>curl</code> also gives the error:</p>
<pre class="lang-none prettyprint-override"><code>$ curl http://baidu.com
curl: (7) Failed to connect to 127.0.0.1 port 80: Connection refused
</code></pre>
<p><code>wget</code> also gives the error:</p>
<pre class="lang-none prettyprint-override"><code>$ wget http://baidu.com
Error parsing proxy URL â http://127.0.0.1:8123 â: Scheme missing.
</code></pre>
<p>But <code>ping</code> is okay:</p>
<pre class="lang-none prettyprint-override"><code>ping http://baidu.com
PING http://baidu.com (180.149.132.47): 56 data bytes
64 bytes from 180.149.132.47: icmp_seq=0 ttl=52 time=24.689 ms
64 bytes from 180.149.132.47: icmp_seq=1 ttl=52 time=23.770 ms
64 bytes from 180.149.132.47: icmp_seq=2 ttl=52 time=25.112 ms
</code></pre>
<p>And my browser is okay.</p>
<p>I have restarted my Mac, closed my proxy, VPN, but the it never changes. This problem appears after I write this python code:</p>
<pre class="lang-python prettyprint-override"><code>socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
socket.socket = socks.socksocket
socket.create_connection = create_connection
socket.getaddrinfo = getaddrinfo
</code></pre>
| <p>i have solved this problem, i hava missed the http_proxy,https_proxy system environment variable in <code>/.bash_profile</code>. remove them, it is okay now.</p>
|
Unity: Infinite While Loop in Coroutine <p>Okay so I'm trying to create a small dash coroutine for my 2d character. When the coroutine calls, gravity switches off, he lerps between 2 speeds over a time. The issue is within my Dash coroutine, the while loop checks when time.time(current time) > start time + dash duration.</p>
<p>While debugging this with Mono, I'm finding that my variable currentTime is not changing after being set, even though I can clearly see the while loop running more than once. This puts me in an infinite loop.</p>
<p>Any suggestions?</p>
<pre><code> void Update () {
MoveAndJump ();
CheckDash ();
}
void MoveAndJump(){
if(dashing){
return;
}
Vector2 moveDir = new Vector2 (Input.GetAxisRaw ("Horizontal") * moveSpeed, rb.velocity.y);
rb.velocity = moveDir;
// Consider Switching to an overlap circle based on the actual character graphic. This currently uses a rectangle
// This can also use 4 points to create a more complex box shape. This only works well when using at least about 1 unit size. any smaller and it is innacurate
isGrounded = Physics2D.OverlapArea (groundPoint_right.position, groundPoint_left.position, groundMask);
Debug.Log (isGrounded);
if (Input.GetAxisRaw ("Horizontal") == 1) {
transform.localScale = new Vector3 (1 , 1 * transform.localScale.y, 1* transform.localScale.z);
} else if (Input.GetAxisRaw ("Horizontal") == -1) {
transform.localScale = new Vector3 (-1, 1* transform.localScale.y, 1* transform.localScale.z);
}
if(Input.GetKeyDown(KeyCode.Space) && isGrounded){
rb.AddForce (new Vector2 (0, jumpHeight));
}
}
void CheckDash(){
if(Input.GetKeyDown(KeyCode.W) && !dashing && Time.time > nextdashtime){
dashing = true;
StartCoroutine ("Dash");
}
}
IEnumerator Dash(){
//Before dash loop
rb.gravityScale = 0f;
float startDashTime = Time.time;
float endDashTime = startDashTime + dashDuration;
float currentDashTime;
//Dash Loop
while(Time.time < (startDashTime + dashDuration)){
currentDashTime = Time.time;
// The value to lerp by should be the % that time.time is between start time and end time
rb.velocity = new Vector2 (Mathf.Lerp (startDashSpeed, endDashSpeed, ((currentDashTime - startDashTime) / (endDashTime - startDashTime))),0f);
}
//When dash loop is complete
nextdashtime = Time.time + dashcooldown;
dashing = false;
rb.gravityScale = 1;
yield return null;
}
// FOR CHECKING GROUND CHECK LIMITS
/*void OnDrawGizmos(){
Gizmos.color = Color.red;
Gizmos.DrawLine (groundPoint_left.position, groundPoint_right.position);
}*/
</code></pre>
<p>}</p>
| <p><strong>You don't need all that for <em>dashing</em> !</strong></p>
<p>If you use rigid bodies then the following code will do:</p>
<pre><code>using UnityEngine;
public class CubeController : MonoBehaviour
{
private Rigidbody _rigidbody;
public float Force = 10;
private void Start()
{
_rigidbody = GetComponent<Rigidbody>();
}
private void FixedUpdate()
{
ForceMode? forceMode = null;
if (Input.GetKeyDown(KeyCode.W)) // normal
forceMode = ForceMode.Force;
else if (Input.GetKeyDown(KeyCode.S)) // dash
forceMode = ForceMode.Impulse;
if (forceMode.HasValue)
_rigidbody.AddRelativeForce(Vector3.forward*Force, forceMode.Value);
}
}
</code></pre>
<p>This is an example using 3D but you have the same for 2D : <a href="https://docs.unity3d.com/ScriptReference/Rigidbody2D.html" rel="nofollow">https://docs.unity3d.com/ScriptReference/Rigidbody2D.html</a></p>
<p><strong>Steps:</strong></p>
<ul>
<li>add rigidbody component to your ground, set it as kinematic</li>
<li>add rigidbody component to your player</li>
<li>sketch the above component for your player using <code>Rigidbody2D</code> class</li>
<li>adjust the parameters as you'd like</li>
<li>you should have a simple and robust <em>dashing</em> by now :)</li>
</ul>
|
Displaying unique name with total of column value in a group with additional variables in python <p>I'm learning Python and thought working on a project might be the best way to learn it. I have about 200,000 rows of data in which the data shows list of medication for the patient. Here's a sample of the data. </p>
<pre><code>PTID PTNAME MME DRNAME DRUGNAME SPLY STR QTY FACTOR
1 PATIENT, A 2700 DR, A OXYCODONE HCL 15 MG 30 15 120 1.5
1 PATIENT, A 2700 DR, B OXYCODONE HCL 15 MG 30 15 120 1.5
2 PATIENT, B 4050 DR, C MORPHINE SULFATE ER 15 MG 30 15 270 1
2 PATIENT, B 4050 DR, C MORPHINE SULFATE ER 15 MG 30 15 270 1
2 PATIENT, B 840 DR, A OXYCODONE-ACETAMINOPHE 10MG-32 14 10 56 1.5
2 PATIENT, B 1350 DR, C OXYCODONE-ACETAMINOPHE 5 MG-32 15 5 180 1.5
3 PATIENT, C 1350 DR, C OXYCODONE-ACETAMINOPHE 5 MG-32 15 5 180 1.5
3 PATIENT, C 1800 DR, D OXYCODONE-ACETAMINOPHE 10MG-32 30 10 120 1.5
</code></pre>
<p>I've been thinking about this a lot and have tried many ways but none of the code produce any results or makes any sense. Honestly, I don't even know where to begin. A little help would be highly appreciated. </p>
<p>So, what I want to do is consolidate the data for each patients and calculate the <code>Total MME</code> for each patient. The <code>DRUGNAME</code> should show the one that has higher MME. In other words, the dataframe should only have one row for each patient. </p>
<p>One thing I did try is </p>
<pre><code>groupby_ptname = semp.groupby('PTNAME').apply(lambda x: x.MME.sum())
</code></pre>
<p>which shows unique patient names with total MME, but I'm not sure how to add other variables in this new dataframe. </p>
| <p>Have another look at the documentation for the <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow">pandas groupby methods</a>. </p>
<p>Here's something that could work for you:</p>
<pre><code>#first get the total MME for each patient and drug combination
total_mme=semp.groupby(['PTNAME','DRUGNAME'])['MME'].sum()
#this will be a series object with index corresponding to PTNAME and DRUGNAME and values corresponding to the total MME
#now get the indices corresponding to the drug with the max MME total
max_drug_indices=total_mme.groupby(level='PTNAME').idxmax()
#index the total MME with these indices
out=total_mme[max_drug_indices]
</code></pre>
|
Why does decreasing the framerate with videorate incur a significant CPU performance penalty? <p>My understanding of the <a href="https://gstreamer.freedesktop.org/data/doc/gstreamer/head/gst-plugins-base-plugins/html/gst-plugins-base-plugins-videorate.html" rel="nofollow">videorate</a> element is that framerate correction is performed by simply dropping frames and no "fancy algorithm" is used. I've profiled CPU usage for a gst-launch-1.0 pipeline and I've observed that as the framerate decreases below 1 FPS, CPU usage, counter-intuitively, increases dramatically.<a href="https://i.stack.imgur.com/5RqiF.png" rel="nofollow"><img src="https://i.stack.imgur.com/5RqiF.png" alt="enter image description here"></a>
Sample pipeline (you can observe the performance penalty by changing the framerate fraction):</p>
<pre><code>gst-launch-1.0 filesrc location=test.mp4 ! qtdemux ! h264parse ! avdec_h264 ! videorate drop-only=true ! video/x-raw,framerate=1/10 ! autovideosink
</code></pre>
<p>I would expect that decreasing the framerate would reduce the amount of processing required throughout the rest of the pipeline. Any insight into this phenomenon would be appreciated.</p>
<p>System info: Centos 7, GStreamer 1.4.5</p>
<p>EDIT: Seems this happens with the videotestsrc as well but only if you specify a high framerate on the source.</p>
<pre><code>videotestsrc pattern=snow ! video/x-raw,width=1920,height=1080,framerate=25/1 ! videorate drop-only=true ! video/x-raw,framerate=1/10 ! autovideosink
</code></pre>
<p>Removing the framerate from the videotestsrc caps puts CPU usage at 1%, and usage increases as the videorate framerate increases. Meanwhile, setting the source to 25/1 FPS increases CPU usage to 50% and it lowers as the videorate framerate increases.</p>
| <p><code>videorate</code> is tricky and you need to consider it in conjunction with every other element in the pipeline. You also need to be aware of how much CPU time is actually available to cut off. For example, if you're decoding a 60fps file and displaying it at 1fps, you'll still be eating a lot of CPU. You can output to <code>fakesink</code> with <code>sync</code> set to true to see how much CPU you could actually save.</p>
<p>I recommend adding a bit of debug info to better understand videorate's behavior.</p>
<p><code>export GST_DEBUG=2,videorate:7</code></p>
<p>Then you can grep for "pushing buffer" for when it pushes:</p>
<p><code>gst-launch-1.0 [PIPELINE] 2>&1 | grep "pushing buffer"</code></p>
<p>..and for storing buffer when it receives data:</p>
<p><code>gst-launch-1.0 [PIPELINE] 2>&1 | grep "storing buffer"</code></p>
<p>In the case of decoding a filesrc, you're going to see bursts of CPU activity because what happens is the decoder will run through say 60 frames, realize the pipeline is filled, pause, wait till a <code>need-buffers</code> event comes in, then burst to 100% CPU to fill the pipeline again.</p>
<p>There are other factors too. Like you may need to be careful that you have <code>queue</code> elements between certain bottlenecks, with the correct <code>max-size</code> attributes set. Or your sink or source elements could be behaving in unexpected ways.</p>
<p>To get the best possible answer for your question, I'd suggest posting the exact pipeline you intend to use, with and without the videorate. If you have something like "autovideosink" change that to the element it actually resolves to on your system.</p>
<p>Here are a few pipelines I tested with:</p>
<p><code>gst-launch-1.0 videotestsrc pattern=snow ! video/x-raw,width=320,height=180,framerate=60/1 ! videorate ! videoscale method=lanczos ! video/x-raw,width=1920,height=1080,framerate=60/1 ! ximagesink</code> 30% CPU in htop</p>
<p><code>gst-launch-1.0 videotestsrc pattern=snow ! video/x-raw,width=320,height=180,framerate=60/1 ! videorate ! videoscale method=lanczos ! video/x-raw,width=1920,height=1080,framerate=1/10</code> 0% with 10% spikes in htop</p>
|
How to get content that isn't loaded yet? <p>I need to get content from ANOTHER SERVER web page, but when I use <code>file_get_content($url)</code>, URL won't show up for certain page probably because it isn't loaded yet.</p>
<p>Is there any option to get content if page loads dynamically for couple of seconds?</p>
<p>Maybe I can load content into an iframe and then wait for completely load and on someway get content from iframe? Something like that</p>
| <p>Use JQuery for this.</p>
<pre><code><div id="url-contents"></div>
<script>
$( "#url-contents" ).load( "your/url.html" );
</script>
</code></pre>
|
Search elements including roots and descendents <p>What's a good way to search a small set of elements structured like this? I want to be able to find any element given its ID, without having to know exactly where I'm looking for it.</p>
<pre><code>const elements = $(`
<div id="a">
<div id="aa"></div>
<div id="ab"></div>
</div>
<div id="b">
<div id="ba"></div>
<div id="bb"></div>
</div>
`);
</code></pre>
<ul>
<li><code>.find("#id")</code> can find <code>aa</code>, but not <code>a</code> or <code>b</code></li>
<li><code>.filter("#id")</code> can find <code>a</code> and <code>b</code>, but not <code>aa</code> or <code>bb</code></li>
<li>I also tried <code>.siblings().addBack().find("#id")</code>, but that doesn't seem to work either (can't even find <code>a</code>)</li>
</ul>
<p>I can't seem to get around the fact that <code>find</code> misses the root elements, but <code>filter</code> misses the descendent elements. I need some combination of the two...</p>
| <p>From jQuery 1.11.2 and 2.1.2 onwards you can effectively use a <code>documentFragment</code> like this:</p>
<pre><code>$(document.createDocumentFragment())
</code></pre>
<p>This does not introduce an element. If you append the <code>element</code> contents to it, and query the parent of <code>#a</code> you'll get no match.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var elements = $(`
<div id="a">
<div id="aa"></div>
<div id="ab"></div>
</div>
<div id="b">
<div id="ba"></div>
<div id="bb"></div>
</div>
`);
// wrap elements in a document fragment
elements = $(document.createDocumentFragment()).append(elements);
// elements.find('#a') works, but second argument of $() can be used:
console.log('#a', $('#a', elements).length);
console.log('#ab', $('#ab', elements).length);
console.log('#ba', $('#ba', elements).length);
console.log('parents of #a:', $('#a', elements).parent().length);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.js"></script></code></pre>
</div>
</div>
</p>
|
How to pass a tuple3 as an argument to function? <p>I'm trying to pass a tuple as an argument to function. Unfortunately i can't do this. Can you give me some tips?</p>
<pre><code>val t = Tuple3(3, "abc", 5.5);
def fun(x: (Int, String, Double) = {
x.productIterator.foreach(i => println("Value: " + i));
}
def(t);
</code></pre>
| <p>There's a missing closing parenthese and you called <code>def(t)</code> instead of <code>fun(t)</code>. Note that you don't need to indicate the constructor <code>Tuple3</code> :</p>
<pre><code>val t = (3, "abc", 5.5);
def fun(x: (Int, String, Double)) = {
x.productIterator.foreach(i => println("Value: " + i));
}
fun(t);
</code></pre>
|
Classification training with only positive sentences <p>I'm starting a project to build an automated fact checking classificator nad I have some doubts about the process to follow.</p>
<p>I've a database of ~1000 sentences, each one being a fact check positive. In order to build a supervised machine learning model I'll need to have a big set of tagged sentences with the true/false result depending if it's a fact check candidate sentence or not. That would require a lot of time and effort, so I'd like to first get results (with less accuracy I guess) without doing that.</p>
<p>My idea is to use the already tagged positive sentences and apply a PoS tagger to them. This would give me interesting information to spot some patterns like the most common words(e.g: raised, increase, won) and the post tags (e.g. verbs in past/present tense, time and numerals).</p>
<p>With this results I'm thinking about assigning weights in order to analyze new unclassified sentences. The problem is that the weight assignment would be done by me in an "heuristical" way. It'd be best to use the results of the PoS tagger to train some model which assigns probabilities in a more sophisticated way.</p>
<p>Could you give me some pointers if there's a way to accomplish this?</p>
<p>I read about Maximum Entropy Classifiers and statistical parsers but I really don't know if they're the right choice.</p>
<p>Edit (I think it'd be better to give more details):</p>
<p>Parsing the sentences with a PoS tagger will give me some useful information about each one of them, allowing me to filter them and weighting them using some custom metrics.</p>
<p>For example:</p>
<p>There are one million more people in poverty than five years ago -> indicatives of a fact check candidate sentence: verb in present tense, numerals and dates, (than) comparison.</p>
<p>We will increase the GDP by 3% the following year -> indicatives of a NOT fact check candidate sentence: it's in the future tense (indicative of some sort of prediction)</p>
| <p>This situation happens often when the true sentences are relatively rare in the data. </p>
<p>1) Get a corpus of sentences that resemble what you will be classifying in the end. The corpus will contain both true and false sentences. Label them as false or non-fact check. We are assuming they are all false even though we know this is not the case. You want the ratio of true/false data created to be approximately its actual distribution if at all possible. So if 10% are true in real data then your assumed false cases are 90% or 9,000 for you 1,000 trues. If you don't know the distribution then just make it 10x or more. </p>
<p>2) Train logistic regression classifier aka maximum entropy on the data with cross validation. Keep track of the high scoring false positives on the held out data.</p>
<p>3) Re-annotate false positives down to what ever score makes sense for possibly being true positives. This will hopefully clean your assumed false data. </p>
<p>4) Keep running this process until you are no longer improving the classifier. </p>
<p>5) To get your "fact check words" then make sure your feature extractor is feeding words to your classifier and look for those that are positively associated with the true category--any decent logistic regression classifier should provide the feature weights in some way. I use LingPipe which certainly does. </p>
<p>6) I don't see how PoS (Part of Speech) helps with this problem. </p>
<p>This approach will fail to find true instances that are very different from the training data but it can work none the less.</p>
<p>Breck</p>
|
How to return related object, in Angular 2 with TypeScript <p>Sorry, i'm new in TypeScrit and Angular 2, and sorry for my poor english, it is not my native language. But i need your help.</p>
<p>I have this data model:</p>
<h2>country.ts</h2>
<pre><code>export class Country{
id: number;
name: string;
}
</code></pre>
<h2>state.ts</h2>
<pre><code>export class State{
id: number;
name: string;
country_id: number
}
</code></pre>
<h2>city.ts</h2>
<pre><code>export class City{
id: number;
name: string;
state_id: number
}
</code></pre>
<p>I have many Countries, related with some states and these related with some cities, for example : EEUU -> Florida -> Orlando</p>
<p>The user select first one country, in the next step, must be select one state related with this country and the last step select one city related with this state.</p>
<p>The goal is complete a <code><select></select></code> tag with this data, but i can't create a method to return the data.</p>
<p>I tried this, but i have this error "Type 'Promise' is not assignable to type 'Promise'" in method "getCitiesRefState" it's something similar to "getCity()", but this work fine.</p>
<p>My code is:</p>
<h2>mock-data.ts</h2>
<pre><code>import { Country } from './country';
import { State } from './state';
import { City } from './city';
export const PAIS: Pais[] = [
{id: 1, name: 'EEUU'}
];
export const PROVINCIA: Provincia[] = [
{id: 1, name: 'Florida', pais_id: 1},
{id: 2, name: 'Georgia', pais_id: 1},
{id: 3, name: 'Alabama', pais_id: 1}
];
export const LOCALIDAD: Localidad[] = [
{id: 1, name: 'Orlando', provincia_id: 1},
{id: 2, name: 'Tampa', provincia_id: 1},
{id: 3, name: 'Gainesvielle', provincia_id: 1}
];
</code></pre>
<h2>city.service.ts</h2>
<pre><code>import { Injectable } from '@angular/core';
import { City } from './city';
import { CITY } from './mock-data';
@Injectable()
export class CityService{
getCities(): Promise<City[]> {
return Promise.resolve(CITY);
}
getCitiesRefState(id: number): Promise<City[]> {
return this.getCities().then(cities=> cities.find(city => city.state_id === id));
}
getCity(id: number): Promise<City> {
return this.getCities()
.then(cities => cities.find(city=> city.id === id));
}
}
</code></pre>
| <p>Your <code>getCitiesRefState</code> method is declared to return a <code>Promise<City[]></code> but actually returns a <code>Promise<City></code>. It helps to see if we expand the method out.</p>
<pre><code>getCitiesRefState(id: number): Promise<City[]> {
return this.getCities()
.then(cities=> {
// cities.find() will return a City, not a City[]
return cities.find(city => city.state_id === id)
});
}
</code></pre>
<p>As far as your <code><select></code> you will need to give more code to show what is going on there.</p>
|
How to not load unused assembly <p>In ASP.NET MVC4 application System.Data.OracleClient assembly is loaded.</p>
<p>Code in controller</p>
<pre><code> var sb = new StringBuilder();
foreach (Assembly b in AppDomain.CurrentDomain.GetAssemblies())
sb.AppendLine(b.FullName);
</code></pre>
<p>Outputs it:</p>
<pre><code> System.Data.OracleClient, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
</code></pre>
<p>According to <a href="http://stackoverflow.com/questions/40082667/how-to-avoid-loading-unnessecary-assemblies">How to avoid loading unnessecary assemblies</a> answer this is caused by presence of Oracle section in machine.config:</p>
<pre><code><section name="system.data.oracleclient" type="System.Data.Common.DbProviderConfigurationHandler, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
</code></pre>
<p>Trying to remove in using remove element in application web.config show error</p>
<p><a href="https://i.stack.imgur.com/vEUok.png" rel="nofollow"><img src="https://i.stack.imgur.com/vEUok.png" alt="enter image description here"></a></p>
<p>and after running application <code>System.Data.OracleClient</code> still appears in list of loaded assemblies.
Solution does not contain any direct reference to any Oracle namespace.
How to remove this amnd other unused assemblies from loaded assemblies.</p>
<p>Application is running in VPS with limited memory and hopefully this frees some memory.</p>
| <p>After further investigation I found that that this <code>system.data.oracleclient</code> is called and used by <code>System.Data</code> that is critical if you use any kind of data base.</p>
<p>After even more investigation using the <code>ILSpy</code> I also found that the <code>mscorlib</code> (the core library) is also have reference to that Oracle Client... so probably you can not avoid it at all...</p>
<p>So you need to remove this System.Data to avoid the oracle client - but it will not play if you have any kind of data.</p>
<p>Remove it from assemblies as I also have post here <a href="http://stackoverflow.com/a/40085122/159270">http://stackoverflow.com/a/40085122/159270</a> </p>
<pre><code><compilation>
<assemblies>
<clear/>
<add assembly="Microsoft.VisualStudio.Web.PageInspector.Loader, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add assembly="mscorlib" />
<add assembly="Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add assembly="System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add assembly="System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add assembly="System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<!--
<add assembly="System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
-->
<add assembly="System.Web.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add assembly="System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add assembly="System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add assembly="System.EnterpriseServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add assembly="System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add assembly="System.Runtime.Serialization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add assembly="System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add assembly="System.ServiceModel.Activation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add assembly="System.ServiceModel.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add assembly="System.Activities, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add assembly="System.ServiceModel.Activities, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add assembly="System.WorkflowServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add assembly="System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add assembly="System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add assembly="System.Data.DataSetExtensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add assembly="System.Xml.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add assembly="System.ComponentModel.DataAnnotations, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add assembly="System.Web.DynamicData, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add assembly="System.Web.ApplicationServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add assembly="*" />
<add assembly="System.Web.WebPages.Deployment, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</assemblies>
</compilation>
</code></pre>
<p>Now the message that you see on the visual studio if false alert because visual studio can not compile the web.config as IIS... actually the remove works and the site is run.</p>
<p>At the end I like to say you that I am not sure that you can gain much from that oracle client remove because this is only check if there is any database connection in web.config, if not exist actually is not do anything.</p>
<p>Most important is to minimize the pipe line of the request as I have type on my previous answer...</p>
|
How to Remove Trailing Comma <p>I am trying to remove the trailing comma from my php statement</p>
<pre><code><?php foreach( $speaker_posts as $sp ): ?>
{
"@type" : "person",
"name" : "<?php the_field('name_title', $sp->ID); ?>",
"sameAs" : "<?php echo post_permalink( $sp->ID ); ?>"
},
<?php endforeach; ?>
</code></pre>
| <p>Assuming your array is well formed (has indexes starting from zero) you can put it at the beginning, skipping the first record:</p>
<pre><code><?php foreach( $speaker_posts as $idx => $sp ): ?>
<?php if ($idx) echo ","; ?>
{
"@type" : "person",
"name" : "<?php the_field('name_title', $sp->ID); ?>",
"sameAs" : "<?php echo post_permalink( $sp->ID ); ?>"
}
<?php endforeach; ?>
</code></pre>
<p>Otherwise you need an external counter:</p>
<pre><code><?php $idx = 0; foreach( $speaker_posts as $sp ): ?>
<?php if ($idx++) echo ","; ?>
{
"@type" : "person",
"name" : "<?php the_field('name_title', $sp->ID); ?>",
"sameAs" : "<?php echo post_permalink( $sp->ID ); ?>"
}
<?php endforeach; ?>
</code></pre>
|
Why does adding parenthesis around a yield call in a generator allow it to compile/run? <p>I have a method:</p>
<pre><code>@gen.coroutine
def my_func(x):
return 2 * x
</code></pre>
<p>basically, a tornado coroutine.</p>
<p>I am making a list such as:</p>
<pre><code>my_funcs = []
for x in range(0, 10):
f = yield my_func(x)
my_funcs.append(x)
</code></pre>
<p>In trying to make this a list comprehension such as:</p>
<pre><code>my_funcs = [yield my_func(i) for i in range(0,10)]
</code></pre>
<p>I realized this was invalid syntax. It <a href="http://chat.stackoverflow.com/transcript/message/33540588#33540588">turns out you can do this</a> using <code>()</code> around the yield:</p>
<pre><code>my_funcs = [(yield my_func(i)) for i in range(0,10)]
</code></pre>
<ul>
<li>Does this behavior (the syntax for wrapping a <code>yield foo()</code> call in () such as <code>(yield foo() )</code> in order to allow this above code to execute) have a specific type of name?
<ul>
<li>Is it some form of operator precedence with <code>yield</code>?</li>
</ul></li>
<li>Is this behavior with <code>yield</code> documented somewhere?</li>
</ul>
<p>Python 2.7.11 on OSX. This code does need to work in both Python2/3 which is why the above list comprehension is not a good idea (see <a href="http://stackoverflow.com/a/32139977/1048539">here</a> for why, the above list comp works in Python 2.7 but is broken in Python 3).</p>
| <p><code>yield</code> expressions must be parenthesized in any context except as an entire statement or as the right-hand side of an assignment:</p>
<pre><code># If your code doesn't look like this, you need parentheses:
yield x
y = yield x
</code></pre>
<p>This is stated in the <a href="https://www.python.org/dev/peps/pep-0342/" rel="nofollow">PEP that introduced <code>yield</code> expressions</a> (as opposed to <code>yield</code> statements), and it's implied by the contexts in which <code>yield_expr</code> appears in the <a href="https://docs.python.org/2/reference/grammar.html" rel="nofollow">grammar</a>, although no one is expecting you to read the grammar:</p>
<blockquote>
<p>A yield-expression must always be parenthesized except when it
occurs at the top-level expression on the right-hand side of an
assignment.</p>
</blockquote>
|
Use password parameter in Jenkins as Secret in Pipeline <p>I have a Jenkins pipeline job that needs to provide the username and password to checkout from RTC as parameters.</p>
<p>The checkout action can use a userId and password variable, but the Password must be of the class "Secret".</p>
<p>When trying to create a secret using <code>hudson.util.Secret secret = hudson.util.Secret.fromString("${Build_Password}")</code>, I get the following error:</p>
<pre><code>org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use staticMethod hudson.util.Secret fromString java.lang.String
</code></pre>
<p>Is there a way to create a Secret or Credential from parameters?</p>
| <p>I had to disable the groovy sandbox. After that, I was able to use the Secret class:</p>
<pre><code>hudson.util.Secret secret = hudson.util.Secret.fromString(Build_Password)
</code></pre>
|
.Net Core 1.0 Relative Project Dependencies Not Found <p>I have the project structure:</p>
<pre><code>/src
- common
- common-x
+ project.json
- module-a
- project-a
+ project.json
- project-a-tests
+ project.json
+ global.json
</code></pre>
<p>I'm trying to include the <code>common-x</code> project using relative file paths in the <code>global.json</code> file.</p>
<p>The <code>global.json</code> file in the <code>module-a</code> directory is as follows:</p>
<pre><code>{
"projects": [
"project-a",
"project-a-tests",
"../common/common-x"
]
}
</code></pre>
<p>and the <code>project.json</code> file in <code>project-a</code> is</p>
<pre><code>{
// Default config options are also in this...
"dependencies": {
"Microsoft.NETCore.App": {
"version": "1.0.1",
"type": "platform"
},
"common-x": {
"target": "project"
}
}
}
</code></pre>
<p><code>project-a-tests</code> has no problem referencing <code>project-a</code> since they are in the same directory, but <code>project-a</code> can't find the <code>common-x</code> project. I receive a "Unable to resolve ..." error from <code>dotnet restore</code>.</p>
<p>I have tried using absolute paths but that doesn't work either. The closest solution so far is to use symlinks but that is not preferable. </p>
<p>Note: This is all being run on Ubuntu 16.04.</p>
| <p>You should only need to specify top level folders in your <code>global.json</code> file, since sub-folders will be scanned automatically. <a href="https://docs.microsoft.com/hu-hu/dotnet/articles/core/tools/global-json" rel="nofollow">Global.json reference</a>.</p>
<p>So your <code>global.json</code> should look like this.</p>
<pre><code>{
"projects": [ "src" ]
}
</code></pre>
<p>If you are still getting any dependencies issues that might related to compatibility problems between projects/modules, however I would need to see the exact output you are getting to troubleshoot that.</p>
<p><strong>UPDATE</strong></p>
<p>A few tips that might be useful:</p>
<ul>
<li>Delete old project.json.lock files</li>
<li>Add a <code>.sln</code> solution file if you don't have one created.</li>
</ul>
<p><strong>UPDATE 2</strong></p>
<p>As per your comment, the working solution was to move <code>global.json</code> into <code>src</code> folder, and list your top-level folders in the projects array.</p>
|
Provisioning CoreOS with Ansible pip error <p>I am trying to provision a coreOS box using Ansible. First a bootstapped the box using <a href="https://github.com/defunctzombie/ansible-coreos-bootstrap" rel="nofollow">https://github.com/defunctzombie/ansible-coreos-bootstrap</a></p>
<p>This seems to work ad all but pip (located in /home/core/bin) is not added to the path. In a next step I am trying to run a task that installs docker-py:</p>
<pre><code>- name: Install docker-py
pip: name=docker-py
</code></pre>
<p>As pip's folder is not in path I did it using ansible:</p>
<pre><code> environment:
PATH: /home/core/bin:$PATH
</code></pre>
<p>If I am trying to execute this task I get the following error:</p>
<p>fatal: [192.168.0.160]: FAILED! => {"changed": false, "cmd": "/home/core/bin/pip install docker-py", "failed": true, "msg": "\n:stderr: /home/core/bin/pip: line 2: basename: command not found\n/home/core/bin/pip: line 2: /root/pypy/bin/: No such file or directory\n"}</p>
<p>what I ask is where does <code>/root/pypy/bin/</code> come from it seems this is the problem. Any idea?</p>
| <p>You can't use shell-style variable expansion when setting Ansible variables. In this statement...</p>
<pre><code>environment:
PATH: /home/core/bin:$PATH
</code></pre>
<p>...you are setting your <code>PATH</code> environment variable to the <em>literal</em> value <code>/home/core/bin:$PATH</code>. In other words, you are blowing away any existing value of <code>$PATH</code>, which is why you're getting "command not found" errors for basic things like <code>basename</code>.</p>
<p>Consider installing <code>pip</code> somewhere in your existing <code>$PATH</code>, modifying <code>$PATH</code> <em>before</em> calling ansible, or calling <code>pip</code> from a shells cript:</p>
<pre><code>- name: install something with pip
shell: |
PATH="/home/core/bin:$PATH"
pip install some_module
</code></pre>
|
Splitting sidebar into top and bottom around main content with Bootstrap <p>I am trying to use Bootstrap to split a left aligned sidebar into 2 different parts whenever the screen size gets to be near mobile device resolution. <a href="http://stackoverflow.com/questions/24990775/is-there-a-way-in-bootstrap-to-split-a-column-on-small-screens/24995765">This StackOverflow post</a> sets up what I am trying to do, but as can be seen from the image below, I encounter column wrapping issues when trying to get the sidebar to display as one connected section. </p>
<p>The image below shows the top of the sidebar in green, bottom of the sidebar in blue, and the main content section outlined in red. I am just trying to connect the top and bottom of the sidebars at this particular screen size. </p>
<p><a href="https://i.stack.imgur.com/HsR5f.png" rel="nofollow">BootstrapSidebarSplitImg</a> (Can't paste img until my rep is higher.. >.< )</p>
<p>Here is the code I have pulled directly from the link I referred to earlier. The code is the same, but for some reason the bottom sidebar column is getting wrapped to the bottom of the text for the previous content section. </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-css lang-css prettyprint-override"><code>@media (min-width: 768px) {
.col-sm-pull-right {
float: right;
}
}
.lower {
clear: left;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta charset="UTF-8">
<title>test Sidebar Split</title>
<link rel="stylesheet" href="style/main.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="upper col-sm-3" style="background:red">
<h3>I want to be <b>above</b> the main content on small screens!</h3>
</div>
<div class="col-sm-9 col-sm-pull-right" style="border: 3px solid blue">
<h1>Main content</h1>
<p>Lorem ipsum dolor sit amet</p>
<p>Lorem ipsum dolor sit amet</p>
<p>Lorem ipsum dolor sit amet</p>
<p>Lorem ipsum dolor sit amet</p>
<p>Lorem ipsum dolor sit amet</p>
</div>
<div class="lower col-sm-3" style="background:green">
<h3>I want to fill the white space above!</h3>
</div>
</div>
</div>
<!-- scripts at bottom -->
<script
src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>I would prefer to find a solution that doesn't require having to do something completely different like show/hiding sections.</p>
<p>Any ideas would be greatly appreciated! Thanks!</p>
| <p>Welp, thanks to Google Chrome's developer tools I was able to find out that the code was fine, it was just getting reset during runtime by the Bootstrap code. Once I realized that, all I needed to do was add "!important" to the float right statement and it started working.</p>
<pre class="lang-css prettyprint-override"><code>@media (min-width: 768px) {
.col-sm-pull-right {
float: right !important;
}
}
.lower {
clear: left;
}
</code></pre>
|
Prevent touchStart but allow click events <p>I would like to prevent <code>touchStart</code> events in order to prevent Safari from bouncing in iOS devices under certain conditions. </p>
<p>To do so I'm using the folowing:</p>
<pre><code>$('.wrapper').on('touchstart', function(e) {
e.preventDefault();
});
</code></pre>
<p>But now none of the click events work on it:</p>
<pre><code>$('.wrapper').on('click', function() {
$('.wrapper').text('Click fired');
});
</code></pre>
<p><a href="https://jsfiddle.net/8n47whd0/4/" rel="nofollow">Reproduction online</a></p>
<p>I can not replace the <code>click</code> event for any other one. As this might come from the end user. </p>
<p>Previously to iOS 10, the bouncing <a href="http://stackoverflow.com/questions/20461485/ios-disable-bounce-scroll-but-allow-normal-scrolling">could be avoided by preventing only <code>touchMove</code></a> but since iOS 10 it will bounce unless <code>touchStart</code> is prevented too.</p>
<p>Is there any way to prevent only the <code>touchStart</code> event but allow the use of the <code>click</code> event?</p>
| <p>I don't have iOS 10 available for a test-drive, and this is a wild guess, but check this snippet:</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>$('.wrapper').on('click touchstart', function(e) {
if (e.type != 'click') {
e.preventDefault();
} else {
$('.wrapper').text('Click fired');
}
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">asd</div></code></pre>
</div>
</div>
</p>
|
Difference between a list of object types and a list of objects extending a type <p>I often encounter situations like:</p>
<pre><code>List<Fooable> fooList;
</code></pre>
<p>vs</p>
<pre><code>List<? extends Fooable> fooList;
</code></pre>
<p>What is the difference between these two? Or is there a name for this / pre-existing link where this difference is described? I can't Google this concept because I don't know what it's called or how else you'd describe this.</p>
<p>Does it matter if Fooable is an interface? A concrete class? An abstract class? Does this only apply to classes that extend and/or implement something?</p>
| <p>Well if there is no duplicate...</p>
<p>A <code>List<Animal></code> <em>can</em> contain <code>Cat</code>s and <code>Dog</code>s. You can add Cats and Dogs to the list. It does not mean it can only contain <code>Animal</code>s.</p>
<p>But if you have a method <code>foo(List<Animal> foo)</code>, you can not pass a <code>List<Cat></code> to it. But you can add <code>Cat</code>s, <code>Dog</code>s or <code>Animal</code>s to the passed <code>List<Animal></code>. </p>
<p>If you have a <code>foo(List<? extends Animal> foo)</code>, you can pass a <code>List<Animal></code>,<code>List<Dog></code>, and <code>List<Cat></code> to it and read from it, i.e. you can access <code>Animal</code>s methods. </p>
<p>But since any List of subtype of <code>Animal</code> may be passed to it (you don't know which type, it may be an <code>Animal</code>, a <code>Cat</code> or a <code>Dog</code>, or some totally different <code>Animal</code>, you cannot add any elements (except <code>null</code>) to it.</p>
|
subset whole data frame for value and return rows in which value are found <p>I am trying to subset a data frame containing 626 obs. of 149 variables and I want to look for a specific string and return the rows that have that value regardless of what column it is found in. </p>
<p>For example:</p>
<p>I am looking for this string "GO:0004674" in a data frame that can contain this string in many different columns and rows as shown below in the image link.</p>
<p><a href="https://i.stack.imgur.com/Ha7jP.png" rel="nofollow"><img src="https://i.stack.imgur.com/Ha7jP.png" alt="enter image description here"></a></p>
<p>For example the string "GO:0004674" can be found in row 12, 13 and 14. So I would want to keep only those rows and later on export them. </p>
<p>How can I perform this? All examples that I have seen thus far only look for string in a specific column and not in the whole dataframe. </p>
<p>Ant help will be greatly appreciated. </p>
| <p>You can use <code>apply</code> to do row-wise operation using the argument <code>MARGIN = 1</code>. Example:</p>
<pre><code>mydf[apply(mydf, MARGIN = 1, FUN = function(x) {"GO:0004674" %in% x}), ]
</code></pre>
|
Closed DLL still shows in GetAssemblies() list (.NET) <p>My project calls a (non-referenced) DLL project with UI. The end user is supposed to close this form before closing the main form (main project) but sometimes they do not. </p>
<p>I tried using AppDomain.GetAssemblies() to see if the DLL Form is closed. However, even when I close the DLL form, it still shows in the GetAssemblies list. My guess is it remains in the memory until some point?! </p>
<p>What is the best practice to ensure all loaded DLLS from the main project are unloaded and released in memory before allowing the closure of my main project?</p>
| <p>The only way to unload an assembly in .Net is to unload the AppDomain that it was loaded into. This means you need to load additional assemblies into their own app domains This, however, brings in additional complexity as you will not be able to share data between app domains and will have to use inter-process communication technologies to call methods from an assembly loaded into another AppDomain. Depending on your requirements, you may have to inherit your classes from MarshalByRefObject or make them [Serializable].</p>
<p>Some additional information and examples are available in this topic: <a href="http://stackoverflow.com/questions/658498/how-to-load-an-assembly-to-appdomain-with-all-references-recursively">How to Load an Assembly to AppDomain with all references recursively?</a></p>
|
Enforcing non-emptyness of scala varargs at compile time <p>I have a function that expects a variable number of parameters of the same type, which sounds like the textbook use case for varargs:</p>
<pre><code>def myFunc[A](as: A*) = ???
</code></pre>
<p>The problem I have is that <code>myFunc</code> cannot accept empty parameter lists. There's a trivial way of enforcing that at runtime:</p>
<pre><code>def myFunc[A](as: A*) = {
require(as.nonEmpty)
???
}
</code></pre>
<p>The problem with that is that it happens at <em>runtime</em>, as opposed to <em>compile time</em>. I would like the compiler to reject <code>myFunc()</code>.</p>
<p>One possible solution would be:</p>
<pre><code>def myFunc[A](head: A, tail: A*) = ???
</code></pre>
<p>And this works when <code>myFunc</code> is called with inline arguments, but I'd like users of my library to be able to pass in a <code>List[A]</code>, which this syntax makes very awkward.</p>
<p>I could try to have both:</p>
<pre><code>def myFunc[A](head: A, tail: A*) = myFunc(head +: tail)
def myFunc[A](as: A*) = ???
</code></pre>
<p>But we're right back where we started: there's now a way of calling <code>myFunc</code> with an empty parameter list.</p>
<p>I'm aware of scalaz's <code>NonEmptyList</code>, but in as much as possible, I'd like to stay with stlib types.</p>
<p>Is there a way to achieve what I have in mind with just the standard library, or do I need to accept some runtime error handling for something that really feels like the compiler should be able to deal with?</p>
| <p>What about something like this?</p>
<pre><code>scala> :paste
// Entering paste mode (ctrl-D to finish)
def myFunc()(implicit ev: Nothing) = ???
def myFunc[A](as: A*) = println(as)
// Exiting paste mode, now interpreting.
myFunc: ()(implicit ev: Nothing)Nothing <and> [A](as: A*)Unit
myFunc: ()(implicit ev: Nothing)Nothing <and> [A](as: A*)Unit
scala> myFunc(3)
WrappedArray(3)
scala> myFunc(List(3): _*)
List(3)
scala> myFunc()
<console>:13: error: could not find implicit value for parameter ev: Nothing
myFunc()
^
scala>
</code></pre>
<p>Replacing Nothing with a class that has an appropriate <code>implicitNotFound</code> annotation should allow for a sensible error message.</p>
|
Error while trying to port a repo from github <p>There is a github code I am trying to use that is located <a href="https://github.com/PX4/pyulog" rel="nofollow">here</a>.</p>
<p>I am trying to run <code>params.py</code> which is a code that will take a binary file and converts it so that I can plot it (or so I think).</p>
<p>I tried to run:</p>
<pre><code>pip install git+https://github.com/PX4/pyulog.git
</code></pre>
<p>However, that gave me an error:</p>
<pre><code>C:\Users\Mike\Documents>pip install git+https://github.com/PX4/pyulog.git
Collecting git+https://github.com/PX4/pyulog.git
Cloning https://github.com/PX4/pyulog.git to c:\users\mike\appdata\local\temp\pip-t_vvh_b0-build
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Anaconda3\lib\tokenize.py", line 454, in open
buffer = _builtin_open(filename, 'rb')
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Mike\\AppData\\Local\\Temp\\pip-t_vvh_b0-build\\setup.py'
</code></pre>
| <p>Pip install tries to install the module from :</p>
<ul>
<li>PyPI (and other indexes) using requirement specifiers. </li>
<li>VCS project urls. </li>
<li>Local project directories. </li>
<li>Local or remote source archives.</li>
</ul>
<p>When looking at the items to be installed, pip checks what type of item each is, in the following order:</p>
<ul>
<li>Project or archive URL.</li>
<li>local directory (which must contain a <strong>setup.py</strong>, or pip will report an error).</li>
<li>Local file (a sdist or wheel format archive, following the naming conventions for those formats).</li>
<li>A requirement, as specified in PEP 440.</li>
</ul>
<p>In your case, git repo doesn't meet the requirement. It doesn't have setup.py that's why you get the error.<br>
Instead try cloning the repo on your local machine.</p>
|
Batch consumer with Blocking Collection <p>I'm using Blocking Collection within a producer consumer pattern.
In order to speed up my program, i have to make the consumer process in batch: process a list of items in the blocking collection(50 item) instead of one at a time.</p>
<p>So i tried using <code>queue.Take(50)</code> instead of <code>queue.GetConsumingEnumerable()</code> method with no luck.
Is there a way to do that or should i reconsider using the Blocking Collection?</p>
| <p>Writing <code>queue.Take(50)</code> is using the LINQ <code>Take</code> method (rather than the <code>BlockingCollection</code> <code>Take</code> method) on the <em>non</em> consuming enumerable, so you'll end up getting 50 items but leaving them all in the collection.</p>
<p>If you just want to get 50 items you could use <code>queue.GetConsumingEnumerable().Take(50)</code> and then you'd be getting 50 items and ensuring that they're actually removed from the collection as you go. You'd want to materialize the query (using <code>ToList</code> or an equivalent) if you want to ensure that you've gotten all 50 items before you start processing any of them. (That likely wouldn't speed up your processing, it'd probably slow it down, but it is what you asked for.)</p>
|
Homework-Prove Big omega with witness <p>I am having trouble solving a proof. Given the situations : f(x)=x^4-50x^3+1 g(x)=x^4 we need to show that f(x)is big omega of g(x), also need to provide the witness</p>
| <p>We have that <code>f(X)>= X^4</code> for every <code>X>=1</code> which by definition means that f is Ω(n^4) (or since g(X)=n^4, f is Ω(g(X)) ).</p>
|
Within a view, how do I return the MEDIA_URL for Imagefield queryset? <p>Assume I have the following model:</p>
<pre><code>class ProductImage(models.Model):
image = models.ImageField('Product image', null=True,blank=True)
view = models.CharField(max_length=2, choices=VIEW_TYPES, default='FR', null=True,blank=True)
description = models.CharField(max_length=125, blank=True, null=True)
def __str__(self):
return self.view + "-" + self.image.url
</code></pre>
<p>I have the following queryset:</p>
<p><code>allProductImages = ProductImage.objects.all()</code></p>
<p><strong>How do I extract the MEDIA_URL + path + filename for all objects (e.g. /media/image.jpg)</strong></p>
<p>here's what I have already tried (follows on from previous queryset statement):
<code>urlValues = allImages.values('image')</code></p>
<p><code><QuerySet [{'image': 'greenSwatch.jpg'}, {'image': 'blueSwatch.jpg'}, {'image': '3037-outer-black.jpg'}, {'image': '3037-outer-black.png'}]</code></p>
<p>I'm trying to get the following:
<code><QuerySet [{'image': '/media/path/greenSwatch.jpg'}, {'image': '/media/path/blueSwatch.jpg'}, {'image': '/media/path/3037-outer-black.jpg'}, {'image': '/media/path/3037-outer-black.png'}, {'image': '/media/path/3037-inner-blue.png'}, {'image': '/media/path/3037-outer-green.png'}, {'image': '/media/path/3037-outer-blue.png'}]></code></p>
<p>Also, I know there's no upload_to parameter specified, but this is optional according to the <a href="https://docs.djangoproject.com/en/1.10/ref/models/fields/#filefield" rel="nofollow">docs</a> for Django 1.10</p>
<p>I'm running Django 1.10 + Python 3.5</p>
| <p><code>p.image.url</code> gives you the full URL for the image, given p as a ProductImage instance. Since you have a queryset, you just need to iterate through; you shouldn't use <code>values</code> though.</p>
<pre><code>allProductImages = ProductImage.objects.all()
image_urls = [p.image.url for p in allProductImages]
</code></pre>
|
Dagger 2 components chain dependencies <p>I have 3 components:
Main app component:</p>
<pre><code>@Singleton
@Component(modules = {AppModule.class, UserModule.class, DatabaseModule.class})
public interface AppComponent {
Context getContext();
DatabaseHelper getDatabaseHelper();
UserManager getUserManager();
}
</code></pre>
<p>Repository component:</p>
<pre><code>@DataScope
@Component(dependencies = AppComponent.class, modules = CategoryRepositoryModule.class)
public interface CategoryRepositoryComponent {
CategoryRepository getCategoryRepository();
}
</code></pre>
<p>And screen component:</p>
<pre><code>@MenuScope
@Component(dependencies = CategoryRepositoryComponent.class, modules = {MenuModule.class, DrawerModule.class})
interface MenuComponent {
void inject(MenuActivity activity);
}
</code></pre>
<p>The problem is that my MenuComponent cannot see dependencies that provides AppComponent. But MenuComponent depend on CategoryRepositoryComponent and CategoryRepositoryComponent depend on AppComponent, so MenuComponent should see AppComponent(MenuComponent -> CategoryRepositoryComponent -> AppComponent). </p>
<p>If I will add getters to CategoryRepositoryComponent </p>
<pre><code>@DataScope
@Component(dependencies = AppComponent.class, modules = CategoryRepositoryModule.class)
public interface CategoryRepositoryComponent {
CategoryRepository getCategoryRepository();
DatabaseHelper getDatabaseHelper();
UserManager getUserManager();
}
</code></pre>
<p>But thats looks incorrect, duplicates. Do you know how to resolve this problem in a clean, correct way? </p>
<p>Thanks,
Nick.</p>
| <p>Your approach is correct. Components only have access to the types explicitly exposed by their direct parent component. </p>
<p>This can be useful when, as a parent, you don't want to expose all of your dependencies to whoever depends on you. For example, a <code>Parent</code> may depend on a BankComponent and not want to expose <code>BankAccount</code> to its <code>Children</code>. </p>
<p>An alternative approach is to use <code>Subcomponent</code>. The docs and this other answer will help understand: <a href="http://stackoverflow.com/questions/29587130/dagger-2-subcomponents-vs-component-dependencies">Dagger 2 subcomponents vs component dependencies</a>.</p>
|
How to cast NSData to Data <p>I have created array of UInt8</p>
<pre><code>var pixels: [UInt8] = []
</code></pre>
<p>filled by alpha, red, green and blue components and need to create NSImage from he array. I wrote following code</p>
<pre><code>let imageData = NSData(bytes: pixels, length: 1000)
Swift.print(imageData)
newImage = NSImage(data: imageData as Data)!
</code></pre>
<p>where print command prints my bytes like ff0493f8 ff455772 ffa281ed ff9c14d7 ff6eb302... but creating of newImage fails with error "fatal error: unexpectedly found nil while unwrapping an Optional value".
What I did wrong?
Thanks.</p>
| <p>You have a few issues.</p>
<ol>
<li>Why use <code>NSData</code> at all? Just use <code>Data</code>.</li>
<li>Your error is the fact that <code>imageData</code> doesn't actually represent a valid image so <code>NSImage</code> is <code>nil</code> but you try to force unwrap it.</li>
</ol>
<p>Try something like this:</p>
<pre><code>let imageData = Data(bytes: pixels)
Swift.print(imageData)
if let newImage = NSImage(data: imageData) {
// Do something with the image
} else {
// oops - can't create the image
}
</code></pre>
|
How to access a dictionary value with Swift 3? <p>So since the release of Swift 3, a part of my code where I access a dictionary isn't working anymore, here is the code with the previous release of swift:</p>
<pre><code>var locationDict: NSDictionary?//location dictionary
if let getLocation = item.value?["Location"]{locationDict = getLocation as? NSDictionary}
//get dictionary values
let getLatitude = locationDict?.valueForKey("latitude") as! Double
let getLongitude = locationDict?.valueForKey("longitude") as! Double
</code></pre>
<p>Now with the new release I'm not sure how to rewrite "getLocation". I only rewrote the last two lines with the new syntax:</p>
<pre><code>//get dictionary values
let getLatitude = locationDict?.value(forKey: "latitude") as! Double
let getLongitude = locationDict?.value(forKey: "longitude") as!
</code></pre>
<p>I am using Firebase, this is the complete function: (it adds an array of annotations to a map)</p>
<pre><code> func setAnnotations(){
//get data
ref.child("Stores").observe(.value, with: { (snapshot) in
self.mapView.removeAnnotations(self.annArray)
for item in snapshot.children {
let annotation = CustomAnnotation()
//set all data on the annotation
annotation.subtitle = (snapshot.value as? NSDictionary)? ["Category"] as? String
annotation.title = (snapshot.value as? NSDictionary)? ["Name"] as? String
annotation.annImg = (snapshot.value as? NSDictionary)? ["Logo"] as? String
var locationDict: NSDictionary?//location dictionary
if let getLocation = item.value?["Location"]{locationDict = getLocation as? NSDictionary}
let getLatitude = locationDict?.value(forKey: "latitude") as! Double
let getLongitude = locationDict?.value(forKey: "longitude") as! Double
annotation.coordinate = CLLocationCoordinate2D(latitude: getLatitude, longitude: getLongitude)
self.annArray.append(annotation)
self.mapView.addAnnotation(annotation)
}
})
}
</code></pre>
| <p>Try this:- </p>
<pre><code> func setAnnotations(){
//get data
FIRDatabase.database().reference().child("Stores").observe(.value, with: { (snapshot) in
self.mapView.removeAnnotations(self.annArray)
for item in snapshot.children{
if let itemDict = (item as! FIRDataSnapshot).value as? [String:AnyObject]{
annotation.subtitle = itemDict["Category"] as! String
annotation.title = itemDict["Name"] as! String
annotation.annImg = itemDict["Logo"] as! String
if let locationDict = itemDict["Location"] as? [String:AnyObject]{
let getLatitude = locationDict["latitude"] as! Double
let getLongitude = locationDict["longitude"] as! Double
annotation.coordinate = CLLocationCoordinate2D(latitude: getLatitude, longitude: getLongitude)
self.annArray.append(annotation)
self.mapView.addAnnotation(annotation)
}
}
}
})
}
</code></pre>
|
Wrong direction of movement after changing node's velocity <p>After a node (car) collides into a "speed up" type of obstacle, it should speed up. Instead it slows down and starts moving out of the straight line. I checked if code is properly executed and it is, I assume the problem is with the coordinate system of the node or something of similar nature.</p>
<p>In <code>SceneKit</code>, y-axis represents the axis that point upwards and in my case, everything is happening on a plane with x-axis pointing in the direction of cars movement and z-axis for left/right direction of movement. </p>
<p>Before and after changing the velocity, I print out its velocity with this code:</p>
<pre><code>print(car.physicsBody?.velocity)
car.physicsBody?.velocity.x += 0.2
print(car.physicsBody?.velocity)
</code></pre>
<p>The output is:</p>
<pre><code>SCNVector3(x: 0.245669901, y: -0.120455861, z: 0.119086474) and
SCNVector3(x: 0.445669889, y: -0.120455861, z: 0.119086474).
</code></pre>
<p>So the car's x component does increase but does not cause him to move in the desired direction. As I said, the world's x-ray does point in the direction I want the car to continue moving. The car is also moving in the right direction before increasing the velocity.</p>
<p>I want to understand why does increasing car's velocity slow it down and why does it sometimes make it move in slight right/left as if the velocity vector is not applied in the same position as before.</p>
<p>I did try to apply a force at car's center before, with this code:</p>
<pre><code>car.physicsBody?.applyForce(SCNVector3(0.2, 0, 0), at: car.presentation.position, asImpulse: true)
</code></pre>
<p>and this code (without applying at position):</p>
<pre><code>car.physicsBody?.applyForce(SCNVector3(0.2, 0, 0), asImpulse: true),
</code></pre>
<p>but they both gave the car similar weird behaviors.</p>
<p>Am I doing something wrong? What else can I try?</p>
| <p>I am not familiar with SceneKit. But if you add a value to a component of a vector without changing the other components then the direction of the vector changes.</p>
<p>If you want to make the vector longer by a certain factor without changing its direction you have to multiply all components by that factor.</p>
|
layout_gravity="bottom" doesn't work <p>Hello stackoverflow community!
I'm newbie both in programming and on this site, but let's get to the point.
I wrote an app:</p>
<pre><code> <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:orientation="horizontal"
android:layout_marginTop="10dp">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:orientation="vertical"
tools:context="com.example.android.courtcounter.MainActivity"
android:padding="24dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:padding="4dp"
android:text="Team A"
android:textSize="14sp"
android:fontFamily="sans-serif-medium"/>
<TextView
android:id="@+id/team_a_score"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:padding="4dp"
android:text="0"
android:textSize="56sp"
android:textColor="#000000"
android:fontFamily="sans-serif-light" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:onClick="plus3a"
android:text="+3 Points" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:onClick="plus2a"
android:text="+2 Points" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:onClick="plus1a"
android:text="Free throw" />
</LinearLayout>
<View
android:layout_width="1dp"
android:background="@android:color/darker_gray"
android:layout_height="match_parent">
</View>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:orientation="vertical"
tools:context="com.example.android.courtcounter.MainActivity"
android:padding="24dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:padding="4dp"
android:text="Team B"
android:textSize="14sp"
android:fontFamily="sans-serif-medium"/>
<TextView
android:id="@+id/team_b_score"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:padding="4dp"
android:text="0"
android:textSize="56sp"
android:textColor="#000000"
android:fontFamily="sans-serif-light"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:onClick="plus3b"
android:text="+3 Points" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:onClick="plus2b"
android:text="+2 Points" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:onClick="plus1b"
android:text="Free throw" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center_horizontal"
android:onClick="scoreReset"
android:text="reset" />
</LinearLayout>
</LinearLayout>
</code></pre>
<p>I have a problem with positioning a button at the end.
I want it to be at the bottom of a screen and centered horizontally.
I know I could use relative layout but I decided to check if I can do this using linear layout. And seems that I can't... "bottom" attribute is being ignored.</p>
| <p>This should work : </p>
<pre><code><LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="bottom|center">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center|bottom"
android:onClick="scoreReset"
android:text="reset"/>
</LinearLayout>
</code></pre>
|
Conditionals are true but are returning false <p>When debugging, <code>$var</code> is not equivalent to "<code>folder\that\isNot\equivalent\".</code></p>
<p>I have tried changing it to an equivalency statement, but it is not working. Any insight would be appreciated.</p>
<p>Here is all the relevant code:</p>
<pre><code>$process = "Explorer++.exe"
$var = Get-WmiObject Win32_Process -Filter "name = '$process'" | select -expandproperty CommandLine
$var = $var -split '\\\\' | select -Last 1
Write-Host $var
if ($var -ne "folder\that\isNot\equivalent\")
{
Stop-Process -processname explorer++
Stop-Process -processname curProc
}
else
{
return $true
}
</code></pre>
| <p>The issue was whitespace surrounding the $var. I used the command <code>$var = $var -replace "\s",""</code></p>
<p>That replaces every space symbol with an empty string, I also changed it to an equivalency statement. </p>
<p><code>if ($var -eq "\folder\that\is\")</code></p>
|
Render a React element inside a React component <p>OK I'm trying to pass a component inside an object I use as a parameters to an action I'm triggering.</p>
<pre><code>this.context.alt.actions.notificationActions.logMessage({
component: <ModalLayoutEditorComments subscription="pop-up" contextualClass="info" callback={this._submitCaisseChangeAction} />,
subscription: 'pop-up',
});
</code></pre>
<p>Inside the target component I receive the object as props with the component which is now React Element.</p>
<p><a href="https://i.stack.imgur.com/8lfYZ.png" rel="nofollow"><img src="https://i.stack.imgur.com/8lfYZ.png" alt="React element inside object"></a></p>
<p>Now I would to know how I can convert this React element inside another React component if possible?</p>
<pre><code> render() {
const Component = this.props.notifications[0].component;
return (
<div>
{Component}
</div>
);
}
</code></pre>
| <p>Your <code>render</code> logic is OK. It looks like you are using the wrong prop:</p>
<pre><code>render() {
return (
<div>
{this.props.notifications[0].component}
</div>
);
}
</code></pre>
<p>As an aside, <code>component</code> is quite a confusing property name. The object is a React element, which is a <a href="https://facebook.github.io/react/blog/2015/12/18/react-components-elements-and-instances.html#elements-describe-the-tree" rel="nofollow">description of a Component instance</a>.</p>
|
run bash (command line) inside emacs text editor? <p>i want to run command line inside emacs text editor .
i have just finished the emacs tutorial i want to practice in some SQL files and i need the command line near to me to see SQL changes and results
any idea ?
is this a profesional step i can't understand it now ?</p>
| <p><a href="http://www.nongnu.org/emacsdoc-fr/manuel/shell.html" rel="nofollow">http://www.nongnu.org/emacsdoc-fr/manuel/shell.html</a> There you have some tips how to or basicaly run 2 terminals on one Computer(Subshells)</p>
<p>or GNU documentation website of emacs with some valuable links for shells
<a href="https://www.gnu.org/software/emacs/manual/html_node/emacs/Shell.html" rel="nofollow">https://www.gnu.org/software/emacs/manual/html_node/emacs/Shell.html</a></p>
|
Is it possible to use Spring MVC with Jersey annotations? <p>I am wondering, if it's possible to use Spring Web MVC with Jersey annotations, as I'm having a massive problem with Spring not being able to parse part variables the way Jersey can and I need to migrate some Jersey code to Spring MVC.</p>
<p>I have the following code in Jersey:</p>
<pre><code>@PUT
@Path("{storageId}/{repositoryId}/{path:.*}")
@PreAuthorize("hasAuthority('ARTIFACTS_DEPLOY')")
public Response upload(@PathParam("storageId") String storageId,
@PathParam("repositoryId") String repositoryId,
@PathParam("path") String path,
InputStream is)
{
...
}
</code></pre>
<p>I would like to convert this over to Spring MVC, but, like I've explained in this <a href="http://stackoverflow.com/questions/40091229/how-to-get-a-path-variable-that-is-the-remainder-of-the-path-in-spring-mvc">SO</a> post, I'm experiencing issues with parsing the path variables.</p>
<p>Hence, my wondering (and a separate question): is it possible to use the same Jersey annotations with Spring MVC?</p>
| <p>it's possible to use Spring Web MVC with Jersey annotations, try make a little sample in <a href="https://start.spring.io/" rel="nofollow">Spring Initializer </a> there you can check the option jersey, see how spring build this project and try in yours</p>
|
Cognos: Using rank() across multiple columns to order bar chart <p>I have some example data like this table:</p>
<p><img src="https://i.stack.imgur.com/GyXDf.png" alt="table"></p>
<p>where the left table is currently the data I have and I want to order by year, company, and product (based on total cost). Currently, the user chooses the year and company on the prompt screen and I am trying to obtain something like a top ten list per year per company based on the total cost per product. I would like my data to sort to the table on the right with keeping track of the billing code area, but not sorting by it. I have been able to write a SQL code that will sort it using a group by, but I cannot add the billing code area. I need the billing code area to display the information in a bar chart.
I have tried using the rank function in Cognos, but I can only do it for one column. I have also tried concatenating the 3 columns together, but no luck with that either. Is there any way to use rank() for 3 columns?</p>
| <p>Looks like you have two different tasks:</p>
<ol>
<li><p>Calculate top 5
AFAIR you can use rank() like this:</p>
<pre><code>rank([total_cost] for [Country],[Year],[Product])
</code></pre></li>
<li><p>List all billing area codes. It's not so simple. There is no special function for it (shame on them). So you can write custom query for it using features of you DB or, better, fake concatenation with repeater object or crosstab with master-detail relationship inserted in Billing Area Code field.</p></li>
</ol>
|
Semantic-UI - Links / A Tags / URLs Inside Semantic Ui Dropdown Menu Do Not Work <p>I am working with Semantic UI in a rails project and wanted to create a dropdown menu with items that would link to other view pages. Most of the problems i've seen with the dropdown stemmed from users not initializing the dropdown menu which I was able to do.</p>
<p>Here's my code:</p>
<pre><code> <div class="ui floating dropdown button">
Course<i class="dropdown icon"></i>
<div class="menu">
<% @topics.each { |topic| %>
<a class="item" href="articles/<%= topic.id %>">
<span class="text"> <%= topic.name %></span>
</a>
<% } %>
</div>
</div>
</code></pre>
<p>Different things i've tried:</p>
<ul>
<li>Creating a separate hardcoded links / a tags like <code><a href="articles/4"></code> outside of the dropdown menu. This creates a working link and directs me to the article show view page with the id of 4. </li>
<li>Changed the wrapping 's class as <code>"ui floating dropdown item"</code> as well</li>
</ul>
<p>I've also looked up other users' posts that shows they have the same exact problem. But when i try their solution, my dropdown menu items still do not work and i'm not sure what i'm doing wrong. Here are their posts:</p>
<ul>
<li><a href="https://github.com/Semantic-Org/Semantic-UI/issues/3234" rel="nofollow">https://github.com/Semantic-Org/Semantic-UI/issues/3234</a></li>
<li><a href="https://github.com/Semantic-Org/Semantic-UI/issues/453" rel="nofollow">https://github.com/Semantic-Org/Semantic-UI/issues/453</a></li>
</ul>
<p>The two most important things seem to be:</p>
<ol>
<li>Not putting the dropdown class definition as part of an anchor tag (inserting an anchor tag inside an anchor tag in the dropdown menu)</li>
<li>Not surrounding each anchor tags with their own <code><div class="items"></code> tags but to integrate them into one line like <code><a class="item" href="#"> # </a></code></li>
</ol>
<p>Can anyone help me understand what i might be overlooking? Let me know if i left out any critical information, would love to update the post with the relevant data right away, thank you!</p>
| <p>After doing more and more research, I came to the conclusion that the links were not working in my semantic-ui dropdown menu because of some code, most likely Javascript, that i had inserted before.</p>
<p>Of course, i ruled this way out of the realm of possibility because there was no way i would forget about such code but i decided to go through all of my .js files just in case.</p>
<p>Lo and behold, i had a jQuery selector <code>return false</code> when a <code>.item</code> was being clicked...</p>
<p>I felt really silly and i didnt want to believe it at first but if you're having this problem and you've checked everything else like i have, it's <strong><em>probably</em></strong> your javascript!</p>
|
Twilio as a proxy for many-to-many SMS conversations <p>What is the best way to proxy marketplace messaging using SMS? </p>
<p><strong>User Model:</strong>
each conversation has <code>owner_id</code> and <code>renter_id</code>, if a message is received from one it should be proxied to the other. </p>
<p><strong>If the owner is connected to many conversations</strong>, what is the best way to make sure the messages are directed to the proper recipient?</p>
<p><strong>Update:</strong>
<a href="http://stackoverflow.com/questions/22619529/twilio-as-a-proxy-for-one-to-many-sms-conversations">It looks like twilio recommends purchasing a phone number for each conversation.</a> </p>
<p>This would require owning <code>N</code> phone numbers where <code>N</code> is greater than the conversations grouped by unique user/recipient. </p>
<p>For example with Airbnb data model, would need to know the owner with the largest number of unique renters... This seems like a lot of potential overhead. please correct me if i'm wrong. </p>
| <p>This concept will definitely require multiple Twilio numbers if you want to give a friction less experience (no PINs to enter ) , but you will only ever need to have as many numbers as people who a single user can contact.
This is explained in more detail <a href="https://support.twilio.com/hc/en-us/articles/223134067-How-users-can-send-text-messages-to-each-other-over-Twilio" rel="nofollow">here</a> . And you only need to work out a starting number and rest can be dynamic .</p>
<p>Say, if you maximum number of property any owner owns is N and he rents out on all 365 days to different renters , it means the owner has N*365 renters in their "address book", you would only ever need 365N numbers, even if you had 100,000 users. If based on historical data , you could work out maximum of N and maximum of rental days ( say M) , you have the required phone numbers = N*M . This could be the starting point and doesnt have to be a fixed constant value .</p>
<p>As a fail safe - add a handler to when you cross a threshold - say 90% of your number pool of N*M numbers , then use the <a href="https://www.twilio.com/docs/api/rest/available-phone-numbers" rel="nofollow">Twilio REST API to add numbers</a> dynamically to this pool . </p>
|
Python - insert lines on txt following a sequence without overwriting <p>I want to insert the name of a file before each file name obtained through glob.glob, so I can concatenate them through FFMPEG by sorting them into INTRO+VIDEO+OUTRO, the files have to follow this order:</p>
<p>INSERTED FILE NAME<br>
FILE<br>
INSERTED FILE NAME<br>
INSERTED FILE NAME<br>
FILE<br>
INSERTED FILE NAME<br>
INSERTED FILE NAME<br>
FILE<br>
INSERTED FILE NAME<br></p>
<p>This is this code I'm using:</p>
<pre><code>import glob
open("Lista.txt", 'w').close()
file = open("Lista.txt", "a")
list =glob.glob("*.mp4")
for item in list:
file.write("%s\n" % item)
file.close()
f = open("Lista.txt", "r")
contents = f.readlines()
f.close()
for x,item in enumerate(list):
contents.insert(x, "CTA\n")
f = open("Lista.txt", "w")
contents = "".join(contents)
f.write(contents)
print f
f.close()
</code></pre>
<p>But I obtain the values in the wrong order:<br></p>
<p>INSERTED FILE NAME<br>
INSERTED FILE NAME<br>
INSERTED FILE NAME<br>
FILE<br>
FILE<br>
FILE
<br></p>
<p>How could I solve this?
EDIT: As pointed out, maybe the issue is being caused by modifying a list that I'm currently using.</p>
| <p>You are trying to modify <code>contents</code> list. I think if new list is used to get final output, then it will be simple and more readable as below. And as <strong>Zen of Python</strong> states</p>
<p><strong>Simple is always better than complex.</strong> </p>
<ol>
<li>Consider you got <code>file_list</code> as below after doing <code>glob.glob</code>.</li>
</ol>
<blockquote>
<p>file_list = ["a.mp4","b.mp4","c.mp4"]</p>
</blockquote>
<ol start="2">
<li>Now you want to add "<code>INSERTFILE</code>" before and after every element of <code>file_list</code> so that final_list will look like </li>
</ol>
<blockquote>
<p>final_list = ['INSERTFILE', 'a.mp4', 'INSERTFILE', 'INSERTFILE',
'b.mp4', 'INSERTFILE', 'INSERTFILE', 'c.mp4', 'INSERTFILE']</p>
</blockquote>
<ol start="3">
<li>This final_list you will write to file.</li>
</ol>
<p><strong><em>Problem summary is how to achieve step 2.</em></strong></p>
<p>Below code will get step 2.</p>
<p><strong>Code (with comments inline:</strong></p>
<pre><code>#File List from glob.glob
file_list = ["a.mp4","b.mp4","c.mp4"]
#File to be added
i = "INSERTFILE"
final_list = []
for x in file_list:
#Create temp_list
temp_list = [i,x,i]
#Extend (not append) to final_list
final_list.extend(temp_list)
#Clean temp_list for next iteration
temp_list = []
print (final_list)
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>C:\Users\dinesh_pundkar\Desktop>python c.py
['INSERTFILE', 'a.mp4', 'INSERTFILE', 'INSERTFILE', 'b.mp4', 'INSERTFILE', 'INSERTFILE', 'c.mp4', 'INSERTFILE']
</code></pre>
|
Render the DepthTexture from a FrameBuffer <p>Hello I am trying to implement shadows in openGL using C++.
I created a FrameBuffer and a DepthTexture. Every frame I<code>m rendering my entities to the FrameBuffer. For now I</code>m just displaying the texture on the screen like any other GUI, but the texture is completely white and it's not changing when I move the camera around. I hope you can help me find the problem.</p>
<p>My Code:</p>
<pre> <code>
//Creating FrameBuffer + Texture
glGenFramebuffers(1, &depthMapFBO);
glGenTextures(1, &depthMap);
glBindTexture(GL_TEXTURE_2D, depthMap);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32, m_width, m_height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO);
glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthMap, 0);
glDrawBuffer(GL_NONE);
glReadBuffer(GL_NONE);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
</code> </pre>
<p>In the renderer:</p>
<pre> <code>
glm::mat4 lightSpaceMatrix = glm::ortho(-10.0f, 10.0f, -10.0f, 10.0f, Camera::ZNEAR, Camera::ZFAR) * glm::lookAt(m_position, m_position + m_forward, m_up);
m_shader.Bind();
m_shader.loadMat4("lightSpaceMatrix", lightSpaceMatrix);
//Bind the FrameBuffer
glViewport(0, 0, m_width, m_height);
glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO);
glClear(GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
//Render all Entitys
for (auto entity : m_entitys) {
m_shader.loadMat4("model", entity->getTransform()->getModel());
entity->getTexturedModel()->getMesh()->Draw();
}
//Unbind the FrameBuffer
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0, 0, Setting::width, Setting::height);
m_shader.unbind();
</code> </pre>
<p>My Vertex Shader:</p>
<pre> <code>
#version 430
in layout(location=0) vec3 position;
uniform mat4 lightSpaceMatrix;
uniform mat4 model;
void main()
{
gl_Position = lightSpaceMatrix * model * vec4(position, 1.0f);
}
</code> </pre>
<p>My Fragment Shader:</p>
<pre> <code>
#version 430
void main()
{
gl_FragColor = vec4(1);
}
</code> </pre>
| <p>After using my normal projection matrix instead of the orthographical matrix it worked fine. So I experimented a bit and the near and far plane were set to 0 when I created the orthographical matrix. I fixed it and its now working. Thank you for your help.</p>
|
Modifying Android Search for ListView <p>I'm new to android app development and currently trying to figure out how to add search to an app. I did some searching and the tutorial that was the simplest for me to understand is <a href="https://www.beginnersheap.com/android-searchview-tutorial-android-search-bar-example/" rel="nofollow">here</a>. </p>
<p>The app runs and searches as it should. The only issue is that the tutorial is for searching a ListView. The activity that my app's search is hosted in has other details(itemview, textview) that need to be on the screen so a ListView won't work for what I'm trying to do. How do I modify this example to provide a dropdown of suggestions as the user types into the search box? Ideally, I would like a search as seen in this <a href="https://androidhub.intel.com/library/nglauber/AndroidSearch_1.png" rel="nofollow">image here</a>.</p>
<p>ItemSearch.java</p>
<pre><code>import android.app.SearchManager;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.List;
public class ItemSearch extends AppCompatActivity {
ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.item_search_activity);
final String[] months = {"January", "February", "March", "April",
"May", "June", "July", "August", "September", "October",
"November", "December"};
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, months);
final ListView listview = (ListView) findViewById(R.id.listView1);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
String text = (String) listview.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), text,
Toast.LENGTH_SHORT).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_search, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
return true;
}
}
</code></pre>
<p>item_search_acitivity.xml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true">
<RelativeLayout 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:id="@+id/item_view_activity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.me.ItemSearch">
<ImageView
/>
<ImageView
/>
<ImageView
/>
<TextView
/>
<TextView
/>
<TextView
/>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/listView1"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
</ScrollView>
</code></pre>
<p>menu_search.xml under res/menu/menu_search</p>
<pre><code><menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="@+id/search"
android:title="@string/hint_search"
android:icon="@android:drawable/ic_menu_search"
app:showAsAction="collapseActionView|ifRoom"
app:actionViewClass="android.support.v7.widget.SearchView" />
</menu>
</code></pre>
<p>searchable.xml under res/xml/searchable</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="@string/app_name"
android:hint="@string/search_hint"
android:searchSuggestIntentAction="android.intent.action.VIEW">
</searchable>
</code></pre>
<p>In AndroidManifest.xml I've added</p>
<pre><code><activity android:name=".ItemSearch" android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data android:name="android.app.searchable"
android:resource="@xml/searchable"/>
</activity>
</code></pre>
| <p>For this type of dropdown suggestion functionality you would use <code>AutoCompleteTextView</code>.</p>
<p>Example usage below:</p>
<p>In your layout file:</p>
<pre><code><AutoCompleteTextView
android:id="@+id/auto_complete_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/key"/>
</code></pre>
<p>In a resource file such as <code>arrays.xml</code> or <code>strings.xml</code>:</p>
<pre><code><string-array name="suggestions">
<item>January</item>
<item>February</item>
<item>March</item>
...
</string-array>
</code></pre>
<p>In your fragment or activity:</p>
<pre><code>AutoCompleteTextView autoCompleteTv;
...
AutoCompleteTextView autoCompleteTv = (AutoCompleteTextView) view.findViewById(R.id.auto_complete_tv);
autoCompleteTv.setAdapter(ArrayAdapter.createFromResource(view.getContext(), R.array.suggestions, android.R.layout.simple_dropdown_item_1line));
</code></pre>
|
Why is my JavaFX window not the right width? <p>When I make a JavaFX window:</p>
<pre><code> Scene scene = new Scene(pane, 600, 800);
primaryStage.setResizable(false);
primaryStage.setScene(scene);
primaryStage.show();
</code></pre>
<p>The resulting window is about 610 pixels wide.</p>
<p> </p>
<p>If I use setWidth:</p>
<pre><code> Scene scene = new Scene(pane, 600, 800);
primaryStage.setResizable(false);
primaryStage.setWidth(600);
primaryStage.setScene(scene);
primaryStage.show();
</code></pre>
<p>The window ends up being about 594 pixels wide.</p>
<p> </p>
<p>Why does this happen, and how can I get my window to be the correct size?</p>
| <p>Apparently it's <a href="http://stackoverflow.com/questions/20732100/javafx-why-does-stage-setresizablefalse-cause-additional-margins">a long standing bug</a> that happens when setResizable is used.</p>
<p>I fixed it by using the sizeToScene function.</p>
<pre><code> Scene scene = new Scene(pane, 600, 800);
primaryStage.setResizable(false);
primaryStage.sizeToScene();
primaryStage.setScene(scene);
primaryStage.show();
</code></pre>
|
Java, prevent class from calling a public method <p>For an assignment I have to write code for a "State" class that has all the attributes about position of an airplane. </p>
<p>The Javadoc is already written up and must be strictly adhered to. All the set methods are public but must throw an exception if any class other than Airplane try to use them. </p>
<p>I can't change the structure of either class at all or the visibility. My professor said to use either a "clone" or a boolean somehow. How would I go about doing this?</p>
<pre><code>public void setSpeed(double speed)
{
if(method called by any class other than Airplane.java)
{
//throw exception
}
else
{
//continue setting speed
}
}
</code></pre>
| <p>I agree that this requirement is nonsense but this could do it:</p>
<pre><code>public void setSpeed(double speed)
{
if(!Airplane.class.equals(Thread.getCurrentThread().getStacktrace()[1].getClass()))
{
//throw exception
</code></pre>
|
How can you seed a first item with bufferWithCount in rx.js? <p>Say you do something like:</p>
<pre><code>Rx.Observable.range(1, 5).bufferWithCount(2, 1).subscribe(console.log);
</code></pre>
<p>This returns:</p>
<pre><code>[1, 2]
[2, 3]
[3, 4]
[4, 5]
[5]
</code></pre>
<p>I'd like for the result to look like (basically force the first value to emit):</p>
<pre><code>[<userDefined>, 1]
[1, 2]
[3, 4]
etc...
</code></pre>
| <p>How about:</p>
<pre><code>Rx.Observable.range(1, 5)
// Note this value will get used for every subscription
// after it is defined.
.startWith(userDefined)
.bufferWithCount(2, 1)
.subscribe(console.log);
</code></pre>
|
What exactly does `: class` do in a protocol declaration? <p>This <a href="http://stackoverflow.com/questions/24066304/how-can-i-make-a-weak-protocol-reference-in-pure-swift-w-o-objc">SO post</a> explains pretty well how to solve the issue of creating a <code>delegate</code> that is <code>weak</code>.</p>
<p>Essentially, there are 2 approaches:</p>
<p><strong>Using the <code>@objc</code> keyword:</strong></p>
<pre><code>@objc protocol MyClassDelegate {
}
class MyClass {
weak var delegate: MyClassDelegate?
}
</code></pre>
<p><strong>Using the <code>:class</code> keyword:</strong></p>
<pre><code>protocol MyClassDelegate: class {
}
class MyClass {
weak var delegate: MyClassDelegate?
}
</code></pre>
<p>I am trying to do some research to understand what exactly the differences between the two approaches are. The <a href="https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html" rel="nofollow">docs</a> are pretty clear about using <code>@objc</code>:</p>
<blockquote>
<p>To be accessible and usable in Objective-C, a Swift class must be a descendant of an Objective-C class or it must be marked <code>@objc</code>.</p>
</blockquote>
<p>However, nowhere I found some information about what <code>:class</code> actually does. Considering the whole notion in detail, it actually doesn't make a lot of sense to. My understanding is that <code>class</code> is a keyword in Swift to declare classes. So, here it seems like we are using the keyword <code>class</code> itself as a protocol (as we're appending it after the <code>:</code> after the protocol declaration). </p>
<p>So, why does this even work syntactically and what exactly does it do?</p>
| <p><code>:class</code> ensures that only classes can implement the protocol. And that's <em>any</em> class, not just subclasses of <code>NSObject</code>. <code>@objc</code>, on the other hand, tells the compiler to use Objective-C-style message passing to call methods, instead of using a vtable to look up functions.</p>
|
Detect shadowed java bean property <p>Is there an easy way (idealy existing helper library) to detect shadowed attributes of a java bean given it has multiple level of hierarchy?</p>
<p>[C] extends [B] extends [A].
Then attribute [A].firstName is defined.</p>
<p>I want to detect beans where [C].firstName is redefined (which is likely a developer error) inside a generic jUnit test so this kind of "hard to find bug" is catched by the build process.</p>
<p>Note: in Eclispe IDE this is equivalent to "Field declaration hides another field or variable" under Java/Compiler/Errors/Name shadowing and conflicts.</p>
| <p>Typically you wouldn't put this in a unit test, rather you'd put something like <a href="http://checkstyle.sourceforge.net/" rel="nofollow">Checkstyle</a> in your integration build process which will flag the same issue. </p>
|
Why is & being converted to &amp? <pre><code>$file="csv.php?task=whovotedwho&election=7";
$filename = "whovotedwho-election7.csv";
if (file_exists("trash.png")) {
header('Content-Description: File Transfer');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="'.($filename).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize("trash.png"));
readfile($file);
exit;
} else { echo "file does not exist"; }
</code></pre>
<p>I get this result in the csv that downloads.</p>
<p><a href="https://i.stack.imgur.com/aYvcf.png" rel="nofollow"><img src="https://i.stack.imgur.com/aYvcf.png" alt="double amp in code"></a></p>
| <p>This:</p>
<pre><code>$file="csv.php?task=whovotedwho&election=7";
</code></pre>
<p>It's not a full/absolute url like <code>http://example.com/csv.php...</code>, so when readfile() kicks in, it's doing a <strong>LOCAL</strong> file request, and looking for a file whose name is literally <code>csv.php?tasketc...</code> It's <strong>NOT</strong> doing an http request - it can't. you didn't provide a protocol, or a host, for that http request to get sent TO.</p>
<p>PHP is not like your browser, where something like <code><img src=kittens.jpg></code> is internally translated into <code><img src="http://example.com/kittens.jpg"></code>.</p>
<p>And frankly, even if you had a full URL there, it's VERY painful to do so - you're already executing code on the exact SAME server you'd be doing the http request so, so it's like hopping in your car and driving 500 miles around the city, just so you could park 1 foot to the left of where you started out on.</p>
<p>And what you're seing in your errors is the raw HTML. Since your filename has <code>&</code> in it, it has to get HTML-encoded so it appears as a literal <code>&</code> in the output, and isn't RENDERED as an html entity.</p>
|
jQuery iFrame Variable from Text File in Wordpress <p>I am trying embed videos using a set of urls and parameters stored in a text file in Wordpress that change at random on F5 refresh. I am not a coder but I think I am close, but wrong and the example is here:</p>
<p><a href="http://aaaad.com/jquery-forum-post/" rel="nofollow">http://aaaad.com/jquery-forum-post/</a></p>
<p>I have tried a lot of different approaches but cannot seem to get the parameters passed correctly from the file to display the random video and parameters on refresh in the second video frame. From the link above:</p>
<ul>
<li>the first video is an iframe embed command with start and stop parameters and works fine</li>
<li>the second video is an attempt to use the var of "video" to use as the beginning of the src= values </li>
<li>at the bottom is a random line from the file that changes correctly using div class on refresh of the page that works like I want the video link to. </li>
</ul>
<p>Any help to redirect my obviously incorrect approach is appreciated. Here is the code:</p>
<p><code><iframe width="854" height="480" src="https://www.youtube.com/embed/ad5pmvJ0zMQ?start=1&end=23" frameborder="0" allowfullscreen></iframe></code></p>
<pre><code>`<iframe width="854" height="480" src=$video frameborder="0" allowfullscreen></iframe>
<div class="video"></div>
<script type="text/javascript" src="js/jquery.js"></script>
<script>// <
jQuery(document).ready(function($) {
$.get('/wp-content/slap/video.txt', function(data) {
var video = data.split("@");
var idx = Math.floor(video.length * Math.random());
$('.video').html(video[idx]);
});
});
</script>
</code></pre>
<p>`
Contents of video.txt</p>
<pre><code>"https://www.youtube.com/embed/ad5pmvJ0zMQ?start=398&end=418"@
"https://www.youtube.com/embed/ad5pmvJ0zMQ?start=39&end=41"@
"https://www.youtube.com/embed/ad5pmvJ0zMQ?start=98&end=108"@
"https://www.youtube.com/embed/ad5pmvJ0zMQ?start=60&end=67"@
"https://www.youtube.com/embed/ad5pmvJ0zMQ?start=7&end=20"
</code></pre>
<p>Thanks again for any help,</p>
| <p>Couple of things I've spotted.. </p>
<ol>
<li><p>The .video div never closes, so that might lead to some issues. (Maybe it does in your normal code, but it doesn't in what you posted above.</p></li>
<li><p>This: </p>
<p><code>var video = data.split("@");
idx = Math.floor(video.length * Math.random());</code></p></li>
</ol>
<p>Doesn't seem to do what you want it to. Math.random(), if called without arguments, returns a decimal between 0 and 1. To make it between two numbers, you have to provide a min and a max. In your code, the idx variable is very likely just going to be zero. I think you may want instead <code>idx = Math.random(0, video.length - 1);</code></p>
<ol start="3">
<li>You're setting the HTML of .video to just the URL of the video selected. That doesn't work -- You'd need to populate the iframe source attribute tag with the URL to make this work.. Which now begs the question: why are you doing this in Javascript? Does the random video need to be changed again once the page loads? It seems like you could just do this much more simply with only PHP. You'd read from the text file, randomly choose one of the URLs, and then output the <code><iframe src="$source"></code> on page load instead of via AJAX and Javascript.</li>
</ol>
|
Jekyll - Image path works during jekyll serve, not on live site <p>I changed my _config.yml file to:</p>
<pre><code>baseurl: "/pages"
</code></pre>
<p>That's where we're storing our pages. When I do <code>jekyll serve</code> on my localhost, everything is fine. The image path shows up as:</p>
<pre><code> <img src="assets/images/foo/foo-icon.png">
</code></pre>
<p>Then I pushed it, and it doesn't work on our live site. The image path is this instead: </p>
<pre><code><img src="/pages/assets/images/foo/foo-icon.png">
</code></pre>
<p>If I change the path to the following, it works:</p>
<pre><code><img src="../assets/images/foo/foo-icon.png">
</code></pre>
<p>How do I get Jekyll to give me the right image path?</p>
| <p>If you are serving your site at <a href="http://example.com/" rel="nofollow">http://example.com/</a> rather than <a href="http://example.com/pages/" rel="nofollow">http://example.com/pages/</a>, then you don't want to set <code>baseurl</code>. <a href="https://byparker.com/blog/2014/clearing-up-confusion-around-baseurl/" rel="nofollow">https://byparker.com/blog/2014/clearing-up-confusion-around-baseurl/</a></p>
|
What is a 32-bit two's complement? <p>I'm really confused about the term "32-bit twos complement"</p>
<p>If I have the number 9, what is the 32-bit twos complement?</p>
<p>9 = 1001</p>
<p>Two's complement = 0111</p>
<p>32-bit 9 = 0000 0000 0000 0000 0000 0000 0000 1001</p>
<p>Two's complement = 1111 1111 1111 1111 1111 1111 1111 0111</p>
<p>That result is so ridiculous! It's way too large! Is that really how you're supposed to do it?</p>
| <p>The most common format used to represent signed integers in modern computers is two's complement. Two's complement representation allows the use of binary arithmetic operations on signed integers.</p>
<p>Positive 2's complement numbers are represented as the simple binary.</p>
<p>Negative 2's complement numbers are represented as the binary number that when added to a positive number of the same magnitude equals zero.</p>
<p>Your 2's complemented output is equivalent to -9 (negative 9).</p>
<p><strong>Edited:</strong></p>
<p>You are asked to perform 32-bit operation hence it should be <code>1111 1111 1111 1111 1111 1111 1111 0111</code></p>
<p>For signed number, leftmost bit represents the sign of the number. If leftmost bit (LSB) is 1 then the number is negative otherwise it's positive. So, your 32-bit 2's complemented number is negative and it's -9. <strong><em>Simply, performing 2's complement on a number is equivalent to negating it</em></strong>
i.e. it makes a positive number into negative and vice versa.
For more browse the link:</p>
<p><a href="http://www.tfinley.net/notes/cps104/twoscomp.html" rel="nofollow">http://www.tfinley.net/notes/cps104/twoscomp.html</a></p>
|
Adding custom pdf stamp to document from VBA <p>I've ran into a problem - I need to add a custom stamp (type of annotation) to a number of .pdf files. I can do it through Actions for Acrobat X Pro, but my clients do not have that license and they still need to do it. The list of files is stored in Excel spreadsheet, so ideally I am looking for a VBA solution. I have came up with the following code :</p>
<pre><code>Option Explicit
Sub code1()
Dim app As Acrobat.AcroApp
Dim pdDoc As Acrobat.CAcroPDDoc
Dim page As Acrobat.CAcroPDPage
Dim recter(3) As Integer 'Array defining the rectangle of the stamp - in real code wil be calculated, simplified for ease of reading
Dim jso As Object
Dim annot As Object
Dim props As Object
Set pdDoc = Nothing
Set app = CreateObject("AcroExch.App")
Set pdDoc = CreateObject("AcroExch.PDDoc")
recter(0) = 100
recter(1) = 100
recter(2) = 350
recter(3) = 350
pdDoc.Open ("C:\Users\maxim_s\Desktop\Code_1\test1.pdf")
Set jso = pdDoc.GetJSObject
If Not jso Is Nothing Then
Set page = pdDoc.AcquirePage(0)
Set annot = jso.AddAnnot
Set props = annot.getprops
props.page = 0
props.Type = "Stamp"
props.AP = "#eIXuM60ZXCv0sI-vxFqvlD" 'this line throws an error. The string is correct name of the stamp I want to add
props.rect = recter
annot.setProps props
If pdDoc.Save(PDSaveFull, "C:\Users\maxim_s\Desktop\Code_1\test123.pdf") = False Then
MsgBox "fail"
pdDoc.Close
Else
MsgBox "success"
pdDoc.Close
End If
End If
End Sub
</code></pre>
<p>The problem is with the <code>setprops</code> and <code>getprops</code> procedures - it seems that at the moment when annotation is created (<code>jso.AddAnnot</code>) it does not posses the <code>AP</code> property, which is the name of the stamp I want to add. If I set the property <code>Type= "Stamp"</code> first and then try to specify the <code>AP</code>, the result is that one of the default stamps is added and it's <code>AP</code> is renamed to my custom stamps' <code>AP</code>. Also note, that if I launch acrobat and use the code below, the proper stamp is added:</p>
<pre><code>this.addAnnot({page:0,type:"Stamp",rect:[100,100,350,350],AP:"#eIXuM60ZXCv0sI-vxFqvlD"})
</code></pre>
<p>If there is a way to execute this Javascript from VBA inside of the PDDoc object, that will solve the problem, but so far I have failed.</p>
| <p>You can use "ExecuteThisJavaScript" from the AForm Api. Short example:</p>
<p>Set AForm = CreateObject("AFormAut.App")</p>
<p>AForm.Fields.ExecuteThisJavaScript "var x = this.numPages; app.alert(x);"</p>
<p>It has the advantage that you don't need to translate the js examples into jso code. If you search for ExecuteThisJavaScript you will get some more and longer examples.</p>
<p>Good luck, reinhard</p>
|
Angular 2: Event Emitter not working properly <p>I have two components. I have a help menu component and a navigation component. When a user clicks the help button, it should show the help menu. I made a variable called help in the app component. In the nav component, I made an event emitter to try two-way binding, but it doesn't work on the nav component. I am kinda confused because the variable help only works when the app loads, but not when I click the help button. </p>
<p><strong>app component.ts</strong></p>
<pre><code>help:boolean = true;
</code></pre>
<p><strong>App component html</strong></p>
<pre><code><!-- app menu div -->
<app-help [(helps)]="help"></app-help>
<!-- app navigation -->
<app-nav [help]="help"></app-nav>
</code></pre>
<p><strong>App-nav component html</strong></p>
<pre><code><button class="circle" (click)="helpMenu()">H</button>
</code></pre>
<p><strong>App-nav component.ts</strong></p>
<pre><code>export class NavComponent implements OnInit{
@Input() help:boolean;
@Output() HelpsChange: EventEmitter<boolean> = new EventEmitter<boolean>();
constructor(){}
// when user clicks the help button
helpMenu(){
this.help = true;
this.HelpsChange.emit(this.help);
}
}
</code></pre>
<p><strong>App-help component.html</strong></p>
<pre><code><div id="helpMenu" *ngIf="help==true">
<p>Help</p>
<button (click)="closeHelp()">Close</button>
</code></pre>
<p></p>
<p><strong>App-help component.ts</strong></p>
<pre><code>export class HelpComponent implements OnInit {
@Input() help:boolean;
@Output() helpsChange: EventEmitter<boolean> = new EventEmitter<boolean>();
constructor() { }
ngOnInit() {
}
closeHelp(){
this.help = false;
this.helpsChange.emit(this.help);
}
}
</code></pre>
| <p>Not just changing the <code>[(helps)]</code> to <code>[(help)]</code> like Fabio mentioned, but you also need to change the name of the variable in the directive to remove the <code>s</code> from <code>helpsChange</code>. It's important that the input and output follow the naming format <code>property/propertyChange</code>, when you when you want to use the "banana in a box" syntax <code>[()]</code></p>
|
What does the Python operater ilshift (<<=)? <p>What does the Python operator ilshift (<<=) and where can I find infos about it?</p>
<p>Thanks</p>
<p><a href="https://docs.python.org/2/library/operator.html#operator.ilshift" rel="nofollow">https://docs.python.org/2/library/operator.html#operator.ilshift</a></p>
<p><a href="http://www.pythonlake.com/python/operators/operatorilshift" rel="nofollow">http://www.pythonlake.com/python/operators/operatorilshift</a></p>
<p>Found no info about what it does in the documentation.</p>
| <p>It is an BitwiseOperators (Bitwise Right Shift):
<a href="https://wiki.python.org/moin/BitwiseOperators" rel="nofollow">https://wiki.python.org/moin/BitwiseOperators</a></p>
<blockquote>
<p>All of these operators share something in common -- they are "bitwise"
operators. That is, they operate on numbers (normally), but instead of
treating that number as if it were a single value, they treat it as if
it were a string of bits, written in twos-complement binary.</p>
</blockquote>
<p>More infos:</p>
<p><a href="https://www.tutorialspoint.com/python/bitwise_operators_example.htm" rel="nofollow">https://www.tutorialspoint.com/python/bitwise_operators_example.htm</a></p>
<p><a href="http://stackoverflow.com/questions/6385792/what-does-a-bitwise-shift-left-or-right-do-and-what-is-it-used-for">What does a bitwise shift (left or right) do and what is it used for?</a></p>
|
Azure - Reverse Hub/Spoke Design ; Policy VPN Workaround <p>Due to a VNet only allowing for a single static gateway, and my onprem location gateways not supporting route based VPNs, I want to see if this is poss.</p>
<ul>
<li>Having a resources in a single vnet. </li>
<li>Create a new VNet for each
policy based VPN, containing a static gateway. </li>
<li>Then VNet peer these Vnets into the one containing all the resources. </li>
<li>Use routing to direct traffic into each of the "spokes". As the "Use Remote Gateway" option is only allowed to be configured on a one of the VNet
peerings.</li>
</ul>
| <p>Oh my, even if that thing works it will be horrific to maintain.</p>
<p>Just spin up a Linux VM with <a href="https://www.strongswan.org/" rel="nofollow">StrongSwan</a> on-prem and IKEv2 to Azure:</p>
<pre><code>conn azure
authby=secret
type=tunnel
leftsendcert=never
left=40.127.xxx.xxx
leftsubnet=10.4.0.0/19,10.0.0.0/24 #Azure side
right=172.31.22.44
rightsubnet=10.1.0.0/16,192.168.3.0/24,192.168.4.0/24 #on-prem
keyexchange=ikev2
auto=start
</code></pre>
|
Semantically disambiguating an ambiguous syntax <p>Using Antlr 4 I have a situation I am not sure how to resolve. I originally asked the question at <a href="https://groups.google.com/forum/#!topic/antlr-discussion/1yxxxAvU678" rel="nofollow">https://groups.google.com/forum/#!topic/antlr-discussion/1yxxxAvU678</a> on the Antlr discussion forum. But that forum does not seem to get a lot of traffic, so I am asking again here.</p>
<p>I have the following grammar:</p>
<pre><code>expression
: ...
| path
;
path
: ...
| dotIdentifierSequence
;
dotIdentifierSequence
: identifier (DOT identifier)*
;
</code></pre>
<p>The concern here is that <code>dotIdentifierSequence</code> can mean a number of things semantically, and not all of them are "paths". But at the moment they are all recognized as paths in the parse tree and then I need to handle them specially in my visitor.</p>
<p>But what I'd really like is a way to express the dotIdentifierSequence usages that are not paths into the <code>expression</code> rule rather than in the <code>path</code> rule, and still have dotIdentifierSequence in path to handle path usages.</p>
<p>To be clear, a dotIdentifierSequence might be any of the following:</p>
<ol>
<li>A path - this is a SQL-like grammar and a path expression would be like a table or column reference in SQL, e.g. <code>a.b.c</code></li>
<li>A Java class name - e.g. <code>com.acme.SomeJavaType</code></li>
<li>A static Java field reference - e.g. <code>com.acme.SomeJavaType.SOME_FIELD</code></li>
<li>A Java enum value reference - e.g. <code>com.acme.Gender.MALE</code></li>
</ol>
<p>The idea is that during visitation "dotIdentifierSequence as a path" resolves as a very different type from the other usages.</p>
<p>Any idea how I can do this?</p>
| <p>The issue here is that you're trying to make a distinction between "paths" while being created in the parser. Constructing paths inside the lexer would be easier (pseudo code follows):</p>
<pre class="lang-antlr prettyprint-override"><code>grammar T;
tokens {
JAVA_TYPE_PATH,
JAVA_FIELD_PATH
}
// parser rules
PATH
: IDENTIFIER ('.' IDENTIFIER)*
{
String s = getText();
if (s is a Java class) {
setType(JAVA_TYPE_PATH);
} else if (s is a Java field) {
setType(JAVA_FIELD_PATH);
}
}
;
fragment IDENTIFIER : [a-zA-Z_] [a-zA-Z_0-9]*;
</code></pre>
<p>and then in the parser you would do:</p>
<pre class="lang-antlr prettyprint-override"><code>expression
: JAVA_TYPE_PATH #javaTypeExpression
| JAVA_FIELD_PATH #javaFieldExpression
| PATH #pathExpression
;
</code></pre>
<p>But then, of course, input like this <code>java./*comment*/lang.String</code> would be tokenized wrongly.</p>
<p>Handling it all in the parser would mean manually looking ahead in the token stream and checking if either a Java type, or field exists.</p>
<p>A quick demo:</p>
<pre class="lang-antlr prettyprint-override"><code>grammar T;
@parser::members {
String getPathAhead() {
Token token = _input.LT(1);
if (token.getType() != IDENTIFIER) {
return null;
}
StringBuilder builder = new StringBuilder(token.getText());
// Try to collect ('.' IDENTIFIER)*
for (int stepsAhead = 2; ; stepsAhead += 2) {
Token expectedDot = _input.LT(stepsAhead);
Token expectedIdentifier = _input.LT(stepsAhead + 1);
if (expectedDot.getType() != DOT || expectedIdentifier.getType() != IDENTIFIER) {
break;
}
builder.append('.').append(expectedIdentifier.getText());
}
return builder.toString();
}
boolean javaTypeAhead() {
String path = getPathAhead();
if (path == null) {
return false;
}
try {
return Class.forName(path) != null;
} catch (Exception e) {
return false;
}
}
boolean javaFieldAhead() {
String path = getPathAhead();
if (path == null || !path.contains(".")) {
return false;
}
int lastDot = path.lastIndexOf('.');
String typeName = path.substring(0, lastDot);
String fieldName = path.substring(lastDot + 1);
try {
Class<?> clazz = Class.forName(typeName);
return clazz.getField(fieldName) != null;
} catch (Exception e) {
return false;
}
}
}
expression
: {javaTypeAhead()}? path #javaTypeExpression
| {javaFieldAhead()}? path #javaFieldExpression
| path #pathExpression
;
path
: dotIdentifierSequence
;
dotIdentifierSequence
: IDENTIFIER (DOT IDENTIFIER)*
;
IDENTIFIER
: [a-zA-Z_] [a-zA-Z_0-9]*
;
DOT
: '.'
;
</code></pre>
<p>which can be tested with the following class:</p>
<pre class="lang-java prettyprint-override"><code>package tl.antlr4;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.misc.NotNull;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
public class Main {
public static void main(String[] args) {
String[] tests = {
"mu",
"tl.antlr4.The",
"java.lang.String",
"foo.bar.Baz",
"tl.antlr4.The.answer",
"tl.antlr4.The.ANSWER"
};
for (String test : tests) {
TLexer lexer = new TLexer(new ANTLRInputStream(test));
TParser parser = new TParser(new CommonTokenStream(lexer));
ParseTreeWalker.DEFAULT.walk(new TestListener(), parser.expression());
}
}
}
class TestListener extends TBaseListener {
@Override
public void enterJavaTypeExpression(@NotNull TParser.JavaTypeExpressionContext ctx) {
System.out.println("JavaTypeExpression -> " + ctx.getText());
}
@Override
public void enterJavaFieldExpression(@NotNull TParser.JavaFieldExpressionContext ctx) {
System.out.println("JavaFieldExpression -> " + ctx.getText());
}
@Override
public void enterPathExpression(@NotNull TParser.PathExpressionContext ctx) {
System.out.println("PathExpression -> " + ctx.getText());
}
}
class The {
public static final int ANSWER = 42;
}
</code></pre>
<p>which would print the following to the console:</p>
<pre class="lang-none prettyprint-override"><code>PathExpression -> mu
JavaTypeExpression -> tl.antlr4.The
JavaTypeExpression -> java.lang.String
PathExpression -> foo.bar.Baz
PathExpression -> tl.antlr4.The.answer
JavaFieldExpression -> tl.antlr4.The.ANSWER
</code></pre>
|
How do I create cluster singleton using FSharp API? <p>I'm not sure how do i spawn a cluster singleton using FSharp API. Should i use [spwane] or [spawnOpt] ? and how one does that ?</p>
| <p>You cannot create cluster singleton using standard Akka.FSharp API. <em>Reason behind that is that Akka.FSharp API already hit v1.0 before the shape of the cluster singleton API was even known.</em></p>
<p>You can however use <a href="https://github.com/Horusiath/Akkling/wiki" rel="nofollow">Akkling.Cluster.Sharding</a> library (Akkling is an alternative F# API for Akka.NET) and establish cluster singleton by using <a href="https://github.com/Horusiath/Akkling/blob/fa6474689475af0c327dfbfda1c2b1dbfcc54f40/src/Akkling.Cluster.Sharding/ClusterSingleton.fs#L24" rel="nofollow">spawnSingleton</a> function.</p>
|
Bigquery If field exists <p>Short: Is there a way to query in BQ fields that doesn't exists, receiving nulls for these fields?</p>
<p>I have almost the same issue than
<a href="http://stackoverflow.com/questions/32276601/bigquery-if-field-exists-then">BigQuery IF field exists THEN</a> but in mine, sometimes my APIs can query tables where there are not some particular fields (historic tables) and this approach fails because it needs a table with that field:</p>
<pre><code>SELECT a, b, c, COALESCE(my_field, 0) as my_field
FROM
(SELECT * FROM <somewhere w/o my_field>),
(SELECT * FROM <somewhere with my_field>)
</code></pre>
<p>Is there a way to do something like:</p>
<pre><code>SELECT IFEXISTS(a, NULL) as the-field
FROM <somewhere w/o my_field>
</code></pre>
| <p>Let's assume your table has x and y fields only!<br>
So below query will perfectly work </p>
<pre><code>SELECT x, y FROM YourTable
</code></pre>
<p>But below one will fail because of non-existing field z</p>
<pre><code>SELECT x, y, z FROM YourTable
</code></pre>
<p>The way to address this is as below</p>
<pre><code>SELECT x, y, COALESCE(z, 0) as z
FROM
(SELECT * FROM YourTable),
(SELECT true AS fake, NULL as z)
WHERE fake IS NULL
</code></pre>
|
HTML Dropdown menu in nav <p>I made a nav bar which has some tabs, but I want to make a dropdown menu which appears on hover in genre tab. Code goes like this:</p>
<pre><code><nav>
<ul>
<li><a class="active" href="index.html">Home</a></li>
<li><a href="index.html">PLaying Now</a></li>
<li><a href="index.html">Genre</a></li>
</ul>
</nav>
</code></pre>
<p>And the css code is:</p>
<pre><code>nav { /* Navbar align */
text-align:center;
}
ul { /* Navbar settings */
display: inline-block;
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;
}
li { /* Text align */
float: left;
}
li a { /* Menu variable */
display: block;
color: white;
font-size: 20px;
text-align: center;
padding: 16px 16px; /* height width */
text-decoration: none;
}
li a:hover:not(.active) { /* Tab over mouse */
background-color: #111;
}
.active { /* Tab active color */
background-color: #791519;
}
</code></pre>
<p>What do I must change to make that happen?</p>
| <p>Add the Links you need at Genre
<code><li><a href="index.html">Genre</a></li></code></p>
<pre><code><li><a href="index.html">Genre</a>
<ul>
<li><a href="link.html">Link</a></li>
</ul>
</li>
</code></pre>
<p>and then add to your CSS</p>
<pre><code>ul ul { display: none; }
ul li:hover ul { display: block; }
</code></pre>
|
Changing static URL as Dynamic - NodeJS <p>I have a directory where all the songs uploaded by user get uploaded. I have used mongodb for this app, mongodb is working fine but I want to use
src url like uploads/something to songs/user/songname I have tried to used Router.get as shown in the Controller.js
But when I use this I have got the internal 500 error, Please let me knwo where I had made mistake.</p>
<p><strong>controller.js</strong></p>
<pre><code>Router.get('/songs/:artist/:song', (req, response) => {
console.dir(req.query)
let file = './uploads/01-Whole Lotta Love.mp3'
var stat = FileSystem.statSync(file)
response.setHeader('Content-Type', 'audio/mpeg');
response.setHeader('Content-Length', stat.length);
fs.createReadStream(file).pipe(response);
})
</code></pre>
<p><strong>app.js</strong></p>
<pre><code>app.use(Express.static(path.join(__dirname, 'uploads')));
</code></pre>
<p><strong>profile.ejs</strong></p>
<pre><code><table border="1">
<% artist.songs.forEach((song) => { %>
<tr>
<td> <%= song.song %> </td>
<td>
<audio controls>
<source src="./songs/<%= artist.artistName+ '/' + song.audioPath %>" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
</td>
<td>3k listens</td>
<td>2k likes</td>
<td>2k comments</td>
</tr>
<% }) %>
</table>
</code></pre>
<p>its like what ever I write for <strong>songs/anyusername/songname</strong> will use the directory <strong>uploads/songname</strong></p>
<p>thankyou in advance :)</p>
| <p>Try this code, open in browser: <code>http://host:port/song/foo/bar</code> <br/>
and write in comment what You get:</p>
<pre><code>const
fs = require('fs'),
path = require('path'),
bufferSize = 100 * 1024;
Router.get('/songs/:artist/:song', (req, res) => {
let
file = '01-Whole Lotta Love.mp3';
file = path.join(__dirname, 'uploads', file);
console.log('Piping file:', file); // check if path is correct
fs.stat(file,
(err, stat) => {
if(err) {
return res.status(500).send(err); // output error to client
}
res.writeHead(200, {
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Pragma': 'no-cache',
'Expires': 0,
'Content-Type': 'audio/mpeg',
'Content-Length': stat.size
});
fs.createReadStream(file, {bufferSize}).pipe(res);
});
})
</code></pre>
|
Kafka API: java.io.IOException: Can't resolve address: 357d78957cf5:9092 <p>I am trying to figure out how to properly write a simple producer application to Kafka. </p>
<p>1) Please tell me if I should avoid using 0.10.0.1, I am totally struggled with it. </p>
<p>This example I found from Apache wiki worked for 0.8
<a href="https://cwiki.apache.org/confluence/display/KAFKA/0.8.0+Producer+Example" rel="nofollow">https://cwiki.apache.org/confluence/display/KAFKA/0.8.0+Producer+Example</a> </p>
<p>Itâs completely different in 0.10
<a href="http://kafka.apache.org/documentation#producerconfigs" rel="nofollow">http://kafka.apache.org/documentation#producerconfigs</a> </p>
<p>So this is what I am using:
"org.apache.kafka" % "kafka_2.10" % "0.10.0.1",</p>
<p>I am feeling very bad about this latest Kafka library, because apparently there are some known issues. In the runtime, it even shows a list of warnings about some configurations are not known config. But if I donât provide them, the app wonât run. On github, people have identified this kind of issue. </p>
<p>2) Honestly, my code is super simple, if their documentation is even right. </p>
<pre class="lang-scala prettyprint-override"><code> val props = new Properties()
props.put("bootstrap.servers", "192.168.99.100:9092");
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer")
props.put("key.deserializer","org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.serializer","org.apache.kafka.common.serialization.StringSerializer");
props.put("value.deserializer","org.apache.kafka.common.serialization.StringDeserializer");
props.put("producer.type", "async")
props.put("advertised.listeners", "192.168.99.100:32777")
val producer = new KafkaProducer[String, String](props)
val t = System.currentTimeMillis()
val runtime = new Date().getTime();
val msg = runtime + ", hello world";
val message = new ProducerRecord[String, String](topic, null, msg)
producer.send(message);
</code></pre>
<p>I am running 2 separate Docker containers for zookeeper (192.168.99.100:32777) and Kafka (192.168.99.100:9092). The settings work. I can use Kafka command line create a producer and consumer properly. However, trying to write my own client doesnât work. </p>
<p>First, their document doesnât even say <strong>advertised.listeners</strong> is required or part of the ProducerConfig. But without it, I encountered this exception âGive up sending metadata request since no node is availableâ. So I found this page: <a href="http://stackoverflow.com/questions/34572621/cannt-connect-to-kafka-server">cann't connect to kafka server</a> </p>
<p>Once I added â<strong>advertised.listeners</strong>â (because according to Apache document, â<strong>advertised.host.name</strong>â has been deprecated). I encountered this infinite exceptions: âjava.io.IOException: Can't resolve address: 357d78957cf5:9092â </p>
<p>I honestly donât know where that address come from. In the terminal, it clearly shows itâs using my docker container IP:</p>
<p><a href="https://i.stack.imgur.com/XfX3r.png" rel="nofollow"><img src="https://i.stack.imgur.com/XfX3r.png" alt="enter image description here"></a></p>
<p>And then I found this: <a href="http://stackoverflow.com/questions/33541114/kafka-0-8-2-2-unable-to-publish-messages">Kafka 0.8.2.2 - Unable to publish messages</a>
I think itâs the right answer to my problem, but I really donât know what I am supposed to do to fix this problem. </p>
| <p>Some backgrounds you'll find useful before using the producer: The old producer(Scala) in 0.8.x had already been removed starting 0.9.0.</p>
<p>Therefore, you are using the new producer(Java) now. Kafka dev team decides to remove any Zookeeper dependencies from the new client, no matter producer or consumer. So you should not set the ZK setting anymore. Besides, letting "advertised.listeners" point to ZK service is incorrect.</p>
<p>"advertised.listeners" is for IaaS machines which usually have more than one NICs. Here is what Kafka doc says about it:</p>
<blockquote>
<p>In IaaS environments, this may need to be different from the interface to which the broker binds. If this is not set, the value for <code>listeners</code> will be used.</p>
</blockquote>
<p>You could set this parameter to have client bind the public NIC, whereas the intra-communication for brokers binds the private NIC.</p>
|
Get Webpack not to bundle files <p>So right now I'm working with a prototype where we're using a combination between webpack (for building .tsx files and copying .html files) and webpack-dev-server for development serving. As you can assume we are also using React and ReactDOM as a couple of library dependencies as well. Our current build output is the following structure:</p>
<pre><code>dist
-favicon.ico
-index.html
-main.js
-main.js.map // for source-mapping between tsx / js files
</code></pre>
<p>This places ALL of the modules (including library dependencies into on big bundled file). I want the end result to look like this:</p>
<pre><code>dist
-favicon.ico
-index.html
-appName.js
-appName.min.js
-react.js
-react.min.js
-reactDOM.js
-reactDOM.min.js
</code></pre>
<p>I have references to each of the libraries in index.html and in import statements in the .tsx files. So my question is this...
How do I go from webpack producing this gigantic bundled .js file to individual .js files (libraries included, without having to specify each individually)? **Bonus: I know how to do prod/dev environment flags, so how do I just minify those individual files (again without bundling them)?</p>
<p>current webpack.config:</p>
<pre><code>var webpack = require("webpack"); // Assigning node package of webpack dependency to var for later utilization
var path = require("path"); // // Assigning node package of path dependency to var for later utilization
module.exports = {
entry: [
"./wwwroot/app/appName.tsx", // Starting point of linking/compiling Typescript and dependencies, will need to add separate entry points in case of not deving SPA
"./wwwroot/index.html", // Starting point of including HTML and dependencies, will need to add separate entry points in case of not deving SPA
"./wwwroot/favicon.ico" // Input location for favicon
],
output: {
path: "./dist/", // Where we want to host files in local file directory structure
publicPath: "/", // Where we want files to appear in hosting (eventual resolution to: https://localhost:4444/)
filename: "appName.js" // What we want end compiled app JS file to be called
},
// Enable sourcemaps for debugging webpack's output.
devtool: "source-map",
devServer: {
contentBase: './dist', // Copy and serve files from dist folder
port: 4444, // Host on localhost port 4444
// https: true, // Enable self-signed https/ssl cert debugging
colors: true // Enable color-coding for debugging (VS Code does not currently emit colors, so none will be present there)
},
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: [
"",
".ico",
".js",
".ts",
".tsx",
".web.js",
".webpack.js"
]
},
module: {
loaders: [
// This loader copies the index.html file & favicon.ico to the output directory.
{
test: /\.(html|ico)$/,
loader: 'file?name=[name].[ext]'
},
// All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'.
{
test: /\.tsx?$/,
loaders: ["ts-loader"]
}
],
preLoaders: [
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{
test: /\.js$/,
loader: "source-map-loader"
}
]
},
// When importing a module whose path matches one of the following, just
// assume a corresponding global variable exists and use that instead.
// This is important because it allows us to avoid bundling all of our
// dependencies, which allows browsers to cache those libraries between builds.
// externals: {
// "react": "React",
// "react-dom": "ReactDOM",
// "redux": "Redux"
// }
};
</code></pre>
<p>Update:
Ended up finding a solution that fit my needs, although, again, in that webpack-y way, requires some additional configuration. Still would like to make it a little more dynamic, but will perfect this at a later point in time. The resolution I was looking for was the ability to "chunk" common modules, but I stated it as filename given "entry"-points provided in webpack. I didn't mind some files being combined, where it made sense, but wanted overall files to be at a component-level given the project wasn't a SPA (single page application).</p>
<p>The additional code ended up being:</p>
<pre><code>plugins: [
new webpack.optimize.CommonsChunkPlugin({ // This plugin is for extracting and created "chunks" (extracted parts of the code that are common and aren't page specific)
// One of these instances of plugins needs to be specified for EACH chunk file output desired
filename: "common.js", // Filename for this particular set of chunks to be stored
name: "common", // Entry point name given for where to pull all of the chunks
minChunks: 3 // Minimum number of chunks to be created
})
]
</code></pre>
<p>I also had to parameterize the entry points (see below for example), by variable name so that I could assign react, react-dom, and redux modules to common.js file.</p>
<pre><code>entry: {
main: "./wwwroot/app/appName.tsx", // Starting point of linking/compiling Typescript and dependencies, will need to add separate entry points in case of not deving SPA
index: "./wwwroot/index.html", // Starting point of including HTML and dependencies, will need to add separate entry points in case of not deving SPA
favicon: "./wwwroot/favicon.ico", // Input location for favicon
common: [ "react", "react-dom", "redux" ] // All of the "chunks" to extract and place in common file for faster loading of common libraries between pages
},
</code></pre>
| <p>Change the <code>output</code> setting to be <em>name driven</em> e.g. </p>
<pre><code> entry: {
dash: 'app/dash.ts',
home: 'app/home.ts',
},
output: {
path: './public',
filename: 'build/[name].js',
sourceMapFilename: 'build/[name].js.map'
},
</code></pre>
|
There has to be a better way <p>Is there a more idiomatic way to accomplish the following in Python3?</p>
<pre><code>if i%1 == 0 and i%2 == 0 and i%3 == 0 and i%4 == 0 and i%5 == 0 and i%6 == 0 and i%7 == 0 and i%8 == 0 and i%9 == 0 and i%10 == 0 and i%11 == 0 and i%12 == 0 and i%13 == 0 and i%14 == 0 and i%15 == 0 and i%16 == 0 and i%17 == 0 and i%18 == 0 and i%19 == 0 and i%20 == 0:
</code></pre>
<p>I'm trying to find the smallest positive number that is evenly divisible by all of the numbers from 1 to 20. I'm not looking for a new solution. I'm looking for a neater way to express what I am doing above.</p>
| <p>Yes use <a href="https://docs.python.org/3/library/functions.html#all" rel="nofollow"><em>all</em></a> with <a href="https://docs.python.org/3/library/functions.html#func-range" rel="nofollow"><em>range</em></a>:</p>
<pre><code>if all(i % j == 0 for j in range(1, 21)): # python2 -> xrange(2, 21)
# do whatever
</code></pre>
<p>If all <code>i % j == 0</code>, it will return <em>True</em> otherwise it will <em>short circuit</em> and return <em>False</em> if there is any remainder for <code>i % j</code>. Also, checking <code>if i % 1</code> is redundant so you can start at 2.</p>
<p>Or conversly, check if there is <em>not</em> <a href="https://docs.python.org/3/library/functions.html#any" rel="nofollow">any</a> <code>i % j</code> with a remainder. </p>
<pre><code>if not any(i % j for j in range(2, 21)):
</code></pre>
<p>Or if you prefer <em>functional</em>:</p>
<pre><code>if not any(map(i.__mod__, range(2, 21)))
</code></pre>
|
Android: How to get back to main activity after click? <p>I am beginner in android and I have question how to get result from other activity and back to my main activity:</p>
<p>Example from my project:
I have some main activity ... when I click on button, application will open activity where is only list. After user click on some item from list, I need back open my main activity and display data from that item. How can I do that ?</p>
| <p>You can use <code>startActivityForResult()</code> .
Have a look here:
<a href="https://developer.android.com/training/basics/intents/result.html" rel="nofollow">https://developer.android.com/training/basics/intents/result.html</a></p>
|
'System.TypeInitializationException' being thrown on previously working code <p><strong>My code worked fine previously, but now when I run it; it throws up this exception:</strong></p>
<blockquote>
<p>An unhandled exception of type 'System.TypeInitializationException'
occurred in Debug Chamber.exe Additional information: The type
initializer for 'varBank' threw an exception.</p>
</blockquote>
<p>What's even weirder is that I have changed nothing except for adding this class:</p>
<pre><code>public class readParameters
{
public static void readLog(int start, int end)
{
for (int x = start; x < end; x++)
{
}
}
public static void nextLine()
{
string[,] logArr = new string[4, 5];
}
}
</code></pre>
<p>The line in question is highlighted in the block below</p>
<hr>
<pre><code>/// </data bank>
public class varBank
{
public static string logInput { get; set; }
public static PathType FilePath { get; private set; }
public static EventLogReader evl = new EventLogReader(logInput, FilePath);
public static EventRecord bsnRecord = evl.ReadEvent();
}
/// </data bank>
namespace EventLogInfoReader
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter Log Location: ");
</code></pre>
<blockquote>
<pre><code> varBank.logInput = Console.ReadLine();
</code></pre>
</blockquote>
<pre><code> Console.WriteLine("Enter Read Parameters: ");
int i = 1;
while (++i > 0)
{
Console.WriteLine("Enter Property: ");
string CommandInput = Console.ReadLine();
getInfo.callInfo(CommandInput);
}
}
}
}
</code></pre>
| <p>That exception means an exception was thrown from a static constructor or field initializer. I suspect it's in the initializer for <code>evl</code>, since it's referencing static properties that do not have initial values set (they will be <code>null</code>).</p>
<p>I would move that code to a static constructor so you can do better error handling and/or logging. Both <code>evl</code> and <code>bsnRecord</code> have static initializers thatr are vulnerable to run-time exceptions and should not go unchecked.</p>
<p>I also question why you have static properties that's initialized using <em>other</em> static properties. What do you expect to happen if client code sets the <code>FilePath</code> property?</p>
|
Set status code on http.ResponseWriter <p>How do I set the http status code on an <code>http.ResponseWriter</code>?</p>
<p>i.e a 500, or 403.</p>
<p>I can see that requests normally have a status code of 200 attached to them.</p>
| <p>Use <a href="https://godoc.org/net/http#ResponseWriter" rel="nofollow"><code>http.ResponseWriter.WriteHeader</code></a>. From the documentation:</p>
<pre><code>// WriteHeader sends an HTTP response header with status code.
// If WriteHeader is not called explicitly, the first call to Write
// will trigger an implicit WriteHeader(http.StatusOK).
// Thus explicit calls to WriteHeader are mainly used to
// send error codes.
</code></pre>
<p>Example:</p>
<pre><code>func ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500 - Something bad happened!"))
}
</code></pre>
|
artifactory upload with powershell <p>How would you upload an artifact using powershell? </p>
<p>The following works with bash</p>
<pre><code>ARTIFACT_MD5_CHECKSUM=$(md5sum /tmp/bar.zip | awk '{print $1}')
ARTIFACT_SHA1_CHECKSUM=$(shasum -a 1 /tmp/bar.zip | awk '{ print $1 }')
curl --upload-file "/tmp/bar.zip" --header "X-Checksum-MD5:${ARTIFACT_MD5_CHECKSUM}" --header "X-Checksum-Sha1:${ARTIFACT_SHA1_CHECKSUM}" -u "admin:${ARTIFACTORY_API_KEY}" -v https://artifactory.example.com/artifactory/foo/
</code></pre>
| <p>Use <code>Invoke-RestMethod</code></p>
<pre><code>$password = ConvertTo-SecureString -AsPlainText -Force -String '<api_key>'
$cred = New-Object Management.Automation.PSCredential ('admin', $password)
$ARTIFACT_SHA1_CHECKSUM=$(Get-FileHash -Algorithm SHA1 c:\bar.zip).Hash
$HEADERS = @{"X-Checksum-SHA1"=$ARTIFACT_SHA1_CHECKSUM;};
Invoke-RestMethod -Uri https://artifactory.example.com/artifactory/foo/bar.zip -Method PUT -InFile c:\bar.zip -cred $cred -Headers $HEADERS
</code></pre>
<p>Including the SHA1 hash as part of the headers is optional. </p>
<p>Make sure: </p>
<ul>
<li>use 'PUT' not 'POST'</li>
<li>filename must be part of the URI</li>
</ul>
|
Android: Pass value from activity to broadcastreceiver <p>First of all, sorry for my bad grammar. I am developing Auto Reply Message Application using broadcastreceiver i have problem with when I can receive value from activity to broadcastreceiver, the Auto Reply won't work. But if I'm not receive value from Activity, it's working. this is my activity code, I put it in onSensorChanged()</p>
<pre><code>Intent i = new Intent("my.action.string");
i.putExtra("apaan", lala);
sendBroadcast(i);
</code></pre>
<p>and this is my broadcastreceiver class</p>
<pre><code>public class AutoReply extends BroadcastReceiver{
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.i("message", "Broadcast Received: " +action);
if (action.equals(SMS_RECEIVED) && action.equals("my.action.string")) {
Bundle bundle = intent.getExtras();
String state = bundle.getString("apaan");
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
final SmsMessage[] sms = new SmsMessage[pdus.length];
String isiSMS = "", noPengirim = "";
for (int i = 0; i < pdus.length; i++) {
sms[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
isiSMS = sms[i].getMessageBody();//mengambil isi pesan dari pengirim
noPengirim = sms[i].getOriginatingAddress();//mengambil no pengirim
}
String message = state;//isi balasan autoreplay
SmsManager smsSend = SmsManager.getDefault();
smsSend.sendTextMessage(noPengirim, null, message, null, null);
}
}
}
</code></pre>
<p>and this is my manifest</p>
<pre><code><receiver android:name=".AutoReply" android:enabled="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
<action android:name="my.action.string" />
</intent-filter>
</receiver>
</code></pre>
| <p>The action will never be both <code>android.provider.Telephony.SMS_RECEIVED</code> and <code>my.action.string</code>. </p>
<p>Change this:</p>
<pre><code>if (action.equals(SMS_RECEIVED) && action.equals("my.action.string")) {
</code></pre>
<p>To this:</p>
<pre><code>if (action.equals(SMS_RECEIVED) || action.equals("my.action.string")) {
</code></pre>
<p>In addition, you're not sending <code>pdus</code> in the manually created Intent, so when you call <code>bundle.get("pdus")</code> it will return null. Then when you call <code>pdus.length</code> it will throw a NullPointerException.</p>
|
Jena Fuseki API add new data to an exsisting dataset [java] <p>i was trying to upload an RDF/OWL file to my Sparql endpoint (given by Fuseki). Right now i'm able to upload a single file, but if i try to repeat the action, the new dataset will override the old one. I'm searching a way to "merge" the content of the data in the dataset with the new ones of the rdf file just uploaded. Anyone can help me? thanks.</p>
<p>Following the code to upload/query the endpoint (i'm not the author)</p>
<pre><code>// Written in 2015 by Thilo Planz
// To the extent possible under law, I have dedicated all copyright and related and neighboring rights
// to this software to the public domain worldwide. This software is distributed without any warranty.
// http://creativecommons.org/publicdomain/zero/1.0/
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ByteArrayOutputStream;
import org.apache.jena.query.DatasetAccessor;
import org.apache.jena.query.DatasetAccessorFactory;
import org.apache.jena.query.QueryExecution;
import org.apache.jena.query.QueryExecutionFactory;
import org.apache.jena.query.QuerySolution;
import org.apache.jena.query.ResultSet;
import org.apache.jena.query.ResultSetFormatter;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.RDFNode;
class FusekiExample {
public static void uploadRDF(File rdf, String serviceURI)
throws IOException {
// parse the file
Model m = ModelFactory.createDefaultModel();
try (FileInputStream in = new FileInputStream(rdf)) {
m.read(in, null, "RDF/XML");
}
// upload the resulting model
DatasetAccessor accessor = DatasetAccessorFactory.createHTTP(serviceURI);
accessor.putModel(m);
}
public static void execSelectAndPrint(String serviceURI, String query) {
QueryExecution q = QueryExecutionFactory.sparqlService(serviceURI,
query);
ResultSet results = q.execSelect();
// write to a ByteArrayOutputStream
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//convert to JSON format
ResultSetFormatter.outputAsJSON(outputStream, results);
//turn json to string
String json = new String(outputStream.toByteArray());
//print json string
System.out.println(json);
}
public static void execSelectAndProcess(String serviceURI, String query) {
QueryExecution q = QueryExecutionFactory.sparqlService(serviceURI,
query);
ResultSet results = q.execSelect();
while (results.hasNext()) {
QuerySolution soln = results.nextSolution();
// assumes that you have an "?x" in your query
RDFNode x = soln.get("x");
System.out.println(x);
}
}
public static void main(String argv[]) throws IOException {
// uploadRDF(new File("test.rdf"), );
uploadRDF(new File("test.rdf"), "http://localhost:3030/MyEndpoint/data");
}
}
</code></pre>
| <p>Use <code>accessor.add(m)</code> instead of <code>putModel(m)</code>. As you can see in <a href="https://jena.apache.org/documentation/javadoc/arq/org/apache/jena/query/DatasetAccessor.html" rel="nofollow">the Javadoc</a>, <code>putModel</code> <em>replaces</em> the existing data.</p>
|
How to remove quotes from each element in a javascript array containing JSON encoded html strings returned from a mysql database with php <p>Ajax call to the mysql data base using data1.php file with pdo returns hmtl strings that are put into an array, encoded with json and sent to the ajax response function for display in html. Of course the elements in the array have tags and quotations, which are difficult to remove. Easiest and closest solution so far is to replace the quotes in the strings with javascript .replace(). This doesn't work for the array of arrays unless the single element is referenced. What's the way around this? Here is the code.</p>
<p>Ajax call:</p>
<pre><code>function processForm_L(){
var topic = $("#topic").val();
// send data
$.ajax({
url: "../php/get_data1.php",
data: {
topic1:topic},
type: 'POST',
dataType: 'json',
success: processResult_L
}); // end .onclick
}
</code></pre>
<p>The response function:</p>
<pre><code>function processResult_L(data, textStatus){
// Required Callback Function
if(data['status']['response'] == 1){
//if(data[0] == 1){
table_1 = [];
table_2 = [];
table_3 = [];
table_1 = data.table['a'].replace( /"/g,"");
table_2 = data.data.replace(/"/g,"");
table_3 = data.table['b'].replace( /"/g,"");
//table_1 = JSON.parse(data.table['a']);
//table_2 = JSON.parse(data.data);
//table_3 = JSON.parse(data.table['b']);
//console.log(table_1);
console.log(table_2);
//console.log(table_3);
}//end if response == 1
else if(data.response == 0){
//var response = data + textStatus;
var table_4 = data.error;
$('#display').html(table_4);
}//end if response==0
}//end process results
</code></pre>
<p>The query part of get_data1.php</p>
<pre><code><?php
$ret_s = Array();//return status
$ret_t = Array();//return table
$ret_d = Array();//return data
$result = Array();
$row_1 = 1;
if(!empty($_POST)){
try{
if(!empty($_POST)){
//connect to database and insert data
// include "db_connect_df.php";
// select everything from the raw_data database
$sql = "SELECT * FROM `raw_data`";
// prepare the sql statement
$stmt_s = $db->prepare($sql);
$stmt_s->execute();
$result = $stmt_s->fetchAll(PDO::FETCH_ASSOC);
//set response variable
$ret_s['response'] = 1;
//table header
$ret_t['a'] ="<table id='display_table'><tr><th>ID</th><th>Organization</th><th>Contact Names</th><th>Telephone</th><th>Email</th><th>Website</th><th>Country</th><th>Region</th><th>City</th><th>Street</th><th>Unit</th><th>Postal Code</th><th>Topic</th><th>Message</th><th>Date</th></tr>";
//fetch each row from database as html
foreach($result as $row){
$ret_d[$row_1] = "<tr>" ."<td>" . $row['ID'] . "</td>" ."<td>" .
$row['Organization'] . "</td>" ."<td>" . $row['Telephone'] . "</td>" . "<td>" . $row['Email'] . "</td>" ."<td>" . $row['Website'] . "</td>" ."<td>" . $row['Country'] . "</td>" ."<td>" . $row['Region'] . "</td>" ."<td>" . $row['City'] . "</td>" ."<td>" . $row['Street'] . "</td>" ."<td>" . $row['Unit'] . "</td>" ."<td>" . $row['Postal_Code'] . "</td>" ."<td>" . $row['Topic'] . "</td>" ."<td>" . $row['Message'] . "</td>" ."<td>" . $row['ts'] . "</td>" ."</tr>";
$row_1++;
}
// end table tag
$ret_t['b'] = "</table>";
//echo and encode array
echo json_encode(array('status' => $ret_s, 'table' => $ret_t,'data'=> $ret_d),JSON_HEX_QUOT|JSON_HEX_TAG);
// echo json_encode(stripslashes_nested(array('status' => $ret_s, 'table' => $ret_t,'data'=> $ret_d)),JSON_HEX_QUOT|JSON_HEX_TAG);
}//end connect
}//end try
catch (PDOException $e) {
$error16 = '<span class="error_s">Try again another time.</span>';
$error17 = '<span class="error_s">ERROR:' . $e->getMessage();
$ret_s['response'] = 0;
$ret_s['error'] = $error16 . $error17;
echo json_encode($ret_s);
} //end failure
}//end if is !empty($_POST)
?>
</code></pre>
<p>Note: this queries a localhost database served through xampp. This isn't all the code but everything works just fine except the following:</p>
<p>1) <code>table_2 = data.data.replace(/"/g,"");</code> returns 'data.data.replace() is not a function, because the array is an object not a string</p>
<p>2) when comment out above line and comment in only <code>console.log(table_1);</code> result in console is:</p>
<p><code><table id='display_table'><tr><th>ID</th><th>Organization</th><th>Contact Names</th><th>Telephone</th><th>Email</th><th>Website</th><th>Country</th><th>Region</th><th>City</th><th>Street</th><th>Unit</th><th>Postal Code</th><th>Topic</th><th>Message</th><th>Date</th></tr></code> So that works.</p>
<p>3) similarly commenting in only <code>console.log(table_3);</code> returns in console:</p>
<p><code></table></code> so that also works.</p>
<p>4) if comment in <code>table_2 = data.data;</code> and enter table_2 into console result is: </p>
<p><code>undefined</code></p>
<p>5) tried this code to remove quotes from the array of arrays:</p>
<p>a) putting a function in the js init file for the page:</p>
<pre><code>function replace_quotes(x){
for(var i=0; i < x.length; i++) {
x[i] = x[i].toString().replace(/"/g,"");
}
}
</code></pre>
<p>and using that function on the data array in the data object created by the response callback function (so x = data.data) </p>
<p>result is undefined, and it doesn't work.</p>
<p><code>JSON.parse(table_1);</code> just runs into a <code><</code> right away and won't parse, for any of the strings in the data array (table_2 or table 3).</p>
<p>adding <code>JSON_HEX_QUOT | JSON_HEX_TAG</code> didn't work. </p>
<p>Presumably looping through the array data.data with a function and using .replace() and a reg exp to replace quotes with nothing should be the easiest solution. Any tips on how to loop through a json_encoded array of html strings in an array returned in an ajax callback? </p>
| <p>Don't replace anything anywhere. The only thing you need is to add <code>htmlspecialchars()</code> when you building the HTML string.</p>
<pre><code><?php
// ...
$rows = [];
foreach ($result as $r) {
$rows[] = '<tr><td>'.htmlspecialchars($r['id'])
.'</td><td>'.htmlspecialchars($r['phone_number'])
.'</td></tr>';
}
header('Content-Type: application/json; encoding=utf-8');
echo json_encode(array('table_rows' => join("\n", $rows)));
</code></pre>
<p>Then, when you receive such JSON, just put it into HTML as it is.</p>
<pre><code>$('table#display').html(received_data.table_rows);
</code></pre>
<p>But there is better way to implement this. -- Send only data without markup via JSON and build markup in JS:</p>
<pre><code><?php
// ...
$rows = [];
foreach ($result as $r) {
$rows[] = [
'id' => $r['id'],
'phone_number' => $r['phone_number']
];
}
header('Content-Type: application/json; encoding=utf-8');
echo json_encode(array('table_rows' => $rows));
</code></pre>
<p>And then:</p>
<pre><code>// ...
for(var i = 0; i < received_data.table_rows.length; i++) {
var r = received_data.table_rows[i];
$table.append($('<tr>')
.append($('td').text(r.id))
.append($('td').text(r.phone_number))
);
}
</code></pre>
|
I am using Kivy in Python and only the last button has it's embedded objects appearing <p>I apologize in advance if my question is stupid or obvious, but I have been researching this over and over and am coming up with nothing. I am currently using Kivy and have multiple buttons in a gridlayout, which is in a scrollview. Withing these buttons I have a label and an image. Only the last of my buttons shows the label and image whenever I run my code. I think it has something to do with the positions, but I can't figure out what it is. Here is my code:</p>
<pre><code> Window.clearcolor = (0.937, 0.698, 0.176, 1)
class Solis(App):
def build(self):
b1 = Button(text= "",
background_color=(237, 157, 59, 1),
size_hint_y= None,
background_normal = '',
valign = 'middle',
font_size=20)
lab1 = Label(text= Content1,
color= (0.937, 0.698, 0.176, 1),
valign= 'middle',
pos=(b1.x , b1.height / 2))
b1I = AsyncImage(source = lead1image)
def callback1(self):
webbrowser.open(lead1)
b1.bind(on_press=callback1)
b2 = Button(text= "",
background_color=(237, 157, 59, 1),
size_hint_y= None,
background_normal = '',
valign = 'middle',
font_size=20)
lab2 = Label(text= Content2,
color= (0.937, 0.698, 0.176, 1),
valign= 'middle',
halign= 'center',
pos=(b2.x + 800, b2.height))
b2I = AsyncImage(source = lead2image)
def callback2(self):
webbrowser.open(lead2)
b2.bind(on_press=callback2)
b3 = Button(text= "",
background_color=(237, 157, 59, 1),
size_hint_y= None,
background_normal = '',
valign = 'middle',
font_size=20)
lab3 = Label(text= Content3,
color= (0.937, 0.698, 0.176, 1),
valign= 'middle',
pos=(b3.x + 800, b3.height / 4))
b3I = AsyncImage(source = lead3image)
def callback3(self):
webbrowser.open(lead3)
b3.bind(on_press=callback3)
l = GridLayout(cols=1, spacing=10, size_hint_y=None, orientation = 'vertical')
l.bind(minimum_height=l.setter('height'))
s = ScrollView(size_hint=(1, None), size=(Window.width, Window.height))
s.add_widget(l)
l.add_widget(b1)
l.add_widget(b2)
l.add_widget(b3)
b1.add_widget(b1I)
b1.add_widget(lab1)
b2.add_widget(b2I)
b2.add_widget(lab2)
b3.add_widget(b3I)
b3.add_widget(lab3)
return s
if __name__ == "__main__":
Solis().run()
</code></pre>
<p>And here is my result <a href="https://i.stack.imgur.com/CMkTi.png" rel="nofollow">here</a></p>
| <p>Here is something that should help you get what you want:</p>
<p>A main.py like this:</p>
<pre><code>from kivy.app import App
import webbrowser
class Solis(App):
def __init__(self, **kwargs):
super(Solis, self).__init__(**kwargs)
self.lead1image='https://pbs.twimg.com/profile_images/562300519008333825/6WcGRXLU.png'
self.lead2image='https://pbs.twimg.com/profile_images/439154912719413248/pUBY5pVj.png'
self.lead3image='https://pbs.twimg.com/profile_images/424495004/GuidoAvatar.jpg'
def callback(self,url):
webbrowser.open(url)
if __name__ == '__main__':
Solis().run()
</code></pre>
<p>And a solis.kv like this:</p>
<pre><code>ScrollView:
GridLayout:
cols:1
size_hint_y:None
height: self.minimum_height
Button:
size_hint_y: None
height:'50dp'
on_press: app.callback(app.lead1image)
AsyncImage:
id:im1
size_hint: None, None
height: self.parent.height
width: '48dp'
source: app.lead1image
pos: (self.parent.x, self.parent.y)
Label:
size_hint: None, None
height:self.parent.height
width: self.parent.width - im1.width
text: 'Text for the 1st Label'
pos: (self.parent.x, self.parent.y)
Button:
size_hint_y: None
height:'50dp'
on_press: app.callback(app.lead2image)
AsyncImage:
size_hint: None, None
height: self.parent.height
width: '48dp'
source: app.lead2image
pos: (self.parent.x, self.parent.y)
Label:
size_hint: None, None
height:self.parent.height
width: self.parent.width - im1.width
text: 'Text for the 2st Label'
pos: (self.parent.x, self.parent.y)
Button:
size_hint_y: None
height:'50dp'
on_press: app.callback(app.lead3image)
AsyncImage:
size_hint: None, None
height: self.parent.height
width: '48dp'
source: app.lead3image
pos: (self.parent.x, self.parent.y)
Label:
size_hint: None, None
height:self.parent.height
width: self.parent.width - im1.width
text: 'Text for the 2st Label'
pos: (self.parent.x, self.parent.y)
</code></pre>
<p>Thus, there is now two files (a ".py" and a ".kv"): This will help you separate the logic of your application from its User Interface. Note that it is possible to reduce the length of the code with some customized widgets. Also, if you want to keep juste one .py file, I would add a "for" loop.
Finally, regarding your issue: I guess your labels and images were superimposed. I avoided this by using "pos:".</p>
|
Only recording motion using gaussian mixture models <p>I am using <a href="http://www.mathworks.com/help/vision/examples/detecting-cars-using-gaussian-mixture-models.html?prodcode=VP&language=en" rel="nofollow">this example</a> on Gaussian mixture models. </p>
<p>I have a video displaying moving cars, but it's on a street that isn't very busy. A few cars go past every now and again, but the vast majority of the time there isn't any motion in the background. It gets pretty tedious watching nothing moving, so I would like to cut that time out. Is it possible to remove the still frames from the video, only leaving the motion frames? I guess it would essentially crop the video.</p>
| <p>The example you give uses a foreground detector. Still frame should not have foreground pixels detected. You can then choose to skip them when building a demo video of your results.</p>
<p>You can build your new video by creating a rule a the type if N frames in a row do not contain foreground, do not write these frames in the output video.</p>
<p>This is just an idea...</p>
|
VS2015 bower glitch with versions <p>I have a problem with VS2015 Community and Bower plugin.
I tried to install bootstrap version 3.3.7 (3.3.6 and early). You can see my <code>bower.json</code> file: </p>
<p><img src="https://i.stack.imgur.com/pvPGE.png" alt="bower.json">
but always see latest version only downloaded in libs folder: </p>
<p><img src="https://i.stack.imgur.com/BkjlL.png" alt="screen of bootstrap file from libs">
I have no ideas why it happen. Can someone help to understand why bower ignore requested version?</p>
| <p>Found reason, it was a old Git version installed issue.
Not VS or Bower problem. When I updated Git to latest and clear Bower cache I got correct version of libs. Don't know why Bower or Git don't show error when it can't execute my request correctly!</p>
|
Trying to repeat a value from a JSON API and AngularJS <p>I'm using PetFinder API with Angular to display a JSON list. The problem I get stuck in is how to ng-repeat an array. My current code is the following:</p>
<p>AngularJS:</p>
<pre><code> awesomePF.controller('dogsController', function($scope, $http) {
...
$scope.dogSearch = function(dogBreed, dogCity, dogState) {
var durl = "https://crossorigin.me/http://api.petfinder.com/pet.find?key=1f0c7f48315c13e63b7b7923cacc7959&breed="+dogBreed+"&location="+dogCity+","+dogState+"&format=json";
$http.get(durl)
.then(function(res){
for(var i = 0; i < x.length; i++ ){
$scope.doggies = res.data.petfinder.pets.pet[x];
}
console.log(res.data);
});
};
});
</code></pre>
<p>..or where the "for" is, I tried using simpler code like
<code>$scope.doggies = res.data.petfinder.pets;</code>
and worked my way up using <code><ul ng-repeat="pet in doggies"></code> </p>
<p>The current work is <a href="http://www.angelcenteno.com/pf-mock/index.html#/dogs" rel="nofollow">located here</a> and the query I'm using is Orlando Florida.</p>
<p>This is how the json looks like:
<a href="https://i.stack.imgur.com/vJWYZ.png" rel="nofollow"><img src="https://i.stack.imgur.com/vJWYZ.png" alt="enter image description here"></a></p>
<p><strong>EDIT</strong>:</p>
<p>More info. I can't seem to repeat the array. For example, I need only the dog's name to repeat for all pets in Orlando Florida. It can only get one at a time because I can only seem to get one result at a time: <code>{{ pet[0].name.$t }}</code>. I need the array to be a var instead of just one number</p>
<p>Thanks in advance.</p>
| <p>Looks to me like it should look like this</p>
<pre><code>$http.get(durl).then(function(res) {
$scope.doggies = res.data.petfinder.pets.pet;
});
</code></pre>
<p>then in your template</p>
<pre><code><dl ng-repeat="dog in doggies track by dog.id.$t">
<dt>Name</dt>
<dd>{{dog.name.$t}}</dd>
</dl>
</code></pre>
|
Unable to update main form control from subclass <p>Attempt #2.</p>
<p>I'm attempting to call functions within two classes. One function to obtain data and call function B in class B to display the data through a Windows Form application. </p>
<pre><code> //Class B containing function B
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GUI_Server
{
public partial class ChatServer : Form
{
private delegate void EnableDelegate(bool enable);
private static ChatServer CHT = new ChatServer();
public ChatServer()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
ServerBackBone.test();
}
public static void TestConnectivity(string text)
{
CHT.TestLabel.Text = text;
}
}
} // Assume Class B
</code></pre>
<p>and the following is Class A and function A</p>
<pre><code> using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace GUI_Server
{
class ServerBackBone
{
private static ChatServer CHT = new ChatServer();
public static void test()
{
ChatServer.TestConnectivity("test");
}
}
}
</code></pre>
<p>So, what is going on here is that the form is being loaded, calling a static function within class A to contact class B > function B to update a label on the main window... The problem lays with updating the label with the new text. </p>
<p>Stepping through the code shows that all functions are successfully called & expected text is passed through to the function. </p>
<p>Although, when pressing F5 to start debugging said application, Diagnostic tools show the following message: </p>
<blockquote>
<p>The diagnostic tools failed unexpectedly</p>
</blockquote>
<p>The diagnostic hub output shows: </p>
<blockquote>
<p>Response status code does not indicate success: 401 (Unauthorized).</p>
</blockquote>
<p>General output shows: </p>
<blockquote>
<p>The thread 0x20c0 has exited with code 0 (0x0).</p>
<p>The thread 0x1624 has exited with code 0 (0x0).</p>
<p>'GUI Server.vshost.exe' (CLR v4.0.30319: GUI Server.vshost.exe):
Loaded 'c:\users\shaiya\documents\visual studio 2015\Projects\GUI
Server\GUI Server\bin\Debug\GUI Server.exe'. Symbols loaded.</p>
<p>The thread 0x20fc has exited with code 0 (0x0).</p>
<p>The thread 0xae8 has exited with code 0 (0x0).</p>
</blockquote>
<p>Application successfully runs after these messages show. Stepping through shows now errors, nor do breakpoints. Label is not updated in the main control either </p>
<p>Completely new project. Only element on the actual form interface is the label with the property renamed to TestLabel.</p>
<pre><code> this.TestLabel = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// TestLabel
//
this.TestLabel.AutoSize = true;
this.TestLabel.Location = new System.Drawing.Point(43, 70);
this.TestLabel.Name = "TestLabel";
this.TestLabel.Size = new System.Drawing.Size(35, 13);
this.TestLabel.TabIndex = 0;
this.TestLabel.Text = "label1";
</code></pre>
| <p>I'm not sure that <code>this</code> in <code>Form1_Load</code> and <code>CHT</code> in <code>TestConnectivity</code> are the same object. They would have to be, because it is <code>this</code> that you are trying to update.</p>
|
Vim: How do I jump back from a multi-line move? <p>In vim, I usually have <code>:set relativenumber</code> active so that I can see what line to move to with a quick <code><n>k</code> or <code><n>j</code>. This allows me to move around quite efficiently, but as always in vim, I want more!</p>
<p>Is there a way to add the origin of a long (say, more than 5 lines) <code><n>j</code> or <code><n>k</code> movement added to the jump-list, so that I can use `` (backtick-backtick) to jump back to it? While we are at it, adding the origin of a sequence of <code>ctrl-f</code> or <code>ctrl-b</code> would be nice too!</p>
| <p>There's the <a href="http://www.vim.org/scripts/script.php?script_id=4571" rel="nofollow">reljump plugin</a>. Or you could just put the following into your <code>~/.vimrc</code>; adapt the limit of <code>1</code> to your needs (e.g. <code>4</code>):</p>
<pre><code>nnoremap <expr> k (v:count > 1 ? "m'" . v:count : '') . 'k'
nnoremap <expr> j (v:count > 1 ? "m'" . v:count : '') . 'j'
</code></pre>
|
How to add buttons to a JavaFX gui via the controller.java file using the fx:id of a GridPane <p>Still relatively new to JavaFX and I'm having a bit of trouble getting buttons to add to a GUI that I've setup.</p>
<p>I have 3 files: Main.java, Controller.java, and sample.fxml (each located below)</p>
<p>From what I've read via tutorials and docs, the Controller.java file is loaded and linked to the fxml file due to the "fx:controller" section -- but beyond that I cannot properly get the program to run that method.</p>
<p>I've tried setting up the Main.java to be the controller and just fusing the code in that way (bombed). Even actively went against the form and trying creating a new instance of the Controller.java in the Main.java file (which would essentially just be creating another instance alongside of what's loaded when the program runs) and that too bombed.</p>
<p>Any pointers?</p>
<p><strong>Main.java</strong></p>
<pre><code>package soundboardEoZ;
import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class Main extends Application {
int sound_index = 1;
int target = 10;
@Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Hello World");
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();
while (sound_index < target){
// This is where I want to call the addButton() method from Controller.java
sound_index++;
}
}
public static void main(String[] args) {
launch(args);
}
}
</code></pre>
<p><strong>Controller.java</strong></p>
<pre><code>package soundboardEoZ;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
public class Controller {
int index = 2;
int target = 10;
@FXML
GridPane button_grid;
void test(){
System.out.println("Testing");
}
void addButton(){
Button sound_button = new Button("Button_" + index);
button_grid.add(sound_button, index,2);
}
}
</code></pre>
<p><strong>And our FXML file</strong></p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Menu?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.control.SeparatorMenuItem?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.Pane?>
<?import javafx.scene.layout.RowConstraints?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.text.Text?>
<!--VBox is a single column panel-->
<?import javafx.scene.text.Font?>
<VBox id="vbox" prefHeight="400" prefWidth="1000" xmlns="http://javafx.com/javafx/8.0.76-ea" xmlns:fx="http://javafx.com/fxml/1" fx:controller="soundboardEoZ.Controller">
<MenuBar fx:id="menuBar"> <!--Literally a MenuBar-->
<menus> <!--Holds the menu concept for the bar-->
<Menu text="File"> <!--Menu holds Items-->
<items>
<MenuItem text="New" />
<MenuItem text="Open" />
<SeparatorMenuItem />
<MenuItem text="Save Settings" />
<SeparatorMenuItem />
<MenuItem text="Settings" />
</items>
</Menu>
<Menu text="Edit">
<items>
<MenuItem text="Copy" />
</items>
</Menu>
<Menu text="About">
<items>
<MenuItem text="Team" />
</items>
</Menu>
<Menu text="Help">
<items>
<MenuItem text="Guide" />
<MenuItem text="Forums" />
</items>
</Menu>
</menus>
</MenuBar>
<Pane>
<GridPane>
<Button GridPane.columnIndex="0">I'm another Test</Button>
<Text fill="RED" stroke="BLACK" strokeWidth="2.0" GridPane.columnIndex="1">
<font><Font size="25"/></font>
Testing
</Text>
</GridPane>
</Pane>
<GridPane fx:id="button_grid" hgap="10" vgap="10" xmlns:fx="http://javafx.com/fxml">
<!--<Button GridPane.columnIndex="0" GridPane.rowIndex="1">Hello!</Button>-->
<!--<Button GridPane.columnIndex="1">Hiya!</Button>-->
<!--<Text text="Clickity!" GridPane.columnIndex="0" GridPane.rowIndex="0" GridPane.columnSpan="2" />-->
<!--<Label text="Configuration Name:" GridPane.columnIndex="0" GridPane.rowIndex="1" />-->
<!--<TextField GridPane.columnIndex="1" GridPane.rowIndex="1" />-->
<!--<Button fx:id="test_button" text="Hello"></Button>-->
</GridPane>
</VBox>
</code></pre>
| <p>The <code>Application</code> subclass - <code>Main</code> in your example - is really supposed to just startup the application. I.e. it should load the FXML, put it in a window, and show the window. Initialization and other configuration of the UI defined by the FXML, along with event handling, should be done by the controller. So you are not really trying to execute this code from the correct place. You should just do this from the controller:</p>
<pre><code>package soundboardEoZ;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
public class Controller {
int index ;
int target = 10;
@FXML
GridPane button_grid;
public void initialize() {
for (index = 2; index < target ; index++) {
addButton();
}
}
public void test(){
System.out.println("Testing");
}
public void addButton(){
Button sound_button = new Button("Button_" + index);
button_grid.add(sound_button, index,2);
}
}
</code></pre>
<p>and then remove all that functionality from <code>Main</code>:</p>
<pre><code>package soundboardEoZ;
import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Hello World");
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
</code></pre>
<hr>
<p>If you really want to call that method from <code>Main</code> (but again, I can't emphasize enough that this is really using the toolkit in a way contrary to the patterns around which it was designed), create an <code>FXMLLoader</code> instance and get the controller from it. You'll need the controller to track the index properly:</p>
<pre><code>package soundboardEoZ;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
public class Controller {
int index = 2;
@FXML
GridPane button_grid;
public void test(){
System.out.println("Testing");
}
public void addButton(){
Button sound_button = new Button("Button_" + index);
button_grid.add(sound_button, index,2);
index++;
}
}
</code></pre>
<p>and then you could do:</p>
<pre><code>package soundboardEoZ;
import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class Main extends Application {
int sound_index = 1;
int target = 10;
@Override
public void start(Stage primaryStage) throws Exception{
FXMLLoader loader = new FXMLLoader(getClass().getResource("sample.fxml"));
Parent root = loader.load();
primaryStage.setTitle("Hello World");
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();
Controller controller = loader.getController();
while (sound_index < target){
controller.addButton();
sound_index++;
}
}
public static void main(String[] args) {
launch(args);
}
}
</code></pre>
|
Indentation on python <p>My python program isnt running. Im sure im missing something but im pretty sure i just indented wrong. Can anyone lend me a hand? thank you!</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>def main():
sales = getSales()
advancedPay = getAdvancedPay()
commRate = DetermineCommRate(sales)
pay = (sales * commRate) - advancedPay
print("The pay is $". format(pay, ",.2f"), sep="")
if pay < 0:
print("The salesperson must reimburse")
print("the company")
def getSales():
monthlySales = float(input("Enter the monthly sales: "))
return monthlySales
def getAdvancedPay():
print("Enter the amount of advanced pay or ")
print("Enter 0 if no advanced pay was given. ")
advancedPay - float(input("Advanced pay: ")
return advancedPay
def DetermineCommRate
if sales < 10000:
rate = 0.10
elif sales >= 10000 and sales <= 14999.99:
rate = 0.12
elif sales >= 15000 and sales <= 17999.99:
rate = 0.14
elif sales >= 18000 and sales <= 21999.99:
rate = 0.16
else:
rate = 0.18
return rate
main()</code></pre>
</div>
</div>
</p>
<p>My python program isnt running. Im sure im missing something but im pretty sure i just indented wrong. Can anyone lend me a hand? thank you!</p>
| <p>From what I can see, <code>sales</code> is a local variable in the <code>main()</code>, and you are trying to access it in <code>DetermineCommRate</code>, and you have syntax errors in the definition of that function</p>
<pre><code>def DetermineCommRate(sales):
</code></pre>
<p>Currently, you are passing sales to it, but not accepting it. </p>
<p>Also, your following line should be indented to run in the main()</p>
<pre><code>if pay < 0:
print("The salesperson must reimburse")
print("the company")
</code></pre>
<p>And a syntax error in this line too</p>
<pre><code>advancedPay = float(input("Advanced pay: "))
</code></pre>
|
Read colon tags values XML PHP <p>I've already read those topics:
<a href="http://stackoverflow.com/questions/1575788/php-library-for-parsing-xml-with-a-colons-in-tag-names">PHP library for parsing XML with a colons in tag names?</a> and
<a href="http://stackoverflow.com/questions/1186107/simple-xml-dealing-with-colons-in-nodes">Simple XML - Dealing With Colons In Nodes</a> but i coundt implement those solutions.</p>
<pre><code><item>
<title> TITLE </title>
<itunes:author> AUTHOR </itunes:author>
<description> TEST </description>
<itunes:subtitle> TEST </itunes:subtitle>
<itunes:summary> TEST </itunes:summary>
<itunes:image href="yoyoyoyo.jpg"/>
<pubDate> YESTERDAY </pubDate>
<itunes:block>no</itunes:block>
<itunes:explicit>no</itunes:explicit>
<itunes:duration>99:99:99</itunes:duration>
<itunes:keywords>key, words</itunes:keywords>
</item>
</code></pre>
<p>I want to get only itunes:duration and itunes:image. Here is my code:</p>
<pre><code>$result = simplexml_load_file("http://blablabla.com/feed.xml");
$items = $result->xpath("//item");
foreach ($items as $item) {
echo $item->title;
echo $item->pubDate;
}
</code></pre>
<p>I tried using <code>children()</code> method but when i try to <code>print_r</code> it it says that the node no longer exists.</p>
| <p>You should use the <code>children()</code> on the <code>$item</code> element to get it's child-elements:</p>
<pre><code>$str =<<< END
<item>
<title> TITLE </title>
<itunes:author> AUTHOR </itunes:author>
<description> TEST </description>
<itunes:subtitle> TEST </itunes:subtitle>
<itunes:summary> TEST </itunes:summary>
<itunes:image href="yoyoyoyo.jpg"/>
<pubDate> YESTERDAY </pubDate>
<itunes:block>no</itunes:block>
<itunes:explicit>no</itunes:explicit>
<itunes:duration>99:99:99</itunes:duration>
<itunes:keywords>key, words</itunes:keywords>
</item>
END;
$result = @simplexml_load_string($str);
$items = $result->xpath("//item");
foreach ($items as $item) {
echo $item->title . "\n";
echo $item->pubDate . "\n";
echo $item->children()->{'itunes:duration'} . "\n";
}
</code></pre>
<p>Output:</p>
<pre><code>TITLE
YESTERDAY
99:99:99
</code></pre>
|
Dynamic struct member names like in javascript in golang <p>I am writing a multi-lang website.
I read the language info from users cookies, and I have several translation modules such as <code>en.go</code> <code>gr.go</code> etc.
The modules are of type <code>map[string]string</code>.The problem here is in javascript I can do something like <code>lang[cookies.lang]["whatever message"].'But go does not support accessing struct members in this way.
I could make switch case or</code>map[string]map[string]string` and map all possible languages, but this is much extra work.
So is there any way golang provides some way to access members like js brackets notation?
Not: There was a similar question on the stack, and somebody wrote to use "reflect" package, but I could not quite understand how it works and failed to reproduce by myself works and failed to reproduce by myself.</p>
| <p>One possible route would be to use a <code>map[string]map[string]string</code>.</p>
<p>You could then have a base package in which you declare your base translation variable and in your translation modules, you can use an <code>init</code> function to populate the relevant sub-map. It's essentially optional if you want to do this as separate packages or just separate files (doing it as packages means you have better compile-time control of what languages to include, doing it as files is probably less confusing).</p>
<p>If you go the packages root, I suggest the following structure:</p>
<pre><code>translation/base This is where you export from
translation/<language> These are "import only" packages
</code></pre>
<p>Then, in translation/base:</p>
<pre><code>package "base"
var Lang map[string]map[string]string
</code></pre>
<p>And in each language-specific package:</p>
<pre><code>package "<language code>"
import "language/base"
var code = "<langcode>"
func init() {
d := map[string]string{}
d[<phrase1>] = "your translation here"
d[<phrase2>] = "another translation here"
// Do this for all the translations
base.Lang[code] = d
}
</code></pre>
<p>Then you can use this from your main program:</p>
<pre><code>package "..."
import (
"language/base"
_ "language/lang1" // We are only interested in side-effects
_ "language/lang2" // Same here...
)
</code></pre>
<p>Not using separate packages is (almost) the same. You simply ensure that all the files are in the same package and you can skip the package prefix for the <code>Lang</code> variable.</p>
<p>A toy example <a href="https://play.golang.org/p/4ctb4BoBr0" rel="nofollow">on the Go Playground</a>, with all the "fiddly" bits inlined.</p>
|
VSTS API Refresh Token Expires <p>I'm using the VSTS REST API. I use the refresh token, as instructed, to refresh the access token. This morning, the refresh tokens stopped working. Do they expire? If the access token and refresh token have both expired, how do I proceed? I can't find anything on this.</p>
<p>For reference: <a href="https://www.visualstudio.com/en-us/docs/integrate/get-started/auth/oauth#refresh-an-expired-access-token" rel="nofollow">https://www.visualstudio.com/en-us/docs/integrate/get-started/auth/oauth#refresh-an-expired-access-token</a></p>
| <p>Yes, the refresh token will be expired, you need to send request to re-authorize to get access token and refresh token again (your previous steps to authorize).</p>
|
Exclude matched regex pattern <p>I want to match all consecutive lines, prefixed with a space until a line starts without a space!</p>
<p>The problem is that the "end pattern" [^ ] is part of the match. The end pattern is a start-of-line not starting with a space.</p>
<p>The used pattern: <code>(?im)(?:^( (?s:.*?))(?:^[^ ])) /g</code></p>
<p>See example at
<a href="https://regex101.com/r/msVC5b/1" rel="nofollow">https://regex101.com/r/msVC5b/1</a></p>
<p>Please can anyone help me? I've spent hours and hours searching on SO and trying negative lookarounds ;)</p>
| <p>If I've interpreted your request right, you're overthinking it. The pattern you want is this:</p>
<pre><code>/(?:^ .+\n)+/gm
</code></pre>
<p>What it'll do is match every line that starts with a space and ends with a newline, one or more times, in a contiguous fashion.</p>
<p><a href="https://regex101.com/r/msVC5b/6" rel="nofollow">Demo on Regex101 (adapted from yours)</a></p>
|
Adding category id or name to where clause $wpdb <p>This seems like it should be an easy answer but im struggling with this. How can I add category ID to the where clause? I have a bunch of post categories and I want to sort where category ID = 4 or category name = Restaurants. Below is my working $wpdb get_results but without category id or name in the where clause. How do I add this?</p>
<pre><code>$posts = $wpdb->get_results("SELECT *, ( 6371 * acos( cos( radians($currLat) ) * cos( radians( m1.meta_value ) ) * cos( radians( m2.meta_value ) - radians($currLong) ) + sin( radians($currLat) ) * sin( radians( m1.meta_value ) ) ) ) AS distance, m3.meta_value as bAddressOne, m1.meta_value as bLat, m2.meta_value as bLong, m4.meta_value as bOpenClose
FROM wp_posts p
LEFT JOIN wp_postmeta m1
ON p.id = m1.post_id AND m1.meta_key = 'bLat'
LEFT JOIN wp_postmeta m2
ON p.id = m2.post_id AND m2.meta_key = 'bLong'
LEFT JOIN wp_postmeta m3
ON p.id = m3.post_id AND m3.meta_key = 'bAddressOne'
LEFT JOIN wp_postmeta m4
ON p.id = m4.post_id AND m4.meta_key = 'bOpenClose'
WHERE post_type='el2-business' HAVING distance < $thedistance ORDER BY distance");
</code></pre>
| <p>Assuming that you are using the 'category' taxonomy and interested in the posts with either term id 4 or term name 'Restaurants', the query would look something like:</p>
<pre><code>...
LEFT JOIN wp_postmeta m4
ON p.id = m4.post_id AND m4.meta_key = 'bOpenClose'
INNER JOIN wp_term_relationships AS tr
ON tr.object_id = ID
INNER JOIN wp_term_taxonomy AS tt
ON tr.term_taxonomy_id = tt.term_taxonomy_id AND tt.taxonomy = 'category'
INNER JOIN wp_terms AS t
ON tt.term_id = t.term_id
WHERE (tt.term_id = 4 OR t.name = 'Restaurants') AND post_type='el2-business' HAVING distance < $thedistance ORDER BY distance");
</code></pre>
|
sklearn: semi-supervised learning - LabelSpreadingModel memory error <p>I am using the <code>sklearn LabelSpreadingModel</code> as below:</p>
<pre><code>label_spreading_model = LabelSpreading()
model_s = label_spreading_model.fit(my_inputs, labels)
</code></pre>
<p>But I got the following errors:</p>
<pre><code> MemoryErrorTraceback (most recent call last)
<ipython-input-17-73adbf1fc908> in <module>()
11
12 label_spreading_model = LabelSpreading()
---> 13 model_s = label_spreading_model.fit(my_inputs, labels)
/usr/local/lib/python2.7/dist-packages/sklearn/semi_supervised/label_propagation.pyc in fit(self, X, y)
224
225 # actual graph construction (implementations should override this)
--> 226 graph_matrix = self._build_graph()
227
228 # label construction
/usr/local/lib/python2.7/dist-packages/sklearn/semi_supervised/label_propagation.pyc in _build_graph(self)
455 affinity_matrix = self._get_kernel(self.X_)
456 laplacian = graph_laplacian(affinity_matrix, normed=True)
--> 457 laplacian = -laplacian
458 if sparse.isspmatrix(laplacian):
459 diag_mask = (laplacian.row == laplacian.col)
MemoryError:
</code></pre>
<p>Looks like something wrong with the laplacian of my input matrix. Is there any parameter I can config or any change that I can avoid this error? Thanks!</p>
| <p><strong>It's obvious: your PC is running out of memory.</strong></p>
<p>As you are not setting any parameters, the <strong>rbf-kernel is used by default</strong> (<a href="http://scikit-learn.org/stable/modules/generated/sklearn.semi_supervised.LabelSpreading.html#sklearn.semi_supervised.LabelSpreading" rel="nofollow">proof</a>).</p>
<p>Some excerpt from <a href="http://scikit-learn.org/stable/modules/label_propagation.html#label-propagation" rel="nofollow">scikit-learn's docs</a>:</p>
<pre><code>The RBF kernel will produce a fully connected graph which is represented in
memory by a dense matrix. This matrix may be very large and combined with the
cost of performing a full matrix multiplication calculation for each iteration
of the algorithm can lead to prohibitively long running times
</code></pre>
<p>Maybe the following (next sentence in the docs above) will help:</p>
<pre><code>On the other hand, the KNN kernel will produce a much more memory-friendly
sparse matrix which can drastically reduce running times.
</code></pre>
<p>But i don't know your data, PC-configuration and co. and can only guess...</p>
|
Unable to place a Bitmap file on Desktop <p>I'm creating a Drawing Application and for that i need to create a bitmap for a panel. My problem is when I get the desktop placement it gives me the Error of
" Field initializer cannot reference the non-static field, method, or property 'Form1.path'" </p>
<pre><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace Paint_AppLication
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private bool mouse_down = false;
//My Problem
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
private Bitmap bit = new Bitmap(path + "\\" + "Bitmap.bmp");
// Other Code Not my problem
private Color col = Color.Black;
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
mouse_down = true;
}
private void panel1_MouseUp(object sender, MouseEventArgs e)
{
mouse_down = false;
}
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
toolStripStatusLabel1.Text = e.X + ", " + e.Y;
if (mouse_down == true)
{
panel1.BackgroundImage = bit;
bit.SetPixel(e.X, e.Y, col);
}
}
private void button1_Click(object sender, EventArgs e)
{
colorDialog1.ShowDialog();
col = colorDialog1.Color;
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
</code></pre>
| <p><strong>Because your field must be static:</strong></p>
<p>Initial code:</p>
<pre><code>using System;
using System.Drawing;
internal class MyClass1
{
private readonly string _path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
private Bitmap _bitmap = new Bitmap(_path + "\\" + "Bitmap.bmp");
}
</code></pre>
<p>Fixed code:</p>
<pre><code>using System;
using System.IO;
internal class MyClass2
{
private static readonly string _path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
private Bitmap _bitmap = new Bitmap(_path + "\\" + "Bitmap.bmp");
}
</code></pre>
<p>Even better, let <code>System.IO.Path</code> class build the path:</p>
<p>No more static field is required.</p>
<pre><code>using System;
using System.Drawing;
using System.IO;
internal class MyClass3
{
private Bitmap _bitmap =
new Bitmap(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Bitmap.bmp"));
}
</code></pre>
|
How to use a unit-testing framework for a function that has a dynamic output in Racket? <p>I was doing exercise 3.5 on SICP book.</p>
<p>A Monte Carlo implementation in Racket generates the following code:</p>
<pre><code>(define (monte-carlo trials experiment)
(define (iter trials-remaining trials-passed)
(cond ((= trials-remaining 0)
(/ trials-passed trials))
((experiment)
(iter (- trials-remaining 1) (+ trials-passed 1)))
(else
(iter (- trials-remaining 1) trials-passed))))
(iter trials 0))
(define (random-in-range low high)
(let ((range (- high low)))
(+ low (random range))))
; questão propriamente dita
(define (estimate-integral predicate x1 x2 y1 y2 trials)
(*(* (- x1 x2) (- y1 y2))
(monte-carlo trials predicate)))
(define (circulo?)
(>= 1 (+ (square (random-in-range -1 1))
(square (random-in-range -2 1)))))
(define (estimate-pi)
(estimate-integral circulo? -1.0 1 -2 1 100000))
; Fiquei brincando com os os parametros do retangulo, desde que o circulo continue dentro dele
(define square
(lambda (x) (* x x)))
</code></pre>
<p>The code is right.
However, I decided to insert some unit tests.</p>
<p>Hence, I imported the library rackunit and used the following test:</p>
<pre><code>(require rackunit)
(check-equal? (estimate-pi) 3.00906)
</code></pre>
<p>This is obviously a problem and the tests will always fail since the output is dynamic due to a random function.</p>
<p>What should I do in this case?</p>
| <p>There's a built-in check for this - the preferred solution:</p>
<pre><code>(check-= (estimate-pi) 3.1416 1e-4 "Incorrect value for pi")
</code></pre>
<p>The previous check verifies that the result falls within an acceptable <em>tolerance</em> value (also known as <em>epsilon</em>), and it's equivalent to this:</p>
<pre><code>(check-true (<= (abs (- (estimate-pi) 3.1416)) 1e-4))
</code></pre>
<p>The <code>1e-4</code> part is the tolerance in scientific notation, it means that if the difference between the actual value and the expected value is less than <code>0.0001</code>, then we accept the result as correct. Of course, you can tweak the tolerance value to suit your needs - the smaller the number, the higher the required precision. Also, it's useful to know that if <code>check-=</code> didn't exist, we could define our own check, like this:</p>
<pre><code>(define-binary-check (check-in-tolerance actual expected tolerance)
(<= (abs (- actual expected)) tolerance))
(check-in-tolerance (estimate-pi) 3.1416 1e-4)
</code></pre>
|
How do I concat a string of chars together from a matrix in python? <p>The problem I'm working on is outputting a matrix in a clockwise inwards spiral. My code, right now, does this but the output is a little different than what is expected. </p>
<pre><code>matrix = [
['a','d','g','e','t','c'],
['p','k','h','w','e','f'],
['m','j','y','h','b','n'],
['e','o','j','n','g','y']
]
def spiralPrint(mat):
top = 0
left = 0
right = len(mat[0])-1
bot = len(mat)-1
result = []
while(True):
#TRAVERSE ACROSS TOP ROW
for j in range(left, right+1, 1):
result.append(mat[top][j])
#INC TOP INDEX SO WE DON'T REPEAT
top += 1
#EXIT CONDITION
if top > bot or left > right:
break
#TRAVERSE RIGHTMOST COLUMN
for i in range(top, bot+1, 1):
result.append(mat[i][right])
right -= 1
if top > bot or left > right:
break
#TRAVERSE BOTTOM ROW
for k in range(right, left-1, -1):
result.append(mat[bot][k])
bot -=1
if top > bot or left > right:
break
#TRAVERSE LEFT COLUMN
for p in range(bot, top-1, -1):
result.append(mat[p][left])
if top > bot or left > right:
break
left += 1
return result
print(spiralPrint(matrix))
</code></pre>
<p>The output is supposed to look like: adgetcfnygnjoempk...</p>
<p>My output is: ['a', 'd', 'g', 'e', 't', 'c', 'f', 'n', 'y', 'g', 'n', 'j', 'o', 'e', 'm', 'p', 'k', 'h', 'w', 'e', 'b', 'h', 'y', 'j']</p>
<p>How do I output just the chars without the quotes and commas?</p>
| <p>Instead of returning <code>result</code>, do</p>
<pre><code>return ''.join(result)
</code></pre>
<p>As the name implies, it joins the contents of list <code>result</code> into one string. The empty string at the beginning means nothing will be put between successive elements. For more details, see the join section <a href="https://docs.python.org/2/library/stdtypes.html#string-methods" rel="nofollow">here</a>.</p>
<p>You get a list for <code>result</code> rather than a string since you repeatedly <code>append</code> to it, which is a list method. (Of course, you also initialized it as the empty list.) You could concatenate and keep <code>result</code> a string, but using a list then joining together is actually the recommended way of adding characters to a string. So you hit the Pythonic way perhaps by accident.</p>
|
Websphere and MQ as JMS provider: Lost messages <p>We are using the following</p>
<p><strong>Websphere 8.0.0.10</strong></p>
<p><strong>MQ as JMS Provider</strong></p>
<p>I have an MDB that is putting messages on to another Queue like this (gets triggered by a another message) </p>
<pre><code> if (connectionFactory == null) {
throw new BatchProcessException("connectionFactory injection failed");
}
if (queue == null) {
throw new BatchProcessException("queue injection failed");
}
List<Customer> customers = getAllCustomers();
if (customers != null && customers.size() > 0) {
try {
connection = connectionFactory.createConnection();
connection.start();
for (Customer customer : customers) {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = session.createProducer(queue);
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
TextMessage textMessage = session.createTextMessage(customer.toString());
producer.send(textMessage);
session.close();
}
} catch (JMSException e) {
LOG.error("error", e);
} finally {
if (connection != null) {
try {
connection.close();
connection = null;
} catch (JMSException e) {
LOG.error("error closing mq connection", e);
}
}
}
</code></pre>
<p>As you can see, this code is running in a loop creating and putting messages.
All this works fine for us in a lower environment but in another environment, we hit a limit of 10000 msgs only allowed to be put this way. Dont know where the other messages disappeared. We have checked max queue depth and MAXUMSGS. The transaction logs for the queue manager are also the same size. Unfortunately this code running inside an MDB does not get any exception. Could someone please shed some light. Any prompt response would be greatly appreciated. Any details sought would be provided immediately.</p>
<p>I am not an MQ expert but we have configured Websphere to put messages Asynchronously. What that means in terms of a NON_PERSISTENT messages and NOT_TRANSACTED session, if someone could explain would also be very useful.</p>
| <p>If this is happening in production then I would recommend opening a PMR with IBM Support and setting the ticket to Sev 1 so we can get the appropriate SMEs engaged.</p>
|
PL/SQL Triggers in Oracle <p><a href="https://i.stack.imgur.com/af0UO.jpg" rel="nofollow">enter image description here</a></p>
<p>I have the following tables shown in the image. I need to create a trigger that inserts data into an AUDIT table from the PAYMENT table including information about the payment like- who made the payment (pay_from), Oracle user who processed the payment, appointment id (apt_id) and patient who made the payment (patient_id).</p>
<p>From the image above, the PAYMENT table has a relationship with the APPOINTMENT table which in turn has a relationship with PATIENT table.</p>
<p>My question is, how can I add "patient_id" from the APPOINTMENT table into my AUDIT table using the trigger?
This is my code: </p>
<pre><code>CREATE OR REPLACE TRIGGER PAYMENT_AUDIT_TRIGGER
AFTER INSERT ON PAYMENT
FOR EACH ROW
BEGIN
INSERT
INTO AUDIT_LOG VALUES
(
AUDIT_LOG_AUDIT_ID_SEQ.NEXTVAL,
:new.PATIENT_ID,
:new.APT_ID,
USER,
SYSDATE,
:new.PAY_FROM
);
END;
</code></pre>
| <p>This is easy in Oracle because it has both <em>before</em> and <em>after</em> triggers. The difference between them is, as may well be guessed, when they execute -- just before the operation or after the operation.</p>
<p>A <em>before</em> trigger is useful for intercepting the input stream for more sophisticated data testing and/or modifying some of the data (such as generating the key value from a sequence in INSERT operations). By "just before", I mean that all defined integrity checking is performed first -- type checking, check constraints, referential constraints, etc. So you can know that the data has already passed all those checks.</p>
<p>An <em>after</em> trigger is useful for logging the operation that just occurred. If there is any error condition that prevents the operation from finishing, even though it may have passed the initial system checking and the additional checking that may have taken place by the <em>before</em> trigger, this trigger will not execute. A handy feature of this trigger is that the row presented to it will be exactly the row that was inserted/updated/deleted. That means the generated key value will be there for the <em>after INSERT</em> trigger.</p>
<p>This description is for Oracle and other systems that have both types of triggers. SQL Server only has the <em>after</em> trigger although it has recently extended the <em>instead of</em> trigger to work with tables -- in effect, making it a <em>before</em> trigger, although there are differences with "normal" triggers so users should read the documentation to be aware of these differences.</p>
|
bash find doesn't find text with underscores in it <p>new thing making me crazy today:</p>
<p>create a file with this text:</p>
<pre><code>get_modal_file_name_from_service
get_modal_file_name_from
get_modal_file_name
get_modal_file
get_modal
</code></pre>
<p>name it foo.py</p>
<p>then try these commands in order:</p>
<pre><code>find . -type f -name "*.py" | xargs -Ifile grep -nH "get_modal_file_name_from" file
find . -type f -name "*.py" | xargs -Ifile grep -nH "get_modal_file_name" file
find . -type f -name "*.py" | xargs -Ifile grep -nH "get_modal_file" file
</code></pre>
<p>but this works: </p>
<pre><code>find . -type f -name "*.py" | xargs -Ifile grep -nH "get_modal" file
</code></pre>
<p>wtf? why didn't the first 3 commands work?</p>
| <h3>The Problem, In Short</h3>
<p>It's nothing to do with the underscores.</p>
<p>Your problem is <code>-Ifile</code>, as GNU xargs replaces the sigil specified with <code>-I</code> even when it exists as a substring in a larger argument.</p>
<h3>The Solution, In Detail</h3>
<p>Use a sigil that doesn't exist in the name you're searching for -- or better, don't use <code>xargs -I</code> at all:</p>
<pre><code># BEST: find ... -exec ... {} +
# (uses modern POSIX find features)
find . -type f -name "*.py" -exec grep -nH "get_modal_file_name_from" '{}' +
# GOOD: find ... -print0 | xargs -0 ...
# (just as correct as BEST, but with more startup overhead and not POSIX-compliant)
find . -type f -name "*.py" -print0 | xargs -0 grep -nH "get_modal_file_name_from"
# NOT-SO-GOOD: find ... | xargs -I{} ... {}
# (fixes the problem if there's no {} in your search string, but has other bugs)
find . -type f -name "*.py" | xargs -I'{}' grep -nH "get_modal_file_name_from" '{}'
</code></pre>
<hr>
<h3>The Problem, In Detail</h3>
<p>To explain with a concrete example -- let's say you're running this command, and have a file named <code>./hello.py</code>:</p>
<pre><code># original, broken command
find . -type f -name "*.py" | xargs -Ifile grep -nH "get_modal_file_name_from" file
</code></pre>
<p>What GNU <code>xargs</code> will actually invoke is:</p>
<pre><code>grep -nH get_modal_./hello.py_name_from ./hello.py
</code></pre>
<p>...with the name found substituted not only for the <code>file</code> instance passed as its own argument, but also substituted for the <code>file</code> in the string <code>get_modal_file_name_from</code>.</p>
|
Detect whether a Python string is a number or a letter <p>How can I detect either numbers or letters in a string? I am aware you use the ASCII codes, but what functions take advantage of them?</p>
| <p>You may use <a href="https://docs.python.org/2/library/stdtypes.html#str.isdigit" rel="nofollow"><code>str.isdigit()</code></a> and <a href="https://docs.python.org/2/library/stdtypes.html#str.isalpha" rel="nofollow"><code>str.isalpha()</code></a> to find this. </p>
<p>Sample Results:</p>
<pre><code># For alphabet
>>> 'A'.isdigit()
False
>>> 'A'.isalpha()
True
# For digit
>>> '1'.isdigit()
True
>>> '1'.isalpha()
False
</code></pre>
|
Flexbox layout pattern 1/3 <p>I'm looking for some help with preparing layout pattern in flexbox, the thing is that I will have a set of divs printed inside container and I can not change the rendering logic (i.e. add some wrapping rows), yet, I'd like to get something like this:</p>
<p><a href="https://i.stack.imgur.com/FPYKh.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/FPYKh.jpg" alt="desired layout"></a></p>
<p>Unfortunately got stuck every time, results weren't satisfactory at all :/
Height of those divs is fixed, 1 is a sum of 2 + 3 + gap.</p>
<p><a href="https://jsfiddle.net/zechkgf4/" rel="nofollow">https://jsfiddle.net/zechkgf4/</a></p>
<pre><code>[]
</code></pre>
<p>Thank you in advance</p>
| <p>What you want to do is not posible with flex-box as is pointed in <a href="http://stackoverflow.com/a/39645224/3597276">link</a> provided by @Michael_B</p>
<p>You can generate something really close to what you want using floats:</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-css lang-css prettyprint-override"><code>.boxed {
width:100%;
background:#fff;
overflow:hidden;
}
.boxed div {
height:50px;
margin:4px;
background:#f5f5f5;
width:calc(40% - 16px);
float: left;
}
.boxed div:nth-child(6n + 1), .boxed div:nth-child(6n + 4) {
background:salmon;
height:108px;
width:60%;
}
.boxed div:nth-child(6n + 4), div:nth-child(6n + 5), div:nth-child(6n + 6) {
float: right;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="boxed">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
</div></code></pre>
</div>
</div>
</p>
<p>Note that the big block aligned to right is changed to be 6n+4 instead of 6n+6</p>
|
MySQL - How to Refer to Table in UPDATE Clause in Multiple Levels of Subqueires <p>I am having trouble getting the following query to work...</p>
<pre><code>/*SET APPROPRIATE DATABASE CONTEXT*/
USE IDMAS_VESSELS;
/*BEGIN UPDATE SCRIPT*/
UPDATE INSPECTION i SET i.WALL_LOSS =
CASE WHEN i.STATUS IN('A','R')
THEN CASE WHEN i.INSPECTION_NO = (
SELECT INSPECTION_NO
FROM (SELECT * FROM INSPECTION) AS insp
/*CAN REFER TO TABLE IN UPDATE CLAUSE*/
WHERE EQUIPMENT_ID = i.EQUIPMENT_ID AND CML_ID = i.CML_ID
ORDER BY INSPECTION_DATE ASC, INSPECTION_NO
LIMIT 1
)
THEN i.NOMINAL_WALL_THICKNESS - i.MINIMUM_REMAINING_WALL_THICKNESS
ELSE (
SELECT MINIMUM_REMAINING_WALL_THICKNESS
FROM (
SELECT @rank:=@rank+1 AS DATE_POSITION, INSP.*
FROM (SELECT * FROM INSPECTION) AS insp
/*CODE FAILS AT THIS LINE*/
/*CAN NOT REFER TO TABLE IN UPDATE CLAUSE*/
WHERE insp.EQUIPMENT_ID = i.EQUIPMENT_ID AND insp.CML_ID = i.CML_ID
) as DATA_WITH_DATE_POSITIONS
WHERE DATE_POSITION = 1
) - i.MINIMUM_REMAINING_WALL_THICKNESS
END
ELSE NULL
END
WHERE i.EQUIPMENT_ID = '%';
</code></pre>
<p>Upon running I get the following error:</p>
<pre><code>Error Code: 1054. Unknown column 'i.EQUIPMENT_ID' in 'where clause'
</code></pre>
<p>I have concluded that MySQL will not let you refer to the table in the UPDATE Clause when it is embedded within multiple sub queries. However, you can refer to it when embedded in only one sub query (as identified in the notes within the code above).</p>
<p>So my question is how do I refer to the table in the UPDATE clause when it is embedded in multiple sub queries?</p>
| <p>I have updated your code please see below. This should now work as you intend. Update format has been based off the following link...</p>
<p><a href="http://stackoverflow.com/questions/45494/mysql-error-1093-cant-specify-target-table-for-update-in-from-clause?rq=1">MySQL Error 1093 - Can't specify target table for update in FROM clause</a></p>
<pre><code>-- SET REQUIRED VARIABLE DEFAULTS
SET @prev_equip := null;
SET @prev_cml := null;
SET @prev_rwt := null;
SET @cnt := 1;
-- 1. WALL LOSS
UPDATE INSPECTION i
-- JOIN QUERIES TO MATCH INSPECTION RECORDS WITH ALL DATA TO BE MERGED/UPDATED TO INSPECTION TABLE
LEFT JOIN (
-- CREATE VIRTUAL INSPECTION TABLE WITH NEW RANKING AND PREVIOUS MIN RWT COLUMNS
SELECT IF(@prev_equip = ORDERED_DATA.EQUIPMENT_ID AND @prev_cml = ORDERED_DATA.CML_ID, @cnt := @cnt + 1, @cnt := 1) AS DATE_POSITION
, (@prev_rwt) AS PREVIOUS_MIN_RWT
, ORDERED_DATA.*
-- RE-EVALUATING VARIABLES BASED ON CURRENT ROW
, @prev_equip := ORDERED_DATA.EQUIPMENT_ID
, @prev_cml := ORDERED_DATA.CML_ID
, @prev_rwt := ORDERED_DATA.MINIMUM_REMAINING_WALL_THICKNESS
FROM (
-- ORDER DATA BY INSPECTION_DATE
SELECT EQUIPMENT_ID, CML_ID, INSPECTION_NO, MINIMUM_REMAINING_WALL_THICKNESS
FROM INSPECTION
ORDER BY EQUIPMENT_ID, CML_ID, INSPECTION_DATE ASC, INSPECTION_NO
) ORDERED_DATA
) R1 ON i.EQUIPMENT_ID = R1.EQUIPMENT_ID AND i.CML_ID = R1.CML_ID AND i.INSPECTION_NO = R1.INSPECTION_NO
SET i.WALL_LOSS =
CASE WHEN i.STATUS IN('A','R')
THEN CASE WHEN R1.DATE_POSITION = 1
THEN i.NOMINAL_WALL_THICKNESS - i.MINIMUM_REMAINING_WALL_THICKNESS
ELSE R1.PREVIOUS_MIN_RWT - i.MINIMUM_REMAINING_WALL_THICKNESS
END
ELSE NULL
END
WHERE i.EQUIPMENT_ID = '%';
</code></pre>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.