query_id stringlengths 4 64 | query_authorID stringlengths 6 40 | query_text stringlengths 66 72.1k | candidate_id stringlengths 5 64 | candidate_authorID stringlengths 6 40 | candidate_text stringlengths 9 101k |
|---|---|---|---|---|---|
0ccfaeeef99fc8a22d400945b2095625fbf7e0d07fa0e8af6a2bf166365e546a | ['0dab071bb02441e4835c9ab89496d625'] | On Linux, something like this will do, without modifying the source:
strace -fe open make 2>&1 1>/dev/null | grep plots | sed 's/.*\"\(.*\)\".*/\1/' > plots.list
Where :
make is the command you use to build your output (could be some variation of pdflatex file.tex).
strace displays the syscalls. With the options we are providing, we keep only the "open" syscalls (-e option) in order to get the figures that are inserted (as well as other opened files foe now). The -f options is to display syscalls of subprocesses and the redirections are to keep only the strace output.
grep plots selects the lines containing a common string in the path ("plots" in this case).
sed selects what is inside the quotes.
The final redirection dumps the result in a file.
You may get duplicate filenames this way, but could be good enough depending what you want.
| ef8f65ac8e1b999bb9b492f240ebbd43d294395d715c80fe2ae11cdb2ce73d69 | ['0dab071bb02441e4835c9ab89496d625'] | I have encountered a small issue with SCP (and also rsync). I need to copy certain files from server A (running SunOS 5.8) to server B (running SunOS 5.10).
First, I get the list of files (several hundred) via ssh and find
FILES=`ssh user@remote find ./ -name "*.sh" -o -name "*.cbs" -print`
scp -r user@remote:"$FILES" /u01/appl/somedir/
My problem is, I want to copy files with relative paths, e.g. product/11/ora/clean.sh
creating also the directory structure (in result having /u01/appl/somedir/product/11/ora/clean.sh). Currently I am only able to download the file and no directories are created. As you can see I used -r flag in scp.
|
ee3cea29d29d22dbed643751a8df740341741ce4848e3b3ca0574009961c62d0 | ['0daf9d37848e4825948c2c38b868c74a'] | With a little modification from @Ctx 's answer:
The solution is to first parse the input as an object (so, not directly from args), then check its type:
static PyObject* from_uint64(PyObject* self, PyObject* args){
PyObject* output;
PyObject* input_obj;
if (!PyArg_ParseTuple(args, "O", &input_obj)){
return PyErr_Format(PyExc_TypeError, "Wrong input: expected py object.");
}
unsigned long long input = PyLong_AsUnsignedLongLong(input_obj);
if(input == -1 && PyErr_Occurred()) {
PyErr_Clear();
return PyErr_Format(PyExc_TypeError, "Parameter must be an unsigned integer type, but got %s", Py_TYPE
(input_obj)->tp_name);
}
This code, as expected, works on any input in [0, 2^64-1] and throws error on integers outside the boundaries as well as illegal types like float, string, etc.
| 1a1ae298100e018bfa638b4df6ca3da29047e7d5f8bb50c30049b5ae8e8c3b3b | ['0daf9d37848e4825948c2c38b868c74a'] | I'm writing a Python3 script with some computationally heavy sections in C, using the Python C API. When dealing with int64s, I can't figure out how to ensure that an input number is an unsigned int64; that is , if it's smaller than 0. As the official documentation suggests, I'm using PyArg_ParseTuple() with the formatter K - which does not check for overflow. Here is my C code:
static PyObject* from_uint64(PyObject* self, PyObject*){
uint64_t input;
PyObject* output;
if (!PyArg_ParseTuple(args, "K", &input)){
return PyErr_Format(PyExc_ValueError, "Wrong input: expected unsigned 64-bit integer.");
}
return NULL;
}
However, calling the function with a negative argument throws no error, and the input number is casted to unsigned. E.g., from_uint64(-1) will result in input=2^64-2. As expected, since there's no overflow check.
What would be the correct way of determining whether the input number is negative, possibly before parsing it?
|
1606eb66902a64bf675490db6af8bafdf865413be3c12d82ecb64487a8e1e897 | ['0dbb92c8730e452693664a8ad422f1f1'] | I'm currently making a Word Web Add-in.
This uses Internet Explorer as engine.
My Add-in needs to load multiple selected images from the users computer.
Because some of the selected images might be quite big, I resize them using HTML5 canvas. This is my code to resize:
function makeSmallImage(imageContainer, retries)
{
if (retries === undefined)
retries = 0;
console.log('Resizing image..')
return new Promise(function (resolve, reject)
{
img = img || new Image();
img.onload = function ()
{
// calculate new size
var width = 200;
var height = Math.floor((width / img.naturalWidth) * img.naturalHeight);
console.log('new size', width, height);
try
{
// create an off-screen canvas
canvas = canvas || document.createElement('canvas'),
ctx = ctx || canvas.getContext('2d');
// antialiasing
ctx.imageSmoothingEnabled = true;
// set its dimension to target size
canvas.width = width;
canvas.height = height;
// draw source image into the off-screen canvas:
ctx.drawImage(img, 0, 0, width, height);
// clean up
imageContainer.largeData = undefined;
if (img.src.substr(0, 4) === 'blob')
URL.revokeObjectURL(img.src);
img.src = '';
// encode image to data-uri with base64 version of compressed image
var newDataUri = canvas.toDataURL();
ctx.clearRect(0, 0, canvas.width, canvas.height);
console.log('Image resized!');
imageContainer.resizedData = newDataUri;
resolve(imageContainer);
}
catch (e)
{
if (img.src !== undefined && img.src.substr(0, 4) === 'blob')
URL.revokeObjectURL(img.src);
console.log(e);
if (e.message === "Unspecified error." && retries < 5)
{
setTimeout(function (imgContainer, re)
{
makeSmallImage(imgContainer, re).then(resolve).catch(reject);
}, 2000, imageContainer, retries + 1);
}
else
reject('There was an error while trying to resize one of the images!');
}
};
try
{
var blob = new Blob([imageContainer.largeData]);
img.src = URL.createObjectURL(blob);
} catch (e)
{
reject(e);
}
});
}
'img', 'canvas' and 'ctx' are global variables, so the same elements are reused.
'imgcontainer.largedata' is an uint8array. To avoid a lot of memory usage i'm loading and resizing the images one by one.
Despite of that, after loading for example 120 images of 10mb, it might happen that I get an error:
Unable to decode image at URL:
'blob:D5EFA3E0-EDE2-47E8-A91E-EAEAD97324F6'
I then get an exception "Unspecified error", with not a lot more info.
You can see in the code now that I added a litle mechanism to try again, but all new attempts fail.
I think the reason is that internet explorer is using too much memory. I think some resources are not being cleaned up correctly, but I can't seem to spot a memory leak in my code here (if you can, please let me know).
Does anybody have an idea of how I could fix this, or work around this?
| 5865a3810af66352fb8a9ddee5efda07a66e6bc84cbf6cce7b955a16fcce8d0c | ['0dbb92c8730e452693664a8ad422f1f1'] | My website embeds videos from YouTube.
Right now, I'm using the iframe API for embedding from YouTube (https://www.youtube.com/iframe_api).
The footprint of my website is currently ~1MB.
About 300kB is my JavaScript, StyleSheets, images and fonts. Then I have ~105kB for the Facebook API and Google Analytics.
All the remaining footprint comes from YouTube.
So that means that the YouTube player is more than 0.5MB (gzipped!).
I don't understand how the footprint of a player can be so large.
I'm trying to make my website work really good on mobile devices, so I was wondering if I could reduce the footprint of the YouTube player somehow?
Or is there perhaps some alternative way to show YouTube videos that has a smaller footprint? Note that it must work on mobile devices.
|
3dbdc9abdc57e27984666a29c05fd59898f185cd7e66255652abd8f8aa6c4208 | ['0dc347e5fe1243c4af6acbd3656687c5'] | While answer of @tomgalpin is good, you can also use that in your scrip1.py:
import os
import csv
import re
import __main__.document_path
open_document= open(document_path)
file_name = (os.path.basename(document_path))
def start_s1(good, bad):
with open ((('fqdn_') +(str(file_name).rstrip('.csv'))) , 'w') as output:
with open_document as file:
fqdn_data = csv.writer(output)
reader = csv.reader(file)
good_nums = good
bad_nums = bad
maybe_nums = []
for row in reader:
if row[3] in good_nums:
fqdn_data.writerow([row[2]])
and this in your main.py script:
import sys
import os
import csv
import pandas as pd
from maybe import start_maybe
document_path = input("What is the file path? ")
from script1 import start_s1
open_document = open(document_path) #filelocation
good = input("What is/are the good numbers? ")
bad = input("What is/are the bad numbers? ")
function1 = start_s1(good,bad)
print ("FQDN document created!")
maybeasn = start_maybe(good,bad)
print("Directory created for manual review, file is located inside")
The __main__ module in script.py is one of the magics of Python.
| f73c83e63a31cece485d867ee878a6632820528af068bec98f69521538f64ef7 | ['0dc347e5fe1243c4af6acbd3656687c5'] | You are trying to iterate integer because len function return an int. You should use range in the outer place:
mydict = {
'ServiceResult': {
'msgBody': {
'itemList': [{
'busRouteId': '100100016',
'busRouteNm': '110A',
}, {
'busRouteId': '100100015',
'busRouteNm': '110B',
}, {
'busRouteId': '165000146',
'busRouteNm': '1100',
}, {
'busRouteId': '165000147',
'busRouteNm': '1101',
}, {
'busRouteId': '218000011',
'busRouteNm': '1100',
}, {
'busRouteId': '222000074',
'busRouteNm': '1100',
}, {
'busRouteId': '235000085',
'busRouteNm': '1100',
}, {
'busRouteId': '234000879',
'busRouteNm': '1101',
}, {
'busRouteId': '204000082',
'busRouteNm': 'G8110',
}]
}
}
}
item_list = mydict['ServiceResult']['msgBody']['itemList']
for i in range(len(item_list)):
print(item_list[i]['busRouteId'])
|
8e4da92d9a4b2f5d6723d89e44596341e62300c6ea941896935ec7f426e50b5b | ['0dc41d82de0041b781187efee0a84e61'] | My raspberry pi 3 has apache2 installed and i have run a php file in it smoothly. Can I open this php file from my android phone browser if it is connected to the same wifi as my pi? I am very new to php and this is for a school project.
| 73eb0a482b53319de918be7b3f2e9b729043fa7231ea2a53eef33a1521b806bd | ['0dc41d82de0041b781187efee0a84e61'] | I want to open an html file I made in rpi3 on the web browser of my phone immediately as I connect to pi AP. My pi AP is not connected to the internet. Nodogsplash doesn't work without internet. Also this html page isn't a login or authentication page. Just a normal page with some buttons on it.
|
baeec6d77f09a4bdb75ce9e3b2af0b696f3c38bff9f6b5617d96067a1adb09f7 | ['0dd684445f9e415081c4c6d8070aea2b'] | ((BaseClass)myClass).Method1(); --> object slicing hence always base class method will get called.
Real polymorphic behaviour is achieved through base class pointer which can contain any objects of derived classes.
Hence to achieve what you want you need to do pass address of derived class object and typecase it to base class pointer. as below:
((BaseClass *) &myClass)->Method1();
| e12916a49d2664626edc7be36b047a757a37ec0d322aaa5499115146205820dc | ['0dd684445f9e415081c4c6d8070aea2b'] | I created a application let say "Mydesktopapp"(which is mix of C# and c++ deliverables and few XML's file).
'Mydesktopapp' can be run by clicking a batch file. Hence once user click on batch file, application gets executed and does it functionality on a desktop system.
Now i want to provide this application to the user through a webpage(so that everybody don't need to explicitly copy Mydesktopapp and then run it, instead user should just open a webpage from anywhere...and should click a button on webpage and application should get downloaded and run.
To achieve this...i created a webpage with a button and published it. On button click i will run the batch file. but i don't know how to embed Mydesktopapp with webpage...so that it get published with it and get downloaded automatically when user open webpage.
I am new to WPF but yes..i don't want to create a WCF(or webservice etc ) instead i just want to enbed/attach this app with my webpage and get it downloaded automatically.
Please provide help.
|
ecb1b9c57274e30d598da146e3c6a280ef45e6af24a2c5be35a9b5365e52d1ef | ['0dd7d208f48b4159923148a03664ed3e'] | I had a similar problem and 'fixed' it by subclassing ConfigObj and overwriting the methods that remove and add the quotes -
from configobj import ConfigObj
class MyConfigObj(ConfigObj):
def __init__(self, *args, **kwargs):
ConfigObj.__init__(self, *args, **kwargs)
def _unquote(self, value):
return value
def _quote(self, value, multiline=True):
return value
Then use MyConfigObj in place of ConfigObj and config entries with quotation marks are read in and written back without change.
This works on the simple config files I have used, but I imagine on more complex config files (multiline entries, entries with lists etc.) further refinement will be needed!
| c3a69458ff8dcfbc6f909f6c3c8d26b6690994f8fc462fd172d982e944be5749 | ['0dd7d208f48b4159923148a03664ed3e'] | I am trying to use the RotatingFileHandler handler to manage potentially long logfiles for a Python project running under Windows. I have found that the log file rotation works fine when run using the IDLE interpreter (on a Windows PC) but fails with a WindowsError exception when run from the Windows command prompt.
Here is an example code that shows the problem -
import logging, logging.handlers
import datetime
import time
mainlogfile = 'fred.log'
logging_level = logging.DEBUG
logging_rotate_time = datetime.timedelta(minutes=1)
logger = logging.getLogger('Main_Logger')
logger.setLevel(logging.DEBUG)
handler = logging.handlers.RotatingFileHandler(mainlogfile, backupCount=7)
handler.setLevel(logging_level)
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
next_rotate = datetime.datetime.now() + logging_rotate_time
while True:
time.sleep(5)
logger.info('Tick ')
n = datetime.datetime.now()
if n>next_rotate:
logger.info('Rotating logfile')
handler.doRollover()
logger.info('Succesfully rotated logfile')
next_rotate = next_rotate + logging_rotate_time
logger.info('Next logfile rotate at '+ str(next_rotate))
When I run this in the IDLE interpreter, it works fine and the log file fred.log is rotated every minute producing fred.log.1, fred.log.2 etc. with contents such as -
2018-12-10 12:24:40,269 INFO Succesfully rotated logfile
2018-12-10 12:24:40,269 INFO Next logfile rotate at 2018-12-10 12:25:40.182000
2018-12-10 12:24:45,269 INFO Tick
2018-12-10 12:24:50,269 INFO Tick
2018-12-10 12:24:55,269 INFO Tick
2018-12-10 12:25:00,267 INFO Tick
2018-12-10 12:25:05,267 INFO Tick
2018-12-10 12:25:10,266 INFO Tick
2018-12-10 12:25:15,266 INFO Tick
2018-12-10 12:25:20,266 INFO Tick
2018-12-10 12:25:25,266 INFO Tick
2018-12-10 12:25:30,265 INFO Tick
2018-12-10 12:25:35,265 INFO Tick
2018-12-10 12:25:40,263 INFO Tick
2018-12-10 12:25:40,263 INFO Rotating logfile
However, when run in a command prompt it fails on the first rotate attempt -
C:\> python try10.py
Traceback (most recent call last):
File "try10.py", line 29, in <module>
handler.doRollover()
File "C:\Python27\lib\logging\handlers.py", line 142, in doRollover
os.rename(self.baseFilename, dfn)
WindowsError: [Error 32] The process cannot access the file because it is being used by another process
I have searched and found that there are problems under Windows when trying to close or rename log files that are in use by another Python process but I can't see how that is relevant to my simple example. I have tried calling handler.flush() and handler.close() before handler.doRollover() but this did not change the behavior.
My questions are -
Why is the exception raised when run at the command prompt but not under IDLE?
Is there any changes I can make to the code to allow it to run at the Windows command prompt
|
7c1beac3deb13b37016cf7f2344ee5d88036f2ac5f23b0f5c8b57d7934687a03 | ['0deacf7f0bcf4abfbd0495890a6cb8b4'] | The path given in -fx-shape is the shape of the region, and is implicitly closed (last point connected to first) - this explains the result you are seeing, where the top right corner is connected back to the top left to create a triangle.
You may be able to use this exact path using an SVGPath node, as in this question: How to style a SVG using CSS in javaFX FXML
Another possibility is to "transform" the path to the outline of the shape you want - by retracing the points in reverse order with slightly higher (or lower) Y values:
.check-box > .box > .mark {
/* SVG path directly copied from the site. */
-fx-shape: "M1.73,12.91 8.1,19.28 22.79,4.59 22.79,1.59 8.1,16.28 1.73,9.91";
}
In this case I have subtracted 3 from the Y values of every point and repeated them in reverse order, so get the original shape, 3 pixels wide. Note that this very basic transformation doesn't simulate any "miter" or "joint" effect, but it works in a pinch.
| 5eeaef88b8bb04c2e80c31aea94e6db0eaf2997f2c4bf9e1e5a53d908c4a340e | ['0deacf7f0bcf4abfbd0495890a6cb8b4'] | The JavaFX thread/toolkit must be running. Apparently, creating a JFXPanel is enough to initialize it, but once it is closed the thread is terminated automatically.
To stop it from automatically closing call
Platform.setImplicitExit(false);
so the JavaFX toolkit only closes when the Platform#exit method is called, or the entire application terminates.
|
9e5255e8420de17eda6337330a6834606815c3e6d49a055afa653b634297f108 | ['0defdc4f01684fc29510feffdb4084f7'] | The code is correct.
The problem should be the URL of images. Check if the path is ok.
Or try to save the images in other format, like png. Can be any pattern color problem.
Change your images like this and test if works:
$(document).ready(function() {
//Array of images which you want to show.
var images = new Array(
"https://images.freeimages.com/images/large-previews/ed3/a-stormy-paradise-1-1563744.jpg",
"https://images.freeimages.com/images/large-previews/f2c/effi-1-1366221.jpg",
"https://images.freeimages.com/images/large-previews/851/poppies-1369329.jpg");
var nextimage = 0;
doSlideshow();
function doSlideshow() {
if (nextimage >= images.length) {
nextimage = 0;
}
$("#home").css(
"background-image",
'linear-gradient(rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0.4)),url("' + images[nextimage++] + '")'
).fadeIn(500, function() {
setTimeout(doSlideshow, 6000);
});
}
});
| 3cbd6d7c5801629c704286d2d988fa1fcbf85912b1204731fc9fad6afc29d42e | ['0defdc4f01684fc29510feffdb4084f7'] | You can use the CHRONIC gem.
Chronic is a Ruby natural language date/time parser written by <PERSON> (@mojombo) which takes surprisingly human readable text
and converts it to dates. (http://robdodson.me/playing-with-ruby-dates/)
You can use like this:
require 'chronic'
Chronic.parse('Monday').wday
=> 1
I hope help you!
|
7dfe071f9bbcd1cbf17a69049f550a227153a6dc5d68ba0fb71cf419a07ff4d1 | ['0df122696fa941a4958d843f73ae7aed'] | For example: The utility function is ln(W), where W refers to the Wealth level. The initial wealth is $10,000 $ and you have a equal chance of winning and losing $1000.
What if the insurance policy only covers the loss, how are you willing to pay for the insurance premium?
Need some guidance on solving this question.
| ec2ba83a2c00decb8191b670ef9cc9a2cbd3306355739c794b9734b839d2eeea | ['0df122696fa941a4958d843f73ae7aed'] | I recently started playing Star Wars: The Old Republic Online. Everything went fine on the starting planet, but once I hit my first off-world mission/flashpoint/what-have-you, I hit serious graphic trouble. Namely, I suddenly ran into enemy NPCs that I couldn't see. And I don't mean they were cloaked: I mean they were totally bodiless. If they had weapons I could see those, floating in the air and held by no one. Half the time I can't even target them, because I can't detect any bodies to target! AOE attacks will hurt them, and about half the time an AOE will cause me to target the NPCs once I've begun to hurt them, but most of the time unless they are accompanied by other, visible enemies that I can target first (which usually allows me to switch targets to the invisible ones using the keyboard controls), I just have to sit there and take damage until someone else kills these invisible jerks.
The problem seems to be linked to what kind of enemy it is, although I can't list all of the ones I've had trouble with, because they don't show up and neither do their names or identities. I can't even loot the corpses unless they're carrying a weapon; then I can click on the weapon and it will allow me to loot, but there's no body to click on even though the "loot indicator" lights up.
Some NPCs that are always invisible:
Most of the droids on the Black Talon
Vine Cats
HK-droids
Guild Lifter Droids
Any "boss" droid (in those cases I can see forceshields etc, but not the bodies)
Additionally, some background elements do not render properly, but instead appear as round green cones. Mostly, numerous plants and some security chests.
I have updated all of my graphics, etc., and the computer I'm using is only a few weeks old anyway. It's an Inspiron 5748 with Windows 7, 64-bit, with i7 core. This happens on missions, in Heroic Areas, in Flashpoints, and just walking around the world at random. It affects both of my characters, a bounty hunter and a Jedi Sentinel, equally. They are currently level 12 and level 14, respectively, but have been having this problem since they were both level ten and left their starting worlds. My companions can target the invisible enemies, and so can any other players in the area. No one I've asked has experienced anything like this problem. I've tried playing the game in different graphics settings, but no matter how low or high I set my graphics, the exact same thing happens. This isn't just dangerous for my characters' health; it directly affects my ability to complete missions.
Any help, suggestions, or solutions would be great, thank you!
|
98c0a08b23ce47ad4e98cd09e1b1665f24e643aa3f7cb03e7edf6fb7ffe972e9 | ['0df1a9c3f3fe4bc1a30395318f650b7d'] | Yes, and I have attached the illustrated region. For me, unfortunately, it does not illuminate much. Both versions of the limits I have presented, in my mind, 'end up' at the same place. That is, for $\sqrt{x}\leqslant y\leqslant 1$, $y$ 'starts at' 0 and 'ends up at' 1, as it does in $0\leqslant y\leqslant\sqrt{x}$. I feel as though my line of thought is wrong, which is why I am struggling to understand why we choose limits in this way. | 12a1a795e50b2d93712f72c486ec066af59bffaa4645cc1b4c75b527bff0eb3f | ['0df1a9c3f3fe4bc1a30395318f650b7d'] | Thank you for your response. I think I am starting to understand---since $y^2\leqslant x\leqslant 1$, this would suggest that my region on the $y$ axis is going to be all the $y^2$ 'below' the $x$-values, and for $0\leqslant x\leqslant y^2$, my region on the $y$ axis is going to be all the $y^2$ 'above' the $x$-values. |
69a1e29567a3cb3a2099cf5613c7a26d5f0d6f700657fd7782bba0c7996c8cba | ['0df9fed09ed8411ba5c9d493d9d768fd'] | I have an Error in JDBCTemplate.
Can't infer the SQL type to use for an instance of com.xurpas.util.hitsRowMapper. Use setObject() with an explicit Types value to specify the type to use.
inc_var.getType= "Select type from table group by type"
public List<Map<String, Object>> getType(String table){
JdbcTemplate getJdbcTemplate = new JdbcTemplate(dataSource);
inc_var.getType = inc_var.getType.replace("$table", table);
logger.LogFile("EDIT: " + inc_var.getType);
return getJdbcTemplate.queryForList(inc_var.getType, new hitsRowMapper());
}
public class hitsRowMapper implements RowMapper<Object> {
//@Override
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
hitsRowExtractor ext = new hitsRowExtractor();
return ext.extractData(rs);
}
public class hitsRowExtractor implements ResultSetExtractor {
@Override
public Object extractData(ResultSet rs) throws SQLException {
logger.initializeLogger();
hitsModel hits = new hitsModel();
hits.setType(rs.getString(1));
logger.LogFile(rs.getString(1));
return hits;
}
}
| 61aca04053e33a909444a93a68df838fb3f846e34b9f7fd0f1cc927e33a40278 | ['0df9fed09ed8411ba5c9d493d9d768fd'] | This is my @RequestMapping("VIEW"). If the param is null. it will direct to edit mode
@Controller(value = "viewController")
@RequestMapping("VIEW")
public class viewController {
@RenderMapping
public void handleRenderRequest(RenderRequest request,RenderResponse response,Model model){
PortletMode mode = request.getPortletMode();
PortletPreferences prefs = request.getPreferences();
String server = prefs.getValue("server", "");
request.setAttribute("server", server);
System.out.println("server: " +server)`enter code here`;
if(server == null || server == "")
{
//go to edit mode
}
}
}
|
6e3ba7959f31639d3c0dffa68849012af38d39ddbac8276231854e2a53c26678 | ['0e015e8135d84a3ebd44d4f6a27e7d75'] | <PERSON>,
I am aware that <PERSON>’s conditions are to stop doing the sin, regretting and resolving never to do it again.
Now my question is, is this something you orally declare you are doing? For example you make supplication to Allah SWT telling Him this?
Or is this an action from your heart? For instance, you’ve stopped doing the sin, you regret it and you have the intention never to do it again.
<PERSON> for passing on your knowledge.
| 5466b3f92f5dfc587f9927e9387f323f5af837c5dc078a60d49938ba86ac44df | ['0e015e8135d84a3ebd44d4f6a27e7d75'] | As-salamu Alaykum sister,
There are many scholarly arguments for this.
The most popular view is that she has to catch up her prayers that she didn’t perform.
With istihada, she has to do wudu for each salat IF she is still suffering from istihada. If this is a lot for you, trying spreading it out throughout the day?
I hope this helps.
|
be1c90e5af761a96684be265d21fdc6936c694f6c3e25012f85e5d007735d3ea | ['0e1865f6f0fe43888b236a6c760eb2d4'] | I want to make my first android application and i'm new to Android world, i have seen so many tutorials and videos about android development, some say Android Studio is better and some say Eclipse is the core that all android apps is built with.
I'm confused here, which one should i work on in my android development learning and first app ?
Note I already followed a tutorial that uses Eclipse so i know something about Eclipse, and i have no idea what Android Studio is like.
Thanks in advance.
| 8ab71e42366c6e2719770bd85aec7884b7fab0c8d2938a22256d308b444ff8d5 | ['0e1865f6f0fe43888b236a6c760eb2d4'] | I'm developing an app for a news website, i'm displaying the news articles using UITableView where each cell is an article title, when a user clicks on a cell (i.e an article), another view opens (using segue), now in this view i want to put the following:
The article's Image at the top.
The article's date under the image.
The article's description under the date. (Which could be very long)
The ability for the user to scroll the entire view. (not only the description)
NOTE: I have tried so many ways, i can't seem to know the proper way to implement this structure.
|
edcdb31511a9e8902a693b9bafc7ba75bc60401803efc25e2db0a1345c090e11 | ['0e19c500821e4bc598c973675a3543ff'] | They are probably not encoded correctly. You might need to open them in your textviewer and do a save as to your local encoding. Try to save it as UTF-8 or WIN-xxxxx. There are a few options. The SRT has to have the same name of the film of the DVD(data) and be the same directory as the file on the DVD(data) to be load automatically on startup by most players. If the film is the DVD-VIDEO format, then you need to re-encode the movie with the subtitles embedded into it and burn it back on to a blank DVD.
| dae584f5bc4f9d26677d7f831586f839a5eefa80fe0036552343c79dc9e8653d | ['0e19c500821e4bc598c973675a3543ff'] | THe fact that your AP has a DHCP mode tells me that it's probably an AP/ROUTER and not just a simple AP. If you wish to connect to your "outer network" you should do so with your AP in BRIDGE MODE so there is no FIREWALL/PACKET-FILTERING.
If your AP/ROUTER does not have a BRIDGE MODE, to get around this you can disable DHCP on the AP, but you will have to plug the "outer network" into a standard switch port on the back of the AP/ROUTER, NOT the WAN/INTERNET port(which has a firewall/packet-filtering which cannot be disabled by a BRIDGE-MODE).
|
e376905f64b3f7849fc30437f23a389668dc2a1115f65e9f45cb8d86f8faf33f | ['0e267b32fc924708ba6bb1af32ef53cc'] | And would something like this also work? In this case I setup the listener, and attach the listener to the table. After the table is clicked, the listener is removed, and a new table is created using a create() method.
It sort of works recursively (the create() function calls itself after the table is clicked), which leaves me in doubt. But it 'should' remove the eventListener, remove the view from the window and set its proxy to zero?
function create(i) {
var listener = function(e) {
win.removeEventListener('click', listener);
win.remove(clickedview);
clickedview = null;
create(e.rowData.data);
}
var sub_table = Ti.UI.createTableView({top:'50dp',separatorColor: rowSeparatorColor});
sub_table.setData(data);
sub_table.addEventListener('click', listener);
new_view = populateView(i);
new_view.add(sub_table);
}
| feece7a6c9bb9d7cf8a758a5f93c974f6d2569c533293d63f032bcdd687af8c3 | ['0e267b32fc924708ba6bb1af32ef53cc'] | I've read through a lot of webpages discussing how to control memory leakage in a Titanium-based mobile application for Android.
My situation is that I'm building an app that uses multiple levels of lists (in practice these are tableViews) where the user can navigate through. It is using one window, and when the user selects a list item a new view is created which is animated right-to-left. I have chosen this option, as it appeared to be impossible to create a new window which slides in from right to left an all platforms.
In every view, an eventListener is created to check which tableRow is clicked, and the corresponding submenu is then created and is animated into the screen.
I notice that the memory usage is steadily growing after each click on a view, but I'm can't seem to pinpoint where the memory leak is present.
Currently I'm checking the main window to see if the window has been animated out of view (then the .left property is 320 on a 320px wide device). Then I remove this view from the window, and set the proxy to null, using:
for ( i = 0; i < win.children.length; i++) {
if ( (win.children[i] != null) && (win.children[i].left == 320) ) {
win.remove(win.children[i]);
win.children[i] = null;
}
}
It is still building up memory usage though. This could be because every new view contains a table and an event listener, using a function containing:
var sub_table = Ti.UI.createTableView({top:'50dp',separatorColor: rowSeparatorColor});
sub_table.setData(data);
sub_table.addEventListener('click', function(e) {
create(e.rowData.data);
});
new_view.add(my_navbar);
new_view.add(sub_table);
return new_view;
Do I have to erase them separately or are they destroyed when the view is destroyed? Of I have to erase them manually, how would I go about that?
On a more general note, I don't know how to determine the causes of memory usage. Is there a way to get all objects and/or variables that are in memory at a certain time? Is there a way to drill down on the memory usage that the Dalvik toolkit provides? Is there a method for obtaining all global variables or event listeners?
|
bdf628faecf3ef9d1970e5735e074e545c1649a9eccdbe97c0c0201a0e188f01 | ['0e2c4c9301984ad1bfeef0761736f7f3'] | I made a small program to count days. to count 150 days from May 22nd. But the result is 18th of October. The actual date is 19th October. Can anyone help me find whats wrong with my code.
Calendar mine = new GregorianCalendar(2013, Calendar.MAY,22);
int month = Calendar.MAY;
int counter = 0;
for(int i=mine.get(Calendar.DAY_OF_MONTH);i<=mine.getActualMaximum(Calendar.DAY_OF_MONTH);i++){
System.out.println("i "+i);
counter++;
System.out.println("counter "+counter);
if(i==mine.getActualMaximum(Calendar.DAY_OF_MONTH)){
month++;
i=1;
mine.set(2013, month, i);
counter++;
System.out.println("i "+i+" "+mine.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.ENGLISH));
if(counter == 150){
System.out.println("day "+i+ counter +"days"+ "month:"+ mine.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.ENGLISH));
break;
}
}
if(counter == 150){
System.out.println("i "+i+" counter "+ counter +" date:"+mine.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.ENGLISH));
break;
}
}
| 79ffd0b1a0f647d73b7488c7cf6b9ed5ad88d4211143ddba053df541eaa0849f | ['0e2c4c9301984ad1bfeef0761736f7f3'] | Dear All,
I'm testing a Struts webApp using hibernate-mysql on tomcat7...
After the 8 hours timeout period my webApp always crashes. I've changed configurations here and there. But no success.
I really appreciate your attention...
Here some lines from hibernate.xml
property name="hibernate.bytecode.use_reflection_optimizer">false
property name="hibernate.c3p0.idle_test_period">30
property name="hibernate.c3p0.max_size">600
property name="hibernate.c3p0.max_statements">50
property name="hibernate.c3p0.min_size">5
property name="hibernate.c3p0.timeout">1800
property name="hibernate.c3p0.testConnectionOnCheckout">true
property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider
property name="hibernate.c3p0.validate">true
property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver
property name="hibernate.connection.url">jdbc:mysql://localhost:3306/stockdb?autoReconnect=true
Here are some of lines from my stacktraces:
com.mchange.v2.c3p0.impl.NewPooledConnection handleThrowable
WARNING: [c3p0] A PooledConnection that has already signalled a Connection error is still in use!
...
WARNING: [c3p0] Another error has occurred [ com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after statement closed. ] which will not be reported to listeners!
...
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after statement closed.
...
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1014)
...
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.getMaxRows(NewProxyPreparedStatement.java:1200)
at org.hibernate.jdbc.AbstractBatcher.closeQueryStatement(AbstractBatcher.java:212)
...
at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:452)
...
Please help!
|
a0b5b76c103f7befa70b7e24efd37d6de167631760cbdfedfe3d56a281cfbca4 | ['0e2fdb55a9104e85949c1c95cf74d3f5'] | Seeeeeecreeeets. My preeeeciooouss secretts. But yeah I can understand the frustration so I'll throw this one to you OP/SO. Feel free to update the PCG Wiki if you're not as lazy as me :3
There are actually many ways to do this. Some of the best techniques for procgen are:
Asking what you really want.
Design backwards. Play in reverse. Result is forwards.
Look at a random sampling of your target goal and try to see overall patterns.
But to get back to the question, there are two simple ways and they both start from asking what your really want. I'll give those first.
The first is to create 2 layers. Both are random noise. You connect the top and the bottom so they're fully connected. No isolated portions. This is asking what you really want which is connected-ness. And then guaranteeing it in a local clean-up step. (tbh I forget the function applied to layer 2 that guarantees connected-ness. I can't find the code atm.... But I remember it was a really simple local function... XOR, Curl, or something similar. Maybe you can figure it out before I fix this).
The second way is using the properties of your functions. As long as your random function is smooth enough you can take the gradient and assign a tile to it. The way you assign the tiles changes the maze structure but you can guarantee connectivity by clever selection of tiles for each gradient (b/c similar or opposite gradients are more likely to be near each other on a smooth gradient function). From here your smooth random can be any form of Perlin Noise, etc. Once again a asking what you want technique.
For backwards-reversed you unfortunately have an NP problem (I'm not sure if it's hard, complete, or whatever it's been a while since I've worked on this...). So while you could generate a random map of distances down a maze path. And then from there generate the actual obstacles... it's not really advisable. There's also a ton of consideration on different cases even for small mazes...
012
123
234
Is simple. There's a column in the lower right corner of 0 and the middle 2 has an _| shaped wall.
042
123
234
This one makes less sense. You still are required to have the same basic walls as before on all the non-changed squares... But you can't have that 4. It needs to be within 1 of at least a single neighbor. (I mean you could have a +3 cost for that square by having something like a conveyor belt or something, but then we're out of the maze problem) Okay so....
032
123
234
Makes more sense but the 2 in the corner is nonsense once again. Flipping that from a trough to a peak would give.
034
123
234
Which makes sense. At any rate. If you can get to this point then looking at local neighbors will give you walls if it's +/-1 then no wall. Otherwise wall. Also note that you can break the rules for the distance map in a consistent way and make a maze just fine. (Like instead of allowing a column picking a wall and throwing it up. This is just loop splitting at this point and should be safe)
For random sampling as the final one that I'm going to look at... Certain maze generation algorithms in the limit take on some interesting properties either as an average configuration or after millions of steps. Some form Voronoi regions. Some form concentric circles with a randomly flipped wall to allow a connection between loops. Etc. The loop one is good example to work off of. Create a set of loops. Flip a random wall on each loop. One will delete a wall which will create access to the next loop. One will split a path and offer a dead-end and a continuation. For a random flip to be a failure there has to be an opening and a split made right next to each other (unless you allow diagonals then we're good). So make loops. Generate random noise per loop. Xor together. Replace local failures with a fixed path if no diagonals are allowed.
So how do we get random noise per loop? Or how do we get better loops than just squares? Just take a random function. Separate divergence and now you have a loop map. If you have the differential equations for the source random function you can pick one random per loop. A simpler way might be to generate concentric circular walls and pick a random point at each radius to flip. Then distort the final result. You have to be careful your distortion doesn't violate any of your path-connected-ness conditions at that point though.
| b10db99a9e9013f4bfff06394ff038f646242a30ae2bff2d4d938de37e87150b | ['0e2fdb55a9104e85949c1c95cf74d3f5'] | I've done this task a ton of times. The answer is simple and it's what you do with children. Play a game
There's probably many games you could play but the best I've run into is
"Guess the Number". You play the game and they understand it. Then you tell them they just did a thing called binary search and it solves a lot of problems. Then show them some C or BASIC code for that function. The structure is simple enough that since they fundamentally understand the algorithm they can almost read the code. (If it's 100% Greek, you may have coding style issues.)
C is probably better for overall structure. If you can squeeze some gotos into the BASIC one that's perfect. Jumps are very much the heart of programming, and being able to actually see them in the code is amazing for comprehension. Assembly is too cluttered with arcane syntax to the uninitiated. And C and higher-level languages hide the jumps more often than not inside different types of constructions.
Even better might be to throw up the printout for both BASIC, C, and Lisp and tell them that those are different languages that try to say the same thing in different ways, and that real programmers think about many different things in many different ways. And if running to make a printout is too daunting for a simple explanation then just make a business card of the printouts and keep it in your wallet. They should easily fit on one card if you strip out any comments.
|
6a674b80bc14ff9213d5414b25376ba04a80de9701cc432efd2c8fc5ec3cd5c1 | ['0e2fe43f5ce7407d9e9c7d7d802dd25b'] | I have understood now.The video was recorded with angular js version 1.0.x and the version I am using is the latest one. Actually,the transcluded markup completely replaces the contents of the element with the ng-transclude attribute in latest versions. In previous versions, the transcluded markup would be appended.Thanks everyone
| ef3e149635e3392c0959c2203b04c3c5b2b43ad8d48444477d594eab80fb3a02 | ['0e2fe43f5ce7407d9e9c7d7d802dd25b'] | Im working on a DynamicWebProject in Eclipse IDE.I got an error in console while running a jsp page showing "Failed to load resource: the server responded with a status of 404 (Not Found)".I already referred many questions regarding this problem but could not resolve it.Here is my javascript file
availability.js
var ajaxRequest = null;
if (window.activeXObject) {
ajaxRequest = new ActiveXObject("Microsoft.HTTP");
} else {
ajaxRequest = new XMLHttpRequest();
}
function ajaxValidation() {
var name = document.getElementById("username").value;
ajaxRequest.open("GET", "/SpringHibernateProject/validate?name=" + name,
true);
ajaxRequest.onreadystatechange = function() {
if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
var message = ajaxRequest.responseText;
document.getElementById("div").innerHTML = "<font color='red'>"
+ message + "</font>";
}
};
ajaxRequest.send(null);
}
Here is my jsp page
AjaxPage.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="../Js/availability.js"></script>
</head>
<body>
<input type="text" name="username" id="username" onkeyup="ajaxValidation()"></input>
<div id="div"></div>
</body>
</html>
Im getting this error though I referred the script file correctly.Why is it so?
|
9669217313753b1d7b0ed134a6f53d67d705b6f93e22d16e0f8fa8f119378ae3 | ['0e3eaed0672641b3ba10f12182fd653d'] | In my case the following worked: KeyEvent.consume()
Consumes this event so that it will not be processed in the default manner by the source which originated it.
This stops Windows from stealing my focus, but I'm still able to access my menuitems with the keyboard mnemonics with ALT.
Thanks to <PERSON> for his comment!!
| aca0809484c7c012e8af6804d176fe63950ddbe8daf60819c256cdc3adbf05d5 | ['0e3eaed0672641b3ba10f12182fd653d'] | I'm currently working on a research involving Graph theory.
More specifically, I would like to make an analytical or theoretic connection between different characteristics of the graph (e.g. size, node degree distribution, number of nodes with degree 1, etc.) to its minimal cut. The graph is also characterized by a source and a sink for flow purposes. By minimal I mean the number of edges or sum of capacities.
Relevant connections might be on the distribution of number of paths from S to T in the minimal cut, distribution of cut-sizes, etc.
I'd appreciate if someone can suggest a lead, paper or a good approach to tackle this both theoretically and analytically.
Thank you in advance for the effort,
<PERSON>
|
77a744121401e35cbbb30f8c37547e347954900051722994732ff9eca93e24ec | ['0e457995dfcf42b68efc214a2c6f5bc3'] | Two three item navbars do the trick:
<div style="margin:20px">
<div data-role='navbar'>
<ul>
<li><button>A</button></li>
<li><button>B</button></li>
<li><button>C</button></li>
</ul>
</div>
<div data-role='navbar'>
<ul>
<li><button>D</button></li>
<li><button>E</button></li>
<li><button>F</button></li>
</ul>
</div>
</div>
| 122b3c985ff07bd41b958768aa79e715e2ae24c3b26d9c62afb3019ade3edd45 | ['0e457995dfcf42b68efc214a2c6f5bc3'] | The following code shows a disabled textbox wrapped in a div with a jQuery UI tooltip attached to it. The jQuery tooltip will be shown properly in Chrome, Safari and IE when hovering the textbox (or, more precisely, the textbox covered div) but not in Firefox (28.0). Can somebody explain this behaviour and offer a fix? I know that event are generally not fired on disabled elements, so that's why it is bound to the wrapping div.
HTML:
foo
<div id="container" title="Tooltip test"
style="background: green; display: inline; position: relative; z-index: 10">
<input id="box" type="textbox" disabled="disabled" value="baz"
style="position: relative; z-index: 1"></input>
</div>
bar
JavaScript:
$("#container").tooltip();
Here is a jsfiddler
|
3aa73a90af1b0ebb70e39921db9c111e2d511c4005926d7bd578cb0405edb0d3 | ['0e4a4216f6d84604a11310d2037e85c6'] | I found a workaround. I was using the shade plugin in Maven to package all the jars into an Uber JAR.
Not using the shade plugin and just adding all the JARs on the classpath made the problem go away.
Not sure what the exact reason is why Hibernate fails in this peculiar way, but I have a workaround now. To be clear, it's not failing to find the config file - if I put the wrong DB user/pass in it will fail with a connection error. So it IS finding the config, class mapping just seems to be wonky.
| b0e2daa3d9f548a03c419d0490a79a75708f676f8570691d5192e97ad68b0767 | ['0e4a4216f6d84604a11310d2037e85c6'] | I have a simple hibernate query:
public AtMessage getMessageById(int messageId)
{
AtMessage message = (AtMessage) session.createQuery(
"FROM com.persistence.AtMessage where atMessageKey=:atMessageKey"
).setParameter("atMessageKey", messageId).uniqueResult();
return message;
}
when I call the method, I get a org.hibernate.QueryParameterException with the message could not locate named parameter [atMessageKey]
I don't get why this is happening as the query looks right.
|
1f2910507d37dbc2d17b94348259776679a9ad25741bbf0a500df77a9c23bae9 | ['0e4cbdad76e24eb097c43abda29b207d'] | Sorry the error is "Run-time error'13'" type mismatch. I original thought it was a simple syntax error after doing some online research. I tried changing the plus sign "+" range statement into "&". doing this would allow the macro to complete but the output was not even close to outputing the correct value or response .The error occurrs on teh following line of code. " For Each c1 In Worksheets(MyRollup).Range("D" & TopRow + ":D" & NewLastRow) " | c8d4dc94b82c3bed75bf527445463285c07eeb2874ea0e188d16a3c10e819e04 | ['0e4cbdad76e24eb097c43abda29b207d'] | I am backing up my MacBook Air that runs OS X El Capitan 10.11.6 to an external Hard Drive using Time Machine. I have another older MacBook that runs Mac OS X 10.6.8. If I wipe the hard drive of the older macbook can I restore it using my the Time Machine that was created using OS X El Capitan? Any issues that I should be aware of?
|
215d6932c8a39df6dbf426ac8152242ff65a027f961ee752c8ac96ff9e4c0ad8 | ['0e4d253c69554768ab85b3e0dfda1451'] | The code is in this jsFiddle: http://jsfiddle.net/r8ND3/1/. I cannot figure out how to center the div "#game" and its contents. I have tried using margin: 0 auto;, float:center;, and even $("game").css("margin-left", .5*$(window).width()-.5*$("#game").width()) inside of $(document).ready(), but none have worked.
| 76f6ddcbbe20242983862972c082aa06a9969ae7127cc5c6c80a83ae95951662 | ['0e4d253c69554768ab85b3e0dfda1451'] | Note: All code is in this jsFiddle: http://jsfiddle.net/5qrkk/
I have this code to register spaces in Javascript
$(window).on("keydown", function(key){
if(key==32){
console.log("SPACE");
$(".sh").fadeOut(600).toggleClass("hdt").toggleClass("sh");
$(".hd").fadeIn(600).toggleClass("sht").toggleClass("hd");
$(".sht").toggleClass("sh").toggleClass("sht");
$(".hdt").toggleClass("hd").toggleClass("hdt");
}
});
The content inside of the if loop makes the div with the class sh (which is shown) become hidden, and replace the class sh with hdt (rather than instantly going to hd because the old hd classes still need to be modified). The same thing happens with the div currently at the hd class (which starts hidden). None of these events, including the console.log, are happening when I click space. I also would like to avoid putting these in the $(document).ready() function as this might create errors as this changes the DOM and needs to be using the updated DOM each time it runs.
|
a1f7523c589c3f81ec315873f5e1bed370a8c981cdb067441c30e168da7181be | ['0e5a7c8d34e2407f86bfe2e59963e074'] | You can do this with java.io.File, by using the constructor which takes a File and a String as arguments, will interpret the String as a relative path to the File.
Or with java.net.URL, you can send an URL and a String to the constructur, which will interpret the URL as a context for the String parameter.
| 138b00f763aa6a8ad9b9e2979bb50ede7a3f92a2ef339fe5be7e11dc64524ccc | ['0e5a7c8d34e2407f86bfe2e59963e074'] | I'm not sure I understand the question, you want to know if b.a is infact the same variable as c.a?
In your case, b.a will be the same as c.a if b==c. If you declare a static, it will be shared between all instances of foo.
|
d00641a5b19b16c86faa761ae6cbb7b29f3f3509241e6590ac8095fef2ef6ef5 | ['0e5b4c39051d42b4a56839b57d01e8fd'] | I have a Users entity that is duplicated across a few different applications where it just inherits the datasource from the application.cfc. I am trying to consolidate some sections of the applications to one spot, so I need to access the entity with different datasources since the one application will access all sections.
component accessors=true persistent=true table="Users" entityName="Users" extends="common.model.BaseActiveEntity"{...}
From what I have found online I should be able to set the datasource for this entity from a Virtual Entity Service like so:
Component singleton=false accessors=true autowire=false Datasource="DB2" extends="common.model.BaseVirtualEntityService"{
public testUser function init(){
super.init(argumentCollection=arguments,entityName="Users");
return this;
}
}
but when I dump the entity to the page to see what it contains, it has defaulted back to the datasource set in the application.cfc. I'm trying to figure out if there is a way to force the datasource to the entity. Any ideas?
| 0d0f276a4cf1c3956e4daab6fe707b4a45464239ad5cec67207c1cceb8f3848d | ['0e5b4c39051d42b4a56839b57d01e8fd'] | Do you mean something like this?
DECLARE @Age as int
SET @Age = SELECT PERSONAGE FROM PERSON WHERE ID=2
SELECT
PERSONID,
PERSONAGE AS CURRENTAGE,
MAX(CASE WHEN (@Age-PERSONAGE) >1 THEN PERSONAGE ELSE NULL END)
OVER (PARTITION BY PERSONCITY) AS OldestYounger
FROM
PERSON
This way you have the age of the one user and comparing it to others. What your query is doing now is comparing each user to themselves and ordering by city.
|
941865c503a9b50d6aec3dde02e661adfe6b1cf29522998dfc77127e06cb9722 | ['0e625c74531346c588c58a9f7fac6972'] | So I made a simple service that allows Registrations and LogIns, so the only methods in my service contract are : Register(string username, string password) and LogIn(string username, string password). When starting the service in the Visual Studio service hosting gizmo I can call my methods properly and everything works well.
My problem is when I try to implement my service in an application. I kept it really simple, one form with fields for username and password for a login. I added a the service by going to Data -> Add New Data Source and gave my address from IIS (the service is hosted in IIS7). Here is a snipped of the would-be implementation code
public class LoginServiceClient
{
static LoginService.LoginClient client = new LoginClient();
public static bool LogIn(string username, string password)
{
string Username = username;
string HashedPassword = password; // No hash in place yet.
client.
return true;//Its *that* easy to get in my system.
}
}
Now the part that isn't working is the line where I started typing "client." expecting to find method names like LogIn and Register instead its LoginAsync and RegisterAsync. Both does not return anything therefore I cannot use them, neither are they offering callback methods.
What did I do wrong ? I can post more code if needed, from the service or details about implementation (as small as it is).
| dcef160ceb0692353583a1285e019a484787ea197293928b8da9d274c790ec49 | ['0e625c74531346c588c58a9f7fac6972'] | I have a pretty basic Laravel setup that I am starting to test. I have my own library files in the folder app/framework and all the files are under the namespace "CompanyName\Framework". I added these files to the composer.json file to have it autoloaded in my app.
My composer.json is then :
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/models",
"app/database/migrations",
"app/database/seeds",
"app/tests/TestCase.php",
"app/framework"
]
In my controller I can use my library fine and autoloading seems to work. When I try to test that controller in my unit test it says
....PHP Fatal error: Class 'CompanyName\Framework\DatabaseUpdater' not found in C:\
Production\CompanyName\laravel\app\controllers\DatabaseController.php on line 19
Why is that namespace suddently invalid when I call my controller from my unit test ? The unit test itself is very basic, it is simply a $this->client->request('GET', '/'). Absolutely everything works perfectly except the unit test.
|
c98375d7f99ee4b7ce2d4a885d0f4bdf9028abcf9d0acc782ad144a8b89b7d2b | ['0e66005b655e47e381910717d385ad74'] | As far as I know, you can't set content mode to both aspect fit and center. However, center will do what aspect fit does providing the image size is smaller than the size of the imageView. If not, use aspect fit. The following code ought to allow you to differentiate between the two:
if (theImageView.bounds.size.width > UIImage(named: "coolimage")?.size.width && theImageView.bounds.size.height > UIImage(named: "coolimage")?.size.height) {
theImageView.contentMode = .aspectFit
} else {
theImageView.contentMode = .center
}
As for the second part of your question, I'll refer you to this thread, which has a fairly comprehensive explanation of UIViewController vs UIView. Hope that helps.
| 7e5173a37c6060ef551946723acb0faf66a900c8904353229dca9c739630c4c7 | ['0e66005b655e47e381910717d385ad74'] | I'm trying to fix some odd behaviour which occurs when I rotate an iPhone app using UISplitView from portrait to landscape.
I have two Master Table Views. When I am in portrait I can navigate from Master Table View 1 to 2 fine, but when I rotate to landscape from Master Table View 2, it then appears in the detail pane whereas I would like it to stay on the 'Master side'. Images below. Happy to add code as requested!
<PERSON>, navigated to Master Table View 2
When rotated:
Desired outcome:
|
f5dfd7972008a2dfeb900a8a4f42c1f6b7b96754de07a918cbeda140c94002fd | ['0e7952af03e44e2d927100ea6d7da518'] | I know this is an older question, but I just ran into the same problem today. Laravel would not validate a .mov filetype, even if I had 'mov', 'quicktime', or 'video/quicktime' in the validator. getMimeType() on the file was showing 'video/quicktime' so it seemed really odd.
Digging into Laravel's validator class, it seemed that it was using guessExtension() instead of getMimeType() to check the file. When I put 'qt' as the mime type into the validator (which is what guessExtension() was returning) it worked.
| 847f2565b6280653418b75fb0d3b09fbccdd6dd940776d71eeaa44896113c245 | ['0e7952af03e44e2d927100ea6d7da518'] | I have written a bookmarklet that functions just fine in Chrome and Firefox but it IE 10 it fails to append to the document. I believe it has something to do with it being listed as "unrated" in the IE favorites bar, but I am not sure what part of the code is triggering that:
<a href="javascript:(function() {
var elem=document.createElement('script');
elem.setAttribute('type','text/javascript');
elem.setAttribute('src', 'http://www.joshdforbes.com/web2mobile/
web2mobile.js?t='+(new Date().getTime()));
document.body.appendChild(elem);
})()">Web2Mobile</a>
Having a hard time finding any information on the internet about what the differences are in IE10 that would be causing this. Any help would be appreciated.
Thanks!
|
332c6c6e5e448ee264b13d686c9bdbcc1335bbd604c5aca6493ba722b4295110 | ['0e8a043236ee4c5391abedc442b95804'] | I'm trying to convert latitude and longitude to a byte arrayusing Java and then convert the byte array to double using C++. SO far, here's what I'm doing:
I have a byte array of {0x40,0x4a, 0x62, 0x65, 0x27, 0xa2, 0x05, 0x79} which gives 52.768712 in JAVA.
I'm trying to do the same thing in C++ using:
unsigned char data[8] = { 0x40,0x4a, 0x62, 0x65, 0x27, 0xa2, 0x05, 0x79};
double sample;
double conversion;
copy(data, data+ sizeof(double), reinterpret_cast<char*>(&sample));
memcpy(&conversion, data, sizeof(double));
cout <<fixed << sample << endl;
cout <<fixed << conversion << endl;
But this outputs
93624845218206212768416858147698568034806357864636725490778543828533000856049725637297881892477906693728822997596617150540736669122257619339758101303551253860040255473731364930515446918886205365571056786975140751691636070476504921373224351498841838203471739594278994672877568.000000
What am I doing wrong here?
| dea992f717835dd137ca09b23f396b1fed7d5249cff83684e946a95321a083e3 | ['0e8a043236ee4c5391abedc442b95804'] | I'm trying to use FreeRTOS to write ADC data to SD card on the STM32F7 and I'm using V1 of the CMSIS-RTOS API. I'm using mail queues and I have a struct that holds an array.
typedef struct
{
uint16_t data[2048];
} ADC_DATA;
on the ADC half/Full complete interrupts, I add the data to the queue and I have a consumer task that writes this data to the sd card. My issue is in my Consumer Task, I have to do a memcpy to another array and then write the contents of that array to the sd card.
void vConsumer(void const * argument)
{
ADC_DATA *rx_data;
for(;;)
{
writeEvent = osMailGet(adcDataMailId, osWaitForever);
if(writeEvent.status == osEventMail)
{
// write Data to SD
rx_data = writeEvent.value.p;
memcpy(sd_buff, rx_data->data, sizeof(sd_buff));
if(wav_write_result == FR_OK)
{
if( f_write(&wavFile, (uint8_t *)sd_buff, SD_WRITE_BUF_SIZE, (void*)&bytes_written) == FR_OK)
{
file_size+=bytes_written;
}
}
osMailFree(adcDataMailId, rx_data);
}
}
This works as intended but if I try to change this line to
f_write(&wavFile, (uint8_t *)rx_data->data, SD_WRITE_BUF_SIZE, (void*)&bytes_written) == FR_OK)
so as to get rid of the memcpy, f_write returns FR_DISK_ERR. Can anyone help shine a light on why this happens, I feel like the extra memcpy is useless and you should just be able to pass the pointer to the queue straight to f_write.
|
cc66e21a3eeb248ee058e797cbfe2625eb784f93bfd224a06e870f41379d7d59 | ['0e8f98ddd3994a4a88b9d29d20e8059f'] | Lets say you want to quickly share /somefolder to someuser temporary readonly.
Add a system user:
useradd -r someuser
Often by default the folder is other-readable (check with ls -ld /somefolder), if you need to force it:
chmod -R o+r /somefolder
Add the user to samba with some password like:
smbpasswd -a someuser
Quickly edit smb.conf and add at the bottom
[someshare]
path = /somefolder
read list = someuser
exit, save, and finally run
smbcontrol smbd reload-config
et voila.
Obviously you may want to remove the "someshare" section once done and rerun the reload-config command.
Disclaimer: i didnt fully test this but i was amazed how simple the answer to the question could be.
You can possibly skip some steps and dive straight into editing of smb.conf if you already have some user with existing samba access - exactly what i just ran into.
| a2be856c5c6032a77bb9504ab2c92b6ebf3a479e713ef0ac1ad9721d3f2fea6b | ['0e8f98ddd3994a4a88b9d29d20e8059f'] | I have a use case to make updates to a slightly complex JSON object and then return the list of changes made (not the updated data). The process of finding the list of changes is extremely similar to the process of making the changes and it would bring in some redundancy if I chose to separate the two methods. So I'm wondering if there is a way to do this without choosing DRY over CQS and SRP.
|
994cf0efbdf4df1c3fed0154d1ba8ff85f5bf48a455e693300e39f9ed695e730 | ['0e9b8bf39fcd4e48ad1d2f16b7f568d4'] | Turns out there is very limited support for customization and it is all outlined here: https://docs.aws.amazon.com/aws-mobile/latest/developerguide/add-aws-mobile-user-sign-in-customize.html
To present the Email and Password user SignInUI, set userPools to true.
To present Facebook or Google user SignInUI, add signInButton(FacebookButton.class) or
signInButton(GoogleButton.class).
To change the logo, use the logoResId.
To change the background color, use backgroundColor.
To cancel the sign-in flow, set .canCancel(true).
To change the font in the sign-in views, use the fontFamily method and pass in the string that represents a font family.
To draw the backgroundColor full screen, use fullScreenBackgroundColor.
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import com.amazonaws.mobile.auth.facebook.FacebookButton;
import com.amazonaws.mobile.auth.google.GoogleButton;
import com.amazonaws.mobile.auth.ui.AuthUIConfiguration;
import com.amazonaws.mobile.auth.ui.SignInUI;
import com.amazonaws.mobile.client.AWSMobileClient;
import com.amazonaws.mobile.client.AWSStartupHandler;
import com.amazonaws.mobile.client.AWSStartupResult;
public class YourMainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AWSMobileClient.getInstance().initialize(this, new AWSStartupHandler() {
@Override
public void onComplete(final AWSStartupResult awsStartupResult) {
AuthUIConfiguration config =
new AuthUIConfiguration.Builder()
.userPools(true) // true? show the Email and Password UI
.signInButton(FacebookButton.class) // Show Facebook button
.signInButton(GoogleButton.class) // Show Google button
.logoResId(R.drawable.mylogo) // Change the logo
.backgroundColor(Color.BLUE) // Change the backgroundColor
.isBackgroundColorFullScreen(true) // Full screen backgroundColor the backgroundColor full screenff
.fontFamily("sans-serif-light") // Apply sans-serif-light as the global font
.canCancel(true)
.build();
SignInUI signinUI = (SignInUI) AWSMobileClient.getInstance().getClient(YourMainActivity.this, SignInUI.class);
signinUI.login(YourMainActivity.this, YourNextActivity.class).authUIConfiguration(config).execute();
}
}).execute();
}
}
| e317b1acbecb4dca4fdb84c0113be036ea86d505b9bc6d107418ecc983f34e60 | ['0e9b8bf39fcd4e48ad1d2f16b7f568d4'] | There are two surveys I need to send to the users of my mobile app to complete. The first is sent to all users and is done right after they sign up.
The other survey however is sent to a select group of users a few months into their app usage. At the moment, I'm using Amazon Cognito for user pools and management so I would be able to identify the specific users this way.
As far as I know, I can't send an update to the app for the selected users only and include the new survey in it.
Maybe a viable idea is to include the survey hidden within the app and include a 0 or 1 in one of my user databases and include a check for that 0 or 1. Show the survey if it's a 1.
In general, how could I go about this?
|
8a5106cd44467588ec67091f6bbfb767d433e2e1d57a1643a3d23c0429970070 | ['0e9f7c792eaf405a960ac28a980d8933'] | I'm using the Google Identity Platform's OAuth 2.0 flow to authorize a javascript/HTML teacher observation form to write to a Google Sheets document. Everything is working well most of the time; however, last night one of our principals hit the following error:
"Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project."
I determined that he had launched the observation tool in the afternoon, and now maybe five hours later was trying to click the submit button. My hunch was that the token had expired, but from Google's documentation it seems like the JS auth library is meant to handle refreshing the access token as necessary - I believe it's not actually possible to get a refresh token to do anything manually.
I'm using what is essentially the sample auth code, and the app responds to being signed out appropriately. That is, if I sign out in another tab, the submit button is disabled and the sign-in button appears again. Assuming token expiration is the issue here, any ideas on the correct way to identify if the token has expired and how to request a new one, ideally without user interaction? Or if it's not an expiration issue, what else could it be? This user has successfully submitted data in earlier observations; it was just this one time when he waited ~5 hours (potentially losing internet connectivity / sleeping his laptop) during that time.
Here's the auth code:
var clientId = ""; //id removed
var discoveryDocs = ["https://sheets.googleapis.com/$discovery/rest?version=v4"];
var scopes = "https://www.googleapis.com/auth/spreadsheets";
var authorizeButton = document.getElementById('authorize-button');
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
function initClient() {
gapi.client.init({
discoveryDocs: discoveryDocs,
clientId: clientId,
scope: scopes
}).then(function () {
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
});
}
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
document.getElementById('submit').disabled = false;
findRow(); //find the empty row once we're logged in
} else {
authorizeButton.style.display = 'block';
document.getElementById('submit').disabled = true;
}
}
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
Thank you!
| e433d8d8c0826e41c59c1076755821765eab56b84e98ddb513eb9f5ee4e91542 | ['0e9f7c792eaf405a960ac28a980d8933'] | I believe How to refresh expired google sign-in logins? had the answer I needed. Since all of my API calls happen at once, I added a new Date() when the page loads, a second new Date() when the submission flow begins, and if they are more than 45min (2,700,700ms) apart, I use gapi.auth2.getAuthInstance().currentUser.get().reloadAuthResponse() to force an access token refresh, as documented at https://developers.google.com/identity/sign-in/web/reference#googleuserreloadauthresponse.
Hopefully Google will eventually update their documentation to reflect this now-necessary step when using the auth2 flow vs the older auth flow.
Time will tell if this actually solved the issue, but I'm hopeful!
|
60c4ef4b25275d0afa3c68040c6d04419dc8e78bca2cdebbaca9966ccbb38a27 | ['0ea2f270e04e413f81526bba3f5307b2'] | Um erro bobo, porém acabei encontrando a solução com a ajuda dos outros usuários.
Segue a solução:
Como informado nos comentários, adicionei um IF para receber o erro, sendo que a pagina era encaminhada mesmo com um problema no envio de dados.
Após, isso recebi o problema:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '�o, cidade, complemento, uf, telefone_residencial,
telefone_comercial, categori' at line 1
É importante ressaltar que que o carácter ç não está sendo procesado devido a falta de uma colação específica no código, sendo assim utilizei de um pequeno IF que define exatamente qual colação utilizar:
if (!mysqli_set_charset($conn, 'utf8')) {
printf('Error ao usar utf8: %s', mysqli_error($conn));
exit;
}
Assim, o próximo erro exibido foi:
Field 'email' doesn't have a default value
Sendo que apenas não tinha adicionado a variável do input EMAIL para ser inserida na db, após essa correção, as informações são inseridas normalmente no banco.
Sendo assim, o código atualizado:
<?php
// conecta com o banco
$db = mysqli_connect("localhost", "root", "", "login");
if (!mysqli_set_charset($db, 'utf8')) {
printf('Error ao usar utf8: %s', mysqli_error($db));
exit;
}
$errors = array();
$erro = array();
// define as variáveis
$nome = "";
$data_de_nascimento = "";
$numero_de_cadastro = "";
$CEP = "";
$numero = "";
$bairro = "";
$endereço = "";
$cidade = "";
$complemento = "";
$uf = "";
$telefone_residencial = "";
$telefone_comercial = "";
$categoria_de_cliente = "";
$telefone_celular = "";
$telefone_0800 = "";
$CPF = "";
$insc_estadual = "";
$CNPJ = "";
$RG = "";
$insc_municipal = "";
$PIS = "";
$site = "";
$email = "";
$historico = "";
// se o botão for clicado...
if (isset($_POST['register_btn'])) {
session_start();
// coleta os dados dos imputs
$nome = mysqli_real_escape_string($db, $_POST['nome']);
$data_de_nascimento = mysqli_real_escape_string($db, $_POST['data_de_nascimento']);
$numero_de_cadastro = mysqli_real_escape_string($db, $_POST['numero_de_cadastro']);
$CEP = mysqli_real_escape_string($db, $_POST['CEP']);
$numero = mysqli_real_escape_string($db, $_POST['numero']);
$bairro = mysqli_real_escape_string($db, $_POST['bairro']);
$endereço = mysqli_real_escape_string($db, $_POST['endereço']);
$cidade = mysqli_real_escape_string($db, $_POST['cidade']);
$complemento = mysqli_real_escape_string($db, $_POST['complemento']);
$uf = mysqli_real_escape_string($db, $_POST['uf']);
$telefone_residencial = mysqli_real_escape_string($db, $_POST['telefone_residencial']);
$telefone_comercial = mysqli_real_escape_string($db, $_POST['telefone_comercial']);
$categoria_de_cliente = mysqli_real_escape_string($db, $_POST['categoria_de_cliente']);
$telefone_celular = mysqli_real_escape_string($db, $_POST['telefone_celular']);
$telefone_0800 = mysqli_real_escape_string($db, $_POST['telefone_0800']);
$CPF = mysqli_real_escape_string($db, $_POST['CPF']);
$insc_estadual = mysqli_real_escape_string($db, $_POST['insc_estadual']);
$CNPJ = mysqli_real_escape_string($db, $_POST['CNPJ']);
$RG = mysqli_real_escape_string($db, $_POST['RG']);
$insc_municipal = mysqli_real_escape_string($db, $_POST['insc_municipal']);
$PIS = mysqli_real_escape_string($db, $_POST['PIS']);
$site = mysqli_real_escape_string($db, $_POST['site']);
$historico = mysqli_real_escape_string($db, $_POST['historico']);
$email = mysqli_real_escape_string($db, $_POST['email']);
// define cada mensagem de erro se os campos não forem preenchidos
if (empty($nome)) { array_push($errors, "Nome é obrigatório"); }
if (empty($data_de_nascimento)) { array_push($errors, "<PERSON> é obrigatório"); }
if (empty($numero_de_cadastro)) { array_push($errors, "<PERSON> é obrigatório"); }
if (empty($CEP)) { array_push($errors, "CEP é obrigatório"); }
if (empty($numero)) { array_push($errors, "Numero Residencial é obrigatório"); }
if (empty($bairro)) { array_push($errors, "<PERSON>"); }
if (empty($endereço)) { array_push($errors, "<PERSON>"); }
if (empty($cidade)) { array_push($errors, "Cidade é obrigatório"); }
if (empty($complemento)) { array_push($errors, "Complemento é obrigatório"); }
if (empty($uf)) { array_push($errors, "UF é obrigatório"); }
if (empty($categoria_de_cliente)) { array_push($errors, "Categoria de Cliente é obrigatório"); }
if (empty($CPF)) { array_push($errors, "CPF é obrigatório"); }
if (empty($insc_estadual)) { array_push($errors, "Inscrição Estadual é obrigatório"); }
if (empty($RG)) { array_push($errors, "RG é obrigatório"); }
if (empty($insc_municipal)) { array_push($errors, "Inscrição Municipal é obrigatório"); }
if (empty($PIS)) { array_push($errors, "PIS é obrigatório"); }
// Grava os dados no banco
$sql = "INSERT INTO registro(nome, data_de_nascimento, numero_de_cadastro, CEP, numero, bairro, endereço, cidade, complemento, uf, telefone_residencial, telefone_comercial, categoria_de_cliente, telefone_celular, telefone_0800, CPF, insc_estadual, CNPJ, RG, insc_municipal, PIS, site, historico, email) VALUES('$nome', '$data_de_nascimento', '$numero_de_cadastro', '$CEP', '$numero', '$bairro', '$endereço', '$cidade', '$complemento', '$uf', '$telefone_residencial', '$telefone_comercial', '$categoria_de_cliente', '$telefone_celular', '$telefone_0800', '$CPF', '$insc_estadual', '$CNPJ', '$RG', '$insc_municipal', '$PIS', '$site', '$historico', '$email')";
if (!mysqli_query($db, $sql)) die(mysqli_error($db));
// Redireciona para outra pagina caso seja <PERSON>
header("location: painel.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<title><PERSON>>
</head>
<body>
<form action="reg2.php" method="post">
<? include('errors.php') ?>
Nome:<br>
<input type="text" name="nome" required>
<br>
Data de nascimento:<br>
<input type="text" name="data_de_nascimento">
<br>
Numero de cadastro:<br>
<input type="text" name="numero_de_cadastro" required>
<br>
CEP:<br>
<input type="text" name="CEP" required>
<br>
Numero residencial:<br>
<input type="text" name="numero" required>
<br>
Bairro:<br>
<input type="text" name="bairro" required>
<br>
Endereço:<br>
<input type="text" name="endereço" required>
<br>
Cidade:<br>
<input type="text" name="cidade" required>
<br>
<PERSON>>
<input type="text" name="numero_de_cadastro" required>
<br>
Complemento:<br>
<input type="text" name="complemento" required>
<br>
UF:<br>
<input type="text" name="uf" required>
<br>
Telefone Residencial:<br>
<input type="text" name="telefone_residencial" required>
<br>
Telefone Comercial:<br>
<input type="text" name="telefone_comercial" required>
<br>
Categoria de cliente:<br>
<input type="text" name="categoria_de_cliente" required>
<br>
Telefone Celular:<br>
<input type="text" name="telefone_celular" required>
<br>
Telefone 0800:<br>
<input type="text" name="telefone_0800" required>
<br>
CPF:<br>
<input type="text" name="CPF" required>
<br>
Inscrição Estadual:<br>
<input type="text" name="insc_estadual" required>
<br>
CNPJ:<br>
<input type="text" name="CNPJ" required>
<br>
RG:<br>
<input type="text" name="RG" required>
<br>
Inscrição Municipal:<br>
<input type="text" name="insc_municipal" required>
<br>
PIS:<br>
<input type="text" name="PIS" required>
<br>
Site:<br>
<input type="text" name="site" required>
<br>
Email:<br>
<input type="text" name="email" required>
<br>
Historico:<br>
<input type="text" name="historico" required>
<br><br>
<input type="submit" name="register_btn" value="Register">
</form>
</body>
</html>
Esta solução só foi possível graças a grande ajuda nos comentários da pergunta.
Obrigado!
| 3f134c144a67095203c1e7b920209ba1ab336410e9bc82473d4bf513f869a48c | ['0ea2f270e04e413f81526bba3f5307b2'] | I tried using your shader and could get it to work with moderate success. As I want to use my own sprites I experimented with some different setting in Photoshop, which didn't really work out I have trouble understanding this section of your post regarding the creation of own sprites with your shader: "First of all, your sprite doesn't really need to be grayscale..." can you explain in more detail how the sprite should be prepared to work with this shader? |
05433c4b45c39131b22dfde09c3709f94742799debc60bae384d671f4f2453fe | ['0eabc865b7d9497996245090688942c6'] | We're working on an Android App that requires resizing (frame size) and compressing videos. We tested the code sample below and it's currently slow:
https://github.com/hoolrory/AndroidVideoSamples/blob/master/CommonVideoLibrary/src/com/roryhool/commonvideolibrary/VideoResampler.java
The output video frame size is reduced (e.g., 480x320), and the bit-rate is also reduced to achieve compression. The final video looks very good and the compression ratios are good, too. It's just that the process is slow. I tested on a Galaxy S4 running Android 4.4 and Galaxy Note 5 running Android 6.0. The later is faster, but not by much. On Galaxy S4, a 30-second video takes about a minute to compress (on average).
The code above decods the input video on an input surface, reduces frame size, and outputs to an output surface. MediaMuxer is used to mux-in the audio. The example is using an MPEG container and H264 encoder. Some relevant questions:
Are there some parameters we can use to speed up the compression?
How is the video compression speed affected by the target bit rate and frame size, if any?
We didn't use FFMpeg. Is that faster?
Any pointers or hints, even if not related to the code sample above, would be highly appreciated.
Thank you very much!
<PERSON>
| ad348cab383335e0e22b0993fec8201f56480603c91c25e3f1b7a50555efd22e | ['0eabc865b7d9497996245090688942c6'] | ANSWER:
I found the solution to this problem. It turned out there was a firewall active that was blocking the port. The firewall is called "firestarter". Not sure how this was installed, but it can be downloaded from the ubuntu software center. The default inboud policy blocks all ports except for SSH (22). I opened port 8080 and everything worked just fine. The other firewalls (ufw and SELinux) were disabled.
Thank you all again for your help.
<PERSON>
|
5aa1f5caca79e4cab56aa3c3cd9859a3e00b5537f2ee1aa4414a4592ff0f78f3 | ['0eafa6fea4fd4cb5a960dd19faf3a866'] | When I want to pass a parameter to the view constructor I am getting an error in the MasterDetailPage xaml.
Error: No constructors found for Xamarin.Forms.NavigationPage with matching x:Arguments.
MasterDetailPage:
<MasterDetailPage.Master>
<pages:LoginMasterDetailPageMaster x:Name="MasterPage" />
</MasterDetailPage.Master>
<MasterDetailPage.Detail>
<NavigationPage>
<x:Arguments>
<pages:LoginView/>
</x:Arguments>
</NavigationPage>
</MasterDetailPage.Detail>
</MasterDetailPage>
LoginView:
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class LoginView : ContentPage
{
public LoginView(bool showAutoLogOutMessage)
{
InitializeComponent();
BindingContext = ((ViewModelLocator)Application.Current.Resources["Locator"]).Login;
}
Does anyone know how to solve this issues? Many thanks in advance.
| 700550cc62bbd7e3bebf190197c5be102ed2e39f3069e6d5d8e2ce9adb494b69 | ['0eafa6fea4fd4cb5a960dd19faf3a866'] | I am trying to make a SOAP request and I am catching an Exception, you can see it below. (I am not consuming WCF)
Maybe someone had similar issues and knows how to solve it? Thanks in advance.
{System.ArgumentException: The empty string '' is not a valid local name.
at (wrapper managed-to-native) System.Object:__icall_wrapper_mono_delegate_end_invoke (object,intptr)
at (wrapper delegate-end-invoke) :end_invoke_object__this___object[]&_IAsyncResult (object[]&,System.IAsyncResult)
at System.ServiceModel.MonoInternal.ClientRuntimeChannel.EndProcess (System.Reflection.MethodBase method, System.String operationName, System.Object[] parameters, System.IAsyncResult result) [0x0001f] in <475dec2c1fe44b95bbfbd21b550b63f8>:0
at System.ServiceModel.ClientBase1+ChannelBase1[TChannel,T].EndInvoke (System.String methodName, System.Object[] args, System.IAsyncResult result) [0x00045] in <475dec2c1fe44b95bbfbd21b550b63f8>:0
at App3.AscoTms.imcwpPortTypeClient+imcwpPortTypeClientChannel.EndLogin (System.IAsyncResult result) [0x00008] in C:\Users\georgij.nebudrov\source\repos\App3\App3\App3\Connected Services\AscoTms\Reference.cs:3833
at App3.AscoTms.imcwpPortTypeClient.App3.AscoTms.imcwpPortType.EndLogin (System.IAsyncResult result) [0x00001] in C:\Users\georgij.nebudrov\source\repos\App3\App3\App3\Connected Services\AscoTms\Reference.cs:3088
at App3.AscoTms.imcwpPortTypeClient.EndLogin (System.IAsyncResult result) [0x00001] in C:\Users\georgij.nebudrov\source\repos\App3\App3\App3\Connected Services\AscoTms\Reference.cs:3093
at App3.AscoTms.imcwpPortTypeClient.OnEndLogin (System.IAsyncResult result) [0x00001] in C:\Users\georgij.nebudrov\source\repos\App3\App3\App3\Connected Services\AscoTms\Reference.cs:3103
at System.ServiceModel.ClientBase1+<>c__DisplayClass39_0[TChannel].<InvokeAsync>b__0 (System.IAsyncResult ar) [0x00006] in <475dec2c1fe44b95bbfbd21b550b63f8>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <896ad1d315ca4ba7b117efb8dacaedcf>:0
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <896ad1d315ca4ba7b117efb8dacaedcf>:0
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <896ad1d315ca4ba7b117efb8dacaedcf>:0
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <896ad1d315ca4ba7b117efb8dacaedcf>:0
at System.Runtime.CompilerServices.TaskAwaiter1[TResult].GetResult () [0x00000] in <896ad1d315ca4ba7b117efb8dacaedcf>:0
at App3.MainPage+d__2.MoveNext () [0x00081] in C:\Users\georgij.nebudrov\source\repos\App3\App3\App3\MainPage.xaml.cs:47 }
|
1af91f148fa7dd8603346b12fc9b446fedba5b17c84da1cebac5419d90fa3830 | ['0ed5fe90a5ac4642a3f3206deea5dff7'] | A solution for your problem might be:
Throw out your @header definitions.
Build .java files with ANTLR Tool by command:
java org.antlr.v4.Tool -package com.splendit.pli2uct
Reason for the error when you leave your @header in, is that the ANTLR Tool combines the two grammars, so it is nearly the same as if you put it in one file.
Have fun with ANTLR, its a very nice Tool
| ce469391766f4fdfee479491599fa68f26a1f7e90dbfd1ec4c9686c85c125ff6 | ['0ed5fe90a5ac4642a3f3206deea5dff7'] | You are omitting whitespace, so why do you match ' ' in your grammar rule functionValue?
Remove this parts and you get a complete working grammar (on your given example) including the correct parsing of the calculation expression.
The rule is now:
functionValue : 'VALUE(' (STRING)* functionNumber ((STRING|functionNumber))* ')' (match)?;
Have fun with ANTLR4, it is a very nice tool.
PS: Think about splitting your parser grammar and lexer grammar, it will give you two files which are better to read.
Their headers will be
CapsaParser.g4
parser grammar CapsaParser;
options { tokenVocab = CapsaLexer; }
CapsaLexer.g4
lexer grammar CapsaLexer;
|
5f49eb3b3e7aeb6056544129b77b7753a99508df7bd76e18df45fc47d43b08f8 | ['0eecc05d8c8343098df5747ef63f909a'] | You have shown that $$N:=\left\{a\in\mathbb R:f(a)=0\text{ and }f'(a)\ne0\right\}$$ is countable and $h$ is differentiable at $a$ with $$h'(a)=\begin{cases}e^{g(a)}g'(a)&\text{, if }g(a)<0\\0&\text{, if }g(a)>0\\0&\text{, if }g(a)=0\text{ and }g'(a)=0\end{cases}$$ for all $a\in\mathbb R\setminus N$. What can we say about the second derivative? It's clear that $$h''(a)=\begin{cases}e^{g(a)}\left(\left|g'(a)\right|^2+g'(a)\right)&\text{, if }g(a)<0\\0&\text{, if }g(a)>0\end{cases}$$ for all $a\in\mathbb R$ though. | 802b91c68f8dd3979662447a87b051452a2e3576ca72d33a23dff17d42cf1c26 | ['0eecc05d8c8343098df5747ef63f909a'] | Let
$T>0$
$(\Omega,\mathcal A,\operatorname P)$ be a probability space
$(\mathcal F_t)_{t\in[0,\:T]}$ be a complete filtration on $(\Omega,\mathcal A)$
$B$ be a (standard, real-valued) $\mathcal F$-Brownian motion on $(\Omega,\mathcal A,\operatorname P)$
Moreover, let $$\mathcal E^2_{\text{loc}}(H):=\left\{\Phi:\Omega\times[0,T]\to H:\Phi\text{ is }\mathcal F\text{-progressively measurable with }\operatorname P\left[\int_0^t\left\|\Phi_s\right\|_H^2{\rm d}s<\infty\right]=1\right\}$$ for any separable $\mathbb R$-Hilbert space $H$.
Let
$d\in\mathbb N$
$\Lambda\subseteq\mathbb R^d$ be Borel measurable
$\left\{\Phi^x:x\in\Lambda\right\}\subseteq\mathcal E^2_{\text{loc}}(\mathbb R)$ with $$\left(\Lambda\ni x\mapsto\Phi_t^x(\omega)\right)\in L^2(\Lambda)\;\;\;\text{for all }(\omega,t)\in\Omega\times[0,T]\tag 1$$
Moreover, let $$\Psi:\Omega\times[0,T]\to L^2(\Lambda)\;,\;\;\;(\omega,t)\mapsto\left(\Lambda\ni x\mapsto\Phi_t^x(\omega)\right)\;.$$ I want to show that $$\int_0^t\Phi_s^x\:{\rm d}B_s=\left(\int_0^t\Psi_s\:{\rm d}B_s\right)(x)\;\;\;\text{for all }x\in\Lambda\text{ and }t\in[0,T]\tag 2\;.$$
Is that possible, and if so, how? Of course, the usual approach would be to start with considering the case where each $\Phi^x$ is an elementary process (in the usual sense), but it's not trivial to show that then $\Psi$ is an elementary process (in the corresponding sense) too. So, maybe we need additional assumptions. Please take note of my related comment below.
|
5015cf8c4f839d83d4dbd2d41a9e1c1f10e48477c7f7188103e257f7069d979a | ['0f00e21267ea430d94f5bae646ddee91'] | This seems to be a 'better' answer, as I am using sbt together with sbt-native-packager plugin:
mappings in Universal ++= contentOf( baseDirectory.value / "conf" )
This takes all the files under the specified "conf" folder and dumps them in the package root folder.
Which uses the MappingsHelper I stumbled upon in the very terse documentation for it in the sbt-native-packager.
| 5fd095d9022fd24b5ed0892067006f1f8bbf27eca0f184e147bb998facbcbaf0 | ['0f00e21267ea430d94f5bae646ddee91'] | Silverlight had a nice feature ("design time data") that allowed one to indicate data for use in views which was only used at design time. This allowed a designer to work with fleshed out screens that looked realistic rather than just a skeleton.
(for a bit of background on this feature in Silverlight, here's a random msdn post about it)
Is there a similar approach for doing this in angularjs?
|
b958e40eac5fd3aa1ac03e3da928b83c6c6f5c08ca35dc52f5dadcea4575b716 | ['0f234fdafb9d40f9be79c84b53f573e9'] | The answer is NO.
The reason I was getting the behavior I describes was that the gi module is not present in the installation of python that I was using, namely the factory installation on my new MacBook. I was aware that python 2 came installed on Macs. Using Homebrew, I installed python3 thinking I had to in order to get into python programming.
Using "which python" in Terminal, I found a python3 installation in /usr/bin/python3. I could find no 'gi' module in this installation and it is version 3.7.3. Using "which python3" I found a python3 alias in /usr/local/bin/python3. There is a 'gi' module with that one and it is version 3.7.7 with the original file python3.7 located in the Cellar of Homebrew.
I confirmed interactively that running this version DID NOT generate the error:
SMMac3:~-> python3
Python 3.7.7 (default, Mar 23 2020, 10:54:01)
[Clang 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import gi
>>> exit
So I added the following lines to the .zshrc file:
alias python=/usr/local/bin/python3
alias python3=/usr/local/bin/python3
And I no longer get the 'module not found' error. :)
Now I have a new problem which I will ask about in a separate question...
| affe1a4f4389df86663a2fa9007eb42d5a46e7e0eea7158a1170fde40c21d06a | ['0f234fdafb9d40f9be79c84b53f573e9'] | Thank you <PERSON> for your suggestion. Before I saw your post, I came to a similar conclusion:
Using the Arraylist of vertices from the paint operation, I populated a "Path2D.Float" object called "contour" by looping through the points list that was created during the "painting" operation. Using this "contour" object, I instantiated an Area called "interferogram". Just to check my work, I created another PathIterator, "PI", from the Area and decomposed the Area, "interferogram" into "segments" sending the results to the console. I show the code below:
private void mnuitmKeepInsideActionPerformed(java.awt.event.ActionEvent evt)
{
// Keeps the inner area of interest
// Vertices is the "pts" list from Class MouseDrawing (mask)
// It is already a closed path
ArrayList<Point2D.Float> vertices =
new ArrayList<>(this.mask.getVertices());
this.contour = new Path2D.Float(Path2D.WIND_NON_ZERO);
// Read the vertices into the Path2D variable "contour"
this.contour.moveTo((float)vertices.get(0).getX(),
(float)vertices.get(0).getY()); //Starting location
for(int ivertex = 1; ivertex < vertices.size(); ivertex++)
{
this.contour.lineTo((float)vertices.get(ivertex).getX(),
(float)vertices.get(ivertex).getY());
}
this.interferogram = new Area(this.contour);
PathIterator PI = this.interferogram.getPathIterator(null);
//Test print out the segment types and vertices for debug
float[] p = new float[6];
int icount = 0;
while( !PI.isDone())
{
int type = PI.currentSegment(p);
System.out.print(icount);
System.out.print(" Type " + type);
System.out.print(" X " + p[0]);
System.out.println(" Y " + p[1]);
icount++;
PI.next();
}
BufferedImage masked = Mask(this.image_out, this.interferogram);
// Write image to file for debug
String dir;
dir = System.getProperty("user.dir");
dir = dir + "\\00masked.png";
writeImage(masked, dir, "PNG");
}
Next, I applied the mask to the image testing each pixel for inclusion in the area using the code below:
public BufferedImage Mask(BufferedImage BIM, Area area)
{
/** Loop through the pixels in the image and test each one for inclusion
* within the area.
* Change the colors of those outside
**/
Point2D p = new Point2D.Double(0,0);
// rgb should be white
int rgb = (255 << 24);
for (int row = 0; row < BIM.getWidth(); row++)
{
for (int col = 0; col < BIM.getHeight(); col++)
{
p.setLocation(col, row);
if(!area.contains(p))
{
BIM.setRGB(col, row, rgb);
}
}
}
return BIM;
}
public static BufferedImage deepCopy(BufferedImage B2M)
{
ColorModel cm = B2M.getColorModel();
boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
WritableRaster raster = B2M.copyData(B2M.getRaster()
.createCompatibleWritableRaster());
return new BufferedImage(cm, raster, isAlphaPremultiplied, null);
}
This worked beautifully (I was surprised!) except for one slight detail: the lines of the area appeared around the outside of the masked image.
In order to remedy this, I copied the original (resized) image before the painting operation. Many thanks to user1050755 (Nov 2014) for the routine deepCopy that I found on this website. Applying my mask to the copied image resulted in the portion of the original image I wanted without the mask lines. The result is shown in the attached picture. I am stoked!
masked image
|
3484c461305f7d628f9c5a50e4c60d22896997f4f1ce57a9dfd688b4295c3f36 | ['0f2c4ccfbd0b4ed7a1aa697bd0e868da'] | I am trying to override how the categories are display in Timely's All-In-One-Event-Calendar. This calendar uses twig to display all categories in and alphabetical list. I need to group the list by parent id.
At location /all-in-on-event-calendar/app/view/calendar/taxonomy.php is:
/**
* Creates the html for categories filter
*
* @param array $view_args
* @return string
*/
public function get_html_for_categories( array $view_args ) {
return $this->_get_html_for_taxonomy( $view_args );
}
/**
* Generates the HTML for a taxonomy selector.
*
* @param array $view_args Arguments to the parent view
* @param bool $tag whether it's tags or categories.
*
* @return string Markup for categories selector
*/
protected function _get_html_for_taxonomy( $view_args, $tag = false ) {
$taxonomy_name = 'events_categories';
$type = 'category';
$type_for_filter = 'cat_ids';
$type_for_view_args = 'categories';
.... DOES STUFF THAT I WANT TO OVERRIDE....
.... TWIG LOADER THAT FEEDS THE TWIG TEMPLATE....
$loader = $this->_registry->get( 'theme.loader' );
return $loader->get_file( $type_for_view_args . '.twig', $args, false )
->get_content();
}
Then in /all-in-on-event-calendar/public/themes-ai1ec/mytemplate/categories.twig is:
<li class="ai1ec-dropdown ai1ec-category-filter
{% if selected_cat_ids is not empty %}ai1ec-active{% endif %}">
<a class="ai1ec-dropdown-toggle" data-toggle="ai1ec-dropdown">
<i class="ai1ec-fa ai1ec-fa-folder-open"></i>
<span class="ai1ec-clear-filter ai1ec-tooltip-trigger"
data-href="{{ clear_filter }}"
{{ data_type | raw }}
title="{{ text_clear_category_filter }}">
<i class="ai1ec-fa ai1ec-fa-times-circle"></i>
</span>
{{ text_categories }}
..... cut off rest .....
Basically - I would like to know how I can properly override the get_html_for_categories in my custom template so that it feeds the twig template. I know I could just modify /all-in-on-event-calendar/app/view/calendar/taxonomy.php but those changes will just get rewritten every update. There is a functions.php located at /all-in-on-event-calendar/public/themes-ai1ec/mytemplate/functions.php but can't seem to override the class from there. Any suggestions? THANKS!
| 08b5045256ad97bdc6de7f03ef926a7d1fc4b511f26bcee29b60af1d0560126b | ['0f2c4ccfbd0b4ed7a1aa697bd0e868da'] | I have a computer that does not show all of the files in windows explorer or when doing a dir from command line. When browsing in windows explorer - it goes up until file "cat.doc" then no more. If I do a dir in my documents - it will list until it gets to "cat.doc" and then next line says "File Not Found".
If I go to microsoft word- and type the filename exactly of a file not shown - it will open. Example - "Dog.doc" will open in word if I type the filename in the open file dialog box even though it doesn't show in windows explorer or the dir command.
Thanks for any help in advance!
|
9fb5c6258f2083805c8bae28ee8e1bbd854d7009db2bb9dd506821b481222e87 | ['0f3aeb9973d042068f507a9e95ef2579'] | One of the simple ways to handle this situation is using variables. You can easily import a file to set the current latest version. You will need to reload your nginx config when you update the version with this method.
Create a simple configuration file for setting the latest version
# /path/to/latest.conf
set $latest 15;
Import your latest configuration in the server block, and add a location to proxy to the latest version.
server {
listen 80 default_server;
server_name localhost;
# SET LATEST
import /path/to/latest.conf;
location / {
proxy_pass http://s3host;
expires 30d;
}
# Note the / at the end of the location and the proxy_pass directive
# This will strip the "/latest/" part of the request uri, and pass the
# rest like so: /$version/$remaining_request_uri
location /latest/ {
proxy_pass http://s3host/$latest/;
expires 30d;
}
...
}
Another way to do this dynamically would be to use lua to script this behavior. That is a little more involved though, so I will not get into that for this answer.
| 3251be291fc03973fb849d22d6461f920faf44d8108f3a0a44ae536f4b54e426 | ['0f3aeb9973d042068f507a9e95ef2579'] | Indeed the timeout you are setting is not working as you expect it to. Both scripts are spawned, and the expect "assword:" after each spawn is actually catching and reacting to the same password prompt.
expect is actually more sophisticated than a cursory glance would lead you to believe. Each spawn should return a PID, which you can use with your expect to look for output from a specific process.
expect can also be broken down into multiple parts, and have the ability to define subroutines. Here are some more advanced use examples https://wiki.tcl-lang.org/10045
In this specific case I would suggest waiting for the scp to complete before spawning the next process.
expect {
"assword:" {
send "$password\r"
exp_continue # Keep expecting
}
eof {
puts -nonewline "$expect_out(buffer)"
# eof so the process should be done
# It is safe to execute the next spawn
# without exp_continue this expect will
# break and continue to the next line
}
}
|
521217f709d89114c4bc21c7c6ef5ec6def0bbef58596436cd6da9c5aa940e89 | ['0f3ca5f5072d462bb1b6e4c5a5f27200'] | I have three drop-down menus on my site that I created via Bootstrap.
Ideally, when a user clicks on a drop-down menu and selects one of the inner menu items, the drop-down menu should update its text content to the text content of the selected menu item.
However, for any drop-down menu, if a user clicks on a menu item, all three drop-down menus' text content update instead of only that individual drop-down menu as seen below
My current approach is that the aria-expanded attribute for each drop-down button changes to true if a drop-down is open on a button. If the aria-expanded value of a specific drop-down menu is true, then that button's text content changes to the text content of the selected menu item.
JS
function addPlanesToDropDowns() {
let dropdowns = document.querySelector('.dropdown-menu');
let dropDownButtonOne = document.querySelector('#dropdownMenuButtonOne');
let dropDownButtonTwo = document.querySelector("#dropdownMenuButtonTwo");
let dropDownButtonThree = document.querySelector("#dropdownMenuButtonThree");
dropDownDisabledCheck();
for (let i = 0; i < state.airplaneData.length; i++) {
let dropDownMenuItem = document.createElement('a');
dropDownMenuItem.classList.add('dropdown-item');
dropDownMenuItem.href = '#';
dropDownMenuItem.textContent = state.airplaneData[i].make + " " + state.airplaneData[i].model;
dropDownMenuItem.addEventListener('click', function (event) {
event.preventDefault();
if (dropDownButtonOne.getAttribute('aria-expanded')) {
dropDownButtonOne.textContent = dropDownMenuItem.textContent;
dropDownButtonOne.setAttribute('aria-expanded', false);
}
if (dropDownButtonTwo.getAttribute('aria-expanded')) {
dropDownButtonTwo.textContent = dropDownMenuItem.textContent;
dropDownButtonTwo.setAttribute('aria-expanded', false);
}
if (dropDownButtonThree.getAttribute('aria-expanded')) {
dropDownButtonThree.textContent = dropDownMenuItem.textContent;
dropDownButtonThree.setAttribute('aria-expanded', false);
}
dropDownDisabledCheck();
});
dropdowns.appendChild(dropDownMenuItem);
}
}
HTML
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButtonOne" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Plane 1</button>
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButtonTwo" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Plane 2</button>
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButtonThree" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Plane 3</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<!-- <a class="dropdown-item" href="#">Planes go here</a> -->
</div>
</div>
Despite this, all three drop-down menus update with the same selected menu item text content even though I am only setting the text content on the button element with the specific ID attribute.
| 972676ffd3f6cffae9eb18b79e3dafa45093fa915544fbf5db7fd6956e92347f | ['0f3ca5f5072d462bb1b6e4c5a5f27200'] | Example of text file that I am trying to read in
One of the most <adjective> characters in fiction is named
"<PERSON> of the <plural-noun> ." <PERSON> was raised by a/an
<noun> and lives in the <adjective> jungle in the
heart of darkest <place> . He spends most of his time
eating <plural-noun> and swinging from tree to <noun> .
Whenever he gets angry, he beats on his chest and says,
" <funny-noise> !" This is his war cry. <PERSON> always dresses in
<adjective> shorts made from the skin of a/an <noun>
and his best friend is a/an <adjective> chimpanzee named
Cheetah. He is supposed to be able to speak to elephants and
<plural-noun> . In the movies, <PERSON> is played by <person's-name> .
My current program's code
import java.util.*;
import java.io.*;
public class MadLibs {
public static void main(String[] args) throws FileNotFoundException {
intro();
System.out.println();
Scanner console = new Scanner(System.in);
boolean continueGame = true;
while (continueGame == true) {
continueGame = gameMenu(console);
}
}
public static void intro() {
System.out.println("Welcome to the game of Mad Libs.");
System.out.println("I will ask you to provide various words");
System.out.println("and phrases to fill in a story.");
System.out.println("The result will be written to an output file.");
}
public static boolean gameMenu(Scanner console) throws FileNotFoundException {
System.out.print("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
String userChoice = console.nextLine();
if (userChoice.equalsIgnoreCase("c")) {
createMadLib(console);
return true;
} else if (userChoice.equalsIgnoreCase("v")) {
viewMadLib(console);
return true;
} else if (userChoice.equalsIgnoreCase("q")) {
return false;
} else {
return true; //keep continuing even if user input is irrelevant
}
}
public static void createMadLib(Scanner console) throws FileNotFoundException {
System.out.print("Input file name: ");
String fileName = console.nextLine();
File textFile = new File(fileName);
while (!textFile.exists()) {
System.out.print("File not found. Try again: ");
fileName = console.nextLine();
textFile = new File(fileName);
}
System.out.print("Output file name: ");
String output = console.nextLine();
PrintStream outputFile = new PrintStream(output);
Scanner fileRead = new Scanner(textFile);
while (fileRead.hasNextLine()) {
String word = fileRead.next();
if (word.startsWith("<") && word.endsWith(">")) {
char vowel = word.charAt(1);
String beforeVowel = "";
if (vowel == 'a' || vowel == 'A' ||
vowel == 'e' || vowel == 'E' ||
vowel == 'i' || vowel == 'I' ||
vowel == 'o' || vowel == 'O' ||
vowel == 'u' || vowel == 'U') {
beforeVowel = " an";
} else {
beforeVowel = " a";
}
word = word.replace("<", " ");
word = word.replace(">", " ");
word = word.replace("-", " ");
System.out.print("Please type" + beforeVowel + word + ": ");
String inputWord = console.nextLine();
outputFile.print(" " + inputWord + " ");
} else {
outputFile.print(" " + word + " ");
}
}
System.out.println("Your mad-lib has been created!");
}
the full stack trace of the error in question
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at MadLibs.createMadLib(MadLibs.java:58)
at MadLibs.gameMenu(MadLibs.java:29)
at MadLibs.main(MadLibs.java:13)
It occurs right after the final line of the text file is read by the program. I believe the main cause of the error may be due to the fact that it is still continuing to search for the next placeholder after the last line.
|
8201f1b20bde7476857f68fc6d242195fb04e75696efafb0e9c7301bbaf17f76 | ['0f407c4d597b4827800f7747f169df76'] | I completely agree with <PERSON>: think about performance when you need to and focus on clarity.
If I would have to choose between the two though, I would choose the second way - but slightly adjust it, with help of LINQ.
I would want to, for each array, do:
arr.Where(x => /*Some condition*/ ).ForEach(x => {/*Do Something*/} )
.Where() returns an IEnumerable and to get a ForEach() for IEnumerable,
I would have to introduce an extension method along the lines of:
public static class IEnumerableExtensions
{
public static void ForEach<T>(this IEnumerable<T> enumerable, Action<T> action)
{
foreach (var element in enumerable)
{
action(element);
}
}
}
This will allow for .Where().ForEach() syntax. So the result would resemble the following:
arr1.Where(x => /*Some condition*/ ).ForEach(x => { /*Do Something*/ });
arr2.Where(x => /*Some condition*/ ).ForEach(x => { /*Do Something*/ });
arr3.Where(x => /*Some condition*/ ).ForEach(x => { /*Do Something*/ });
arr4.Where(x => /*Some condition*/ ).ForEach(x => { /*Do Something*/ });
arr6.Where(x => /*Some condition*/ ).ForEach(x => { /*Do Something*/ });
arr5.Where(x => /*Some condition*/ ).ForEach(x => { /*Do Something*/ });
arr7.Where(x => /*Some condition*/ ).ForEach(x => { /*Do Something*/ });
arr8.Where(x => /*Some condition*/ ).ForEach(x => { /*Do Something*/ });
arr9.Where(x => /*Some condition*/ ).ForEach(x => { /*Do Something*/ });
Still pretty repetative. So I would like to see if I could somehow simplify this even further -- maybe
encapsulate the actions and/or conditions so you could then apply it for each of the arrays.
Unfortunately it's not very clear from your question - what exactly needs to be done.
| acb8f5bf4d796c8094cbb39c1f60b82b0ef3eaa363c6168ac3afd090eaa52928 | ['0f407c4d597b4827800f7747f169df76'] | The problem is that you're not using the value that you compute in your SubjectExistsChecker().
In order to use what you return from within a method, you could perform an assignment upon the call to the method, like so:
String exists = SubjectExistsChecker(input, exists);
But if we go this way, we don't really need to supply it as a parameter to the method - because if you look at it, nothing depends on this parameter.
Also note that we tend to name methods with verbs - as it reflects their nature. For example, your method could be named DoesSubjectExist.
So you could adjust the method like so:
private static string DoesSubjectExist(string input)
{
string exists = "";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand("SELECT Subject_Name FROM Subject WHERE Subject_Name ='" + input + "'", connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
for (int j = 0; j < reader.FieldCount; j++)
{
exists = reader.GetValue(j) + "";
}
}
}
}
return exists;
}
}
But still it is unclear what did you want the result of this method to be?
What we can guess from the name, we want to check if a subject exists - we don't have to know what it is.
In that case, it would make sense that the method returns either true if subject with given name exists or false otherwise.
So, with further adjustments:
private static bool DoesSubjectExist(string input)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// Note that query will probably need to be changed too for a more optimal solution.
using (SqlCommand command = new SqlCommand("SELECT Subject_Name FROM Subject WHERE Subject_Name ='" + input + "'", connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
// Do we need this loop?
while (reader.Read())
{
// There is at least one match - so the subject exists.
if (reader.FieldCount > 0) return true;
}
}
}
return false; // If we get here, we didn't find anything.
}
}
So this will be much more expressive. Note your use case:
MethodName()
{
//some code asking for subjectName which we call `input`
if (DoesSubjectExist(input))
{
//do some code
}
else
{
//do some code
}
}
Also, please take the advice other people here are giving and abstract your SQL data access somehow.
|
4d5997131cafe9fc626dcc79518b9b03a9886d5046da86b076ac89e0cc0bf928 | ['0f582b0e296a45f78ec87049907155ff'] | I think that you need to include first the AngularJs's file/cdn and then your app.js file. You probably need to send all the files that are involved in your page like css, js and so on. If you post more code about your server-side application we may help you.
| 0c9d3968c80a2d86c15cd845513e61c0dab8e009688044a592f85bd102d23c5f | ['0f582b0e296a45f78ec87049907155ff'] | This query work for me:
db.collection.update({
'_id': new mongoose.Types.ObjectId("59198a3e73ae303f97e97e8f"),
'child.id': A SPECIFIC ID
},
{
$inc: { 'age': 1, 'child.$.age': 1 }
});
Your query doesn't work because the $ operator need a condition to verify before increase the appropriate child from the nested array. If you want to go deepen, here is the official documentation.
|
07a4218880d3918c0421eeeed6443c990047c99dfd725accc7987618b1d770a8 | ['0f595ef3151f4210864a46f5165551df'] | A thought: why do you have to convert the images in the first place? Why not just use Flash to display the images. That can be done using ActionScript.
If the images are not the correct size, then use your application server to resize them before putting them in a location accessible to your Flash application.
| 6d0a6272fa64b9ab5d443a3d1faf1d4ece83774164068f5c8b88c42d88b7cc5f | ['0f595ef3151f4210864a46f5165551df'] | Well you need to run the query (or a count(*)) at least once to get the total number. You could:
Cache this query and refer to the
cached query's recordcount again
and again
Store the record count in the session scope until the next time it is run for this user
|
9c61be5e41239b684d9ed0d0301aa6dd63b263d1c1306155f101966601a1004a | ['0f5f0e671b72447094b924033f24860d'] | I am reading <PERSON> - Difference between Weil and canonical heights, and on page 739 in Example 7.1, the author is investigating the curve $E: y^2=x^3-x+1.$ The goal is to determine $E(\mathbb{Q})$. Here is an excerpt:
I do not understand the last part. What result is used to conclude that $x(P)\in\mathbb{Z}$ implies $x(R)\in\mathbb{Z}$? I know this isn't true in general, but does it hold for all curves with trivial torsion? Any help would be appreciated. Thanks.
| defb84eb7be9ae9e72092e87ed403f21f7829f261a3a282a4346994a5533b7b9 | ['0f5f0e671b72447094b924033f24860d'] | I believe we have a short exact sequence (writing tildes for quotient) $0\to\tilde{m}_x\to\tilde{m}_{x,y}\to\tilde{m}_y\to0$. The first map is inclusion, and the second kills all terms involving $X_1,\dots,X_n$. Assuming this, we can use the fact that the alternating sum of dimensions in a short exact sequence of vector spaces is $0$. In other words, $N_x-N_{x,y}+N_y=0,$ which is what we needed. I am not an expert though so only posting as a comment. |
02c7dd5bba921e02c01fd166742c1b7a9d49e9c2d4e25230d0c58e243337c921 | ['0f65488762344084b4c0ba7178a38fed'] | Let's say I have an array of arrays containing JavaScript Date Objects, grouped by day.
How would I go about displaying them in HTML as a table (or any other way), so that all matching times are on the same height?
Array:
let array = [
[
new Date("2020-01-01 08:00:00"),
new Date("2020-01-01 08:30:00"),
new Date("2020-01-01 09:00:00")
],
[
new Date("2020-01-02 08:30:00"),
new Date("2020-01-02 09:00:00"),
new Date("2020-01-02 09:30:00")
],
[
new Date("2020-01-04 09:00:00"),
new Date("2020-01-03 10:00:00")
]
]
Desired output as HTML table:
|-------|-------|-------|
| 08:00 | | |
|-------|-------|-------|
| 08:30 | 08:30 | |
|-------|-------|-------|
| 09:00 | 09:00 | 09:00 |
|-------|-------|-------|
| | 09:30 | |
|-------|-------|-------|
| | | 10:00 |
|-------|-------|-------|
Just for displaying the data, I'd simply use two nested foreach loops but then I would end up with all rows starting in the first, not padding as anticipated.
I am using Date-Fns so I suppose I could use getHours(date) somehow to compare two dates and if they should be on the same height.
Are there any simple solutions to do this?
| 0cfcc8a68af1fe5914d8ccbf4c1fcc8c09bbb4f147accf285ec9bba918afb989 | ['0f65488762344084b4c0ba7178a38fed'] | Let's assume I wrote a class Authentication that provides methods for registering users and signing them in.
Of course I need another class DB that will run the actual database statements and retrieve the data.
When importing Authentication in another application to make use of it, I would call its method signUpUser() that will sign up a user.
Now this method will run essentially a method with the same name and purpose that you would expect from Authentication.signUpUser() but actually doing the database statements in DB.
Is there any way of preventing this "methods in this class do nothing but calling another methods" approach? Should I event prevent such wrapper functions? What are good habits here and why?
|
20dbbd498d7e2993b859bb0b95a51073dc844975380065efd1648f78f0afb98c | ['0f6aec4b31454f56bb00c63e8c1bf026'] | últimamente estuve teniendo problemas con la instalación y creación de paquetes (En Python). En primer lugar, por alguna razón, no se me crean carpetas caché cuando defino un paquete con el archivo __ init __.py, cosa que siempre pasaba. Luego viene el problema de la instalación (porque crear uno, se ve, no es un problema):
El código de CMD:
Microsoft Windows [Versión 10.0.18363.959]
(c) 2019 Microsoft Corporation. Todos los derechos reservados.
C:\Users\Usuario>desktop
"desktop" no se reconoce como un comando interno o externo,
programa o archivo por lotes ejecutable.
C:\Users\Usuario>cd desktop
C:\Users\Usuario\Desktop>python setup.py sdist
running sdist
running egg_info
creating paquetefinal.egg-info
writing paquetefinal.egg-info\PKG-INFO
writing dependency_links to paquetefinal.egg-info\dependency_links.txt
writing top-level names to paquetefinal.egg-info\top_level.txt
writing manifest file 'paquetefinal.egg-info\SOURCES.txt'
reading manifest file 'paquetefinal.egg-info\SOURCES.txt'
writing manifest file 'paquetefinal.egg-info\SOURCES.txt'
warning: sdist: standard file not found: should have one of README, README.rst, README.txt, README.md
running check
warning: check: missing required meta-data: url
creating paquetefinal-1.0
creating paquetefinal-1.0\Paquetesdistribuidores
creating paquetefinal-1.0\paquetefinal.egg-info
copying files to paquetefinal-1.0...
copying setup.py -> paquetefinal-1.0
copying Paquetesdistribuidores\1modulo.py -> paquetefinal-1.0\Paquetesdistribuidores
copying Paquetesdistribuidores\__init__.py -> paquetefinal-1.0\Paquetesdistribuidores
copying paquetefinal.egg-info\PKG-INFO -> paquetefinal-1.0\paquetefinal.egg-info
copying paquetefinal.egg-info\SOURCES.txt -> paquetefinal-1.0\paquetefinal.egg-info
copying paquetefinal.egg-info\dependency_links.txt -> paquetefinal-1.0\paquetefinal.egg-info
copying paquetefinal.egg-info\top_level.txt -> paquetefinal-1.0\paquetefinal.egg-info
Writing paquetefinal-1.0\setup.cfg
creating dist
Creating tar archive
removing 'paquetefinal-1.0' (and everything under it)
C:\Users\Usuario\Desktop>cd dist
C:\Users\Usuario\Desktop\dist>pip3 install paquetefinal-1.0.tar
WARNING: Requirement 'paquetefinal-1.0.tar' looks like a filename, but the file does not exist
Processing c:\users\usuario\desktop\dist\paquetefinal-1.0.tar
ERROR: Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory: 'C:\\Users\\Usuario\\Desktop\\dist\\paquetefinal-1.0.tar'
C:\Users\Usuario\Desktop\dist>
| 9f1b1f403c7bc6aa45084017e936ab975090fcd17c7ca4bdb2ba6680f0782398 | ['0f6aec4b31454f56bb00c63e8c1bf026'] | ok, because you mention that for comparing symmetric and anti-symmetric we cannot assume a≠b, so for that i understand for symmetric part.
but for anti-symmetric it mean aRb and bRa mean
a = b. so for my previous post, anti-symmetric mean
a = mb and b = na does that imply we using the reflexive property a = b or it is not because the expression
a = b ≠ a = mb even thought the result is the same? |
087b0c0b2b652106dbb0cb6a330893e5b11dbb38dc6caace256c43c9aa9178b8 | ['0f6afb4ff59c4a50adacf604594292dd'] | Thanks for everyone's comments!
I managed to solve this for my problem by writing my own <PERSON> optimisation:
import numpy as np
from sksparse.cholmod import cholesky
f = np.zeros(n_data)
difference = 999
while difference > 1e-5:
cur_hess = hess(f)
cur_jac = jac(f)
cur_chol = cholesky(cur_hess)
sol = cur_chol.solve_A(cur_jac)
new_f = f - sol
difference = np.linalg.norm(f - new_f)
f = new_f
I'm using scikit-sparse to do a sparse Cholesky decomposition with CHOLMOD here. This works really well for my problem and typically converges within a few iterations. Hope it's of use to some!
| c915ad3546ce123c042d65ce71bd4fb3a7c62fc0b4bd9b6a3f5c7b5a813e9a3a | ['0f6afb4ff59c4a50adacf604594292dd'] | The problem I am trying to solve involves minimising a function with respect to a large number (probably 10,000+) of parameters. I can cheaply compute both its Jacobian and its Hessian. The Hessian is very helpful; I am not entirely sure the function is convex, but using the Newton-CG algorithm in scipy.optimize:
result = minimize(to_minimize, f, jac=jac, hess=hess, method='Newton-CG')
converges quickly.
So far so good, but unfortunately, scipy.optimize.minimize is unable to deal with sparse Hessians, so I have to convert the extremely sparse Hessian to a dense matrix. Internally, I believe the Newton-CG method multiplies that Hessian with other things, which I assume will also be much slower than using its sparseness.
In short, my question is: does anyone know of a library that can exploit the sparse Hessian, preferably using the Newton-CG algorithm, or do I have to write one myself? It would be nice if it were in python, but I'm happy to use C++ if that is more fruitful.
|
33a7f669c389f112b47fa29ed2fbfbbc4aa55b1e296b805489c12d52a4e5c55a | ['0f89e38960984b2c8b8718a1963006c0'] | Not sure if I fully understand your problem, but you can create a py.ini file on Windows as described in the Customized Commands section of PEP 397 of which PyLauncher is an implementation.
[commands]
ipython=C:\Anaconda\Scripts\ipython.exe -v
Changing the path to where your local IPython is installed. If you associate the .ipy file extension with the pylauncher executable ( typically C:\Windows\py.exe and you can save the py.ini file to the same path ) and use the shebang below at the top of your .py/.ipy files they should run with ipython and the options specified in the py.ini file
#! ipython
You can also associate the ipython.exe with .ipy files on Windows and it will run the .ipy files.
| 443a3dc3d1c3c7ca35bf7658c35cb06908e13ada83cb2e193c53bdfccfd021ad | ['0f89e38960984b2c8b8718a1963006c0'] | The WinPython IPython QT console appears to default to pylab with the inline backend as <PERSON> suggested in the comments.
It can be a little confusing to know what mode Matplotlib is working in see Matplotlib pylab and pyplot: how they are related?
I tend to use the Python distribution Anaconda it's QTConsole doesn't preload pylab by default so you can import pyplot and use show(), With WinPython you can launch the IPython QT console like this by going to the WinPython*\python*\Scripts directory with the windows command prompt and launching ipython3.exe qtconsole
import matplotlib.pyplot as plt
plt.plot(range(3))
plt.show()
Although that halts the execution in the IPython QT console when plot is open. You can detect which backend is being used by plt.get_backend(), the Anaconda IPython QT console uses QT4Agg on my Windows 7 install.
|
a269b92fc348788b9d7638b4b837c524564c763b24098234fe3d1bc4a187a76f | ['0f9ac314074146368153690e71e63f58'] | The correct solution from my code example above is as follows:
function resolveLatestEvent() {
var eventsPromise = getLatestEvent();
eventsPromise.then(function(result) {
eventDetails = result;
const config = { headers: { 'Content-Type': 'application/json' } };
axios({
method: 'post',
url: 'http://localhost:3000/events/notify',
headers: {},
data: {
title: eventDetails[0].title,
team: eventDetails[0].team,
day: eventDetails[0].day,
creator: eventDetails[0].creator,
description: eventDetails[0].description,
jira: eventDetails[0].ticket
}
}, config);
// Log out what we get for debugging
//console.log('here are the eventDetails', eventDetails)
}, function(err) {
console.log(err);
})
}
| 18b9309c6aa67fa1ca3c712b1dbdc31fc86873881f2c0c63d0026c4b18677c7b | ['0f9ac314074146368153690e71e63f58'] | I am trying to create a secondary private interface to communicate between 2 openvz containers.
I have tried the steps indicated in the manual here: http://openvz.org/Virtual_Ethernet_device
Doing this I am able to get the container to communicate with the br0 interface I have created on the host machine but the host machine cannot communicate with the container and the containers cannot talk to eachother.
If anyone has experience with this can you share how you accomplished it?
|
8e9d78b84b0a88a7a975e6ade0199e2ff630922b91c687a6f85a4004b4befd03 | ['0fa2f2df508d4e798e4ae9fe5e3d30ad'] | I'm trying to make a scheduling program where no two talks can proceed at the same time, although a talk can proceed as the other one ends. After putting the first talk into Scheduler plan, I want to go through each talk in my arrayList and check if there compatible with the last talk in the schedule.
I figure I can check by comparing if the startTime of index i is greater than the endtime of index i-1.
I sorted my talks and lectures by there endTime and inputted the first array. Now I'm having trouble comparing the events and adding the right ones into Scheduler plan.
public class Scheduler {
private ArrayList<Event> events = new ArrayList <Event>();
public Scheduler(ArrayList<Event> events){ //Constructor
for (int i=0; i<events.size(); i++)
this.events.add(events.get(i));
}
public ArrayList<Event> getsortSchedule(){ //Sorting Algorithm
int N = events.size() -1;
for (int i = 0; i <=(N-1); i++)
{
for(int j = 1; j <= N;j++)
{
if(events.get(i).getendTime().compareTo(events.get(j).getendTime()) > 0)
Collections.swap(events, i, j);
}
}
return events;
}
public Scheduler getSchedule(){ //Scheduling attempt
Scheduler plan = new Scheduler(events);
this.events.add(events.get(0));
for (int i=0; i == events.size(); i++)
{
//if(events.get(i).getStartTime() > events.get(i).getendTime())
//if(events.get(i).getStartTime().compareTo(events.get(l).getendTime()) > events.get(i-1).getendTime().compareTo(events.get(l).getendTime()))
this.events.add(events.get(i));
}
return plan;
}
| 2319d36c3479fdf0b0b860467b40c8e08f0a98d5c8a6e1965d390cac90c5643e | ['0fa2f2df508d4e798e4ae9fe5e3d30ad'] | I've been having trouble with this for a few days and cannot get past it. I have an arrayList that stores.
public class Application {
Time startTime = new Time(hour,minute);
Time endTime = new Time((startTime.getHour()), (startTime.getMinute() + duration));
Event e1 = new Event("Lecture", title, startTime, endTime);
I want to sort my events based on my endTime, the issue I'm getting is that endTime is based on startTime which uses the hour and minute from my Time class. When I tried using compareTo I was getting confused. I put it in my Time class, but then realized it had to be in my Event class to compare instances. How would I use compareTo to compare endTimes, and how do I output the sort. When I had put compareTo in my events I got
The method sort(List<T>) in the type Collections is not applicable for the arguments (ArrayList<Event>)
Collections.sort(events);
public Event(String type, String title, Time startTime, Time endTime) {
this.type = type;
this.title = title;
this.startTime = startTime;
this.endTime = endTime;
}
private int minute;
public Time(int hour, int minute) {
this.minute = hour * 60 + minute;
}
Also could I extend a class, or would I have to implement it to use compareTo
|
f1841f4c119b53515cd4ca7c06eb236da3ec29532b3274c5abdc1dff9cc62638 | ['0fa6f2084660406db0be6bd048f47bcd'] | The issue here is that the on_ready event should not receive any parameters. See the Minimal Bot documentation here and the on_ready documentation in the Event Reference here. If you want to send a message when the bot connects. You must first get the channel object and then use the send method. You can find an example of getting a channel and sending a message in the FAQ section of the docs here
| 721d0b8399785e51b32e79fe23e92a0216d3a000dff3faa405aa7e2e609e45d8 | ['0fa6f2084660406db0be6bd048f47bcd'] | I ran into the exact same problem a while back and figured out that decorators are not applied for inherited classes. Decorators i.e. (@IsString) must be applied to the class directly so you unfortunately must redefine the fields in your parent classes to your child DTO's.
See the TypeScript documentation on this here. Specifically this portion
A method decorator cannot be used in a declaration file, on an overload
|
cc269c11da7ffcc7526162d7a69c70dafb51dbb3ef9ba42f5eb7954b02596f10 | ['0ff6514e0f9947d2b1091b901c0e3850'] | The condition you're looking for is in_array($nid, array(51, 52, 53)) (or you could use a bunch of logical ORs).
Putting it all together yields:
<?php if(in_array($nid, array(51, 52, 53))): ?>
<div class="band main-content">
<?php print render($page['content']); ?>
</div>
<?php else: ?>
<div class="band main-content">
<section class="layout">
<?php print render($page['content']); ?>
</section>
</div>
<?php endif; ?>
Also, I'm not sure what the end goal is here, but I would be wary about hard coding node IDs in a template. It's definitely not best practice.
| 565114b7b4ef7109b75854f601b51406d9af591bbb1b98934a8fe9f150977e84 | ['0ff6514e0f9947d2b1091b901c0e3850'] | As far I can tell there is no way to directly test LEDs in the emulator. The best you can do is ensure your notification is working properly and then assume that the LED is working as well. Maybe you could borrow a friend's device with an LED? If anyone else knows how to do this in the emulator, I'd love to know how!
|
b35f956170b24af68e238d7b1a2a1cac658798e3630e25c27a815985d7881ce3 | ['0fff0138f5f349daa60bc1298ccbd3be'] | $(\cos a + \cos b)^2 + (\sin a + \sin b)^2 = \cos^2 a + \cos^2 b + 2\cos a \cos b + \sin^2 a + \sin^2 b + 2\sin a \sin b=(\cos^2 a + \sin^2 a) + (\cos^2 b + \sin^2 b) + 2(\cos a \cos b + \sin a \sin b)=1 + 1 + 2 \cos (a-b)=2+2\cos \frac{\pi}{6}=2+2.\frac{\sqrt{3}}{2}=2+\sqrt{3}$
| abfc7bd8185256d305ef49929cab79fc32553a283efb0406c38051a07bd4222a | ['0fff0138f5f349daa60bc1298ccbd3be'] | You may use root test: This is because note that for sufficienlt large $n$, $\cos (\frac{1}{n})>0$ and hence $\lvert U_n\rvert ^{\frac{1}{n}
}=(\cos (\frac{1}{n}))^{n^2}$ and hence $\limsup_{n\rightarrow\infty}\lvert U_n\rvert ^{\frac{1}{n}}=\lim_{n\rightarrow\infty}\lvert U_n\rvert ^{\frac{1}{n}
}=\lim_{n\rightarrow\infty}(\cos (\frac{1}{n}))^{n^2}=e^{-\frac{1}{2}}<1$. Hence the series converges absolutely.
|
fac2b7508d4d5d2f73eba3e3843a4afa060e9be2537b527453787b3eb24f8b26 | ['101f6a51d6cd47179e5d2a83177c0f16'] | You have to give access_type=offline while authorization. And also you need to use the refreshtoken to refresh to get new access token for your operation.The access token have expiery time. So if you want to use your acess token you have to refresh it.otherwise it will be an invalid token after the expiry.
| 811d3c8a05babfcda27495c81ddf5524f334224f2adab230526d7f33251e0b97 | ['101f6a51d6cd47179e5d2a83177c0f16'] | if you want to fetch the whole profile of the google+ user, you can use the below URL
https://www.googleapis.com/plus/v1/people/me/?access_token={YOUR_ACCESS_TOKEN}
Then call the GET method. You will be given by an array containing authorized profile details.
Another method is that, if you want to store the authorized users email, its already present in the field as id_token. It is a base64_encoded data with some fields. If you decode the id yo will get some information about the user.For example in your result you found id_token as
eyJhbGciOiJSUzI1NiIsImtpZCI6ImRhNjYyNWIzNmJjMDlkMzAwMzUzYjI4YTc0MWNlMTc1MjVhNGMzM2IifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwic3ViIjoiMTE0MjE4NDEwODI0NzM1ODkyMDg0IiwiYXpwIjoiMTY5NzY2MjI4OTY4LWtoNzI1dTFpZWdzNHN1bnFhOThhcHUxMHU4djhhcmFmLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiZW1haWwiOiJhcmp1bkBsaW5rd2FyZS5pbiIsImF0X2hhc2giOiJQVnJxTURpNDViZnVGTm9kTmlsSFlRIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImF1ZCI6IjE2OTc2NjIyODk2OC1raDcyNXUxaWVnczRzdW5xYTk4YXB1MTB1OHY4YXJhZi5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbSIsImhkIjoibGlua3dhcmUuaW4iLCJpYXQiOjE0Mzc0ODIwNTUsImV4cCI6MTQzNzQ4NTY1NX0.uSMrV8rOz4T4i5MhiCeQueNVGLv4NBLP-gtOcyow8t4BY9qvUO78sG4y0jPhbclPdX1kUZjzMVTeah2nU9fTYyl50dlj5FzWNy7LyM-a1GC2jEwkgWMgHdRPh6l7dqMrjQ9sU1rF-ZaiWfG7C9VJTJ76uEWRiSKKA9EFQtBil3xBtmDH07UMRxkbri2jBwaCPAWgjU8-dTarrxNESrwrO_nptaRzfGeaTyQBIYCAk6_9deXmblPgteER1OHoa65xb1OVK3ZPeZ3_dj9gjlXSyGp2ho5WIFGf2xRvW4XoROpUYqhLvrS3s-YrrZ8J5X5-3mafrs1qDjJYJogctbW7dg
The above id_token contains 2 parts separated by '.'. The first part is thebase64_encoded key and the second part is metadata.
you can decode both the data as
$key=base64_decode(eyJhbGciOiJSUzI1NiIsImtpZCI6ImRhNjYyNWIzNmJjMDlkMzAwMzUzYjI4YTc0MWNlMTc1MjVhNGMzM2IifQ)
will give you the key
$data=base64_decode(eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwic3ViIjoiMTE0MjE4NDEwODI0NzM1ODkyMDg0IiwiYXpwIjoiMTY5NzY2MjI4OTY4LWtoNzI1dTFpZWdzNHN1bnFhOThhcHUxMHU4djhhcmFmLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiZW1haWwiOiJhcmp1bkBsaW5rd2FyZS5pbiIsImF0X2hhc2giOiJQVnJxTURpNDViZnVGTm9kTmlsSFlRIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImF1ZCI6IjE2OTc2NjIyODk2OC1raDcyNXUxaWVnczRzdW5xYTk4YXB1MTB1OHY4YXJhZi5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbSIsImhkIjoibGlua3dhcmUuaW4iLCJpYXQiOjE0Mzc0ODIwNTUsImV4cCI6MTQzNzQ4NTY1NX0.uSMrV8rOz4T4i5MhiCeQueNVGLv4NBLP-gtOcyow8t4BY9qvUO78sG4y0jPhbclPdX1kUZjzMVTeah2nU9fTYyl50dlj5FzWNy7LyM-a1GC2jEwkgWMgHdRPh6l7dqMrjQ9sU1rF-ZaiWfG7C9VJTJ76uEWRiSKKA9EFQtBil3xBtmDH07UMRxkbri2jBwaCPAWgjU8-dTarrxNESrwrO_nptaRzfGeaTyQBIYCAk6_9deXmblPgteER1OHoa65xb1OVK3ZPeZ3_dj9gjlXSyGp2ho5WIFGf2xRvW4XoROpUYqhLvrS3s-YrrZ8J5X5-3mafrs1qDjJYJogctbW7dg)
will give you the metadata.
while decoding the data ,it will give the result as
{"iss":"accounts.google.com","sub":"114218410824735892084","azp":"169766228968-kh725u1iegs4sunqa98apu10u8v8araf.apps.googleusercontent.com","email":"<EMAIL_ADDRESS><PHONE_NUMBER>-kh725u1iegs4sunqa98apu10u8v8araf.apps.googleusercontent.com","email":"arjun@linkware.in","at_hash":"PVrqMDi45bfuFNodNilHYQ","email_verified":true,"aud":"<PHONE_NUMBER>-kh725u1iegs4sunqa98apu10u8v8araf.apps.googleusercontent.com","hd":"linkware.in","iat":<PHONE_NUMBER>,"exp":<PHONE_NUMBER>}
Above result you can find the email filed. I hope this will help you.
|
1e232f43039f8c3740cc8480dd5403fe0301888358b2cdfef864972e593ace3b | ['103a1e2d053f421d824f1ffdded9beb2'] | I have configured two datasources in my Spring/MyBatis application. I don't get any error while startup (its reading the Mapper XML and interface). But when invoking the method, its throwing the following exception:
MyBatisSystemException: SqlSession operation; nested exception is java.lang.IllegalArgumentException: selectByPrimaryKey is ambiguous in Mapped Statements collection (try using the full name including the namespace, or rename one of the entries)
It doesn't quite clearly say the cause for ambiguity.
| d7f4d1b1e7307373605b03938aba3d38ffceea50c94f0d34d4134309ffe032ef | ['103a1e2d053f421d824f1ffdded9beb2'] | I am implementing a NiFi processor and have couple of clarifications to make with respect to best practices:
session.getProvenanceReporter().modify(...) - Should we emit the event immediately after every session.transfer()
session.commit() - Documentation says, after performing operations on flowfiles, either commit or rollback can be invoked.
Developer guide: https://nifi.apache.org/docs/nifi-docs/html/developer-guide.html#process_session
Question is, what do I lose by not invoking these methods explicitly?
|
2424c32a03868ffe3dca3b3c3d0c75c37f9ccad08caf2240f9924da0af0cae06 | ['104116423c0e452fb7ac603ca5e5aa20'] | I cannot reduce the screen brightness in Ubuntu 13.04, my device is an Acer Aspire 5742. Ubuntu systems settings says the graphics driver is "Intel® Ironlake Mobile x86/MMX/SSE2" but my laptop comes with "Intel HD Graphics". So I assume it's a problem with my graphic drivers. It would be great if some one could tell me how to uninstall my current driver and install the correct one. Thank you.
| 93b316307d20479889e8cf0f0f5d65157a58414a55bac6b94bc79b713f8a1489 | ['104116423c0e452fb7ac603ca5e5aa20'] | Turns out that along the trail of calculations I was trying to use as an argument for the Math.Pow() function, I was using the "Value" parameters from one of my "Choice" type fields.
The values I'd assigned to the choices in that field could be used in most calculations, but not in the Math.Pow() function.
So I ended up creating a new hidden "Number" type field that returns the correct value based on the choice option selected. Not super elegant, but it's working for me.
|
d6b2f50b0e3b75b3e31552dfb724965b340886f9dfb5ba5b01844734e3d8e29a | ['1051fb7134a7481ea111216ae9793bdd'] | Now that we've all fought over micro/macro optimization, let's try to help with the actual question.
I don't have a full, definitive answer, but you might be able to start here. GCC has some macro hooks for describing performance characteristics of the target hardware. You could theoretically set up a few key macros to help gcc favor "smaller" instructions while optimizing.
Based on very limited information from this question and its one reply, you might be able to get some gain from the TARGET_RTX_COSTS costs hook. I haven't yet done enough follow up research to verify this.
I would guess that hooking into the compiler like this will be more useful than any specific C++ idioms.
Please let us know if you manage any performance gain. I'm curious.
| 0754f41a85cc44be3995910a0144c379b278c6ba50cde98d413a6027555c8ba9 | ['1051fb7134a7481ea111216ae9793bdd'] | This doesn't exactly answer the questions as asked, but I wanted to start by trying a more thorough English translation. It's not perfect, and there are a few lines where I'm still trying to track down the intent. Everyone please speak up with questions and corrections.
lea ecx, [esp+var_8]; Load Effective Address // make ecx point to somewhere on the stack (I don't know where var_8 is being generated in this case, but I'm guessing it's set such that it makes ecx point to the local stack space allocated on the next line)
sub esp, 10h ; Integer Subtraction // make room on stack for 16 bytes of local variable -- doesn't all get used but adds padding to allow aligned loads and stores
and ecx, 0FFFFFFF8h ; Logical AND // align pointer in ecx to 8-byte boundary
fld st ; Load Real // duplicates whatever was last left (passed by calling convention) on the top of the FPU stack -- st(1) = st(0)
fistp qword ptr [ecx] ; Store Integer and Pop // convert st(0) to *64bit* int (truncate), store in aligned 8 bytes (of local variable space?) pointed to by ecx, and pop off the top value from the FPU stack
fild qword ptr [ecx] ; Load Integer // convert truncated value back to float and leave it sitting on the top of the FPU stack
;// at this point:
;// - st(0) is the truncated float
;// - st(1) is still the original float.
;// - There is a 64bit integer representation pointed to by [ecx]
mov edx, [ecx+4] ; // move [bytes 4 thru 7 of integer output] to edx (most significant bytes)
mov eax, [ecx] ; // move [bytes 0 thru 3 of integer output] to eax (least significant bytes) -- makes sense, as EAX should hold integer return value in x86 calling conventions
test eax, eax ; Logical Compare // (http://stackoverflow.com/questions/13064809/the-point-of-test-eax-eax)
jz short loc_3 ; Jump if Zero (ZF=1) // if the least significant 4 bytes are zero, goto loc_3
; // else fall through to loc_1
loc_1: ;
fsubp st(1), st ; Subtract Real and Pop // subtract the truncated float from the original, store in st(1), then pop. (i.e. for 1.25 st(0) ends up 0.25, and the original float is no longer on the FPU stack)
test edx, edx ; Logical Compare // same trick as earlier, but for the most significant bytes now
jz short loc_2 ; Jump if Zero (ZF=1) // if the most significant 4 bytes from before were all zero, goto loc_2 -- (i.e. input float does not overflow a 32 bit int)
fstp dword ptr [ecx] ; Store Real and Pop // else, dump the fractional portion of the original float over the least significant bytes of the 64bit integer
;// at this point:
;// - the FPU stack should be empty
;// - eax holds a copy of the least significant 4 bytes of the 64bit integer (return value)
;// - edx holds a copy of the most significant 4 bytes of the 64bit integer
;// - [ecx] points to a float representing the part of the input that would be lost in integer truncation
;// - [ecx+4] points at the most significant 4 bytes of our 64bit integer output (probably considered garbage now and not used again)
mov ecx, [ecx] ; // make ecx store what it's pointing at directly instead of the pointer to it
add esp, 10h ; Add // clean up stack space from the beginning
xor ecx, 80000000h ; Logical Exclusive OR // mask off the sign bit of the fractional float
add ecx, 7FFFFFFFh ; Add // add signed int max (still need to figure out why this)
adc eax, 0 ; Add with Carry // clear carry bit
retn ; Return Near from Procedure
; ---------------------------------------------------------------------------
loc_2:
;// at this point: the FPU stack still holds the fractional (non-integer) portion of the original float that woud have been lost to truncation
fstp dword ptr [ecx] ; Store Real and Pop // store non-integer part as float in local stack space, and remove it from the FPU stack
mov ecx, [ecx] ; // make ecx store what it's pointing at directly instead of the pointer to it
add esp, 10h ; Add // clean up stack space from the beginning
add ecx, 7FFFFFFFh ; Add // add signed int max to the float we just stored (still need to figure out why this)
sbb eax, 0 ; Integer Subtraction with Borrow // clear carry bit
retn ; Return Near from Procedure
; ---------------------------------------------------------------------------
loc_3:
test edx, 7FFFFFFFh ; Logical Compare // test the most significant bytes for signed int max
jnz short loc_1 ; Jump if Not Zero (ZF=0) // if the high bytes equal signed int max go back to loc_1
fstp dword ptr [ecx] ; Store Real and Pop // else, empty the FPU stack
fstp dword ptr [ecx] ; Store Real and Pop // empty the FPU stack
add esp, 10h ; Add // clean up stack space from the beginning
retn ; Return Near from Procedure
|
a368a7123e0ad05289f153d50fff0207547bad69267be153fc0c987ecb07dfc9 | ['10569e3fe8af43a9b0e2e10507962196'] | My bad, it´s a feature of HDIV.
A6 (Sensitive data exposure) : HDIV offers a confidentially property to all data generated at sever side. That is to say, HDIV replace original parameter values generated at server side by relative values (0,1,2,4, etc.) that avoid exposing critical data to the client side.
Reference: http://www.hdiv.org/hdiv-documentation-single/doc.html
| 5c7678c4a8dbfe69fcd9d0ecc25b03d7674c6a9cc2b47b142fed552d1b38a001 | ['10569e3fe8af43a9b0e2e10507962196'] | I have a web application that uses Spring MVC and Spring Security. When I add the following configuration to my web.xml, it turns impossible do login, it just gets the session expired and I´m not able to authenticate:
<session-config>
<session-timeout>15</session-timeout>
<cookie-config>
<http-only>true</http-only>
<secure>true</secure>
<max-age>31536000</max-age>
</cookie-config>
<tracking-mode>COOKIE</tracking-mode>
</session-config>
If I remove the following, works fine:
<cookie-config>
<http-only>true</http-only>
<secure>true</secure>
<max-age>31536000</max-age>
</cookie-config>
Is there any conflict with Spring configuration? Following is my spring-security.xml:
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd">
<context:component-scan base-package="com.blank.controller"/>
<global-method-security secured-annotations="enabled"/>
<http auto-config="false" use-expressions="true">
<intercept-url pattern="/usuario**" access="hasRole('ROLE_USER')" />
<intercept-url pattern="/usuario/**" access="hasRole('ROLE_USER')" />
<!-- Access denied page -->
<access-denied-handler error-page="/403" />
<form-login login-page="/login" default-target-url="/index"
always-use-default-target="true" authentication-failure-url="/login?error"
username-parameter="username" password-parameter="password" />
<logout logout-success-url="/login?logout" invalidate-session="true" delete-cookies="JSESSIONID" />
<!-- Proteção contra Cross Site Request Forgery (CSRF) -->
<csrf />
<session-management invalid-session-url="/invalidate.do" session-fixation-protection="migrateSession" session-authentication-error-url="/login?error">
<concurrency-control error-if-maximum-exceeded="true" expired-url="/login?expire" max-sessions="1"/>
</session-management>
<remember-me key="terror-key"/>
</http>
<authentication-manager>
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query="select <PERSON> as username, <PERSON> as password, <PERSON> as enabled from usuario where usuario = ?"
authorities-by-username-query="select u.usuario as username, r.nome as perfil from usuario u, perfil r, usuario_perfil ur where ur.usuario = u.id and ur.perfil = r.id and u.usuario = ?" />
<password-encoder ref="encoder" />
</authentication-provider>
</authentication-manager>
<beans:bean id="encoder"
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
<beans:constructor-arg name="strength" value="11" />
</beans:bean>
</beans:beans>
Any ideas?
Thanks in advance.
|
cefacaae242f4d3f8345cc93f858e7426c9687f503c9cde4e13643d488ac1807 | ['106e7b6260364bb3bcb55c4bd7a9aa4e'] | I have a small script for manipulating a sparse matrix in C++. It works perfectly fine except taking too much time. Since I'm doing this manipulation over and over, it is critical to speed it up. I appreciate any idea.Thanks
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#include <iostream> /* cout, fixed, scientific */
#include <string>
#include <cmath>
#include <vector>
#include <list>
#include <string>
#include <sstream> /* SJW 08/09/2010 */
#include <fstream>
#include <Eigen/Dense>
#include <Eigen/Sparse>
using namespace Eigen;
using namespace std;
SparseMatrix<double> MatMaker (int n1, int n2, double prob)
{
MatrixXd A = (MatrixXd<IP_ADDRESS>Random(n1, n2) + MatrixXd<IP_ADDRESS>Ones(n1, n2))/2;
A = (A.array() > prob).select(0, A);
return A.sparseView();
}
////////////////This needs to be optimized/////////////////////
int SD_func(SparseMatrix<double> &W, VectorXd &STvec, SparseMatrix<double> &Wo, int tauR, int tauD)
{
W = W + 1/tauR*(Wo - W);
for (int k = 0; k < W.outerSize(); ++k)
for (SparseMatrix<double>::InnerIterator it(W, k); it; ++it)
W.coeffRef(it.row(),it.col()) = it.value() * (1-STvec(it.col())/tauD);
return 1;
}
int main ()
{
SparseMatrix<double> Wo = MatMaker(5000, 5000, 0.1);
SparseMatrix<double> W = MatMaker(5000, 5000, 0.1);
VectorXd STvec = VectorXd<IP_ADDRESS><IP_ADDRESS>InnerIterator it(W, k); it; ++it)
W.coeffRef(it.row(),it.col()) = it.value() * (1-STvec(it.col())/tauD);
return 1;
}
int main ()
{
SparseMatrix<double> Wo = MatMaker(5000, 5000, 0.1);
SparseMatrix<double> W = MatMaker(5000, 5000, 0.1);
VectorXd STvec = VectorXd::Random(5000);
clock_t tsd1,tsd2;
float Timesd = 0.0;
tsd1 = clock();
///////////////////////////////// Any way to speed up this function???????
SD_func(W, STvec, Wo, 8000, 50);
//////////////////////////////// ??????????
tsd2 = clock();
Timesd += (tsd2 - tsd1);
cout<<"SD time: " << Timesd / CLOCKS_PER_SEC << " s" << endl;
return 0;
}
| c03c3337f995bd5b07344f2bce4875e414c3b107bf96e1185ab8a7209285ee68 | ['106e7b6260364bb3bcb55c4bd7a9aa4e'] | This might work for you and others who check this out. In order to set elements of a matrix m based on the condition on another matrix A, you can use this notation:
m = (A.array() != 0).select(1, m);
This command replaces those elements in matrix m that have non-zero corresponding elements in A, with one.
|
6b629e1ff9e1ea8cd506955a1a4d9c3b3e92bc27e5075b34fe8daf0120ee6ea1 | ['10994facdea44b6e919c9da193333d51'] | I'm working on a bigger app, where we are using lazy loading for modules. After we load a module, then in some cases a component get rendered to a <ng-container><ng-container>. The problem is, the animation which is defined on container is not getting called.
I've created a dummy stackblitz example to demonstrate what I mean: link
app.component.html:
<ng-container *ngIf="visible" [@myAnimation]>
<hello [ngStyle]="{'top': '50px'}" name="not animated"></hello>
</ng-container>
<hello name="animated" [ngStyle]="{'top': '100px'}" *ngIf="visible" [@myAnimation]></hello>
<button (click)="toggle()">Toggle visibility</button>
app.component.ts:
import { Component } from '@angular/core';
import {animate, style, transition, trigger} from '@angular/animations';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ],
animations: [
trigger("myAnimation", [
transition(":enter", [
style({opacity: 0 }),
animate(
"800ms",
style({
opacity: 1
})
),
]),
transition(":leave", [
style({opacity: 1 }),
animate(
"800ms",
style({
opacity: 0
})
),
]),
]),
]
})
export class AppComponent {
name = 'Angular';
visible = false;
toggle() {
this.visible = !this.visible;
}
}
hello.component.ts:
import { Component, Input } from '@angular/core';
@Component({
selector: 'hello',
template: `<h1>Hello {{name}}!</h1>`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
@Input() name: string;
}
| 3ab127edec81bf381ad786e3cfc18b01e8de88d1a887d3a8e33f6e08ce75b27d | ['10994facdea44b6e919c9da193333d51'] | I want to find FIRST and FOLLOW for the following CFG:
S -> O | M
M -> iEtMeM | a
O -> iEtS | iEtMeO
E -> b
I did the left factorization, so I get:
S -> O | M
M -> iEtMeM | a
O -> iEtO'
O'-> S | MeO
E -> b
The FIRST sets:
FIRST(S) = FIRST(O)|FIRST(M) = {i,a}
FIRST(M) = {i,a}
FIRST(O) = {i}
FIRST(O') = FIRST(S)|FIRST(M) = {i,a}
FIRST(E) = {b}
And now I cant find the FOLLOW set for S , because I don't know what FOLLOW(O') is:
FOLLOW(S) = {$, FOLLOW(O')}
|
1ee32ac15210c872bf467d0ce64868b6789ddd5bb96288c80d74b72b60c480f5 | ['10a2ce7b71e14fb3bd3c43be4ec69d80'] | I am submitting a form using ajax with enabling CSRF protection to true in config.php. First time, the form is submitting well but second time it's showing error "Forbidden. The Action you requested is not allowed. 403". How can I securely submit form using ajax by enabling CSRF protection to true.
Below is the ajax function I am using.
$('#loginfrmbtn').on('click', function(){
$(this).prop('disabled', true);
var formdata=$('#loginfrm').serialize();
$.ajax({
type: 'POST',
data: formdata,
url: '<?php echo base_url('logincheck');?>',
dataType: 'json',
success: function(res){
$('#loginfrmbtn').prop('disabled', false);
console.log(res);
}, error: function(jqXHR){
console.log(jqXHR);
}
})
})
| 5f434de0f9f61020412b6584aeab3cee83f0d1425a0acfb45aa8026d767b7b99 | ['10a2ce7b71e14fb3bd3c43be4ec69d80'] | I am deleting an item like this. The delete method is excuting well but I can't echo the last executed query.
public function deleteItems(Request $request){
$query=null;
switch($request->category){
case('categorylist'):
$category = category<IP_ADDRESS>find($request->id);
$query=$category->delete()->toSql();
break;
default:
}
echo json_encode(array('status'=>2, 'msg'=>'Successfully deleted', 'query'=>$query->toSql()));
}
|
b8a5dd4853c75074b0ab6c59abd5562708554cd00321bc0baad01d48de24023e | ['10aee3bd9efb4460abb83bc48bf3eca5'] | Typically this would be done via Flash, not javascript, due to browser compatibility.
That said, html5rocks has a decent tutorial, and also explains some of the technical challenges.
Mainly:
The real problem is that the web's security model is very different from the native world. For example, I probably don't want every Joe Shmoe web site to have random access to my video camera. It's a tough problem to get right.
| a90ee6609e89821cf6cef497f850572f6ac0f41b72330ab175f3fa177eaba68d | ['10aee3bd9efb4460abb83bc48bf3eca5'] | I fixed it to how I was expecting it to work, and am pretty sure this is the correct answer to the question I asked.
<PERSON>.
<div class="container">
<div class="col-sm-6">
<div class="row">
<div class="col-sm-6">Label 1</div>
<div class="col-sm-6">
<input id="input1" name="input1" type="text" value="" maxlength="50"/>
</div>
</div>
<div class="row">
<div class="col-sm-6">Label 3</div>
<div class="col-sm-6">
<input id="input3" name="input3" type="text" value="" maxlength="50"/>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="row">
<div class="col-sm-6">Label 2</div>
<div class="col-sm-6">
<input id="input2" name="input2" type="text" value="" maxlength="50"/>
</div>
</div>
<div class="row">
<div class="col-sm-6">Label 4</div>
<div class="col-sm-6">
<input id="input4" name="input4" type="text" value="" maxlength="50"/>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="row">
<div class="col-sm-6">Label 5</div>
<div class="col-sm-6">
<textarea id="textarea" name="textarea" rows="5" cols="17"></textarea>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="row">
<div class="col-sm-6">Label 6</div>
<div class="col-sm-6">
<input id="input6" name="input6" type="text" value="" maxlength="50"/>
</div>
</div>
<div class="row">
<div class="col-sm-6">Label 7</div>
<div class="col-sm-6">
<input id="input7" name="input7" type="text" value="" maxlength="50"/>
</div>
</div>
</div>
</div>
|
4711adfcf0e4d0bf88468e3552ac15721201892acfcdfa0c47e2e2a958a8444d | ['10d154b01b744929ac722e90975876fb'] | I'm getting a CompileError when running a simple PyStan model in Python:
WARNING:pystan:MSVC compiler is not supported
Traceback (most recent call last): File
"C:\Python36\lib\distutils_msvccompiler.py", line 423, in compile
self.spawn(args) File "C:\Python36\lib\distutils_msvccompiler.py", line 542, in spawn
return super().spawn(cmd) File "C:\Python36\lib\distutils\ccompiler.py", line 909, in spawn
spawn(cmd, dry_run=self.dry_run) File "C:\Python36\lib\distutils\spawn.py", line 38, in spawn
_spawn_nt(cmd, search_path, dry_run=dry_run) File "C:\Python36\lib\distutils\spawn.py", line 81, in _spawn_nt
"command %r failed with exit status %d" % (cmd, rc)) distutils.errors.DistutilsExecError: command 'C:\Program Files
(x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe'
failed with exit status 1 During handling of the above exception,
another exception occurred: Traceback (most recent call last): File
"C:\panormus\venv2\lib\site-packages\IPython\core\interactiveshell.py",
line 3296, in run_code
exec(code_obj, self.user_global_ns, self.user_ns) File "", line 1, in
sm = pystan.StanModel(model_code=model) File "C:\panormus\venv2\lib\site-packages\pystan\model.py", line 349, in
init
build_extension.run() File "C:\Python36\lib\distutils\command\build_ext.py", line 339, in run
self.build_extensions() File "C:\Python36\lib\distutils\command\build_ext.py", line 448, in
build_extensions
self._build_extensions_serial() File "C:\Python36\lib\distutils\command\build_ext.py", line 473, in
_build_extensions_serial
self.build_extension(ext) File "C:\Python36\lib\distutils\command\build_ext.py", line 533, in
build_extension
depends=ext.depends) File "C:\Python36\lib\distutils_msvccompiler.py", line 425, in compile
raise CompileError(msg) distutils.errors.CompileError: command 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe' failed with exit status 1
I've isntalled Pystan using pip (pip install PyStan) on Python 3.6 and am trying to run a simple model (first example here)
I have both MS Visual Studio (not supported) and MinGW-64 (supported) installed on my PC. MinGW works fine to compile similar models using PyMC3, so it seems to me I just need to get my Pystan package to recognize the installation and use that compiler instead. Unfortunately even if that is correct, I am not sure how to do that, can someone help?
| 3c2e18110e0c65c1fb4d9e295c0056067294c8c68adf212f07d1629cf477946e | ['10d154b01b744929ac722e90975876fb'] | Answering myself here. It turns out that others have had similar issues and that the 'standard solution' seems to be to run a conda virtual environment for all pystan modelling. The pystan docs have detailed installation instructions for conda, which worked for me, but no support for non-conda users.
|
75e288424c5a7abf5963054f603157cbaccdf25ead7d558f55ab8459d3c98218 | ['10d7274b9d6e4ddd821785dd963a0d1d'] | Can the other projects see and use the app.config of the main application
Yes. Generally speaking, if the main project references the other projects, which I assume it must, then when you build and deploy the main project, the app.config settings specified in that project's app.config file, will be used for the config references in the other projects.
if i do not distribute the app.config dlls for the other projects in the solution, how do they know know the location of the exposed web services?
Because you've specified them in the app.config of the main project.
if i distribute the other projects app.config with the solution, will the projects reference the attached app.config dll, or will they ignore it, and use the hard coded (at build time) references?
They should use the settings specified in the app.config, at runtime.
| 4b9b877e505f39ad56758f021406b6a04b41aed1566f314f629ae952de9e6027 | ['10d7274b9d6e4ddd821785dd963a0d1d'] | When you initially open a solution in Visual Studio, any installed packages will run the "Init.ps1" script within the package (if it has one).
Sounds like the EF package might be the culprit, and from memory I know it has an Init.ps1, so might be worth removing that package entirely (manually, just delete everything) and reinstalling it.
|
cc31e55cb1cc6b09c351388b08a09f2aadf39d62c20f9d558420453ce71ef8ab | ['10d97b4bdf6e47aea1ff0d3668d9fcf2'] | I thought it was a mistake on RestFB side, parsing the result json, because I got several Exceptions and was kind of confused.
The right way to do this is to use the Multiquery Support of RestFB (Executing Multiqueries with RestFb)
Map<String, String> queries = new HashMap<String, String>();
queries.put("all_posts", "select created_time, post_id, actor_id, message, description, comments from stream where source_id=279947942083512 ORDER BY created_time");
queries.put("comments", "SELECT fromid, username, text, time, post_id FROM comment WHERE post_id in (SELECT post_id FROM #all_posts) ORDER BY post_id");
MultiqueryResults queryResults = facebookClient.executeMultiquery(queries, MultiqueryResults.class);
You have to provide the MultiqueryResults Bean as described in 1
| b01bcefa7a5c805ff8eb136b0c891fd4d043503c5a1e0436a64fe9265b4ddcc1 | ['10d97b4bdf6e47aea1ff0d3668d9fcf2'] | I'm trying to use HashMaps in R and get the following error message:
wrong args for environment subassignment
Here is what I did:
lvls <- union(levels(data$p1), union(levels(data$p2),levels(data2$p3)))
map <- new.env(hash=T, parent=emptyenv())
map[[lvls]] <- 1:length(lvls)
Error in map[[lvls]] <- 1:length(lvls) :
wrong args for environment subassignment
typeof(lvls): character
strangely map[["example-value of lvls"]] <- 1 works fine
but map[[lvls]] <- 1 not
What I'm ultimately trying to do is convert the characters of p1, p2 and p3 into factors while the same character should be the same factor.
|
30c71f27656e4d258d13486341a2d2b9d56c033482b11ca32685c5101924d690 | ['10ec615dd729493387d629852b9a01ac'] | My aim is to connect to a running jupyter qtconsole using the jupyter_client API and to execute commands on that kernel remotely. Execution of code works but it seems not possible to interrupt running code from the kernel frontend using Ctrl-C (either in qtconsole or console). Below my sample code with I execute in a different instance of qtconsole and that can't be interrupted:
import jupyter_client as jc
# Find last accessed connection file
cfile = jc.find_connection_file()
km = jc.KernelManager()
km.load_connection_file(connection_file=cfile)
kc.start_channels()
msg = """
import time
for k in range(10):
print(k)
time.sleep(1)
"""
kc.execute(msg)
The only way I found to interrupt the execution is to send a SIGINIT directly, for example by running the following in another jupyter instance:
import os
import signal
# pid is process identifier of jupyter kernel that runs the loop
os.kill(pid, signal.SIGINT)
Question: Is there a more elegant way of interrupting a running kernel using the jupyter_client API (e.g. KernelClient or KernelManager)?
PS: There is also an open issue on github mentioning this problem but the jupyter developers haven't been very responsive so far.
| ce3f4c246ba57fb1ac4801f4389272e9e1bcbe85c74cb03a7e050549dc78c16d | ['10ec615dd729493387d629852b9a01ac'] | Say we have a Python Pandas DataFrame:
In[1]: df = pd.DataFrame({'A': [1, 1, 2, 3, 5],
'B': [5, 6, 7, 8, 9]})
In[2]: print(df)
A B
0 1 5
1 1 6
2 2 7
3 3 8
4 5 9
I want to change rows that match a certain condition. I know that this can be done via direct assignment:
In[3]: df[df.A==1] = pd.DataFrame([{'A': 0, 'B': 5},
{'A': 0, 'B': 6}])
In[4]: print(df)
A B
0 0 5
1 0 6
2 2 7
3 3 8
4 5 9
My question is: Is there an equivalent solution to the above assignment that would return a new DataFrame with the rows changed, i.e. a stateless solution? I'm looking for something like pandas.DataFrame.assign but which acts on rows instead of columns.
|
c19c485b29154b72d253b0c44bdb08876d64f7c7d5e5bc0e005392d9377e62f2 | ['10ec9416cd3b48c9b21b2f6b2b2168a4'] | @daveloyall That's not how it works. You encrypt the document *today*, and in 5 years, re-encrypt it with a key that is of appropriate length for that time. Do it again every 5 years. In 50 years, your document is still secure, and it is encrypted with of-the-day standards. | d1dd28ea5e1389ff9337ee5e9fba8e6b97de9518b045ea34bb7756332b1601c0 | ['10ec9416cd3b48c9b21b2f6b2b2168a4'] | I'm not sure if you're aware, so I'll let you know here, if she is not on the same network as you, she will not be able to connect unless you port forward. I cannot provide help on port forwarding, as I don't know the model of your router.
If you are on the same network, you can try opening the 'Multiplayer' tab from the main menu and seeing if it shows up there. If it doesn't show up under this, here are some steps to figure out what your address is on your local network.
Windows:
Open the command line (In the Start Menu, type "Command Prompt" and open it)
In the command line type ipconfig | findstr "IPv4"
Something like this should show up:
You'll want to enter the number at the end of your output, including the periods, into the 'Direct Connect' prompt under the 'Multiplayer' tab in minecraft.
I'm afraid I'm not very versed in Linux, but here's a stackoverflow post that may help: "How to get the primary IP address of the local machine on Linux and OS X?"
If you aren't on the same network, you'll need to port forward, instructions per router can be found on this website.
Once you've port forwarded, go to this website. to get your public IP address, and enter this into the 'Direct Connect' prompt.
|
b67b06868a98c77e062b85da1bcba7a42ba90871ac21fb2085eecc3a6c3e59ea | ['10eccf2725fc40019b379b59fe579c47'] | Update:
i measured 1kHz constant noise with oscillator from MX-RM-5V module when it is connected to the raspberry pi 3. With external power supply the module works ok. When the module received something the noise dropped to 300-400 Hz.
I found a visual solution and rather simple way from youtube to really see the noise on the data pin.
THE LED.
When i connected green LED with a 100 Ohm resistor to the data pin the led is constantly glowing. Its not bright but you see small green light. On this occasion the receiver did not receive nothing. So is was pure constant noise.
Next step was to start messing with Low pass filter. I connected 240Ohm resistor and 1.5 uF cap as low pass between data pin and ground. So i connected the greed LED to filtered voltage and the constant noise were filtered.
Led is blinking by the data signals only when the transmitter sends something to the receiver.
Also, my baudrate in the transmitter and receiver code was a bit high. I moved from 1000 bits/s down to 200 bits/s.
From now, the raspberry can detect data from this module and everything is a lot better.
| 6bb25df3a8c8e26a610d2728e480769f1ab8da69f0d4eb908d4cce442b151115 | ['10eccf2725fc40019b379b59fe579c47'] | So, this is my simple voltage divider code:
int sensorValue = 0;
void setup() {
analogReference(INTERNAL);
Serial.begin(9600);
}
void loop() {
sensorValue = analogRead(A0);
// ADC , AREF=1078mV=Vin
Serial.println(sensorValue);
delay(1000);
}
Scematic
The analog reference is set to INTERNAL and this means that divider's Vin=AREF=1078mV. With multimeter i read 350 mV as Vin and 181 mV as Vout
But the analogRead(0) outputs 1023, so its on the end or out of reference.
As i understand that the R1=100,6 Ohm resistor is messing things up.
When i replace R1=1000 Ohm then analogRead=98 and Vin=1070mV, everything looks ok.
But what really happens when i use 100,6 Ohm as R1 ? Can somebody further explain this ?
Also, Arduino official says that there is 32000 Ohm internal resistor on AREF
pin.
*Alternatively, you can connect the external reference voltage to the AREF pin through a 5K resistor, allowing you to switch between external and internal reference voltages. Note that the resistor will alter the voltage that gets used as the reference because there is an internal 32K resistor on the AREF pin. The two act as a voltage divider, so, for example, 2.5V applied through the resistor will yield 2.5 * 32 / (32 + 5) = ~2.2V at the AREF pin.*
How i have to take this into account when i measure the divider's voltage and use analogReference(INTERNAL); // 1.1 V as reference and Vin
I know that it's better to use external ref voltage, but when i want to use INTERNAL 1.1V as ref and supply, is it possible ?
Thanks for any suggestions !
|
51a9c0f03aba3438423c8ceb2907bec807db9cff5092308c3842e708e3765b63 | ['10f9558a672340dfb32e388b5d1c8057'] | I have the follwoing Jquery code to open page on button click passing a parameter but ? is translated to %3F is there anyways to fix this?
$("#PrintDocument").click(function () {
var grid = $("#Billings").data("kendoGrid");
var row = $("input:checked", grid.tbody).closest("tr");
var item = grid.dataItem(row);
window.location.pathname = '/invoice/billing/Print' + '?productId=' + item.ProductID + '&' + 'runId=' + item.RunID;
});
| 2e3238021b8cafbdc612d7ac86bfda3d7be379741fb5b1d9786ad6b4161f8f8b | ['10f9558a672340dfb32e388b5d1c8057'] | I have the following jQuery code on Search button click to read kendo grid data source but for some reason the pager buttons disappear
function onSearchButtonClick() {
var grid = $('#searchProducts').data('kendoGrid');
var gridDS = grid.dataSource;
gridDS.read();
}
On Search button click display all the data and the grid Pager shows only the following P
The highlighted sections are missing, this happend when i uses datasource.read()
|
68e9242d8c342ebb3186a53f2edd2a4447d87712d589972e1731a59bdef8ae7b | ['10fcd7947349421ba27c45376f8d81d8'] | I want to extend a class to include extra data and capabilities (I want polymorphic behavior). It seemed obvious to use inheritance and multiple inheritance.
Having read various posts that inheritance (and especially multiple inheritance) can be problematic, I've begun looking into other options:
Put all data and functions in one class and not use inheritance
Composite pattern
mixin
Is there a suggested approach for the following inheritance example? Is this a case where inheritance is reasonable? (but I don't like having to put default functions in the base-class)
#include <iostream>
//================================
class B {
public:
virtual ~B() { }
void setVal(int val) { val_ = val; }
// I'd rather not have these at base class level but want to use
// polymorphism on type B:
virtual void setColor(int val) { std<IP_ADDRESS>cout << "setColor not implemented" << std<IP_ADDRESS>endl; }
virtual void setLength(int val) { std<IP_ADDRESS>cout << "setLength not implemented" << std<IP_ADDRESS>endl; }
private:
int val_;
};
//================================
class D1 : virtual public B {
public:
void setColor(int color) {
std<IP_ADDRESS>cout << "<IP_ADDRESS>setColor to " << color << std<IP_ADDRESS>endl;
color_ = color;
}
private:
int color_;
};
//================================
class D2 : virtual public B {
public:
void setLength(int length) {
std<IP_ADDRESS>cout << "<IP_ADDRESS>setLength to " << length << std<IP_ADDRESS>endl;
length_ = length;
}
private:
int length_;
};
//================================
// multi-inheritance diamond - have fiddled with mixin
// but haven't solved using type B polymorphically with mixins
class M1 : public D1, public D2 {
};
//================================
int main() {
B* d1 = new D1;
d1->setVal(3);
d1->setColor(1);
B* m1 = new M1;
m1->setVal(4);
m1->setLength(2);
m1->setColor(4);
return 0;
}
| fe327da100b371082a9a1ec6bfe269b202e2fe58cb6bc15bbdca6fc4100abae6 | ['10fcd7947349421ba27c45376f8d81d8'] | I'm wondering if it's possible to pass a reference to a map where the data is a pointer to a derived class?
#include <map>
class B {
public:
private:
int x_;
};
class D : public B {
public:
private:
int y_;
};
typedef std<IP_ADDRESS>map<int, B*> mapB_t;
typedef std<IP_ADDRESS>map<int, D*> mapD_t;
void foo(mapB_t& inmap) {
;
}
int main() {
mapB_t mapB;
mapD_t mapD;
mapB[0] = new B;
mapD[0] = new D;
foo(mapB);
foo(mapD);
return 0;
}
I receive this compiler error:
q.cc: In function 'int main()':
q.cc:34: error: invalid initialization of reference of type 'mapB_t&' from expression of type 'mapD_t'
q.cc:22: error: in passing argument 1 of 'void foo(mapB_t&)'
|
3e4b2e18d2b9e2f7725ad9893d909986a10c75b1c5e2e4a12875310144602f8d | ['110b0e5c59d5430ab5dbc89faca11a6f'] | I want to show only the first 5 digits of the composed SKU for products, here's the context:
Main product SKU: 12345
Variation SKU: 67890
SKU showed on product page: <PHONE_NUMBER>
I want to show only the first (main product) SKU number:
this is what I tried:
$sku = $product->get_sku();
$skunodash = substr($sku, 0, 5);
<span class="sku_wrapper"><?php esc_html_e( 'SKU :', 'woocommerce' ); ?> <span class="sku"><?php echo $skunodash ? $sku: esc_html__( 'N/A', 'woocommerce' ); ?></span></span>
I have also tried:
$skunodash = explode("-", $sku)
But nothing works, and just shows the whole SKU no matter what.
What am I doing wrong?
Thans in advance.
| a7107f59023ab134d6ecf18cd42c536e7a9812c26d15285ab790aa5243e5a8ab | ['110b0e5c59d5430ab5dbc89faca11a6f'] | So, I have an admin user on Wordpress, I can login, I can post, update, install plugins, etc.
But when I try to find my user name, or email on the database wordpress is using (in wp-config file), I'm not able to locate it. and mine is not the only user I'm not able to find in the database.
Now,I got to this discovery, because our wordpress site was hacked not long ago, I'm going through the files, and I see some random code on the top of index.php or other files.
I clean and get rid of this code, and files too ! ( aindex.php, ajax-index.php. etc.)
At some point in the middle of the night, some files is creating this files, and inserting this random code again. SO I need to do this everyday in the morning, otherwise the wordpress admin doesn't work. Any insight on this too, will be very appreciate it.
Anyway, it is possible that whoever hacked the site, is making wordpress to store new users on an external database ?
Thanks, any help will be appreciate it.
Note I'm using: Wordfence, WP security, Cerber Security, Defender, iThemes Security to help scan the files.
|
144a8faf8703500a32fb90191b2d8465f4f9552bc216033cf4939c9962fdcde6 | ['1114c1dbdc3b49979209d3e3f72b33e2'] | From what I understand about the read permission on directories, it allows listing of which files are in a directory and that's about it.
Given a directory with 0744 permissions, owned by userA:
[userA@localhost ~]$ mkdir -m 0744 /tmp/semi-secret
[userA@localhost ~]$ ls -ld /tmp/semi-secret/
drwxr--r--. 2 userA userA 6 Aug 29 10:15 /tmp/semi-secret/
[userA@localhost tmp]$ touch semi-secret/foobar.txt
[userA@localhost tmp]$ chmod 0600 semi-secret/foobar.txt
To userB, The existence of the file foobar.txt is apparent from the ls command.
[userB@localhost ~]$ ls -l /tmp/semi-secret/
ls: cannot access /tmp/semi-secret/foobar.txt: Permission denied
total 0
-????????? ? ? ? ? ? foobar.txt
But why does the test -e command exit with a non-zero status?! Its only job is to confirm if a file exists or not, and directory permissions are supposed to allow that.
[userB@localhost ~]$ test -e /tmp/semi-secret/foobar.txt || echo "The file doesn't exist."
The file doesn't exist.
| c8f01209c4da55dfab235c9f454dacad6628fc6e7ccd7564fa922f9aa702dea7 | ['1114c1dbdc3b49979209d3e3f72b33e2'] | How can I tell if my hard drives have a battery backed write cache (BBWC)?
How can I tell if it is enabled and/or configured correctly?
I don't have physical access to my server. It's a GNU/Linux box.
I can provide supplemental incremental information/details as requested. My frame of reference is that of a DBA -- I have access and privileges, but (usually) only tread where I know am supposed to. :)
|
740bc61efe49e64e24642533a47d5957ced0663998c1fdae46229d4409d1abcf | ['112810f96ebd476aaa1be11ddb5c7e33'] | I want to use jquery jcountdown plugin but I have a problems.
Starting time for timer is stored in collection and it's necessary for plugin init.
I want to do something like:
var time = SeqTimestamp.findOne({}).time;
$('.countdown').countdown({date: new Date});
Rendered callback run once and doesn't see collection that not good point for me.
How I can do that?
| 196a24c917ef198fdef98c46735693f4d0f4e4505ac9d9e40d2fb7f45e35246c | ['112810f96ebd476aaa1be11ddb5c7e33'] | I need to store tests results in any storage. But unfortunately it doesn't work with any db drivers any time it raise exception "CasperError: Can't find module net":
var require = patchRequire(require);
var redis = require("redis"),
client = redis.createClient();
Is it possible connect casperjs to any storage (except plain files of course).
|
b59d165a4d292289ab34ff99bb38a806f901176ad1bf7a1aec3a5686978173b5 | ['113e47e055274dc389c86cf7426373f3'] | I have an answer for you, although almost 1 year later... hopefully it can be of help.
Here is a "simple" example, using Ionic 5.0.0-beta.5 (I think it could work with previous versions but the syntax might vary). Let's say I want to speed up the default "reveal" animation. I copied the original animation code from @ionic/core/dist/collection/utils/menu-controller/animations/reveal.js and changed the duration to 150ms:
import { AnimationBuilder, createAnimation, MenuI } from '@ionic/core';
export const fastReveal: AnimationBuilder = (menu: MenuI) => {
const openedX = menu.width * (menu.isEndSide ? -1 : 1);
const contentOpen = createAnimation()
.addElement(menu.contentEl as Element)
.fromTo('transform', 'translateX(0px)', 'translateX(' + openedX + 'px)');
return createAnimation()
.duration(150)
.addAnimation(contentOpen);
};
Then, in the app.component.ts constructor:
menuController.registerAnimation('fast-reveal', fastReveal);
by importing menuController from @ionic/core and fastReveal from above.
And the final and most important point is to add the CSS classes that would have been automatically added if the type was 'reveal':
<ion-app>
<ion-menu class="menu-type-reveal" contentId="main-content" type="fast-reveal">
<ion-header>
<ion-toolbar>
<ion-title>Menu</ion-title>
</ion-toolbar>
</ion-header>
<ion-content class="ion-padding">
Hello !
</ion-content>
</ion-menu>
<ion-router-outlet id="main-content" class="menu-content-reveal"></ion-router-outlet>
</ion-app>
| 9ad7f0551a4f9a5de8a00ea00004b7801557cc8d92aee7dcdc797a23157915e2 | ['113e47e055274dc389c86cf7426373f3'] | I don't think that onblur can be detected, but this is a code to detect onfocus:
var timestamp=new Date().getTime();
function checkResume()
{
var current=new Date().getTime();
if(current-timestamp>5000)
{
var event=document.createEvent("Events");
event.initEvent("focus",true,true);
document.dispatchEvent(event);
}
timestamp=current;
}
window.setInterval(checkResume,50);
Then you just write:
document.addEventListener("focus",function()
{
alert("Focus detected");
},false);
|
035b504a41ed740df6e454f0c5c06372d120036a862631f554e221972f4d028e | ['1146567d356a437b9c5bd6ae1559bf43'] | Instead of using <th> you have to use <td> even if it is part of the table head.
<table>
<thead>
<tr>
<td>Shops</td>
<td>SOmethng</td>
<td>Something#2</td>
</tr>
</thead>
<tbody>
<tr>
<td>Something in the body of the table</td>
<td>something</td>
<tdSomething</td>
</tr>
</tbody>
</table>
I suggest using w3schools.com for additional info.Also you can add borders in case you want some borders around it.
| 635257ca9ccba1e8228d092e9cbd147002563d3d77c05a449ec7c665a11ed99b | ['1146567d356a437b9c5bd6ae1559bf43'] | I made a code where when the client types something in the input, it will send the data to a jsp file to evaluate, and if the data equals "<PERSON>", it will say "Hello <PERSON>". The problem is that the input tag won't display your input, and only takes 1 input
jQuery w/ input
<fieldset>
<form style="padding:15px;">
<label for=name>Enter Name:</label>
<input type="text" name="name" id="name">
</form>
</fieldset>
<div id="result"></div>
<script>
$(document).ready(function() {
$("input").keypress(function(event) {
event.preventDefault();
var name = $("#name").val();
var send = {
name: name
};
$.ajax({
type: "POST",
url: "process2.jsp",
data: send,
success: function(data) {
$("#result").html(data);
}
})
});
});
</script>
-----------------------
JSP FILE:
<%
String name = request.getParameter("name");
if(name.equals("James")){
out.println("Hello <PERSON>");
} else {
out.println("Hello User");
}
%>
|
b512c58b671cb0658ed6c524a09d76c8fbca3d846a7e3f81d22f0b8f4fa9faec | ['114791a02e2c4d58905faf693fda0bd7'] | i'm a beginner in write code with python.
I wrote this simple script using Pandas and his DataReader to retrieve multiple stock results from yahoo finance:
import pandas as pd
from pandas.io.data import DataReader
from pandas import DataFrame
symbols_list = ['AAPL', 'TSLA', 'YHOO','GOOG', 'MSFT','GILD']
for ticker in symbols_list:
r = DataReader(ticker, "yahoo", '2015-01-20')
cell= r[['Open','High','Low','Adj Close','Volume']]
print cell
With this code i obtain the price stocks with the date + the others column that i specified in "cell= r[[...." as shown below:
Open High Low Adj Close Volume
Date
2015-01-20 107.84 108.97 106.50 108.<PHONE_NUMBER>
2015-01-21 108.95 111.06 108.27 109.<PHONE_NUMBER>
2015-01-22 110.26 112.47 109.72 112.<PHONE_NUMBER>
2015-01-23 112.30 113.75 111.53 112.<PHONE_NUMBER>
2015-01-26 113.74 114.36 112.80 113.10 55375900
Open High Low Adj Close Volume
Date
2015-01-20 193.87 194.12 187.04 191.93 4489400
2015-01-21 189.55 198.68 189.51 196.57 4144000
2015-01-22 197.00 203.24 195.20 201.62 4094100
2015-01-23 200.29 203.50 198.33 201.29 3438600
2015-01-26 201.83 208.62 201.05 206.55 3224500
My questions are: how can i include in the columns the tickers that i specified in the symbol_list?
And a last thing: how can i invert the order of the dates? i want it to show the newest first (2015-01-26 in my example).
Below i show you an example of what i want to obtain (the ticker name as first column and the date order inverted)
TSLA 2015-01-26 201.83 208.62 201.05 206.55 3224500
TSLA 2015-01-23 200.29 203.50 198.33 201.29 3438600
TSLA 2015-01-22 197.00 203.24 195.20 201.62 4094100
TSLA,2015-01-21 189.55 198.68 189.51 196.57 4144000
TSLA 2015-01-20 193.87 194.12 187.04 191.93 4489400
AAPL 2015-01-26 113.74 114.36 112.80 113.10 55375900
AAPL 2015-01-23 112.30 113.75 111.53 112.<PHONE_NUMBER>
AAPL 2015-01-22 110.26 112.47 109.72 112.<PHONE_NUMBER>
AAPL 2015-01-21 108.95 111.06 108.27 109.<PHONE_NUMBER>
AAPL 2015-01-20 107.84 108.97 106.50 108.<PHONE_NUMBER>
I tried a few things founded in forums, but none of that gave me any result.
Thank you all for your consideration, hope that someone can give me an hand on this 2 issues.
| 227be40c6906db6477b4ddfdb9e84055e0e51b392c895a5333804906ac60b925 | ['114791a02e2c4d58905faf693fda0bd7'] | I have this script that for now has static values:
var Lines = [];
var addLine = function(symbol, price, change, percent) {
Lines.push('<tr>' +
'<td class="symbol" >' + symbol + '</td>' +
'<td class="price" >' + price + '</td>' +
'<td class="change" >' + change + '</td>' +
'<td class="percent">' + percent + '</td>' +
'</tr>');
};
// function to get data
function StockPriceTicker() {
var Symbol = "",
CompName = "",
Price = "",
ChnageInPrice = "",
PercentChnageInPrice = "";
var CNames = "TSLA,HPQ,VRSK,CERN,KHC,EXPD";
var flickerAPI = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22" + CNames + "%22)&env=store://datatables.org/alltableswithkeys";
var StockTickerXML = $.get(flickerAPI, function(xml) {
$(xml).find("quote").each(function() {
Symbol = $(this).attr("symbol");
$(this).find("Name").each(function() {
CompName = $(this).text();
});
$(this).find("LastTradePriceOnly").each(function() {
Price = $(this).text();
});
$(this).find("Change").each(function() {
ChnageInPrice = $(this).text();
});
$(this).find("PercentChange").each(function() {
PercentChnageInPrice = $(this).text();
});
var PriceClass = "GreenText",
PriceIcon = "up_green";
if (parseFloat(ChnageInPrice) < 0) {
PriceClass = "RedText";
PriceIcon = "down_red";
}
var htmlSymbol,
htmlPrice,
htmlChange,
htmlPercent;
htmlSymbol = "<span class='quote'>" + Symbol + " </span></span>";
htmlPrice = "<span class='" + PriceClass + "'>";
htmlPrice = htmlPrice + parseFloat(Price).toFixed(2) + " ";
htmlChange = parseFloat(Math.abs(ChnageInPrice)).toFixed(2) + "<span class='" + PriceIcon + "'></span>";
htmlPercent = parseFloat(Math.abs(PercentChnageInPrice.split('%')[0])).toFixed(2) + "%";
// use here the function defined above.
addLine(htmlSymbol, htmlPrice, htmlChange, htmlPercent);
});
$body.empty().html(Lines.join(''));
// we reset the content of Lines for the next interval
Lines = [];
});
}
Here the running code script.
What i want to accomplish is to add a link to every "symbol" contained in "Cnames" var.
The link is something like "https://www.example.com/chart/?symbol=Ticker", where "Ticker" is the "symbol" that i'm clicking in that moment.
So for example, when i click on TSLA, i want that it will open a popup window (like a window.open function) that point exactly to "https://www.example.com/chart/?symbol=TSLA".
The link will be equal for everyone, except for the last words after the "=" symbol.
Is it possible to show me a portion of code tha can to do that?
|
999101cd118a15e5d0bbda3c66ec3419767a0f25a1e5548c2d98c3f84c3e5c61 | ['114ea0442d6e4fe3a6f6391d0cbb3ed1'] | No, Razor cannot easily replace heavy use of javascript (i.e. a web based app) without a complete rewrite of the Html app moving functionality from the client side to the server side.
You are probably best to learn javascript or determine what the underlying requirements were and re-write in Razor.
Potentially replacing javascript with tidier javascript might help, if you look at the likes of Knockoutjs and Jquery Templates maybe that might ease your pain.
| 1a3dc0f8a3a23856ad18b093d3f23fbc023da93e73724b0d557c25f9d618d1f3 | ['114ea0442d6e4fe3a6f6391d0cbb3ed1'] | So, does that the elusive mission statement indicate that a question like "Do I fire a guy that's had an affair with my wife", needs just a (possibly misguided) answer, or should a number of people encourage him, comment on his situation, and possibly criticize the answers? Forum was your guy's term, not mine. Our beloved English is loose enough that you can mean anything by that that you wish. I hold that discussions about semantics are like those of statistically probable timing paths; the last stage before total desperation. |
c1058f5d0e6b28a4969e43bc3ae384c2191702225c40d54010ef813f67d5a2fa | ['1171775242a1437eafdcb0a8bef0e4e8'] | I am new to C# and am trying to kill a list of processes. I was able to use the code below to kill one process but would like to change it so that it kills a list of processes. Over time the list will grow so ideally I would like to find a way to do this where updating the list would be quick and easy.
try
{
foreach (Process proc in Process.GetProcessesByName("notepad"))
{
proc.Kill();
}
}
catch (Exception)
{
Console.WriteLine("Procces not found.");
}
I'm sorry if I have overlooked a question that was already asked about this.
Thank you in advance for any help provided.
| 92c08ec27f52447f3a259e9392bc976529cfd73de9f0161e12bbf2d0b9110e3e | ['1171775242a1437eafdcb0a8bef0e4e8'] | The article below mentions SQUIDs several times but I can't figure out what it stands for. I know what SID and CLSID stand for but not sure about SQUID. Any ideas?
Example from article:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\<SID>\Patches\<SQUID>
Article:
https://support.microsoft.com/en-us/kb/971187
|
75535dde52363f6a2d383f21a96666f9d49801d4136d2c6505e38121222134fa | ['1199bab36ecb477d8689dee71395ab9e'] | Let say that S,T and U are subspaces of V. How can I show these inclusions?
a) $S\cap U\subseteq(S+T)\cap U$ and $T\cap U\subseteq(S+T)\cap U \\$
b) $(S\cap U)+( T\cap U) \subseteq(S+T)\cap U$
I have no idea how to start. Any help?
| f3e04cada9d37d4d9eb1ad4ad8829eaa75eed47affa188b4a84632387a5820ca | ['1199bab36ecb477d8689dee71395ab9e'] | What we know about projection matrices:
$A^T=A $
$A=A^2 $
I want to prove that $(I-A)^T $is also projection matrix :
My solution:
$(I-A)^T =I-A^T=I-A=I-A^2$
we can see that $ I-A=I-A^2 => 0=A-A^2$,
$A^2=A$ then $A-A=0$
Does it look correct?
Thanks for help!
|
c63a3feb6fb1ec0be127f5e3264802e1352e22162135e91af0832b1ceb39827a | ['11a50c79eaec4429bc8fcf670ace2fc5'] | When I try to update the content of a resource in the Active Admin interface, I receive this error:
ActiveModel<IP_ADDRESS>ForbiddenAttributesError in Admin<IP_ADDRESS>ThingsController#update
ActiveModel<IP_ADDRESS>ForbiddenAttributesError
Here are the contents of the update action in the ThingsController
def update
respond_to do |format|
if @thing.update(thing_params)
format.html { redirect_to @thing, notice: 'Thing was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @thing.errors, status: :unprocessable_entity }
end
end
end
What do I have to add to this block to get this to work? I also noticed that I cannot create a new resource in the Active Admin interface either. However, I can delete them.
| 53e34134f57eab23270e006872cd1cd0c8d64bc5a61d3254535fe2d450138e19 | ['11a50c79eaec4429bc8fcf670ace2fc5'] | I can register and remain logged in as the user that has just been created. But once I click sign out and try to sign back in, nothing happens. Here is the server result:
Started POST "/users/sign_in" for 127.0.0.1 at 2013-11-20 16:44:59 -0500
Processing by Devise::SessionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"XzM+pKK4WDDzD2V/jedhR/+E7OKFIBPwIvjTOHCOOZY=", "user"=>{"email"=>"<EMAIL_ADDRESS>", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Sign in"}
Completed 401 Unauthorized in 1ms
Processing by Devise::SessionsController#new as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"XzM+pKK4WDDzD2V/jedhR/+E7OKFIBPwIvjTOHCOOZY=", "user"=>{"email"=>"<EMAIL_ADDRESS><IP_ADDRESS> at 2013-11-20 16:44:59 -0500
Processing by Devise<IP_ADDRESS>SessionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"XzM+pKK4WDDzD2V/jedhR/+E7OKFIBPwIvjTOHCOOZY=", "user"=>{"email"=>"drichards2013@gmail.com", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Sign in"}
Completed 401 Unauthorized in 1ms
Processing by Devise<IP_ADDRESS>SessionsController#new as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"XzM+pKK4WDDzD2V/jedhR/+E7OKFIBPwIvjTOHCOOZY=", "user"=>{"email"=>"drichards2013@gmail.com", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Sign in"}
Rendered /Users/DylanRichards/.rvm/gems/ruby-1.9.2-p320@rails3tutorial/gems/devise-2.2.4/app/views/devise/shared/_links.erb (2.0ms)
Rendered /Users/DylanRichards/.rvm/gems/ruby-1.9.2-p320@rails3tutorial/gems/devise-2.2.4/app/views/devise/sessions/new.html.erb within layouts/application (15.1ms)
Completed 200 OK in 202ms (Views: 32.4ms | ActiveRecord: 2.9ms)
|
0e27cbdf2ebdbe6d94a3c7cf296387ce82172c2b01bca3878a65f4b7fba35b07 | ['11aeaeab79a340e3b51a3eba11cc36bf'] | Error:(24, 32) error: cannot find symbol class PhoneAuthCredential
Gradle
compile 'com.google.firebase:firebase-database:10.2.0'
compile 'com.google.firebase:firebase-storage:10.2.0'
compile 'com.google.firebase:firebase-messaging:10.2.0'
compile 'com.google.firebase:firebase-config:10.2.0'
compile 'com.firebaseui:firebase-ui-auth:1.2.0'
compile 'com.github.bumptech.glide:glide:3.6.1'
compile 'com.android.support:multidex:1.0.1'
compile 'com.android.support:design:25.3.1'
compile 'com.facebook.android:facebook-android-sdk:4.16.0'
compile 'com.google.android.gms:play-services-auth:10.2.0'
compile 'com.google.firebase:firebase-auth:10.2.0'
What other gradle file to include to resolve the error for phone authentication in Firebase?Please help
| a3c6c39983a91cf56a3d185983bd150d36357cc9217b2dc4e74c0d86e056e765 | ['11aeaeab79a340e3b51a3eba11cc36bf'] | I am creating a calculator app in android.Just like a modern calculator you see in your android device. I have created a TextViewand below that, all my buttons are present.I also want to include the trignometric functions so when buttons layout is swipped, i want to show trignometric function and when it is swiped back it show numeric buttons.The TextView should remain constant at the top.Can you somebody please guide me how to do that?
|
11c420b41ff7cbcea77f891ff7a6da35ead1587b9a0e1d238e66715b05e4fbae | ['11b146c7df3a4932803f5c8946aaf221'] | I would like to know the easiest way to read a csv file located on a shared folder on a remote server.
I'm doing this only for testing reasons, I don't really need to accomplish anything more than this task.
The scenario is:
I have a virtual machine A (which is on an azure virtual network) that hosts a csv file.
On another virtual machine B (which is on another azure virtual network) I'm running my package.
I would like this package to read the file from A and write it on a cloud sql server. The package is currently running on B.
I am stuck at the very beginning.
I was just trying to create a flat file connection. When I use a UNC path as the name of the file it just doesn't work. It allows me to set the file format parameters but the error I get is "Columns are not defined for this connection manager" and I am not able to go on.
Can anyone explain how to achieve the task, what am I not considering ?
I apologise if this is a dummy question, I am new to SSIS and networking in general.
Thank you all in advance.
| 461a03eb6230d08ac78873750d974b28ecd6f412942b08d0c63cdc79dfe67ff4 | ['11b146c7df3a4932803f5c8946aaf221'] | I know this might look like an already asked question, and it probably is. But I've checked all of the answers already given and none of them fits my problem.
So here is the thing.
I have a very simple piece of code, like super simple. But I can't get my script to work. I always get the error Uncaught TypeError: document.getElementbyId is not a function.
Obviously the code below is just a practice / testing code, I know it's completely worthless. Still I can't seem to make it work.
Things I've already tried to move the script to the body but nothing changes:
<!DOCTYPE html>
<html>
<head>
<title>SUPPORTO FUNZIONALE BI</title>
<script>
function selectValues(){
var <PERSON> = document.getElementbyId("select_ruolo").innerHTML;
console.log(ruolo);
}
</script>
</head>
<body>
<h1>SUPPORTO FUNZIONALE BI</h1>
<div id= 'main_nav'> <!-- INIZIO MAIN_NAV -->
<ul>
<li><a href="SF.html">HOME</a></li>
<!-- <li><a href ="">SERVIZI ATTIVI / DA ATTIVARE</a></li> -->
<li><a href ="">FAQs</a></li>
<li><a href="service_management.html">SERVICE MANAGEMENT</a></li>
</ul>
</div> <!-- FINE MAIN_NAV-->
<div id= 'content'><!-- INIZIO_CONTENT -->
<form>
<fieldset>
<legend> User information </legend>
<PERSON>: <input type="text" label="nome utente">
<PERSON>: <input type="text" label="cognome">
<PERSON>: <select id= "select_ruolo" onchange="selectValues();">
<option>-</option>
<option>ISF</option>
<option>DM</option>
<option>RCM</option>
<option>RPM</option>
<option>Head of Franchise</option>
</select>
Linea/Franchise: <select id ="select_linea">
<option> </option>
</select>
</fieldset>
</form>
<div> <!-- FINE CONTENT -->
</body>
</html>
Can anyone help me identify where the problem lies ?
|
d4ab884e5f5839f34f5f4c39a34b3d5d7f53a9dc868c46331c03501742c2be46 | ['11b2bbacea264f6e8496557c5173f43a'] | Okay, thanks. A couple of other things. In the same function, you're yielding `self.board_[i, j]`, while I believe you meant `...[i][j]`, but that's a small thing. For consistency, would it also be better for `next_board_state` to hint a return type of `List[List[State]]` or `Sequence[Sequence[State]]`? | a4ac6b879d3617bda113dca4f9326eb9612023c4d8436b222159337e72292f4f | ['11b2bbacea264f6e8496557c5173f43a'] | I'm running into significant difficulty getting my mapping file to work with a collection of elements via a foreign key in Hibernate. Java will try to load these files below and won't have any runtime exceptions, but the events table is never loaded as an object of an employee (it will remain null, but every other attribute loads from the DB). In my MySQL database, I have the following:
TABLE: Employees
Primary Key: username varchar
name varchar
areacode INTEGER
phone INTEGER
addressNumber INTEGER
addressLocation varchar
email varchar
TABLE: Events
Primary Key: ID INTEGER
startDate DateTime
endDate DateTime
customerName varchar
employeeUsername varchar
<?xml version="1.0"?>
<class name="Employee" table="Employees">
<id name="username" column="username" type="string"/>
<many-to-one name="contact" class="Contact" column="username" unique="false" update="false" insert="false" optimistic-lock="true" not-found="exception" embed-xml="true" />
</class>
<class name="Contact" table="Employees">
<id name="username" column="username" type="string"/>
<property name="name" column="name" type="string"/>
<property name="addressNumber" column="addressNumber" type="int"/>
<property name="areacode" column="areacode" type="int"/>
<property name="phone" column="phone" type="int"/>
<property name="addressLocation" column="addressLocation" type="string"/>
<property name="email" column="email" type="string"/>
</class>
<?xml version="1.0"?>
<class name="Event" table="Events">
<id name="ID" column="ID" type="int">
<generator class="assigned"/>
</id>
<property name="startDate" column="startDate" type="date"/>
<property name="endDate" column="endDate" type="date"/>
<property name="customerName" column="customerName" type="string"/>
</class>
<class name="Employee" table="Events" entity-name="Employee2">
<id name="username" column="employeeUsername" type="string"/>
<list name="events" cascade="all">
<key column="employeeUsername"/>
<list-index column="ID"/>
<one-to-many class="Event"/>
</list>
</class>
Assume the hibernate.cfg.xml file exists and works (If you feel this needs to be shown, please let me know). It does include both of the files in its mapping files part.
I have a feeling my error is probably in my declaration of the collection of events in my "list" declaration. Here are the Java classes:
package org.hibernate.employee;
import java.util.Date;
public class Event {
private int ID;
private Date startDate;
private Date endDate;
private String customerName;
public Event(){
System.out.println("blah");
}
/**
* @return the iD
*/
public int getID() {
return ID;
}
/**
* @param id the iD to set
*/
public void setID(int id) {
ID = id;
}
/**
* @return the startDate
*/
public Date getStartDate() {
return startDate;
}
/**
* @param startDate the startDate to set
*/
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
/**
* @return the endDate
*/
public Date getEndDate() {
return endDate;
}
/**
* @param endDate the endDate to set
*/
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
/**
* @return the customerName
*/
public String getCustomerName() {
return customerName;
}
/**
* @param customerName the customerName to set
*/
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
}
/*
* File: Contact.java
*/
package org.hibernate.employee;
/**
* This class represents a Contact information for an Employee.
*
*/
public class Contact {
private int username; // the contact identifier in the database
private int areacode; // the contact areacode
private int phone; // the contact phone
private String name; // the contact's name
private int addressNumber; // the contact's address number
private String addressLocation; // the contact's address location
private String email; // the contact's email
/**
* Constructs a Contact object.
*/
public Contact() {
}
/**
* @return the areacode
*/
public int getAreacode() {
return areacode;
}
/**
* @param areacode the areacode to set
*/
public void setAreacode(int areacode) {
this.areacode = areacode;
}
/**
* @return the phone
*/
public int getPhone() {
return phone;
}
/**
* @param phone the phone to set
*/
public void setPhone(int phone) {
this.phone = phone;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the addressNumber
*/
public int getAddressNumber() {
return addressNumber;
}
/**
* @param addressNumber the addressNumber to set
*/
public void setAddressNumber(int addressNumber) {
this.addressNumber = addressNumber;
}
/**
* @return the addressLocation
*/
public String getAddressLocation() {
return addressLocation;
}
/**
* @param addressLocation the addressLocation to set
*/
public void setAddressLocation(String addressLocation) {
this.addressLocation = addressLocation;
}
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
public String toString(){
String retVal = "";
retVal += "Address: " + this.addressNumber + " " + this.addressLocation + "\n";
retVal += "Email: " + this.email + "\n";
retVal += "Phone: " + this.areacode + " " + this.phone + "\n";
retVal += "Name: " + this.name + "\n";
return retVal;
}
public void setUsername(int username) {
this.username = username;
}
public int getUsername() {
return username;
}
}
/*
* File: Employee.java
*/
package org.hibernate.employee;
import java.util.List;
/**
* This class represents an Employee in a company database.
*
*/
public class Employee {
private String username; // the employee's username
private Contact contact; // the employee's contact information
private List events;
/**
* Constructs an Employee object.
*/
public Employee() {
super();
}
/**
* @return the username
*/
public String getUsername() {
return username;
}
/**
* @param username the username to set
*/
public void setUsername(String username) {
this.username = username;
}
/**
* @return the contact
*/
public Contact getContact() {
return contact;
}
/**
* @param contact the contact to set
*/
public void setContact(Contact contact) {
this.contact = contact;
}
/**
* @return the events
*/
public List getEvents() {
return events;
}
/**
* @param events the events to set
*/
public void setEvents(List events) {
this.events = events;
}
public String toString(){
String retVal = "";
System.out.println(events);
retVal += "Username: " + username + "\n";
retVal += "Contact: " + contact + "\n";
return retVal;
}
}
|
64bc08d2ee807ff12ad02f8994cbc53443ae2da11222bc7fec03fed45429e9d2 | ['11babb55bab24d5cad9f304a6701cb0b'] | I am trying to download an apk file on a button click using phonegap. Why does this code not work? Nothing happens when I click Download. Could someone point me in the right direction? Thanks.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<script charset="utf-8" src = "jquery-1.10.1.min.js"></script>
<script charset="utf-8" src = "cordova-2.7.0.js"></script>
<script>
function foo()
{
var fileTransfer = new FileTransfer();
fileTransfer.download(
"http://samplewebsite.com/example.apk",
"file:///sdcard/example.apk",
function(entry) {
console.log("download complete: " + entry.fullPath);
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code" + error.code);
}
);
}
</script>
</head>
<body>
<button onclick="foo()">Download</button>
</body>
</html>
| 11f54cca8cfea7ee7bd8884c4478a8bb8b311f057635aaa4364b20a950936526 | ['11babb55bab24d5cad9f304a6701cb0b'] | I added the following lines to my header, but when I try to view my webpage on an android device I can't scroll down.
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; minimum-scale=1.0; user-scalable=0;" />
<meta name="apple-mobile-web-app-capable" content="yes" />
Any ideas why I can't scroll down?
|
ccd57069e0d80f3112343116a2c422d6677f87310a7cbc668a3f265d75fde03d | ['11c4de1e6c664de091f1fcab438585e4'] | First, I have Manjaro with Gnome 3.16.
By default, my screen looks unreadable, so I put in ~/.profile xcalib -gammacor 1.3 -alter in order to fix it every time I log in.
It seems to work, but that adjustment is reverted in one or two seconds. If I apply that command manually after, the change is not reverted.
So, I believe that Gnome manages the screen color in some way, but I don't know how to disable it (I have tried to do this in 'Color' configuration, with no result). Could you help me, please?
| d760f320f215e0388a01e8e0f75ac7f924b78310e616a393bd826276dd96c326 | ['11c4de1e6c664de091f1fcab438585e4'] | Currently my web.config has this:
<appSettings>
<add key="UserName" />
<add key="DBServer" />
<add key="DBUserName" />
<add key="DBPwd" />
<add key="DB" />
</appSettings>
If i have to connect to multiple db's I would like my web.config to have the following
<appSettings>
<add key="UserName" />
<add key="DBServer" />
<add key="DBUserName" />
<add key="DBPwd" />
<add key="DB" />
</appSettings>
<!--This section needs to hold data for another db server -->
<appSettings>
<add key="UserName" />
<add key="DBServer" />
<add key="DBUserName" />
<add key="DBPwd" />
<add key="DB" />
</appSettings>
The key names should be the same. Or is having multiple connection string sections the way to go?
|
22dab87d33fe1ad118559c4111264612d80a65326e401638e5f0a0faa73be897 | ['11c6ce70b9cc4b529ec599bfb7e061d1'] | ok because OSX is so dumb and stupid, don't use application path instead use app name or bundle id because it seems OSX needs time to figure out that your application is actually an application:
you can open using bundle id:
#!/usr/bin/env bash
open -b 'com.myapp.mac'
exit 0
or open using app name:
#!/usr/bin/env bash
open -a 'MyApp'
exit 0
| 0cf0bcf8a72c6763c536361cbf128c8076a799129d66354d8832b3d840942e3a | ['11c6ce70b9cc4b529ec599bfb7e061d1'] | actually you should encode the json string using server side or javascript tool and then AS3 will automatically decode it:
for example in JSP:
var flashvars = {
xmlFile: 'http://iyt.psu.edu/xml/abington/home.xml',
preface: 'http://iyt.psu.edu/',
preload: '<c:out value="{"url":"flash/project.swf","x":"375","y":"237","link":"home","tween":{"prop":"y","begin":"0","finish":"-200","duration":"1"}}'" />'
};
|
fab0c67b83f86b45ab8f9d2c8d886514af663c71c9b9a5ffb319911fee19ec2e | ['11cac0f832ab40b5abf5f8c95cf5fe0d'] | I'm building a React Native app and want to include push notifications for Android. We currently have the infrastructure for GCM push from our last app. However this time I need to use the JS code to pass the registration id to our push servers. The old app was a native Java app and used:
gcm = GoogleCloudMessaging.getInstance(mActivityContext);
regid = getRegistrationId(mActivityContext);
I have the API key and sender Id but I need to get the regid using over HTTP not using the Java library used there. I have found https://android.googleapis.com/gcm/register but I can't find any docs on how to use it.
| 1e0c7b242e84afe4451c70d048285b14c1e64eb2f62c3db4aef26735d3b748d9 | ['11cac0f832ab40b5abf5f8c95cf5fe0d'] | I have a guest box that has data I want to sync to the host so that I am able to edit it using an editor on the host. I want any saved changes made on the host to sync back to the guest. I've tried using normal shared folders config.vm.synced_folder "workspace/", "/my/folder/to/sync/" but this just deletes the contents of the guest folder!
I've looked at using rsync but I'm unsure if this supports editing and syncing both ways
|
cc28c6c2821a92a8a11f13de40c1c0880744fda35d6464b169cfad8a28b3f405 | ['11cf9875198d41fcae8a52b40e4f2aaf'] | I got the expected output with Parquet files. Initially, I was using CSV, but csv deserializer doesn't understand how to put the elements into the correct position when schema changes.
Changing the individual csvs into parquet and then crawling them one after another helped me in incorporating the changing schema.
| e2857c5162e9bf845e3b21ed69ad9f2b5527342894e01747df19ea09b2365c27 | ['11cf9875198d41fcae8a52b40e4f2aaf'] | I am planning to execute spark from KNIME analytics platform. For this I need to install KNIME spark executors in the KNIME analytics platform.
Can any one please let me know how to install KNIME spark executors in the KNIME analytics platform for hadoop distribution CDH 5.10.X.
I am referring the installation guide from the below link:
https://www.knime.org/knime-spark-executor
|
18e2bb7e20eed3e1c4caa30b399421c24ebe9cc6e452ddcb5624ba962c888468 | ['11e6ba563d8e4d7795bbf7ddedffdb24'] | I am trying to stop or start a Azure Virtual Machine with PowerShell. I am not very experienced in PowerShell so I wrote a simple script as a test:
Import-Module "C:\Program Files (x86)\Microsoft SDKs\Windows Azure\PowerShell\Azure\Azure.psd1"
$subID = "<GUID>"
$thumbprint = "<Thumbprint>"
$subscriptionName = "testAzure"
$myCert = Get-Item cert:\\CurrentUser\My\$thumbprint
$vmName = "<vm name>"
Set-AzureSubscription –SubscriptionName $subscriptionName -SubscriptionId $subID -Certificate $myCer
Select-AzureSubscription -SubscriptionName $subscriptionName
Get-AzureSubscription -Current
I created a .cer certificate on my pc which I exported and then imported in Azure (I used the exact example from http://msdn.microsoft.com/en-us/library/windowsazure/gg551722.aspx). When I Write-Host the $myCert variable I get a response:
[Subject] CN=testAzure
[Issuer] CN=testAzure
[Serial Number] --serialnumber--
[Not Before] 29-6-2013 15:27:26
[Not After] 1-1-2040 00:59:59
[Thumbprint] --thumbprint--
When I run the script I get the following error:
Get-AzureSubscription : You MUST specify a certificate. Call
Set-AzureSubscription and Select-AzureSubscription first. At
D:\Users\foobar\Desktop\test.ps1:23 char:1
+ Get-AzureSubscription -Current
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzureSubscription], ArgumentException
+ FullyQualifiedErrorId : Microsoft.WindowsAzure.Management.Subscription.GetAzureSubscriptionCommand
I cannot figure out what I am doing wrong? Does anyone has a suggestion?
| 8d8b60005ea236382bebdb29a9102d9a09d959d1acb1a61b7dac12ce616a1a47 | ['11e6ba563d8e4d7795bbf7ddedffdb24'] | I fixed the problem with the following MSBuild script:
<Target Name="DeploySlowCheetahTransforms" AfterTargets="CopyWebRoleFiles" Condition="'@(WebRoleReferences)' != ''">
<PropertyGroup>
<IntermediateWebOutputPath>%(WebRoleReferences.OutputDir)</IntermediateWebOutputPath>
</PropertyGroup>
<ItemGroup>
<TransformedFiles Include="$(WebTargetDir)\**\*.config" Exclude="$(WebTargetDir)\**\*.dll.config;$(WebTargetDir)\**\web*.config" />
</ItemGroup>
<Copy SourceFiles="@(TransformedFiles)" DestinationFiles="@(TransformedFiles->'$(IntermediateWebOutputPath)\%(RecursiveDir)%(Filename)%(Extension)')" />
</Target>
This scripts needs to be added to the ccproj file. The WebRoleReferences and WebTargetDir variables are created in Microsoft.WindowsAzure.targets. This script gets all the transformed config files from the OutputPath of your csproj file and copies them to the OutputDir which is used to create the Azure WebRole package.
|
e59653f71b58c7f5d0e809cbe91f2fc5ed7ce14f11ae1709ebbc1186a3aa53f5 | ['11e8df2dc3514f83a30df246667a0bb9'] | I'm encountering the same issue as mentioned at
https://serverfault.com/questions/743515/my-event-log-has-corrupted-dacl-write-attributes-in-4656-file-audit-events/852636#852636 where there are some invalid characters in the event logs and therefore using .ToXML() fails with the exception:
System.Management.Automation.RuntimeException Cannot convert value
"http://schemas.microsoft.com/win/2004/08/events/event'>
irrelevant data omitted
<Data Name='AccessReason'>%%1538: %%1804
%%1541: %%1801 D:(A;ID;FA;;;S-1-5-21-4261485934-2742084322-1513010315-1120)
%%4416: %%1801 D:(A;ID;FA;;;S-1-5-21-4261485934-2742084322-1513010315-1120)
%%4417: %%1801 D:(A;ID;FA;;;S-1-5-21-4261485934-2742084322-1513010315-1120)
%%4418: %%1801 D:(A;ID;FA;;;S-1-5-21-4261485934-2742084322-1513010315-1120)
%%4419: %%1801 D:(A;ID;FA;;;S-1-5-21-4261485934-2742084322-1513010315-1120)
%%4420: %%1801 D:(A;ID;FA;;;S-1-5-21-4261485934-2742084322-1513010315-1120)
%%4423: %%1801 D:(A;ID;FA;;;S-1-5-21-4261485934-2742084322-1513010315-1120)
%%4424: %%1801 D:(A;ID;FA;;;S-1-5-21-4261485934-2742084322-151301031亖퍲翾</Data>
to type "System.Xml.XmlDocument". Error: "'', hexadecimal value 0x04, is an invalid character. Line 19, position 117."
How could I strip the invalid characters out? I'm thinking the following might be the process:
converting to string (ToString() doesn't seem to work, when outputting via Write-Host it simply outputs the name of the object type)
removing the invalid XML characters using .replace and regex
convert back/serialize to System.Diagnostics.Eventing.Reader.EventLogRecord
object (somehow?)
convert to XML (with .ToXML())
How would I achieve steps 1 and 3 of this process?
| d1caa844f224c8265b8171fef29dd239d40658ae363a5941d0e176f21554ce69 | ['11e8df2dc3514f83a30df246667a0bb9'] | I can't get dependency injection working with a custom ActionFilterAttribute class using the Unity bootstrapper for ASP.NET Web API nuget package.
I've registered the type in UnityConfig and I'm using it elsewhere (using constructor injection there though) and it works fine.
public static void RegisterTypes(IUnityContainer container)
{
container.RegisterType<ISettingService, SettingService>();
...
}
The code is being called successfully, however the instantiated object (settingService) is null.
public class APIKeyValidationAttribute : ActionFilterAttribute
{
[Dependency]
public ISettingService settingService { get; set; }
public override void OnActionExecuting(HttpActionContext actionContext)
{
...
if (settingService == null)
{
throw new Exception("settingService is null");
}
...
}
What do I need to do to get this working? I've been searching for a long time and can only find examples for MVC or for Web API with different dependency injectors.
|
0357661f62cbe09f0c5a8665e774cd5d9d48f50450e4695ff74e70827c482a32 | ['120160f839834d948a9f3195014ab293'] | if (true) {
let x = 5
}
works as expected (no syntax error), but
if (true) let x = 5
throws SyntaxError: Unexpected strict mode reserved word in Node 4.1.0 and babel
Is this expected behavior? I know that this is a stupid example. I'm just wondering wether this is a bug or not.
| cebcb5b5cf935305adbc33287286c38d58f2ce72da89b7a24ce4bf5e64a692ba | ['120160f839834d948a9f3195014ab293'] | I have the following two tables:
orders with orderid | orderdate | userid | ... and
users with userid | ...
where I join them both:
SELECT * FROM orders
JOIN users ON orders.userid = users.id
to get a table with all orders committed by users.
Now I need to get all customers that have bought something between 2016-11-01
and 2017-31-01:
at least once before 2016-11-01 and also between 2016-11-01 and 2017-02-01 and
nothing before 2016-11-01 but have bought something for the first time between
2016-11-01 and 2017-02-01.
Help is very much appreciated.
|
0e8e5d3cd25b69fddfe55ea4304188928f77faae977d0cb85063c2c4e9bc8c60 | ['1209ecd7be5b47ee8783afcb9c05197d'] | My problem is shown here: problem statement. I have one template image, which i have to detect in the camera image. After it is detected i have to normalize the camera image by using an affine transformation. The goal of my work is to identify the crosses. I tried to use SURF features for the image normalization step, but the template image is very regular and not good for SURF matching. Any ideas how this can be done? Maybe some kind of contour matching?
| 1e94e096fee282e1de286976a88544c63c5ca5c9540d0fc382ab9748d31037da | ['1209ecd7be5b47ee8783afcb9c05197d'] | If you are calling it like
./myscript.pl 1 35
You can use @ARGV. E.g.
#!/usr/bin/perl
use strict;
use warnings;
use Data<IP_ADDRESS>Dumper qw(Dumper);
print "ARGV[0]=$ARGV[0]";
print "ARGV[1]=$ARGV[1]";
print Dumper \@ARGV;
Example source.
This is an old example, so it may not be using the latest style. I don't have a perl compiler set up at the moment, so I can't test the output.
You can use the Data<IP_ADDRESS>Dumper to help you debug things.
If you are calling it like
perl -s ./myprogram -$gal="$gal" -$obsid="$obsid" 1 35
Realize that you may get weird results mixing @ARGV and named parameters. You might want to change how you call it to something like
perl -s ./myprogram $gal $obsid 1 35
or
perl -s ./myprogram -gal="$gal" -obsid="$obsid" -first="1" -second="35"
Note also that the named parameters are -gal, not -$gal. I'm not quite sure what the $ would do there, but it would tend to do something other than what happens without it.
Remember, Data<IP_ADDRESS>Dumper can help you debug things if you get confusing results.
|
5c70494974acad2d0bda7fc8b247f1f33e70cfa74a90628e94bdb0a1f4ad1401 | ['1213963f95da4c17b0110d55374e6bb3'] | You could try:
[DisplayName("Controller Display Name")]
[Route("api/[controller]")]
public class ValuesController : Controller
{
// GET api/values
[HttpGet]
[DisplayName("Action Display Name")]
public IEnumerable<string> Get()
{
var ControllerDisplayName = string.Empty;
var ActionsDisplayName = string.Empty;
var ControllerAttributes = ControllerContext.ActionDescriptor.ControllerTypeInfo.GetCustomAttributes(typeof(DisplayNameAttribute), true);
if (ControllerAttributes.Length > 0)
{
ControllerDisplayName = ((DisplayNameAttribute)ControllerAttributes[0]).DisplayName;
}
var ActionAttributes = (ControllerContext.ActionDescriptor.MethodInfo.GetCustomAttributes(typeof(DisplayNameAttribute), false));
if (ActionAttributes.Length > 0)
{
ActionsDisplayName = ((DisplayNameAttribute)ActionAttributes[0]).DisplayName;
}
return new string[] { ControllerDisplayName, ActionsDisplayName };
}
}
| 0a095f7e94bb03886c05a42f51af192d8fcdcf0f561dc21dbf75737985cee19d | ['1213963f95da4c17b0110d55374e6bb3'] | I started live unit testing with visual studio 2017 (15.7.1). After I switch the branch and start the project, an error message comes up saying the following:
Could not load file or assembly 'Microsoft.CodeAnalysis.LiveUnitTesting.Runtime, version= <IP_ADDRESS>, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependenc
I tried to:
- rebuild/restart the project
- stop live unit testing
but it didn't work.
I don't know why load 'Microsoft.CodeAnalysis.LiveUnitTesting.Runtime' from project/bin.
Anyone have a suggestion?
|
e35dd991661697c9f19712496b1364b2f82c08bfdcef35dbd013b6b67cf77d8a | ['121a5a99edb84a50bc076d40df929729'] | how can i make each of the table row clickable to go to new page? is it possible in javaScript?
<?php
$query = mysql_query("SELECT * FROM instructor") or die(mysql_errno());
while ($row=mysql_fetch_array($query)) {
echo "
<tr class='info'>
<td><img src='".$row['profile_picture']."' width='30' height='30' style='border-radius:50%;'></td>
<td>".$row['instructor_Id']."</td>
<td>".$row['firstname']." ".$row['lastname']."</td>
<td>".$row['age']."</td>
<td>".$row['sex']."</td>
<td>".$row['contact_no']."</td>
<td>".$row['teaching_type']."</td>
</tr>
";
}
?>
| 3cee375a2fc265c93c56aa72a82c2f0e516b052285e0ee2955d72f1197097281 | ['121a5a99edb84a50bc076d40df929729'] | How can i exclude subject to be displayed from subject table that is already added in scheduler table? I have this code but it still shows up the subjects that are already added to scheduler table.
<?php
$sem = $_GET['semChooser'];
$res = mysql_query("SELECT * FROM scheduler WHERE semester = '$sem'") or die(mysql_errno());
$row=mysql_fetch_array($res);
$subName = $row['subject_name'];
$res1 = mysql_query("SELECT * FROM subject WHERE semester IN ('$sem', 3) AND subject_name != '$subName'") or die(mysql_errno());
while ($row=mysql_fetch_array($res1)) {
echo "
<tr class='active'>
<td align='center'>
<button type='submit' data-dismiss='modal' class='btn btn-primary btn-block btn-xs subject'><em class='fa fa-plus'></em> Add</button>
</td>
<td>".$row['subject_code']."</td>
<td>".$row['subject_name']."</td>
<td>".$row['subject_type']."</td>
<td>".$row['room_type']."</td>
<td>".$row['subject_category']."</td>
<td>".$row['year_level']."</td>
<td>".$row['units']."</td>
</tr> "; }
?>
|
4f155206a16d2b7309a854b9d28d2d770175ea40ee143ffe510ac83348a66844 | ['121df6fa88f341f8b261b38475c2f74f'] | Hi <PERSON> and @Subash,
You cannot check directly, there isn't any API to do that, you have to write code for it
Below is a code snippet that you can modify as per your requirement:
File file1 = new File("<file path>");
boolean isDeleteSuccess;
do
{
//delete the file
isDeleteSuccess = file1.delete();
if (isDeleteSuccess)
System.out.println(file1.getName() + " is deleted!");
else
{
//if not deleted then wait for 10 seconds for file to be closed
System.out.println("Delete operation is failed.");
Thread.sleep(10000);
}
} while (!isDeleteSuccess);//if not deleted then try again
| 9918d73afb1114168c075f0854e899d612196554a075302e41016c31e54a24a6 | ['121df6fa88f341f8b261b38475c2f74f'] | URL fileURL= yourClassName.class.getResource("yourFileName.extension");
String myURL= fileURL.toString();
now you don't need long path name PLUS this one is dynamic in nature i.e., you can now move your project to any pc, any drive.
This is because it access URL by using your CLASS location not by any static location (like c:\folder\ab.mp3, then you can't access that file if you move to D drive because then you have to change to D:/folder/ab.mp3 manually which is static in nature)
(NOTE: just keep that file with your project)
You can use fileURL as: File file=new File(fileURL.toURI());
You can use myURL as: Media musicFile=new Media(myURL); //in javaFX which need string not url of file
|
5f80ee15e5555a23e980321e4d640213a64a8832d75933d0b2a1b2d1464c1bba | ['1221ce46af854fe1a0db3557711ebff6'] | I'm doing a tweet classification, where each tweet can belong to one of few classes.
The training set output is given as the probability for belonging that sample to each class.
Eg: tweet#1 : C1-0.6, C2-0.4, C3-0.0 (C1,C2,C3 being classes)
I'm planning to use a Naive Bayes classifier using Scikit-learn. I couldn't find a fit method in naive_bayes.py which takes probability for each class for training.
I need a classifier which accepts output probability for each class for the training set.
(ie: y.shape = [n_samples, n_classes])
How can I process my data set to apply a NaiveBayes classifier?
| 405a08bd4609a566142109bc4e6e1f1677cb48268b33af11dffbf1289527dfaf | ['1221ce46af854fe1a0db3557711ebff6'] | Most of those issues are fixed in Pytorch v1.0.1. Intellisense may not be showing suggestions for functions like torch.randn if Jedi language server is being used (Please check this github issue for more details).
Open settings.json and set "python.jediEnabled" to False. You will be prompted to reload VSCode. Once this is done, it will download Language Server and the issue will be fixed.
|
7f8ae7b38b33c60085c5b1c81922028ed7a6b06e3c5747f441808e50e28aa3cf | ['1222dd861ff7402aa88681e7566d127b'] | Use DataReader instead, use this code and just call CheckLogin in login button or somthing else.
Sub CheckLogin()
Dim conn = New SqlConnection("Data Source=SRV-SQL;Initial Catalog=prova;User ID=user;Password=user")
conn.Open()
Try
Dim query As String = "select count(*) from tblLogin where username = @username and password= @password "
Dim cmd = New SqlCommand(query, conn)
cmd.Parameters.AddWithValue("@username", txtUsername.Text)
cmd.Parameters.AddWithValue("@password", txtUserPwd.Text)
Dim DR As SqlDataReader = cmd.ExecuteReader()
If DR.HasRows Then
MsgBox("Logged-in successfully")
Else
MessageBox.Show("The username or the password is wrong!", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
conn.Close()
End Sub
| 79cf9f93f1c5f87c88b37a1dde07317e688f4b718dcc65d10f9703bf334e3c20 | ['1222dd861ff7402aa88681e7566d127b'] | In vb.net you need to change your DataGridView settings to this:
DGV.SelectionMode = DataGridViewSelectionMode.FullRowSelect
DGV.MultiSelect = False
Now you need to add a Button control and use this code:
If DGV.SelectedRows.Count > 0 Then
Try
' SQL part: '
Dim selectedRow = DGV.Rows(e.RowIndex).Cells(0).Value.ToString()
connection.Open()
Dim query as String = "DELETE FROM tablename WHERE [columnname] = @selectedRow "
Dim cmd as New SqlCommand(query, connection)
cmd.Parameters.AddWithValue("@selectedRow",selectedRow)
cmd.ExecuteNonQuery()
MessageBox.Show("Data Deleted !")
connection.Close()
' DGV part: '
Dim Row As Integer = DGV.CurrentCell.RowIndex
DGV.Rows.RemoveAt(Row)
Catch ex As Exception
MsgBox(ex.Message)
End Try
Else
MsgBox("Select an element.")
End If
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.