text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
continueUserActivity method not get called if app running in background
I am working on a big project written in Objective C and stuck in iOS Universal Link process. Universal Link works fine if the app is not running in the background, called continueUserActivity method and do as expected. But if the app is running in the background, hit the Universal Link, it opens the app as well as call willContinueUserActivityWithType method but continueUserActivity method not get called.
I don’t know why this happening. I test Universal Links in another project, everything is ok and works fine. But in my main project continueUserActivity not get called.
iOS version 11.4
A:
The problem is the NSUserActivity object of UIApplication becomes nil. That's why thecontinueUserActivity method not getting called. To fix the problem initialise NSUserActivity and set its delegate inside the willContinueUserActivityWithType method.
- (BOOL)application:(UIApplication *)application willContinueUserActivityWithType:(nonnull NSString *)userActivityType {
application.userActivity = [[NSUserActivity alloc] initWithActivityType:userActivityType];
application.delegate = self;
return true;
}
I don't know whether its a proper way, but it works for me.
| {
"pile_set_name": "StackExchange"
} |
Q:
tools.jar not found OS X
I have scoured stack overflow and have not found a solution to my problem. This is a bit long winded, but I have not found a solution in the past week, searching non-stop.
Problem: tools.jar not found when trying to compile Android source code, and also when trying to install Android Studio
Operating System: Mac OS X El Capitan 10.11
Computer: MacBook Pro Retina, late 2015. (new computer as of couple weeks ago)
Here are the two scenarios that seem to have the same problem.
Scenario 1: I am trying to compile Android Source code to create a custom ROM. I have followed the steps at http://source.android.com for OS X, specifically http://source.android.com/source/initializing.html in the section about MAC.
I have run all steps, leading up to building the System. The next step is
source build/envsetup.sh
lunch aosp_eng
This Error pops up @ lunch aosp_eng:
*** Error: could not find jdk tools.jar at /System/Library/Frameworks/JavaVM.framework/Versions/Current/Commands/../lib/tools.jar, please check if your JDK was installed correctly. Stop.
** Don't have a product spec for: 'aosp_arm'
** Do you have the right repo manifest?
Scenario 2: Download Android Studio to make app, but this error pops up,
'tools.jar' seems to be not in Studio classpath.
Please ensure JAVA_HOME points to JDK rather than JRE.
This is my .bash_profile:
export PATH=/usr/local/opt/mongodb/bin/:$PATH
# mount the android file image
function mountAndroid {
hdiutil attach ~/android.dmg.sparseimage -mountpoint /Volumes/android;
}
#unmount the android file image
function umountAndroid(){
hdiutil detach /Volumes/android;
}
export USE_CCACHE=1
#export JAVA_HOME="$(/usr/libexec/java_home)"
export JAVA_HOME="$(/usr/libexec/java_home -v 1.7)"
#export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.7.0_71.jdk/Contents/Home/"
#export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.8.0_65.jdk/Contents/Home/"
#export JAVA_HOME=$(/usr/libexec/java_home)
First line is for Mongodb, the "mounts" is from the source.android.com step by step process. Use ccache from combination of android tutorial and using MacPorts to be able to use ccache. All the JAVA_HOME that have been commented out is me trying to find a solution online.
Currently, I have a few difference java versions installed
jdk1.7.0_71.jdk
jdk1.7.0_79.jdk
jdk1.8.0_65.jdk
jdk1.9.0jdk
JDK 1.9 is the beta version, but I needed it to install Netbeans Dev JDK 1.9 version since there is a current known bug with MacBook Pro Retina with Netbeans 1.8. Scrolling is laggy and the only current fix is Beta version JDK.
Depending on which $JAVA_HOME I use, this outputs:
me-mbp:~ Me$ echo $JAVA_HOME
/Library/Java/JavaVirtualMachines/jdk1.8.0_65.jdk/Contents/Home/
me-mbp:~ Me$ javac -version
java 1.8.0_65
me-mbp:~ Me$ which java
/usr/bin/java
If I comment out all the $JAVA_HOME, it defaults to jdk1.9. Don't know why, but it does.
Any semblance of a solution came about when I copied tools.jar to Android Studio App folder (see below). It let me "install" Android Studio and run, but as soon as I tried to make a new app, it just sat there, and did nothing. Also, Studio had an error saying: Using jdk1.9, needs to change in settings (paraphrased).
cp /Library/Java/JavaVirtualMachines/jdk1.7.0_71.jdk/Contents/Home/lib/tools.jar /Volumes/Macintosh\ HD/Applications/Android\ Studio.app/Contents/lib/
A solution to the problem would be a godsend. Much of my work is depending on this and I would love to be able from my new Laptop. At the moment, I am having to remote into an Ubuntu machine to do all my Android Source work. The Android Studio problem was just an extension of the problem (I Think). Thanks in advance.
A:
Android need a separator env system variable named ANDROID_JAVA_HOME,
So set env: export ANDROID_JAVA_HOME="your java home", solved my problem
| {
"pile_set_name": "StackExchange"
} |
Q:
Good way to copy a std:set to a std::set
There is an implicit conversion available between uint32_t and int32_t. I was a little surprised to find that I could not say:
void somefunc(std::set<uint32_t> arg);
std::set<int32_t> ary1;
somefunc(ary1);
Why is this? Is there a short-and-sweet syntax to do it without writing out a for loop to copy the first int32_t array into a temporary uint32_t array?
Thank you.
A:
Standard containers can generally be constructed using ranges from other containers, specified by pairs of iterators. Consider the following example :
#include <cstdint>
#include <set>
void foo(std::set<uint32_t> arg) {}
int main()
{
std::set<int32_t> x;
foo({ x.begin(), x.end() });
}
foo expects a std::set<uint32_t> but x is a std::set<int32_t>. {x.begin(), x.begin()} is creating a new temporary std::set<uint32_t> which copies all the values from x. It's similar to std::set<uint32_t>(x.begin(), x.end()) that you might find in older code. This also works between different kinds of containers, provided the contained elements are compatible.
| {
"pile_set_name": "StackExchange"
} |
Q:
MySQL Errno: 150 "Foreign key constraint is incorrectly formed"
Does anyone know why i am getting the following error message?
errno: 150 "Foreign key constraint is incorrectly formed"
CREATE TABLE meter (
`code` CHAR(5) NOT NULL,
`type` VARCHAR(30) NOT NULL,
description VARCHAR(30) NULL,
location_code CHAR(3) NOT NULL,
CONSTRAINT pri_meter
PRIMARY KEY (`code`),
CONSTRAINT for_meter
FOREIGN KEY (location_code) REFERENCES location (`code`));
CREATE TABLE location(
`code` CHAR(3) NOT NULL,
company VARCHAR(30),
`type` VARCHAR(30),
CONSTRAINT pri_location
PRIMARY KEY (`code`));
CREATE TABLE reading(
meter_code CHAR(5) NOT NULL,
`when` DATETIME NOT NULL,
display DECIMAL(9,3) NOT NULL,
estimate BIT NOT NULL,
CONSTRAINT pri_reading
PRIMARY KEY (`when`, meter_code),
CONSTRAINT for_reading
FOREIGN KEY (meter_code) REFERENCES meter (`code`));
CREATE INDEX index_meter ON meter (location_code);
CREATE INDEX index_reading ON reading (meter_code);
A:
Create location table first.
You can't reference a table column when the table being referenced is not there yet.
In your example you have a reference to table location upon creation of meter table.
| {
"pile_set_name": "StackExchange"
} |
Q:
Error while running multiple Tensorflow sessions in the same Python process
I have a project with this hierarchy:
project
├── libs
│ ├── __init__.py
│ ├── sub_lib1
│ │ ├── file1.py
│ │ └── __init__.py
│ └── sub_lib2
│ ├── file2.py
│ └── __init__.py
└── main.py
Content of main.py:
from libs.sub_lib1.file1 import func1
from libs.sub_lib2.file2 import func2
#some code
func1(parameters)
#some code
func2(parameters)
#some code
Content of file1.py:
#import some packages
import tensorflow as tf
def func1(parameters):
#some code
config = tf.ConfigProto()
config.gpu_options.allow_growth=True
tf.reset_default_graph()
x = tf.placeholder(tf.float32,shape=[None,IMG_SIZE_ALEXNET,IMG_SIZE_ALEXNET,3])
y_true = tf.placeholder(tf.float32,shape=[None,output_classes])
with tf.Session(config=config) as session:
saver.restore(session, "path to the model1")
k = session.run([tf.nn.softmax(y_pred)], feed_dict={x:test_x , hold_prob1:1,hold_prob2:1})
#some code
return(the_results)
content of file2.py:
#import some packages
import tensorflow as tf
def func2(parameters):
#some code
config = tf.ConfigProto()
config.gpu_options.allow_growth=True
sess = tf.Session(config=config)
with gfile.GFile('path the model2', 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
sess.graph.as_default()
tf.import_graph_def(graph_def, name='')
sess.run(tf.global_variables_initializer())
#Get the needed tensors
input_img = sess.graph.get_tensor_by_name('Placeholder:0')
output_cls_prob = sess.graph.get_tensor_by_name('Reshape_2:0')
output_box_pred = sess.graph.get_tensor_by_name('rpn_bbox_pred/Reshape_1:0')
#some code to prepare and resize the image
cls_prob, box_pred = sess.run([output_cls_prob, output_box_pred], feed_dict={input_img: blobs['data']})
#some code
return(the_results)
When I run main.py, I got the following error:
Traceback (most recent call last):
File "main.py", line 46, in <module>
func2(parameters)
File "/home/hani/opti/libs/sub_lib2/file2.py", line 76, in func2
cls_prob, box_pred = sess.run([output_cls_prob, output_box_pred], feed_dict={input_img: blobs['data']})
File "/home/hani/.virtualenvs/opti/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 929, in run
run_metadata_ptr)
File "/home/hani/.virtualenvs/opti/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1128, in _run
str(subfeed_t.get_shape())))
ValueError: Cannot feed value of shape (1, 600, 863, 3) for Tensor 'Placeholder:0', which has shape '(?, 227, 227, 3)'
After some debugging, I didn't find any tensor in the second model that has (?, 227, 227, 3) as shape. Instead, I found that the tensor x (defined by x = tf.placeholder(tf.float32,shape=[None,IMG_SIZE_ALEXNET,IMG_SIZE_ALEXNET,3]) in func1 from file1) has (?, 227, 227, 3) as shape.
I checked the shape of input_img (defined by input_img = sess.graph.get_tensor_by_name('Placeholder:0') in func2 from file file2), I found it (?, 227, 227, 3) when I run main.py. However when I run file2.py (independently by running python file2.py), I don't get this error and and I found that the input_img's shape is placeholder shape: (?, ?, ?, 3).
So I assumed that may be both models have the same tensor's name (placeholder) and when I import both file1 and file2 in main.py, the first shape of placeholder (?, 227, 227, 3) remains in the GPU memory.
I tried session.close() in file1.py, but it didn't work!
Is there a more appropriate way to use multiple Tensorflow sessions in the same process without getting into any confusion between them? Or simply, how to properly close a Tensorflow session before starting another one in the same python process?
A:
After reading some related posts in Stack Overflow, I found a solution in this answer from which I quote:
you might get errors during second build_graph() due to trying to
create variables with the same names (what happens in your case),
graph being finalised etc.
To solve my problem, I only needed to add tf.reset_default_graph() to main.py in order to reset the graph and its parameters.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to retrieve item list from html table with xpath?
I am trying to extract table information into a dictionary within python 3.7.
The html from the table looks like this:
<dl class="rlxr-specs__block-list">
<dt class="rlxr-specs__block-list--name">heading</dt>
<dd class="rlxr-specs__definition-content">
<div class="rlxr-specs__definition-title">Key1</div>
<span class="rlxr-specs__definition-desc">bla</span>
</dd>
<dd class="rlxr-specs__definition-content">
<div class="rlxr-specs__definition-title">Key2</div>
<span class="rlxr-specs__definition-desc">blub</span>
</dd>
My best guess is:
items{}
for row in response.xpath('//dd[@class="rlxr-specs__definition-content"]'):
items[row.xpath('./div/text()').extract_first()] = items[row.xpath('./span/text()').extract_first()]
I am getting a Keyerror, with a key from another part of the page. So something within the xpath selector must be wrong.
More info:
>>> for row in response.xpath('//dd[@class="rlxr-specs__definition-content"]'):
... print(row.xpath('./div/text()'))
...
[<Selector xpath='./div/text()' data='Gehäuse'>]
[<Selector xpath='./div/text()' data='Aufbau des Oyster Gehäuses'>]
[<Selector xpath='./div/text()' data='Durchmesser'>]
[<Selector xpath='./div/text()' data='Material'>]
[<Selector xpath='./div/text()' data='Lünette'>]
[<Selector xpath='./div/text()' data='Aufzugskrone'>]
[<Selector xpath='./div/text()' data='Uhrglas'>]
[<Selector xpath='./div/text()' data='Wasserdichtheit'>]
[<Selector xpath='./div/text()' data='Manufakturwerk'>]
[<Selector xpath='./div/text()' data='Kaliber'>]
[<Selector xpath='./div/text()' data='Ganggenauigkeit'>]
[<Selector xpath='./div/text()' data='Funktionen'>]
[<Selector xpath='./div/text()' data='Oszillator'>]
[<Selector xpath='./div/text()' data='Aufzug'>]
[<Selector xpath='./div/text()' data='Gangreserve'>]
[<Selector xpath='./div/text()' data='Armband'>]
[<Selector xpath='./div/text()' data='Material'>]
[<Selector xpath='./div/text()' data='Schließe'>]
[<Selector xpath='./div/text()' data='Zifferblatt'>]
[<Selector xpath='./div/text()' data='Edelsteinfassung'>]
[]
>>> for row in response.xpath('//dd[@class="rlxr-specs__definition-content"]'):
... print(row.xpath('./span/text()'))
...
[<Selector xpath='./span/text()' data='Oyster, 28 mm, Edelstahl Oystersteel und'>]
[<Selector xpath='./span/text()' data='Monoblock-Mittelteil, verschraubter Gehä'>]
[<Selector xpath='./span/text()' data='28 mm'>]
[<Selector xpath='./span/text()' data='Rolesor Everose (Kombination aus Edelsta'>]
[<Selector xpath='./span/text()' data='Diamantlünette'>]
[<Selector xpath='./span/text()' data='Verschraubbare Twinlock-Aufzugskrone mit'>]
[<Selector xpath='./span/text()' data='Kratzfestes Saphirglas, Zykloplupe\xa0zur\xa0V'>]
[<Selector xpath='./span/text()' data='Bis 100 Meter Tiefe wasserdicht'>]
[<Selector xpath='./span/text()' data='Mechanisches Perpetual-Uhrwerk, Selbstau'>]
[<Selector xpath='./span/text()' data='2236, Rolex Manufakturwerk'>]
[<Selector xpath='./span/text()' data='-2/+2 Sekunden pro Tag, gemessen nach de'>]
[<Selector xpath='./span/text()' data='Stunden-, Minuten- und Sekundenzeiger im'>]
[]
[<Selector xpath='./span/text()' data='Selbstaufzugsmechanismus, in beide Richt'>]
[<Selector xpath='./span/text()' data='Circa 55 Stunden'>]
[<Selector xpath='./span/text()' data='Jubilé, fünfreihig'>]
[<Selector xpath='./span/text()' data='Rolesor Everose (Kombination aus Edelsta'>]
[<Selector xpath='./span/text()' data='Verdeckte Crownclasp-Faltschließe'>]
[<Selector xpath='./span/text()' data='Helles Perlmuttzifferblatt mit Diamanten'>]
[<Selector xpath='./span/text()' data='Diamanten, Fassung 18 Karat Gold'>]
[<Selector xpath='./span/text()' data='Chronometer der Superlative (COSC + Rol'>]
>>>
How can I pull the table into the dict?
A:
Try to check whether there is a title and description values or not and if there is no value - set default value:
items{}
for row in response.xpath('//dd[@class="rlxr-specs__definition-content"]'):
title = row.xpath('./div/text()').extract_first() or "No title"
description = row.xpath('./span/text()').extract_first() or "No description"
items[title] = description
| {
"pile_set_name": "StackExchange"
} |
Q:
three.js - THREE.StereoEffect / webVR-boilerplate + THREE.Mirror
I'm trying to get a mirror effect working correctly in a project that is using webvr-boilerplate when VREffect is active.
I tried (using r72dev and r72) to use THREE.Mirror:
//webVR-boilerplate + Mirror.js
verticalMirror = new THREE.Mirror( renderer, camera, { clipBias: 0.03, textureWidth: 256, textureHeight: 256, color:0x889999 } );
verticalMirrorMesh = new THREE.Mesh( new THREE.PlaneBufferGeometry( 10, 10 ), verticalMirror.material );
verticalMirrorMesh.add( verticalMirror );
scene.add( verticalMirrorMesh );
// Request animation frame loop function
function animate( timestamp ) {
verticalMirror.render();
// Update VR headset position and apply to camera.
controls.update();
// Render the scene through the manager.
manager.render( scene, camera, timestamp );
requestAnimationFrame( animate );
}
The render targets stops updating when activating VR Mode and stereo viewing is active.
The mirror is behind the camera and I set a model spinning to observe the mirror behaviour.
Any thoughts of why this happens and possible way to fix it?
Am I missing some initialization parameters for the mirror or the stereoeffect?
example
Thanks in advance.
EDIT : Seems the problem also not only happens with webvr-boilerplate but ALSO with StereoEffect.js and Mirror.js as I setup a scene using by a mirror to three.js StereoEffect.js example and still same problem..
Stereo http://ruidorey.webfactional.com/stereo.png
mirror WITH stereo effect - live example
No Stereo http://ruidorey.webfactional.com/nostereo.png
mirror WITHOUT stereo effect - live example
A:
The mirror breaks when you enter VR mode because you have set the WEBVR_FORCE_DISTORTION flag. This causes webvr-boilerplate's WebVRManager to use its own CardboardDistorter shim (as opposed to distortion support in browsers that implement WebVR). This interferes with the mirror rendering.
CardboardDistorter hijacks the renderer and forces it to draw to a render target that belongs to the distorter. This prevents the mirror from using its own render target.
Ideally WebVRManager should be fixed so that it supports mirrors out of the box but you can work around this problem by storing the original render function and using it during the mirror rendering step:
var renderer = new THREE.WebGLRenderer({antialias: true});
// Save the original render function, so that we can use it
// even after CardboardDistorter hijacks the renderer.
var originalRenderFunc = renderer.render;
...
function animate(timestamp) {
...
// In our animation loop, restore the original render
// function for the mirror to use.
var hijackedRenderFunc = renderer.render;
renderer.render = originalRenderFunc;
verticalMirror.render();
// Set the render function back to the hijacked version
// so that CardboardDistorter can do its job.
renderer.render = hijackedRenderFunc;
...
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Find the highest amount although there are more than one achieving the same amount
I want to find the best customer for each country despite there is one country has two customers the same amount, I want them both to appear.
select customerid,firstname,lastname,country, max(total_amt)
from (select invoice.customerid, customer.firstname,lastname,
sum(invoice.total)total_amt,customer.country
from invoice
join customer
on customer.customerid= invoice.customerid
group by invoice.customerid,customer.country)t2
group by country;
A:
Use window functions:
select c.*
from (select c.country, c.customerid, c.firstname c.lastname, sum(i.total) as total,
dense_rank() over (partition by c.country order by sum(i.total) desc) as seqnum
from customer c join
invoice i
on c.customerid = i.customerid
) c
where seqnum = 1;
Note that I also introduced window functions so the query is easier to write and to read.
| {
"pile_set_name": "StackExchange"
} |
Q:
Get screen info in windows 7
In my app I'm using swing and awt. I am setting the size (and position) of the window I'm creating based on toolkit.getScreenSize() and this works fine. But I would like to deal with the size of the windows 7 task bar at the bottom (or wherever) of the screen. I can not seem to find out how to do this. Anyone know how I can get the size if the task bar?
A:
You'll want to look at java.awt.GraphicsEnvironment#getMaximumWindowBounds(), which returns the bounds of the screen area excluding the area covered by "objects in the native windowing system such as task bars and menu bars".
| {
"pile_set_name": "StackExchange"
} |
Q:
Laravel foreach same record multiple
I'm trying to take our some info from mysql with laravel.
My controller:
$match->message = DB::table('log')->where('match_id', '=', $match->match_id)->get(['message']);
$match->authid = DB::table('log')->where('match_id', '=', $match->match_id)->get(['authid']);
My blade:
@foreach ($match->authid as $username)
@foreach ($match->message as $text)
{{ $username->authid }} {{ $text->message }}<br />
@endforeach
@endforeach
But getting 4 results incorrectly. Getting:
AUTHD_ID1 log1
AUTHD_ID1 log2
AUTHD_ID2 log1
AUTHD_ID2 log2
Should be:
AUTHD_ID1 log1
AUTHD_ID2 log2
Whats wrong?
A:
It is being duplicated since you have a foreach within a foreach.
Try the code below.
$matches = DB::table('log')->where('match_id', '=', $match->match_id)->get();
@foreach ($matches as $match)
{{ $match->authid }} {{ $match->message }}<br />
@endforeach`
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create a Pie chart in react?
I have tried to create pie chart like this:
import React from 'react';
import {Pie} from 'react-chartjs-2';
const state = {
labels: ['January', 'February', 'March','April',
'May', 'June', 'July', 'August',
'September', 'October', 'November', 'December'],
dataset: [
{
label: 'Rainfall',
backgroundColor: 'rgba(75,192,192,1)',
borderColor: 'rgba(0,0,0,1)',
borderWidth: 1,
data: [65, 59, 80, 81, 56, 34, 97, 25,69,75,62,45]
}
]
}
export default class PieChartComponent extends React.Component {
render() {
return (
<div className="container">
<Pie
data={state}
options={{
title:{
display:true,
text:'Average Rainfall per month',
fontSize:16
},
legend:{
display:true,
position:'right'
}
}}
/>
</div>
);
}
}
A:
There is a small typo where you defined the state:
const state = {
labels: ['January', 'February', 'March','April',
'May', 'June', 'July', 'August',
'September', 'October', 'November', 'December'],
datasets: [
{
label: 'Rainfall',
backgroundColor: 'rgba(75,192,192,1)',
borderColor: 'rgba(0,0,0,1)',
borderWidth: 1,
data: [65, 59, 80, 81, 56, 34, 97, 25,69,75,62,45]
}
]
}
Change dataset to datasets. It will work.
| {
"pile_set_name": "StackExchange"
} |
Q:
Mongodb aggregation match ends with using field value
note: I'm using Mongodb 4 and I must use aggregation, because this is a step of a bigger aggregation
Problem
How to find in a collection documents that contains fields that ends with value from another field in same document ?
Let's start with this collection:
db.regextest.insert([
{"first":"Pizza", "second" : "Pizza"},
{"first":"Pizza", "second" : "not pizza"},
{"first":"Pizza", "second" : "not pizza"}
])
and an example query for exact match:
db.regextest.aggregate([
{
$match : { $expr: { $eq: [ "$first" ,"$second" ] } } }
])
I will get a single document
{
"_id" : ObjectId("5c49d44329ea754dc48b5ace"),
"first" : "Pizza", "second" : "Pizza"
}
And this is good.
But how to do the same, but with endsWith?
I've openend another question for start with here that uses indexOfBytes . But indexOf return only first match, and not last one
Edit: I've found an acceptable answer (with a lot of custom logic, my hope is Mongodb team will solve this), here the solution:
db.regextest.aggregate([
{
$addFields : {
"tmpContains" : { $indexOfBytes: [ "$first", { $ifNull : [ "$second" , 0] } ] }
}
},
{
$match: { "tmpContains" : { $gt : -1 } }
},
{
$addFields : {
"firstLen" : { $strLenBytes: "$first" }
}
},
{
$addFields : {
"secondLen" : { $strLenBytes: "$second" }
}
},
{
$addFields : {
"diffLen" : { $abs: { $subtract : [ "$firstLen", "$secondLen"] } }
}
},
{
$addFields : {
"res" : { $substr: [ "$first", "$diffLen", "$firstLen"] }
}
},
{
$match : { $expr : { $eq: [ "$res" , "$second" ] }}
}
])
A:
As you know the length of both fields ($strLenBytes) you can use $substr to get last n characters of second field and the compare it to first field, try:
db.regextest.aggregate([
{
$match: {
$expr: {
$eq: [
"$first",
{
$let: {
vars: { firstLen: { $strLenBytes: "$first" }, secondLen: { $strLenBytes: "$second" } },
in: { $substr: [ "$second", { $subtract: [ "$$secondLen", "$$firstLen" ] }, "$$firstLen" ] }
}
}
]
}
}
}
])
Above aggregation will give you the same result as string comparison is case-sensitive in MongoDB. To fix that you can apply $toLower operator both on $first and on calculated substring of $second, try:
db.regextest.aggregate([
{
$match: {
$expr: {
$eq: [
{ $toLower: "$first" },
{
$let: {
vars: { firstLen: { $strLenBytes: "$first" }, secondLen: { $strLenBytes: "$second" } },
in: { $toLower: { $substr: [ "$second", { $subtract: [ "$$secondLen", "$$firstLen" ] }, "$$firstLen" ] } }
}
}
]
}
}
}
])
| {
"pile_set_name": "StackExchange"
} |
Q:
Codeigniter 3 Session Data On Other Pages While User Logged In
Got this question here (sorry for being stupid), Just started with Codeigniter recently.
I have a login-system working fine. I tried to go to homepage while logged in with code on index-header.php:
<?php
if( !isset($_SESSION) ){
echo '<a href="login" class="popupbox">Login</a>';
} else {
echo '<a href="dashboard/logout">Log Out</a>';
}
?>
And on main_view.php (homepage controller)
public function __construct() {
parent::__construct();
$this->load->library('session');
}
public function index() {
if($this->session->userdata('is_logged_in')){
$data['title'] = "Home";
$this->load->view('headfoot/header-main',$data);
$this->load->view('main_view');
$this->load->view('headfoot/footer-main');
} else {
$data['title'] = "Home";
$this->load->view('headfoot/header-main',$data);
$this->load->view('main_view');
$this->load->view('headfoot/footer-main');
}
}
}
Now, if I click logout from homepage while still logged in, it disconnects the session fine but doesn't change text back to "Login" in homepage after refresh.
In other words, it always shows text as "Logout" whether or not user is logged in.
dashboard.php (controller)
public function logout() {
$this->session->sess_destroy();
$data['title'] = "Logged out";
$data['logout_msg'] = "You have successfully logged out.";
$this->load->view('headfoot/header-login',$data);
$this->load->view('admin/login', $data);
$this->load->view('headfoot/footer-login');
}
Is it a good practice to create is_logged_in.php a separate file? If yes then how to link sessions to it?
A:
change this:
<?php
if( !isset($_SESSION) ){
to:
<?php if($this->session->userdata('username') == null ){
i'm using 'username' here by assuming you have set username as session data when you allow user to log in.
| {
"pile_set_name": "StackExchange"
} |
Q:
bash command output as parameters
Assume that the command alpha produces this output:
a b c
d
If I run the command
beta $(alpha)
then beta will be executed with four parameters, "a", "b", "c" and "d".
But if I run the command
beta "$(alpha)"
then beta will be executed with one parameter, "a b c d".
What should I write in order to execute beta with two parameters, "a b c" and "d". That is, how do I force $(alpha) to return one parameter per output line from alpha?
A:
You can use:
$ alpha | xargs -d "\n" beta
A:
Similar to anubhava's answer, if you are using bash 4 or later.
readarray -t args < <(alpha)
beta "${args[@]}"
| {
"pile_set_name": "StackExchange"
} |
Q:
What do I compare the series $\sum_{i=2}^n \frac{i^2+1}{i^3-1}$ to?
I have tried everything I can think of. I know that the answer is divergent and that you can use a comparison test, I just don't know what to compare it to.
$$\sum_{i=2}^n \frac{i^2+1}{i^3-1}$$
I would love any help possible.
A:
Making the numerator smaller and the denominator larger makes the terms smaller. If it still diverges after this change, then the original series must also diverge.
With that in mind, subtract 1 from the numerators and add 1 to the denominators.
How to figure this out: You have a numerator where the dominating term is $i^2$, and a denominator where the dominating term is $i^3$. So it would be nice if we could make those the only terms.
This time it worked out in that making this change made the fractions smaller, and we wanted to show divergence. But what if the $+$ and the $-$ had been the other way? Then you note that $i^2-1\geq \frac12i^2$ and $i^3+1\leq 2i^3$. It still works more or less the same way, but the transformation isn't quite as simple.
| {
"pile_set_name": "StackExchange"
} |
Q:
iPhone window add subview crashing problem
I have the code [window addSubview:[self.mvController view]]; where mvController is a view controller and whenever I run the program (device and simulator) it crashes.
A:
It turns out that the program was releasing something too early.
| {
"pile_set_name": "StackExchange"
} |
Q:
Spring Boot Data Embedded Cassandra
In my Spring Boot 1.5.1 application I'm going to write unit/integration tests for Cassandra related logic.
I have added folowing Maven dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-cassandra</artifactId>
</dependency>
The default Spring Boot Cassandra configuration is going to connect with a real Cassandra DB server.
Is there any options in Spring/Spring Boot in order to configure my tests to use embedded Cassandra server ? If so, could you please show the required configuration.
A:
We use on the project Cassandra + Spring Boot.
Here are the steps which worked for us:
a) Configure you test like this
import org.cassandraunit.spring.CassandraDataSet;
import org.cassandraunit.spring.CassandraUnitDependencyInjectionTestExecutionListener;
import org.cassandraunit.spring.CassandraUnitTestExecutionListener;
import org.cassandraunit.spring.EmbeddedCassandra;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestConfiguration.class)
@TestExecutionListeners(listeners = {
CassandraUnitDependencyInjectionTestExecutionListener.class,
CassandraUnitTestExecutionListener.class,
ServletTestExecutionListener.class,
DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class
})
@EmbeddedCassandra(timeout = 60000)
@CassandraDataSet(value = {"bootstrap_test.cql"}, keyspace = "local_test")
public abstract class BaseTest {
b) in your src/test/resources/application.properties, add this (please note, embedded cassandra starts on port 9142, but not on default 9042)
spring.data.cassandra.port=9142
spring.data.cassandra.keyspace-name=local_test
c) Create empty file bootstrap_test.cql in src/test/resources
d) Add to your pom.xml
<dependency>
<groupId>org.cassandraunit</groupId>
<artifactId>cassandra-unit-spring</artifactId>
<version>${cassandra-unit.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.cassandraunit</groupId>
<artifactId>cassandra-unit</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.cassandraunit</groupId>
<artifactId>cassandra-unit-spring</artifactId>
<version>${cassandra-unit.version}</version>
</dependency>
This should be enough to run your tests with Embedded Cassandra.
Hope it helps.
A:
There is no embedded Apache Cassandra support in Spring Boot available and it's not planned. There's little demand for embedded Apache Cassandra on the one hand, on the other hand, Apache Cassandra comes with a lot of dependencies that conflict with Boot's other dependencies.
Take a look at Cassandra Unit.
You can also build an own test rule when using JUnit tests that gives you full control over the Apache Cassandra version, runtime behavior and so on. Take a look at a possible implementation: CassandraRule.java.
| {
"pile_set_name": "StackExchange"
} |
Q:
negative number not going into int
I've the below code in java. Here i'm trying to see the random combinations of an array.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
public class Dummy {
public static void main(String args[]) throws Exception {
Random rand = new Random();
int[] a = { 1, 2, 3, 4, 5 };
int[] b = { 1, 0, 1, 0, 1 };
Arrays.sort(a);
Arrays.sort(b);
int x = a.length * b.length;
System.out.println(x);
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 25; i++) {
System.out.println("random of i is" + a[rand.nextInt(i)]
+ "and j is " + b[rand.nextInt(i)]);
}
System.out.println(list);
}
}
and here i'm getting the below error.
Exception in thread "main" java.lang.IllegalArgumentException: n must be positive
at java.util.Random.nextInt(Unknown Source)
at Dummy.main(Dummy.java:20)
please let me know how to fix it. Based on some other posts based on similar issue, i found that only positive numbers are to be given in Random, i want to know how i can give negative numbers also.
Also i want to know how many combinations i can get by perpetuating a[] and b[].
Thanks
A:
Your error is because of you are passing 0 in rand.nextInt(i).
rand.nextInt() expects positive integer greater that 0.
| {
"pile_set_name": "StackExchange"
} |
Q:
Bulletproof ESD Powersupply Inputs
I have a power amp that is essentially functions like a benchtop supply, and you can connect banana plugs into it. I would like to protect it against ESD, but also protect the amplifier. People in our manufacturing floor are stupid and sometimes connect things like batteries to the supply up backwards, I really can't prevent that, and if they do they will blow the diode right out. Is there a good way to protect the diode also? These are the ways I could protect it that I don't necessarily like:
I could fuse it but there would be no way to know if the fuse was blown and then you still have no diode and no protection and nobody on our floor would replace it.
Resistor in series, I don't like this idea because it makes the diode less able to sink ESD and protect the input. 8kv (human body model) across a 1ohm resistor is 8000V
Placing a resistor anywhere from the amp to the terminal will be bad, too much current.
simulate this circuit – Schematic created using CircuitLab
A:
If you use bidirectional TVS diodes instead of unidirectional TVS diodes and spec them above the possible battery that could be connected this would protect your output.
simulate this circuit – Schematic created using CircuitLab
A:
Fuse is the usual way to do it.
I could be 1-time metal fuse. It could be a resettable PTC fuse, which resets itself after some time. It could be a circuit breaker, which @Robherc commented about above.
Add a Zener with decent power rating in series with the TVS, and add a fuse in series with the output (downstream of the TVS and Zener). TVS is good at catching fast spikes such as ESD, while a Zener diode is better at handling prolonged overvoltage. If the output is getting abused, there will be large current flowing into or out of the output stage. This current would trip the fuse, which would disconnect the output stage.
| {
"pile_set_name": "StackExchange"
} |
Q:
My function isn't working
Hi I've got an error I cant find the answer help pls.
package com.tutorial.main;
import java.awt.Canvas;
import java.awt.Frame;
import javax.swing.*;
import java.awt.Dimension;
public class Window extends Canvas {
private static final long serialVersionUID = -240840600533728354L;
public Window(int width, int height, String title) {
JFrame frame = new JFrame(title);
frame.setPreferredSize(new Dimension(width, height));
frame.setMinimumSize(new Dimension(width, height));
frame.setMaximumSize(new Dimension(width, height));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.add(Game);
frame.setVisible(true);
Game.start();
}
}
This is the one that is not working I will include the file that is working at the bottom
It comes up with "Cannot make a static reference to the non-static method start() from the type Game" on line 24.
And that game cannot be resolved to a variable on line 22.
I have included all of my files pls help.
package com.tutorial.main;
import java.awt.Canvas;
public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 7580815534084638412L;
public static final int WIDTH = 640, HEIGHT = WIDTH / 12 * 9;
public Game() {
new Window(WIDTH, HEIGHT, "Lets Build a Game!", this);
}
public synchronized void start() {
}
public void run() {
}
public static void main(String args[]) {
new Game();
}
}
Also line 22 is also buggy on this file
It comes up with error "The constructor Window(int, int, String, Game) is undefined"
Does anyone know how to fix this???
A:
You can't use Game class - you need to instantiate an object of that class and use it.
Instead of doing:
frame.add(Game);
frame.setVisible(true);
Game.start();
Do:
Game game = new Game();
frame.add(game);
frame.setVisible(true);
game.start();
As for the other problem, the class Window doesn't have a constructor that can be applied for the call:
new Window(WIDTH, HEIGHT, "Lets Build a Game!", this);
There is only one constructor that accepts:
Window(int width, int height, String title)
So if you'll change your call to the Window's constructor and remove this as the last argument:
new Window(WIDTH, HEIGHT, "Lets Build a Game!);
I believe you should be good.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I tell TypeScript that I am handling the case where an string is used to access an inexistent property on an object?
Here is a reproducible example in TypeScript playground to base my question off of.
I get a TypeScript error for the code router[trimmedPath]:
Error:(63, 14) TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Router'.
No index signature with a parameter of type 'string' was found on type 'Router'.
trimmedPath comes from an HTTP request and can be anything, so it is typed as string. In the code above, I just call router[trimmedPath], because if the trimmedPath is something not on the router object, I do handle this case.
But how should I handle this? Should I just tell TS to ignore that line?
A:
Given the following definitions:
interface Handlers {
users: Function,
notFound: Function,
}
const handlers: Handlers = {
users: () => {},
notFound: () => {}
}
I'd probably make a Router interface with an index signature so that the compiler knows that router might have arbitrary string-keyed properties holding other Function values. In order to keep strict null/undefined safety, the value type of this index signature should be Function | undefined:
interface Router {
users: Function,
[otherPossibleKeys: string]: Function | undefined;
}
const router: Router = {
users: handlers.users
}
Then you can use this with no error:
const trimmedPath: string = "somethingcomingfromrequest";
const chosenHandler =
typeof router[trimmedPath] !== "undefined"
? router[trimmedPath]
: handlers.notFound;
But a wrinkle: note that chosenHandler is inferred to be Function | undefined. That's because even though router[trimmedPath] has been checked explicitly, bracket-notation access using a non-literal index (trimmedPath is of type string) does not act as a type guard and so router[trimmedPath] afterward is still considered Function | undefined. (The issue is considered a bug or a design limitation; it is easy enough to fix but compiler performance suffers).
But take heart, there is a construct which works the same at runtime but is properly typed:
const definedHandler = router[trimmedPath] || handlers.notFound;
That works because Function is truthy and undefined is falsy, and since x || y evaluates to x if x is truthy and y otherwise, definedHandler will definitely be Function.
So that's my recommendation here. Hope that helps; good luck!
Link to code
| {
"pile_set_name": "StackExchange"
} |
Q:
Parameterized SQL, ORACLE vs SQL Server with regular expression
Oracle and Sql server using different prefix for parameters in parametrized string.
Sql using @p1
ORA using :p1
I would like to use in my SQL just @ and in case that ORA database is used all : character should be replaces with @.
Can you please help me to create regular expression?
Here is some example SQL:
update test_table set text = :p1 where text = 'jana:klara' or some_value = :value or info = 'two'
Similar question and alternative solutions can be found here.
A:
Correct regex:
statement = Regex.Replace(statement, @":(?=(?:'[^']*'|[^'\n])*$)", "@");
| {
"pile_set_name": "StackExchange"
} |
Q:
A subset S of a vector space is linearly independent iff every vector in S can be written as a unique linear combination of other vector in S
A family $(x_\alpha)_{\alpha \in A}$ of vectors is linearly
independent if and only if every vector $x$ can be written in at most
one way as a linear combination of $(x_\alpha)$
How can we prove the $\Leftarrow$ part ?
I'm following Werner Geubs' Linear Algebra Book and this proposition is proved in page 10, but I didn't get it what he means by "the scalar $\lambda_\alpha$ is uniquely determined by x".I mean to show the family of the sets is linearly independent, it chooses $x = 0$, but then concluded that the scalars in the unique expression of the linear combination of $x$ are $0$.
A:
Hint. Given $(x_\alpha)$, the vector 0 can be written in AT MOST one way as a linear combination of the $(x_\alpha)$. ONE way is with all the coefficients equal to zero. So this is the UNIQUE way.
| {
"pile_set_name": "StackExchange"
} |
Q:
Linear Algebra Proof using nonsingularity
In my Linear Algebra course I have come across multiple questions of the sort which I cannot seem to answer.
Let $A\in \mathbb R^{n×n}$ , $B\in \mathbb R^{n×m}$, and $C\in \mathbb R^{m×n}$.
If $A$ and $I − CA^{-1}B$ are nonsingular, show that $A − BC$ is nonsingular and
$(A − BC)^{-1} = A^{-1} + A^{-1}B(I − CA^{-1}B)^{-1}CA^{-1}$.
Edit: Any places where I can find rules and tricks on solving these kinds of matrix equations would be greatly appreciated.
A:
Just by multiplying $A-BC$ and $A^{-1} + A^{-1}B(I - CA^{-1}B)^{-1}CA^{-1}$ you get the desired result, I strongly suggest you to try it yourself before looking at the following.
\begin{align*}
&(A-BC)(A^{-1} + A^{-1}B(I - CA^{-1}B)^{-1}CA^{-1})\\
=&I-BCA^{-1}+B(I - CA^{-1}B)^{-1}CA^{-1}-BCA^{-1}B(I - CA^{-1}B)^{-1}CA^{-1}\\
=&I-BCA^{-1}+B(I-CA^{-1}B)(I - CA^{-1}B)^{-1}CA^{-1}\\
=&I-BCA^{-1}+BCA^{-1}\\
=&I
\end{align*}
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I turn on IPCOMP for a socket?
For reasons I can't go into, our system uses a very small MTU (128 bytes). These embedded devices are on a completely separate network so no internet access or interaction with other devices.
Obviously, TCP takes up 66 bytes per packet leaving not very much for payload.
After some googling, I came across IPCOMP which looks like it may help in reducing the amount of traffic on the network.
My question is how can I enable this? Is there a setsockopt, or do I need a special driver?
The only example I've seen is:
socket(PF_INET, SOCK_RAW, IPPROTO_COMP)
but this means I need to create the IP/TCP/payload manually.
Anyone have experience with this.
EDIT: Perhaps a better method would be to enable cslip or ppp on this connection. I can find tutorials on enabling PPP on a serial port (for dial-up modem), but nothing on enabling PPP on ethernet.
I've seen articles on PPPoE, but this seems to add MORE to the payload rather than reducing it.
Can anyone help with this?
A:
I've played around with IP xfrm in the past but I've never tried the comp option. If you want all outgoing traffic compressed, something like this would work.
ip xfrm policy add dev eth0 dir out tmpl proto comp
| {
"pile_set_name": "StackExchange"
} |
Q:
Duplicate emails from a workflow are going to be sent when creating a new wiki page
I am working on an enterprise wiki site, and I know that when creating a new wiki page it goes through the following life cycle:-
When a user clicks on add new page, and he enters the page title; a new empty wiki page will automatically be created, before adding any content.
After adding the content to the rich text editor and click on save. The page got updated and it will have version number 3!.
The above scenario did not cause any problem to me (or I have to live with the fact that to create a new wiki page it will have version 3 automatically).
But now I created a new List Workflow inside SharePoint designer, and I specify to run the work flow automatically when an item is changed.
The problem i am facing is that when a user creates a new wiki page the workflow will run twice !! so can anyone advice ? Although I specify that the workflow should run when an item is changed.
Regards
A:
It actually creates the file, then renames it in the first step.
I would suggest building in an if statement that prevents it running the first time.
| {
"pile_set_name": "StackExchange"
} |
Q:
Visual Studio: How can I see the same file in two separate tab groups?
I want to be able to edit one method while looking at another method in the same file, as reference.
Can this be done?
A:
You can open the file in another tab (Window -> New Window).
Doing so you have two copies of the same file. Then you can right-click the tab bar and select New Vertical Tab Group (or New Horizontal Tab Group, the one you like more).
Hope I understood you question..
A:
Only vertically that I'm aware. When looking at the code, right above the vertical scroll bar is a small rectangle, drag it down to get a split view of the file.
A:
Be on the tab you want to duplicate,then click in the menu bar at the top onWindow > New Window
Finally drag & drop the second window to the the left or right side to show both views next to each other.
Et voila, there you have it :)
EDIT
It seems that this function is not implemented in all version of VS.
In my case (V 15.4.2 (2017), V 15.9.7 (2017) & V 16.2.5 (2019)) it just works fine.
| {
"pile_set_name": "StackExchange"
} |
Q:
Prevent double-click from double firing a command
Given that you have a control that fires a command:
<Button Command="New"/>
Is there a way to prevent the command from being fired twice if the user double clicks on the command?
EDIT: What is significant in this case is that I am using the Commanding model in WPF.
It appears that whenever the button is pressed, the command is executed. I do not see any way of preventing this besides disabling or hiding the button.
A:
The checked answer to this question, submitted by vidalsasoon, is wrong and it is wrong for all of the various ways this same question has been asked.
It is possible that any event handler that contains code that requires a significant process time, can result in a delay to the disabling of the button at question; regardless to where the disabling line of code is called within the handler.
Try the proofs below and you will see that disable/enable has no correlation to the registration of events. The button click event is still registered and is still handled.
Proof by Contradiction 1
private int _count = 0;
private void btnStart_Click(object sender, EventArgs e)
{
btnStart.Enabled = false;
_count++;
label1.Text = _count.ToString();
while (_count < 10)
{
btnStart_Click(sender, e);
}
btnStart.Enabled = true;
}
Proof by Contradition 2
private void form1_load(object sender, EventArgs e)
{
btnTest.Enabled = false;
}
private void btnStart_Click(object sender, EventArgs e)
{
btnTest.Enabled = false;
btnTest_click(sender, e);
btnTest_click(sender, e);
btnTest_click(sender, e);
btnTest.Enabled = true;
}
private int _count = 0;
private void btnTest_click(object sender, EventArgs e)
{
_count++;
label1.Text = _count.ToString();
}
A:
Simple & Effective for blocking double, triple, and quadruple clicks
<Button PreviewMouseDown="Button_PreviewMouseDown"/>
private void Button_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
if (e.ClickCount >= 2)
{
e.Handled = true;
}
}
A:
I had the same issue and this worked for me:
<Button>
<Button.InputBindings>
<MouseBinding Gesture="LeftClick" Command="New" />
</Button.InputBindings>
</Button>
| {
"pile_set_name": "StackExchange"
} |
Q:
Are STL headers written entirely by hand?
I am looking at various STL headers provided with compilers and I cant imagine the developers actually writing all this code by hand.
All the macros and the weird names of varaibles and classes - they would have to remember all of them! Seems error prone to me.
Are parts of the headers result of some text preprocessing or generation?
A:
I've maintained Visual Studio's implementation of the C++ Standard Library for 7 years (VC's STL was written by and licensed from P.J. Plauger of Dinkumware back in the mid-90s, and I work with PJP to pick up new features and maintenance bugfixes), and I can tell you that I do all of my editing "by hand" in a plain text editor. None of the STL's headers or sources are automatically generated (although Dinkumware's master sources, which I have never seen, go through automated filtering in order to produce customized drops for Microsoft), and the stuff that's checked into source control is shipped directly to users without any further modification (now, that is; previously we ran them through a filtering step that caused lots of headaches). I am notorious for not using IDEs/autocomplete, although I do use Source Insight to browse the codebase (especially the underlying CRT whose guts I am less familiar with), and I extensively rely on grep. (And of course I use diff tools; my favorite is an internal tool named "odd".) I do engage in very very careful cut-and-paste editing, but for the opposite reason as novices; I do this when I understand the structure of code completely, and I wish to exactly replicate parts of it without accidentally leaving things out. (For example, different containers need very similar machinery to deal with allocators; it should probably be centralized, but in the meantime when I need to fix basic_string I'll verify that vector is correct and then copy its machinery.) I've generated code perhaps twice - once when stamping out the C++14 transparent operator functors that I designed (plus<>, multiplies<>, greater<>, etc. are highly repetitive), and again when implementing/proposing variable templates for type traits (recently voted into the Library Fundamentals Technical Specification, probably destined for C++17). IIRC, I wrote an actual program for the operator functors, while I used sed for the variable templates. The plain text editor that I use (Metapad) has search-and-replace capabilities that are quite useful although weaker than outright regexes; I need stronger tools if I want to replicate chunks of text (e.g. is_same_v = is_same< T >::value).
How do STL maintainers remember all this stuff? It's a full time job. And of course, we're constantly consulting the Standard/Working Paper for the required interfaces and behavior of code. (I recently discovered that I can, with great difficulty, enumerate all 50 US states from memory, but I would surely be unable to enumerate all STL algorithms from memory. However, I have memorized the longest name, as a useless bit of trivia. :->)
A:
The looks of it are designed to be weird in some sense. The standard library and the code in there needs to avoid conflicts with names used in user programs, including macros and there are almost no restrictions as to what can be in a user program.
They are most probably hand written, and as others have mentioned, if you spend some time looking at them you will figure out what the coding conventions are, how variables are named and so on. One of the few restrictions include that user code cannot use identifiers starting with _ followed by a capital letter or __ (two consecutive underscores), so you will find many names in the standard headers that look like _M_xxx or __yyy and it might surprise at first, but after some time you just ignore the prefix...
| {
"pile_set_name": "StackExchange"
} |
Q:
Какой, который, что
Какие существуют правила употребления слов который, какой и что? Какая разница между словами который и что?
A:
У Розенталя (в учебнике для вузов "Современный русский язык") есть такие сведения по применению союзных слов который, какой, что в СПП с придаточными определительными.
Местоимение КОТОРЫЙ является универсальным и имеет чисто определительное значение, местоимение КАКОЙ вносит оттенок сравнения или уподобления, местоимение ЧТО заменяет местоимение КОТОРЫЙ, но при этом имеет определенные особенности.
Местоимение ЧТО придает речи эмоциональность, например: Виктор Гюго ворвался в классический и скучноватый век, как ураганный ветер, как вихрь, что несет потоки дождя, листья...
В придаточном предложении ЧТО выполняет роль подлежащего или прямого дополнения (И.п. и В.п.). Также ЧТО не согласуется с определяемым существительным (в главном предложении) в роде и числе (это надо учитывать при построении предложения).
Посмотрим. как это выглядит на примерах.
1) КОТОРЫЙ (распространительное значение, нельзя использовать указательное слово): Потом подул сильный ветер, который (=он) становился холоднее с каждым порывом.
2) КОТОРЫЙ (выделительное значение из ряда однородных предметов): Из их вздохов рождается тот ветер, который превращается в бури.
3) КАКОЙ (качественное значение, выделение по признаку): Дул такой легкий и сладостный ветер, какой только может дуть в сентябре, и участковый подставлял ему лицо.
4) ЧТО (заменяет КОТОРЫЙ в разных значениях):
Устал тот ветер, что листал страницы мировой истории.
Как ветер, что к ним летел с небес, Умытый студеной звездой...
Еще и ветер, что относил в ту сторону взволнованные дымки цигарок, долетал туда за каких-нибудь три счета и вот уже кудрявил надворные ветлы...
Дай Бог, чтобы сохранились, особенно в наши дни, такие люди, что ставят во главу угла не чистый заработок, а интересы дела...
Примечание.
Хотя ЧТО (в паре такой ― что) заменяет одушевленный предмет (что не очень естественно), такие предложения встречаются в тексте. И есть еще один недостаток ― неразличение союзного слова ЧТО и союза ЧТО со значением следствия, например : Дул такой пронзительный ветер, что буквально сносил нас с ног (значение следствия).
| {
"pile_set_name": "StackExchange"
} |
Q:
Only counting data that fits certain criteria in SQL on Microsoft Access
I have 1 table in microsoft access with student information (including gender and grade). I'm trying to use the SQL view to get a count of how many male and females are in each grade. Right now, this is what I have.
SELECT
StudDetails.CurrClass as 'class',
Count(StudeDetails.sex) WHERE (StudDetails.sex="M" AND StudDetails.CurrClass='class') AS 'malecount', Count (StudeDetails.sex) WHERE (StudDetails.sex="F"AND StudDetails.CurrClass='class') AS 'femalecount'
FROM StudDetails
GROUP BY StudDetails.CurrClass;
I know this is super bad but I'm new to SQL. I've tried googling but I don't understand the answers or can't apply them.
A:
You can't use WHERE the way you're using it. You're looking for IIF to do comparisons.
Since Count is rather inflexible, using Sum and assigning ones and zeroes on a comparison is easier.
SELECT
StudDetails.CurrClass as 'class',
Sum(IIF(StudDetails.sex="M", 1, 0)) AS malecount,
Sum(IIF(StudDetails.sex="M", 0, 1)) AS femalecount
FROM StudDetails
GROUP BY StudDetails.CurrClass;
| {
"pile_set_name": "StackExchange"
} |
Q:
Опасно ли открытие портов у сервера на линукс
Опасно ли открытие портов у севера на линукс Debian и чем?
Если я открыл порт командой:
iptables -A INPUT -p tcp -m tcp --dport 90 -j ACCEPT
Плохо ли это? Просто иначе не получается приложение на websocket на node.js запустить. Или можно как-то иначе, если порты открывать небезопасно?
A:
В общем случае открытые порты опасны тем, что по ним можно достучаться до чего-то, что может нанести вред тебе лично или другим людям. Сам по себе открытый порт (любой) не опасен ничем, если за ним не стоит какая-то служба, которой можно воспользоваться для этого.
Для примера, вот какие порты открыты у меня в роутере (щаз запинают за "все протоколы"):
Это в домашней сети, есть внешний IP. Все из них по сути ведут туда же, и доступно снаружи. Постоянно ломятся какие долбоботы с характерными запросами. Но кто ж им разрешит пройти дальше :)
P.S. Хакеры-ломакеры приглашаются сюда.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to overwrite a specific file from a branch to a trunk in SVN?
How can I overwrite a file from a specific branch to a trunk?
Like for example I have https://web/trunk/text.cpp file. Then I want my https://web/branches/tt_branch/text.cpp overwrite the trunk file.
A:
If you want to completely overwrite the trunk file with the branched file, you can delete the trunk file and then make a copy of the branch one (easy and radical)
svn delete https://web/trunk/text.cpp -m "delete trunk file"
svn copy https://web/branches/tt_branch/text.cpp
If you want to do something less absolute, try to use the svn merge operation
svn merge https://web/branches/tt_branch/text.cpp https://web/trunk/text.cpp
that will ask you to solve the potential conflicts, if you don't want to resolve any conflicts, try this :
svn merge --accept theirs-full https://web/branches/tt_branch/text.cpp https://web/trunk/text.cpp
| {
"pile_set_name": "StackExchange"
} |
Q:
Content Security Policy CSP
On Craft 2.x, is it a known limitation that we must allow unsafe-inline for script-src in the Content-Security-Policy? My admin dashboard fails to load when I don't allow it.
...Trying to get a high grade on Mozilla Observatory :)
A:
I implemented this recently and what I ended up doing is return the content security headers using PHP. Depending on the request path (is it a CP URL or not?), we send CSP headers with unsafe-inline and unsafe-eval or not.
Of course, the CP is still unsecured, but what you can do is to specify a custom domain for the CP in your configuration (using the "baseCpUrl" key). Something like "admin.yourwebsite.com" that only certain users can access (using IP filtering for example).
It is still not a perfect solution, but we cannot do anything at the CP level unfortunately. I hope this will not be an issue anymore in Craft 3.
| {
"pile_set_name": "StackExchange"
} |
Q:
Understanding of non-degeneracy and inner product
My class version of the non-degeneracy definition states:
Let $V$ be a vector space over a field $\Bbb F$, equipped with a symmetric bilinear form $b : V \times V → \Bbb F$ . Then $b$ is a non-degenerate bilinear form if $~∀\,u∈V,\ b(v,u)=0 \implies v=0$.
I find myself confused when I try to apply it to proving all inner products are non-degenerate, and here is my confusion:
Given an inner product $b$. I let $u \in V$ and assume $b(v,u)=0$ and I am trying to show $v=0$.
I saw on a few texts that we are allowed to pick $v$ so that $v=u$ and thus we get $v=0$ from positivity. Why are we allowed to choose the value for $v$? I thought $v$ could just be any arbitrary vector and it doesn't have to happen to be $u$. To make it clearer, it doesn't make sense to me that $b(v,u)=0\Rightarrow v=u$ whatsoever. In my mind $v$ is fixed and does not vary with $u$.
Could someone kindly explain what is wrong with my reasoning?
A:
You might find it easier to think of this: the radical of $V$ with respect to a (symmetric, if you may) bilinear form $b: V \times V \to \Bbb C$ is the subspace: $${\rm Rad}(V) = \{ u \in V \mid b(u,v) = 0,~\forall\,v \in V \}$$
We say that $b$ is non-degenerate on $V$ if ${\rm Rad}(V) = \{0\}$. Like a sort of kernel.
Now suppose that $b$ is an inner product, and take $u \in {\rm Rad}(V)$. So $b(u,v) = 0$ for all $v \in V$. Well, $u \in V$, so you can say that $b(u,u) = 0$. Now follows from the defintion of inner product (definite positivity) that $u = 0$. So ${\rm Rad}(V) = \{0\}$ and $b$ is non-degenerate on $V$.
Remark: to be precise, as I have written it, ${\rm Rad}(V)$ is the kernel of the linear map $V \ni u \mapsto b(u,\cdot) \in V^\ast$. You can ignore this, in any case.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to transfer the code from application.html.erb
I know that by default, views in Rails use the template provided in application.html.erb
It's my default template:
<!DOCTYPE html>
<html>
<head>
... any code ...
</head>
<body>
<header> ... any code ... </header>
<%= yield %>
</body>
</html>
I need to transfer the code header> in partial template.
This is my attempt:
I created in section view/layouts/header_menu.html.erb
I added methode in helpers/application_helper.rb
def layout_header
render 'layouts/header_menu'
end
And called it in application.html.erb
<!DOCTYPE html>
<html>
<head>
... any code ...
</head>
<body>
<%= layout_header %>
<%= yield %>
</body>
</html>
It is my Error:
*Missing partial layouts/header_menu with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :coffee, :haml]}. Searched in:
* "E:/BDR_SEVERNEFT/app/views"*
I used Rails 3.2 and Ruby 1.9.3
A:
Look at the guide http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials
You can render partials directly in the .erb file using <%= render layout/header_menu %> and the partial file needs to start with an underscore i.e. "_header_menu.html.erb".
If you want to use your method call approach, call render partial: "layout/header_menu" and again, make the file name "_header_menu.html.erb".
| {
"pile_set_name": "StackExchange"
} |
Q:
Starting Lync conversation from C# WPF desktop app regardless of Lync client version installed
I'm new to Lync integration and development.
I am trying to write a feature to allow an existing desktop WPF line of business application to launch a Lync conversation with another user on the local intranet where the app is running.
The difficulty I face is that the application will not know up front what version of Lync client is installed on the user's PC. The app is deployed in various organizations and therefore can't make assumptions about client or server side versions.
At this stage the app is going to try launch whichever version of the Lync executable it can find on the PC, with a shortcut SIP, as shown here:
https://technet.microsoft.com/en-us/library/gg398376(v=ocs.14).aspx
"You can use command-line parameters to quick-start Microsoft Lync"
I am also considering the UCMA (server side) API, although I'm worried that again I will have to worry about what server version is running.
Is there a better "version agnostic" way of doing this?
It seems that each version of the client SDK is incompatible with previous versions. This will mean I need to first detect what version of Lync is installed; and then use the appropriate SDK. This will also mean distributing multiple copies of the Lync SDK; and will also likely mean needing to create a new version of the application when successive versions of Lync are released.
I did note that there might be a server-side API (UCMA) that I could use across the different versions of Lync/OCS/Skype for Business, although there are mentions that this API is more "advanced" and is "to be avoided".
Some reading I've done:
what are difference between "Lync Server 2010 SDK" / "UCMA 3.0 SDK" / and UCC API?
http://blog.thoughtstuff.co.uk/2014/07/lync-development-picking-the-right-api/
Which Lync SDK? Send IMs from managed code
Can anyone share any thoughts about this problem, have I missed something?
Ideally I'd like some kind of layer of abstraction where I could call a method to start a conversation, and not worry about what client is installed on the PC or what version is installed on the server. I realize this might be an unrealistic expectation!
I have tried searching through SO on the Lync tag; if this is a repeat question, sorry!
A:
It sounds like you want to use the Lync Client SDK. That this SDK really does is remote control the "Lync Client". To start the Lync client if it's not running, is just run "lync.exe". A Lync client install will always have this exe in the path so just running it should work ok. (does for me so far)
Lync 2010 is rather old. I would use Lync 2013 Client SDK. I use that version as it works for the 2013 client up to the latest Skype For Business 2016 client.
I would download / install the client SDK and check out the examples. You should to find examples of most things you want (starting a audio conversation, starting a IM conversation, etc). Pretty much anything you can manually do in the client you can remote control via the Client SDK.
If you want a abstraction layer over the versions, you will have to do that yourself as it's not supported by the SDK's themselves. Although I wouldn't bother and just support from Lync 2013 and greater.
If your going to do a abstraction layer you will need to test on all the Lync server setups. Good luck on that... We have Lync 2103 server and Skype for Business setup here (they can co exist) and it's a huge setup. A basic setup can be about 6-7 servers and it hooks into your AD. So to run different versions will require multiple AD's as well. You may need PSTN / sip trunk access to test external calls or federation setup for external network access to/from external clients or federated orgs (like consumer skype). If you need to go anywhere near high availability you server requirements just skyrocket...
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the purpose of "g" -> generator of the multiplicative group
I am currently beginning to studying the different security protocols and came across the SRP secure remote password protocol. I manage to understand the mathematic formulas behind it and the calculation but i do not understand the reason/purpose of using the "g" -> a generator of the multiplicative group.
Why is "g" a static value
why it should be predefined, why not dynamically assigned
why is "g" has the value of 2 in the most implementations i.e. why not 3,4,5,6,7,8,..
what is so important about this parameter that it needs to be included into the calculation,
what is the purpouse of the generator of the multiplicative group is there any special relation that i must be aware in the matematics
what happens when g is 1
I have read the wikipedia definition of the Generators but i still do not understand what is the reason, WHY do we need to use them i.e. what happens when the group Z is cyclic, why is this an advantage or not.
A:
SRP is one of the large collection of algorithms which operate in a cyclic group. A cyclic group consists in elements 1, g, g2_, g3_,... up to some value gr-1 where r is the group order (the smallest non-zero integer such that gr = 1). So g is "static" because it actually is part of the definition of the playground: SRP operates in the cyclic group generated by a given value g, using multiplication modulo a given prime N as group law. Note that both client and server must agree on g and N, and the same g and N must be used for a given user. It is easier for the server if the same g and N, i.e. the same cyclic group, are used for all users; and sharing the same group is not a problem for security.
For cryptographic purposes, we need a group such that discrete logarithm is hard, but computations are easy (these two conditions imply that we need a cyclic group, but just not any cyclic group). This requires that N is big enough, and also that r (the order of g) is such that it is a multiple of a big enough prime (at least 160 bits). SRP recommends that N be chosen as a "safe prime", i.e. N = 2q+1 where q is also a prime integer. If N is a safe prime, then the order of any g in the 2..N-2 range is necessarily q or 2q, hence appropriate.
If you choose g = 1, then you get a cyclic group of order 1 and all your values will be 1; any password will be accepted and there is no security at all. Similarly, if you choose g = N-1, then you get a cyclic group of order 2, which is not substantially better.
However, any value between 2 and N-2 will be good for g (if N is a safe prime). Then, we may as well use g = 2, which is optimal for performance (though the gain is slight when compared with a random g).
| {
"pile_set_name": "StackExchange"
} |
Q:
android: best view class to create popup page
I am developing an android camera app that allow popup of page upon pressing a button (besides the shoot button)in the view of the photo capture activity for accessing twitter services, including login(of coz with button), view tweets(listview or list fragment) of bookmarked users and posting tweets.
I am considering the approach to build the layout for the popup stuff. What come across my mind are dialog fragment, popupwindow and simply another activity.
Considering my case, what view is recommended for the popup component?
A:
Depends on the content of your popup:
If popup contains only a list of items use PopupWindow.
If popup contains only a few buttons like ok/cancel some text etc. Use DialogFragment.
If you have more stuff, you should probably use Activity.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I delete an image (AMI) in AWS EC2 using the SDK?
I am using CreateImage() to create a new AMI from an existing Instance and I was hoping there was a DeleteImage() which would work in the converse fashion. Unfortunately this method does not exist on the EC2Client.
What is the proper way to delete an AMI through the SDK using C#?
A:
Here is a quick snippet:
AmazonEC2 ec2 = AWSClientFactory.CreateAmazonEC2Client();
DeregisterImageRequest deregisterImageRequest = new DeregisterImageRequest();
deregisterImageRequest.ImageId = AMIName;
DeregisterImageResponse deregisterImageResponse = new DeregisterImageResponse();
deregisterImageResponse = ec2.DeregisterImage(deregisterImageRequest);
Remember to handle exceptions and remove the snapshots..
However there is an issue with deleting the associated snapshots.
If you try to find out the blockdevice mapping using DescribeImageAttributeRequest an exception occurs - "Unauthorized attempt to access restricted resource" :
DescribeImageAttributeRequest describeImageAttributeRequest = new DescribeImageAttributeRequest().WithImageId("ami-name").WithAttribute("blockDeviceMapping");
DescribeImageAttributeResponse describeImageAttributeResponse = new DescribeImageAttributeResponse();
describeImageAttributeResponse = ec2.DescribeImageAttribute(describeImageAttributeRequest);
See post:
https://forums.aws.amazon.com/message.jspa?messageID=231972
A:
There is a DeregisterImage() that should do what you want. Note that it's up to you to delete any snapshots the image may be based upon afterward.
| {
"pile_set_name": "StackExchange"
} |
Q:
Pass argument from ctest to gtest
I am using gtest to write unit tests for my application. I also have ctest that runs all executables added by add_test CMake command. Is it possible to pass gtest variables through ctest when test execution starts?
I would like to for example sometimes filter out tests with --gtest_filter flag but I don't know how or if this is even possible through ctest? I have tried the following ways:
ctest --gtest_filter=AppTest.*
ctest --test-arguments="--gtest_filter=AppTest.*"
But both still run all tests instead the filtered ones.
Thanks!
A:
For anyone looking here in 2019, recent versions of CMake have gtest_discover_tests (GoogleTest module) which will hoist your tests into CTest and you can filter from there.
IOW rather than having a single add_test in CTest, it will use --gtest_list_tests to call add_test for each of your tests.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I simplify this binary-tree traversal function?
template<typename T>
void traverse_binary_tree(BinaryTreeNode<T>* root,int order = 0)// 0:pre, 1:in , 2:post
{
if( root == NULL ) return;
if(order == 0) cout << root->data << " ";
traverse_binary_tree(root->left,order);
if(order == 1) cout << root->data << " ";
traverse_binary_tree(root->right,order);
if(order == 2) cout << root->data << " ";
}
Is there a better way to write this function?
A:
No.
Kidding. I think it looks pretty efficient.
I would enum the order values, for readability.
...
enum TOrder {ORDER_PRE, ORDER_IN, ORDER_POST};
template<typename T>
void traverse_binary_tree(BinaryTreeNode<T>* root,TOrder order = ORDER_PRE) {
...
A:
"Simple" is a matter of opinion. Apart from some stylistic matters (particularly using magic numbers rather than named constants), that's about as simple as you can get, given the spefication "traverse the tree and print its contents, giving a choice of order".
However, you can get more flexibility by separating out the two concerns: traversing the tree, and doing some operation on the data. You may want to analyse and manipulate the data in various ways as well as print it, and it's better not to duplicate the traversal logic for each operation. Instead, you could add extra template parameters to allow arbitrary combinations of pre-, post-, or in-order operations, along the lines of this:
// PRE, IN and POST operations are unary function objects which can
// take Node<T>* as their argument
template <typename T, typename PRE, typename IN, typename POST>
void traverse(Node<T>* root, PRE& pre, IN& in, POST& post)
{
if (!root) return;
pre(root);
traverse(root->left, pre, in, post);
in(root);
traverse(root->right, pre, in, post);
post(root);
}
// This can be used as a template argument to denote "do nothing".
struct Nothing { void operator()(void*) {} } nothing;
// Usage example - print the nodes, pre-ordered
void print(Node<int>* node) {std::cout << node->data << " ";}
traverse(root, print, nothing, nothing);
// Usage example - find the sum of all the nodes
struct Accumulator
{
Accumulator() : sum(0) {}
void operator()(Node<int>* node) {sum += node->data;}
int sum;
};
Accumulator a;
traverse(root, a, nothing, nothing);
std::cout << a.sum << std::endl;
A:
It depends what you are wanting to do with it really - as well as possibly refactoring it to templatize the order, or separating the three traversal types, you might want to turn it into an internal iteration, allowing anything to visit the data in the tree:
enum order_t { PREORDER, INORDER, POSTORDER };
template<typename T, order_t order, typename F>
void traverse_binary_tree(BinaryTreeNode<T>* root, F f)
{
if( root == NULL ) return;
if(order == PREORDER) f(root->data);
traverse_binary_tree<T,order>(root->left,f);
if(order == INORDER) f(root->data);
traverse_binary_tree<T,order>(root->right,f);
if(order == POSTORDER) f(root->data);
}
template<typename T, typename F>
void traverse_binary_tree(BinaryTreeNode<T>* root, F f, order_t order = PREORDER)
{
switch (order) {
case PREORDER:
traverse_binary_tree<T,PREORDER>(root,f);
break;
case POSTORDER:
traverse_binary_tree<T,POSTORDER>(root,f);
break;
case INORDER:
traverse_binary_tree<T,INORDER>(root,f);
break;
}
}
(you may also want const F& and F& versions rather than the simple copying, pass-by-value function parameter, which would let you pass in functors which are mutable and produce a result; by-value is fine as long as your functor has no member variables or constructor)
Or you could create iterators which represent the three traversals, allowing you to write the output using std::copy; however, this would be a lot more code and wouldn't be done just for that purpose. However, creating an iterator would allow large trees to be processed without stack overflow, as you would have to either have a 'parent' pointer in each node, or have the iterator maintain an explicit stack of visited nodes.
Although the function itself becomes very simple:
std::ostream_iterator<std::string>(std::cout, " ");
std::copy(d.begin(order), d.end(), out);
Using an iterator doesn't simplify the implementation, either in terms of loc or actually being able to follow what is going on:
#include<string>
#include<iostream>
#include<functional>
#include<algorithm>
#include<iterator>
#include<vector>
#include<stack>
enum order_t { PREORDER, INORDER, POSTORDER };
template <typename T>
class BinaryTreeNode {
public:
BinaryTreeNode(const T& data) : data(data), left(0), right(0) { }
BinaryTreeNode(const T& data, BinaryTreeNode<T>* left, BinaryTreeNode<T>* right) : data(data), left(left), right(right) { }
public:
BinaryTreeNode<T>* left;
BinaryTreeNode<T>* right;
T data;
class BinaryTreeIterator {
BinaryTreeNode <T>* current;
std::stack<BinaryTreeNode <T>*> stack;
order_t order;
bool descending;
public:
typedef T value_type;
typedef std::input_iterator_tag iterator_category;
typedef void difference_type;
typedef BinaryTreeIterator* pointer;
typedef BinaryTreeIterator& reference;
BinaryTreeIterator (BinaryTreeNode <T>* current, order_t order) : current(current), order(order), descending(true)
{
if (order != PREORDER)
descend();
}
BinaryTreeIterator () : current(0), order(PREORDER), descending(false)
{
}
private:
void descend() {
do {
if (current->left) {
stack.push(current);
current = current -> left;
descending = true;
} else if ((order!=INORDER) && current->right) {
stack.push(current);
current = current -> right;
descending = true;
} else {
descending = false;
break;
}
} while (order != PREORDER);
}
public:
bool operator== (const BinaryTreeIterator& other) {
if (current)
return current == other.current && order == other.order;
else
return other.current == 0;
}
bool operator!= (const BinaryTreeIterator& other) {
return !((*this)==other);
}
const T& operator * () const {
return current -> data;
}
BinaryTreeIterator& operator++ () {
// if the stack is empty, then go to the left then right
// if the descending flag is set, then try to descending first
if (descending)
descend();
// not descending - either there are no children, or we are already going up
// if the stack is not empty, then this node's parent is the top of the stack
// so go right if this is the left child, and up if this is the right child
if (!descending) {
do {
if (stack.size()) {
BinaryTreeNode <T>* parent = stack.top();
// for inorder traversal, return the parent if coming from the left
if ((order == INORDER) && (current == parent->left)) {
current = parent;
break;
}
// if this is the left child and there is a right child, descending into the right
// or if this is the parent (inorder)
if ((current == parent) && (parent -> right)) {
current = parent->right;
descend();
// simulate return from descent into left if only the right child exists
if ((current->left == 0)&&(current->right))
stack.push(current);
break;
}
// if this is the left child and there is a right child, descending into the right
if ((current == parent->left) && (parent -> right)) {
descending = true;
current = parent->right;
if (order != PREORDER)
descend();
break;
}
// either has come up from the right, or there is no right, so go up
stack.pop();
current = parent;
} else {
// no more stack; quit
current = 0;
break;
}
} while (order != POSTORDER);
}
return *this;
}
};
BinaryTreeIterator begin(order_t order) { return BinaryTreeIterator(this, order); }
BinaryTreeIterator end() { return BinaryTreeIterator(); }
};
int main () {
typedef BinaryTreeNode<std::string> Node;
std::ostream_iterator<std::string> out( std::cout, " " );
Node a("a");
Node c("c");
Node b("b", &a, &c);
Node e("e");
Node h("h");
Node i("i", &h, 0);
Node g("g", 0, &i);
Node f("f", &e, &g);
Node d("d", &b, &f);
std::copy(d.begin(INORDER), d.end(), out);
std::cout << std::endl;
std::copy(d.begin(PREORDER), d.end(), out);
std::cout << std::endl;
std::copy(d.begin(POSTORDER), d.end(), out);
std::cout << std::endl;
return 0;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
IComparer on multiple values and specific values
There are two Generic list of Inspectors and InspectorRates. Inspector class has object of Inspector Rate class.
RateType has three different values (0 = Not Select ,1 = Day Rate ,2 = Hourly Rates).
I want to show all inspectors with Day Type Rate first and then lowest rate. If user selects option "Hourly Rates" then list needs to be sorted by Hourly Rate and thenlowest rate. Not seleted rate will always be at the bottom.
Example: After sorting, list content needs to be in following order (First one is ByDay and second is By Hour)
I have create IComparer class for sorting but can't figure out how to sort list based on specific and multiple fields.
Public Class InspectorSort
Implements IComparer(Of Inspector)
Private listOrderBy As OrderBy = OrderBy.FirstName
Private listDirection As Direction = Direction.Assending
Public Enum OrderBy As Byte
InspectorID = 0
FirstName = 2
DayRate = 14
HourlyRate = 15
End Enum
Public Enum Direction As Integer
Assending = 1
Decending = -1
End Enum
Public Sub New(ByVal mOrderBy As OrderBy, ByVal mDirection As Direction)
listOrderBy = mOrderBy
listDirection = mDirection
End Sub
Public Function Compare(ByVal x As Objects.Inspector, ByVal y As Objects.Inspector) As Integer Implements System.Collections.Generic.IComparer(Of Objects.Inspector).Compare
Dim value As Integer = 0
Select Case listOrderBy
Case OrderBy.InspectorID
If x.InspectorID > y.InspectorID Then
value = 1
ElseIf x.InspectorID < y.InspectorID Then
value = -1
End If
Case OrderBy.FirstName
If x.FirstName.ToLower > y.FirstName.ToLower Then
value = 1
ElseIf x.FirstName.ToLower < y.FirstName.ToLower Then
value = -1
End If
Case OrderBy.DayRate
If x.DefaultRate.RateType = Rates.RateTypeEnum.Day_Rate Then
If x.DefaultRate.RateType = Rates.RateTypeEnum.Day_Rate And x.DefaultRate.Rate > y.DefaultRate.Rate Then
value = 1
End If
End Select
Return value * listDirection
End Function
End Class
A:
I didn't take the time to translate to VB, but this is the based on the C# Comparer that I have created.
UPDATED CODE
original
// RateType 0 always greatest of list
if (x.DefaultRate.RateType == 0)
return 1;
This didn't factor in that sometimes it's the y that has the value that you want.
Added check for y and return the value accordingly
so it becomes
// RateType 0 always greatest of list
if (x.DefaultRate.RateType == 0)
return 1;
else if (y.DefaultRate.RateType == 0)
return -1;
public class InspectorDayRateComparer : IComparer<Inspector>
{
public int Compare(Inspector x, Inspector y)
{
// RateType 0 always greatest of list
if (x.DefaultRate.RateType == 0)
return 1;
else if (y.DefaultRate.RateType == 0)
return -1;
int result = x.DefaultRate.RateType.CompareTo(y.DefaultRate.RateType);
if (result == 0)
result = x.DefaultRate.Rate.CompareTo(y.Defaultrate.Rate);
return result;
}
}
public class InspectorHourlyRateComparer : IComparer<Inspector>
{
public int Compare(Inspector x, Inspector y)
{
// RateType 0 always greatest of list
if (x.DefaultRate.RateType == 0)
return 1;
else if (y.DefaultRate.RateType == 0)
return -1;
// So that 1 is greater than 2 to get the order desired
int result = (x.DefaultRate.RateType.CompareTo(y.DefaultRate.RateType) *-1) ;
if (result == 0)
result = x.DefaultRate.Rate.CompareTo(y.Defaultrate.Rate;
}
}
This should get you closer to where you want to get.
IComparer interface here
If you have more element to add to the Compare, chain them using the result variable, result == 0 means that the values are the same, we must check other property for comparer.
Forcing the return value, when you have no RateType, will always make it last.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to wait for animation finished in jQuery?
I need to append 10 divs with animation of them increase. I need them to appear one after another. I have this code
$('#bluebutton').click(function() {
for (var i = 0; i < 10; i++) {
var t = $('<div/>')
t.css('background-color', 'blue');
t.css('float', 'left');
t.css('border', '1px solid white');
t.appendTo(gallery);
t.animate({
width: 100,
height: 100
}, 400, function() {
// Animation complete.
});
}
});
but all 10 divs are appending together. Updated: added complete callback.
A:
You can use the completion callback for that:
var gallery = $("#gallery");
$('#bluebutton').click(function() {
var i = 0;
addDiv();
function addDiv() {
var t = $('<div/>')
t.css('background-color', 'blue');
t.css('float', 'left');
t.css('border', '1px solid white');
t.appendTo(gallery);
++i;
t.animate({
width: 100,
height: 100
}, 400, i < 10 ? addDiv : $.noop);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="bluebutton" value="Click me" type="button">
<div id="gallery"></div>
Note that bit at the end: i < 10 ? addDiv : $.noop. $.noop is a function jQuery provides that does nothing, so what that does is say: "If i is less than 10, call addDiv when the animation is complete."
| {
"pile_set_name": "StackExchange"
} |
Q:
Loop a map and multiply value by lets say 20 in Java8
How to loop a map elements and multiply value by lets say number 20 in java8 and get result?
I don't want to loop in usual for loop i want to make it efficient.
A:
You can use replaceAll if you want to mutate the map itself:
myMap.replaceAll((k, v) -> v * 20);
or collect to a new map:
myMap.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue() * 20));
| {
"pile_set_name": "StackExchange"
} |
Q:
c# operator ! cannot be applied
i wonder why ! cannot be applied
this is my code :
for (int i = 0; i < rowcol.GetLength(0); i++)
{
for (int j = 0; j < rowcol[i].GetLength(0); j++)
{
var top = !((rowcol[i-1][j])) ? rowcol[i-1][j] : '';
var bottom = !(rowcol[i+1][j]) ? rowcol[i+1][j] : '';
var left = !(rowcol[i][j-1]) ? rowcol[i][j-1] : '';
var right = !(rowcol[i][j+1]) ? rowcol[i][j+1] : '';
}
}
i have a jagged array that , i am reading the values from a textfile . i am having error with operator ! cannot be applied to string , but i and j is int , , yes rowcol is reading a string from a textfile .
please tell me if u need the full code . Help is appreciated thanks
A:
The issue is that rowcol[i-1][j] is a string, and ! cannot be applied to a string. The same applies for each of your four lines.
Edit: If your goal is to check that the string is not null or empty, try instead:
var top = !(String.isNullOrEmpty(rowcol[i - 1][j])) ? rowcol[i - 1][j] : '';
and so on, or, if you know that the string will be null and not empty,
var top = (rowcol[i - 1][j]) != null) ? rowcol[i - 1][j] : '';
| {
"pile_set_name": "StackExchange"
} |
Q:
I need to transition from a SpriteKit GameViewController to a regular View Controller in an iOS app (Objective-C)
I am making a game in Objective-C using SpriteKit, but there are also some view controllers. I need to transition from a SpriteKit scene to the non-SpriteKit view controller at a push of a button. The button is simply made of a SpriteKit Node, and can be pressed using this code:
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
SKNode *node = [self nodeAtPoint:location];
//if back button touched, show other view
if ([node.name isEqualToString:@"backbutton"]) {
//transition code goes here
}
}
Now, I'm not quite sure what to put in the if statement that figures out if the back button is pressed. I have no idea, though I tried this. Any help would be appreciated.
A:
Well, one way of going about it would be to use the main.storyboard, actually. Have you tried setting up both view controllers that way? Let me know if this doesn't work:
You can actually use an 'Sprite Kit View Controller' and a 'View Controller' to fit your game. Set up the scene-transitioning button using the storyboard, and fit the rest of the game by using code. The button will be stuck there, so put it in a good place.
Merely set up a transition between the button and the 'View Controller' like you would in any Single View Application.
| {
"pile_set_name": "StackExchange"
} |
Q:
Generating multivariate Gaussian distribution in Rcpp
I used this link here for some Rcpp code to generate samples from a multivariate Gaussian distribution: https://gallery.rcpp.org/articles/simulate-multivariate-normal/
Rcpp code:
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
// [[Rcpp::export]]
arma::mat mvrnormArma(int n, arma::vec mu, arma::mat sigma) {
int ncols = sigma.n_cols;
arma::mat Y = arma::randn(n, ncols);
return arma::repmat(mu, 1, n).t() + Y * arma::chol(sigma);
}
R code:
mvrnormArma(n = 10000, mu = c(0, 0), Sigma = matrix(c(1,0,0,1), 2, 2))
This worked fine until recently and I get the following error:
error: Mat::init(): requested size is not compatible with column vector layout
Does anyone else have this problem?
Any help is much appreciated!
A:
Works for me with the version uploaded to CRAN today. Which version do you claim an error with?
R> library(RcppArmadillo)
R> packageVersion("RcppArmadillo")
[1] ‘0.9.700.2.0’
R> Rcpp::sourceCpp("~/git/stackoverflow/57760655/question.cpp")
R> #mvrnormArma(n = 10000, mu = c(0, 0), Sigma = matrix(c(1,0,0,1), 2, 2))
R> set.seed(123) # make it reproducible
R> mvrnormArma(n = 10, mu = c(0, 0), sigma = matrix(c(1,0,0,1), 2, 2))
[,1] [,2]
[1,] -0.6853851 1.811730
[2,] 0.9302219 0.741069
[3,] -0.2260918 -0.119390
[4,] 0.9513753 0.315338
[5,] 0.0699539 0.670879
[6,] 0.9767215 0.332053
[7,] 2.1650415 0.966927
[8,] -1.8262054 1.294966
[9,] 0.5804146 1.062635
[10,] -0.0592898 2.270198
R>
I used your C++ code as is, and just adjusted Sigma to lowercase sigma.
| {
"pile_set_name": "StackExchange"
} |
Q:
log script output to file and terminal at the same time
I have a simple tcpnotification receiver script that logs notifications. At first I just printed the notifications in terminal but then changed script so that notifications are logged in a file.
But I would like the script to both print the logs in terminal and logged them to a file.
while true;
do
nc -l -p $portL >> ~/tcplog.log
#ipv6 version
#nc -6 -l -p $portL
done
Can this be done in one command? I tried to add printf to nc -l -p $portL >> ~/tcplog.log but this just resulted in access denied. Also tried && but this resulted in notifications logged once in terminal then next time in logfile.
A:
Look at tee
nc -l -p $portL |tee -a ~/tcplog.log
See also man tee for more details
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does my website look different in Safari and how can I fix it?
My site is www.elansz.com. It looks good in Google Chrome but in Safari a lot of the elements are positioned to the right too far. How can I fix this issue? Thanks!
A:
you need this on your site
https://necolas.github.io/normalize.css/
Normalize.css makes browsers render all elements more consistently and in line with modern standards. It precisely targets only the styles that need normalizing.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to "fit in" a cycling bunch?
This is a genuine request for ideas on how to be effective in not following the "Velominati" rules. How to keep cyclists of all persuasions together and be accepting of others, from leadership to newbies.
The alternative:
https://humancyclist.wordpress.com/2014/05/03/the-rules-rewritten-cycling/
Basically
we ride, we do what we want
I ride, I do what I want
and look how I want
How can we keep bunch riders together, have regular rides, and not slip into this elitist Velominati (it's not even a word)?
I am after tips, DO's and DONT's on how to keep a smile and not feed into the egos in the bunch. That's pretty much it.
A:
I've heard once: if a person offers you a gift and you don't accept it - it remains the property of the other person. And it's the same with criticism. And thus, if you engage yourself into a discussion you most likely end up in a fight over the colour of your bar tape.
Assuming that you are not the only one hating the rules try not to get into the discussions. You can use some responses to the comments on your gear (socks, bike, etc.), I've sorted them out from the least offensive:
if it goes about the socks and such, go "laundry day, sorry, I'll do my best to match them next time"
remarks on how old/outdated your equipment is can be replied with "gets me going but I'd be glad to try yours if you say it's that great. I know what to upgrade."
general remarks can be replied with "don't worry, next time I'll go slower so I stay behind you and don't fall into your field of sight"
Whatever you say, don't engage into further discussion. Simply don't and stand your ground - you're there for the ride and not for the looks.
This will most likely introduce a split in your group to those who blindly follow Velominati rules and those who, like you, want to enjoy the ride. Only the time will tell if the division remains or dissolves.
Of course some basic rules apply concerning safety and correct gear (road bike).
And worst case scenario is that you become the only outsider. In such case this group wasn't meant for you.
A:
This is almost a question for https://interpersonal.stackexchange.com/.
Any group of people has a spectrum of attitudes and social skills. Just ignore and don't engage with anyone in the group that you don't like, or who acts in a way you find objectionable. Hang out with the people you do like.
A:
Change the riding style. Either go to the mountain biking or touring/endurance riding.
The Rules do not apply to them: to MTB — because it originated from different historical background; to touring — because after two weeks of uninterrupted cycling nobody could possibly care how many hair you have and what color your clothes are, because everyone is covered with the same amount of (off)road dirt.
The touring is the most relaxed style in this regard because it is based on survival principles, and whatever allows you (and your group) to achieve the goal, is appropriate.
And if someone even dares to mention The Rules — just dismiss that unwise attempt: "But they are for roadies!"
| {
"pile_set_name": "StackExchange"
} |
Q:
ES6 Promise - Why does throw from catch() and throw from then() not behave the same way?
I have this piece of ES6 code that invokes a java backend. The java backend normally returns status code 200 and a json payload, but sometimes status code 500 and a json payload. For 200 I want to deserialize the json and pass the resulting object up the promise chain. For 500 I want to deserialize the json and throw the resulting object up the promise chain, i.e. have it hit the catch blocks.
The following code does almost what I want:
invoke(className, methodName, args) {
return this.httpClient
.fetch('/api/' + className + "/" + methodName,
{
method: 'POST',
body: json(args)
})
.catch(response => {
// Function A
throw response.json();
})
.then(response => {
// Function B
return response.json();
});
}
this.invoke("TestService", "testMethod", {a: 1, b: 2})
.then(response => {
// Function C
console.log(response); // prints the actual json object which I expect
}).catch(response => {
// Function D
console.log(response); // prints: [object Promise]
});
Function A gets invoked for 500. Good.
Function B gets invoked for 200. Good.
response.json() returns a promise of a deserialized object in both A and B. Good.
Function A causes function D to be invoked. Good.
Function B causes function C to be invoked. Good.
The argument, response, to function C is the deserialized object. Good.
But, the argument, response, in function D is not the deserialized object, but a promise of a deserialized object.
I've been working at this for a while now, but I'm having trouble explaining to google what my problem is.
Question: Why does returning a promise 'unwrap' the promise for the next function, but throwing a promise passes the promise itself into the next function?
Is there any way I can achieve what I want, which is for function D to get the 'unwrapped' object just like function C?
A:
The reason you get the promise in catch callback, is that this is by specification.
For returned values within a then or catch callback, the rule is that that promise must resolve before the outer promise resolves, and that the resolved value should be the value promised by the returned promise. From the Promises/A+ specs 2.2.7.1:
If either onFulfilled or onRejected returns a value x, run the Promise Resolution Procedure [[Resolve]](promise2, x).
Chapter 3 in that specification further explains what that means.
However, this is not true for thrown exceptions, as can be seen in point 2.2.7.2:
If either onFulfilled or onRejected throws an exception e, promise2 must be rejected with e as the reason.
No attempt is made to recognise e as a promise nor to wait for its resolution. It is thrown as is, and that will be what you get in the next catch.
Solution
The solution is thus to return a promise, but a promise that will throw the resolved value (not a promise):
return response.json().then(data => { throw data });
| {
"pile_set_name": "StackExchange"
} |
Q:
Can not handle managed/back reference 'defaultReference': no back reference property found
I have two model classes. One is
@Entity(name = "userTools")
@Table(uniqueConstraints = @UniqueConstraint(columnNames = { "assignToUser_id","toolsType_id" }))
@Inheritance(strategy = InheritanceType.JOINED)
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "className")
@JsonIgnoreProperties(ignoreUnknown = true)
public class UserTools {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToOne
private ToolsType toolsType;
@OneToMany(mappedBy = "userTools", fetch = FetchType.EAGER, cascade = { CascadeType.ALL }, orphanRemoval = true)
@Cascade(org.hibernate.annotations.CascadeType.DELETE)
@JsonManagedReference
private List<UserToolsHistory> userToolsHistory;
}
and the second is
@Entity(name = "userToolsHistory")
@JsonIgnoreProperties(ignoreUnknown = true)
public class UserToolsHistory {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToOne
private ToolsType toolsType;
@ManyToOne
@JsonIgnore
@JsonBackReference
private UserTools userTools;
private String comments;
}
But on save I'm getting this error:
Can not handle managed/back reference 'defaultReference': no back
reference property found from type [collection type; class
java.util.List, contains [simple type, class
com.dw.model.tools.UserToolsHistory]]
A:
In order to make troubleshooting easier, you can add a different name to each @JsonManagedReference and @JsonBackReference, for example:
@JsonManagedReference(value="userToolsHistory")
private List<UserToolsHistory> userToolsHistory;
This way the error is more meaningful because it prints the reference name instead of 'defaultReference'.
Please indicate which enity you are trying to serialize - UserTools or UserToolsHistory? Anyway you can try adding getters and setters to your entities and then add @JsonIgnore to the "get{Parent}()" in the "child" class.
A:
The exception you are facing stems from the MappingJackson2HttpMessageConverter.
To fix it swap the annotations so you get this :
public class UserTools {
...
@JsonBackReference
private List<UserToolsHistory> userToolsHistory;
...
}
public class UserToolsHistory {
....
@JsonManagedReference
private UserTools userTools;
----
}
This tutorial explains how it must be done : jackson-bidirectional-relationships-and-infinite-recursion
A:
@JsonManagedReference and @JsonBackReference and replacing it with @JsonIdentityInfo
| {
"pile_set_name": "StackExchange"
} |
Q:
How to dynamically render HTML in ASPX without embedding HTML in C# code or C# code in ASPX code?
I'm trying to loop through a data set on the server-side (not a problem) and dynamically render HTML based on the items in the dataset (super basic stuff). Here's the simplified HTML:
<div>item title</div>
<div>item date</div>
<div>item summary</div>
I have 10 items being returned on the back-end, so I'd like to write out 10 iterations of the HTML above. I know this is super basic stuff, but I'd like to do this in ASP.NET without 1) embedding HTML in the C# code 2) embedding C# in the ASPX code
Is this possible? What's the best way to do this? I'm also not using MVC, so please keep that in mind. Thank you.
A:
I would consider using a Repeater for this
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater(v=vs.110).aspx
It's a control designed for repeating arbitrary html based on the content of a data source
| {
"pile_set_name": "StackExchange"
} |
Q:
Infinity Loop Slider Concepts
I wonder what are the best(good readable code, pest practice code,reusability) concepts to build a Infinity-Image-Loop-Slider for a Website using JavaScript/jQuery? I dont what to know how to code the Slide show but what blueprint matches the requirements mention above.
The main focus of my question is how to arrange the pictures to get the impression of a infinity loop Slider.
By look at Code from different Sliders I came across two solutions:
-change the z-Index of all Images each time the next/previous image is displayed.
-change the Position of the Image in the DOM.
But examine and understanding the code of others is very time-consuming - that's why I ask this question :-)
A:
tl;dr - JSBin Example: http://jsbin.com/ufoceq/8/
A simple approach to create an infinite image slider without too much effort is as follows: let say for the sake of simplicity that you have <n> images to slide in a loop, so that after the nth image the next one to visualize is the 1st (and vice-versa).
The idea is to create a clone of first and last image so that
the clone of the last image is prepended before the first one;
the clone of the first image is appended after the last one.
Whatever is the amount of your images, you will need to append at most only 2 cloned elements.
Again for the simplicity, let say that all images are 100px wide and they're wrapped in a container that you move left/right into a clipped mask with overflow: hidden. Then, all images can be easily aligned in a row with display: inline-block and white-space: nowrap set on the container (with flexbox now it is even easier).
For n = 4 The DOM structure would be something like this:
offset(px) 0 100 200 300 400 500
images | 4c | 1 | 2 | 3 | 4 | 1c
/* ^^ ^^
[ Clone of the last image ] [ Clone of the 1st image ]
*/
At the beginning, your container will be positioned with left: -100px (or also margin-left: -100px or even better (for a matter of performance) transform: translateX(-100px) ), so the slider can show the first image. To switch from an image to another you will need to apply a javascript animation over the same property you've previously chosen.
When your slider is currently at the 4th image, you have to switch from image 4 to 1c, so the idea is to execute a callback at the end of the animation that soon reposition your slider wrapper at the real 1st image offset (e.g. you set left: -100px to the container)
This is analogous when your slider is currently positioned on the 1st element: to show the previous image you just need to perform an animation from image 1 to 4c and when animation has been completed you just move the container so the slider is istantly positioned at the 4th image offset (e.g. you set left: -400px to the container).
You can see the effect on the above fiddle: this is the minimal js/jquery code I used (of course the code can be even optimized so the width of the items is not hardcoded into the script)
$(function() {
var gallery = $('#gallery ul'),
items = gallery.find('li'),
len = items.length,
current = 1, /* the item we're currently looking */
first = items.filter(':first'),
last = items.filter(':last'),
triggers = $('button');
/* 1. Cloning first and last item */
first.before(last.clone(true));
last.after(first.clone(true));
/* 2. Set button handlers */
triggers.on('click', function() {
var cycle, delta;
if (gallery.is(':not(:animated)')) {
cycle = false;
delta = (this.id === "prev")? -1 : 1;
/* in the example buttons have id "prev" or "next" */
gallery.animate({ left: "+=" + (-100 * delta) }, function() {
current += delta;
/**
* we're cycling the slider when the the value of "current"
* variable (after increment/decrement) is 0 or when it exceeds
* the initial gallery length
*/
cycle = (current === 0 || current > len);
if (cycle) {
/* we switched from image 1 to 4-cloned or
from image 4 to 1-cloned */
current = (current === 0)? len : 1;
gallery.css({left: -100 * current });
}
});
}
});
});
As mentioned before, this solution doesn't require really much effort and talking about performance, comparing this approach to a normal slider without looping, it only requires to make two additional DOM insertion when the slider is initialized and some (quite trivial) extra logic to manage a backward/forward loop.
Here is another example when you see two elements at once: in that case you need to clone more elements and make some simple changes to the logic
https://codepen.io/fcalderan/pen/bGbjZdz
I don't know if a simpler or better approach exists, but hope this helps anyway.
Note: if you need to also have a responsive gallery, maybe this answer may help too
A:
I've just created the item slider: check it out:
https://github.com/lingtalfi/jItemSlider/blob/master/README.md
It's 600 lines of code, maybe you can simply browse it.
The idea behind it is inspired by the netflix slider (as of 2016-02-24).
Basically, it uses css transform translations, because those are the fastest/slickest in a browser.
http://eng.wealthfront.com/2015/05/19/performant-css-animations/
Now the basic concept behind the slide movement, is that you only display the current visible slice,
but you also have one invisible slice on the left, and another invisible slice on the right.
And, you also have two extra items, one on each side, so that your items look like this:
previous items - prev extra item - main items - next extra item - next items
Only the main items are visible.
The extra items are partially visible.
The previous and next items are invisible.
More details here:
https://github.com/lingtalfi/jItemSlider/blob/master/doc/conception.md
Now when you slide to the right (for instance), you basically append more items to the right side,
and then remove those from the left side.
This technique is the greatest I've encountered so far, because you don't deal with a long list of items (using
cloning without removing the invisible items), which can make your animation slower.
Note: my first try of this slider was actually cloning without removing, it works, but I don't like it:
https://github.com/lingtalfi/jInfiniteSlider
Also, it's item based (rather than pixels based), and in the end, that's what the user expects because
everything is always aligned, as it should be.
| {
"pile_set_name": "StackExchange"
} |
Q:
Simplifying Fractional Exponents and Can You Explain WHY
How do you solve questions like $2^{1/2}$ and can you explain how this works?
A:
It is known that
x^a × x^b = x^(a+b)
From that, try to input a = b = 0.5
, we get
(x^0.5)×(x^0.5)=x^(0.5+0.5)=x^1=x
(x^0.5)^2=x
By taking the square root of both sides, we obtain
x^0.5= \sqrt{x}
Note that we only take the positive value for the answer.
| {
"pile_set_name": "StackExchange"
} |
Q:
Настройка модального окна bootstrap
Когда через js вызываю модальное окно - modal(), то оно появляется в начале страницы, т.е. если страницы прокручена вниз, то что бы увидеть окно, нужно прокрутить страницу вверх.
Помечу что это только на моб. устройствах.
Как это исправить?
A:
В оригинальном бутстрапе все хорошо в этом вопросе. Вероятно стили вашего сайта переопределяют какие-то стили, которые используются в бутстарпе.
Попробуйте через инспектор сравнить все стили, всех тегов окна, у вас на странице и на оригинальном сайте. Думаю вы найдете различия, которые дадут ответ на вопрос.
| {
"pile_set_name": "StackExchange"
} |
Q:
If $P$ partitions $G$ and $P \simeq \mathbb{Z}_2^+$, then what can we say about $G$?
If $P$ partitions a group $G$ and $P \simeq \mathbb{Z}_2^+$, then what can we say about $G$?
Reason: this showed up in trying to prove that if a partition $P$ of a group $G$ is such that for any two elements $A,B \in P$ the product $AB$ is entirely contained in another element $C$, then then one of the elements is a normal subgroup $N$ of $G$ and $P = G/N$. I'm doing this by induction and the $n = 2$ case results in $P$ must be $\mathbb{Z}_2^+$. Well for that case I don't need the result that $P = \mathbb{Z}_2^+$, I later found out, but it still seems like an interesting question, so I posted it here.
A:
Your general result on partitions can be reformulated in terms of equivalence relations $R$ on $G$ which are compatible with the operation, that is, $a R a'$ and $b R b'$ imply $ab R a'b'$. Then the equivalence class $N = [e]$ of the identity is a normal subgroup, and $[a] = a N$.
(As usual, if $P$ is a partition with your property, then a compatible equivalence relation $R$ is given by $a R a'$ if and only if there is $A \in P$ such that $a, a' \in A$. And if $R$ is a compatible equivalence relation, then $P = \{ [a] : a \in G \}$ is a partition with your property, where $[a] = \{ x \in G : x R a \}$.)
In your particular case when $P \cong \mathbb{Z}_2^+$, you are just considering a group which has a (normal) subgroups of index $2$. The normal subgroup is the element of the partition containing the identity.
| {
"pile_set_name": "StackExchange"
} |
Q:
For what values the real parameter t is a matrix diagonalisable?
What to do with number 25 in the matrix?
A:
A matrix is diagonalizable if the sum of $\dim \ker (A - \lambda I)$ over all eigenvalues $\lambda$ of $A$ is $n$.
When $t = 1$, the only eigenvalue of $A$ is $1$. However, $\dim \ker(A - 1 I) < 3$, so $A$ is not diagonalizable.
However, if $t \neq 1$, then the eigenvalues of $A$ are $1$ and $t$. $\dim \ker (A - tI)$ is $1$. We then note that $\dim \ker (A - tI)$ is $1$ whenever $t \neq 24$, and is $2$ when $t = 24$.
Thus, we find that $A$ is diagonalizable if and only if $t = 24$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Setting tint color for embedded UISearchbar in Navigation bar
I have an app that has a blue tint theme to the entire UI. I also have an embedded search bar in the Navigation Bar on my initial view. My button text color for the app is white and declare that in the app delegate using:
[[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
Problem is that this causes the embedded search bar to hide the cursor when it is selected because of the white tint affecting the search bar. I have tried to specifically set the tint of the search bar to [UIColor blueColor] using two methods but have had no luck. The two ways I have tried to refrence the UISearch bar are:
[self.navigationController.searchDisplayController.searchBar setTintColor:[UIColor blueColor]];
and
[searchBar setTintColor:[UIColor blueColor]]
The searchBar should be referenced properly.
Nothing I do to these outlets affect the embedded search bar at all.
A:
Under iOS 7 (and beyond, presumably), you'll probably want to set barTintColor on your navigation and search bars to change the wrapping UI color.
[searchBar setBarTintColor:[UIColor blueColor]]
For the same appearance, you will want to use barTintColor when in iOS 7+ and use tintColor for anything earlier. If you try changing tintColor in iOS 7, you will change your cursor color, resulting in that "hidden" cursor issue you mention.
A:
Had the same problem. Solved it by using this code after embedding the search bar into navigation bar.
self.navigationItem.titleView.tintColor = [UIColor blueColor];
Probably not the best solution, but it works.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I know where the segment of memory is all Zero
I mean, I malloc a segment of memory, maybe 1k maybe 20bytes..
assume the pointer is pMem
How can I know the content pMem refered is all Zero or \0
. I know memcmp but the second parameter should another memory address...
thanx
A:
As others have already suggested you probably want memset or calloc.
But if you actually do want to check if a memory area is all zero, you can compare it with itself but shifted by one.
bool allZero = pMem[0] == '\0' && !memcmp(pMem, pMem + 1, length - 1);
where length is the number of bytes you want to be zero.
A:
Since Mark's answer has provoked some controversy:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#ifndef count
#define count 1000*1000
#endif
#ifndef blocksize
#define blocksize 1024
#endif
int checkzeros(char *first, char *last) {
for (; first < last; ++first) {
if (*first != 0) return 0;
}
return 1;
}
int main() {
int i;
int zeros = 0;
#ifdef EMPTY
/* empty test loop */
for (i = 0; i < count; ++i) {
char *p = malloc(blocksize);
if (*p == 0) ++zeros;
free(p);
}
#endif
#ifdef LOOP
/* simple check */
for (i = 0; i < count; ++i) {
char *p = malloc(blocksize);
if (checkzeros(p, p + blocksize)) ++zeros;
free(p);
}
#endif
#ifdef MEMCMP
/* memcmp check */
for (i = 0; i < count; ++i) {
char *p = malloc(blocksize);
if (*p == 0 && !memcmp(p, p + 1, blocksize - 1)) ++zeros;
free(p);
}
#endif
printf("%d\n", zeros);
return 0;
}
Results (cygwin, Windows XP, Core 2 Duo T7700 at 2.4 GHz):
$ gcc-4 cmploop.c -o cmploop -pedantic -Wall -O2 -DEMPTY && time ./cmploop
1000000
real 0m0.500s
user 0m0.405s
sys 0m0.000s
$ gcc-4 cmploop.c -o cmploop -pedantic -Wall -O2 -DLOOP && time ./cmploop
1000000
real 0m1.203s
user 0m1.233s
sys 0m0.000s
$ gcc-4 cmploop.c -o cmploop -pedantic -Wall -O2 -DMEMCMP && time ./cmploop
1000000
real 0m2.859s
user 0m2.874s
sys 0m0.015s
So, the memcmp is taking approximately (2.8 - 0.4) / (1.2 - 0.4) = 3 times as long, for me. It'd be interesting to see other people's results - all my malloced memory is zeroed, so I'm getting the worst-case time for each comparison, always.
With smaller blocks (and more of them) the comparison time is less significant, but memcmp is still slower:
$ gcc-4 cmploop.c -o cmploop -pedantic -Wall -O2 -DEMPTY -Dblocksize=20 -Dcount=10000000 && time ./cmploop
10000000
real 0m3.969s
user 0m3.780s
sys 0m0.030s
$ gcc-4 cmploop.c -o cmploop -pedantic -Wall -O2 -DLOOP -Dblocksize=20 -Dcount=10000000 && time ./cmploop
10000000
real 0m4.062s
user 0m3.968s
sys 0m0.015s
$ gcc-4 cmploop.c -o cmploop -pedantic -Wall -O2 -DMEMCMP -Dblocksize=20 -Dcount=10000000 && time ./cmploop
10000000
real 0m4.391s
user 0m4.296s
sys 0m0.015s
I am slightly surprised by this. I expected memcmp to at least compete, since I expect it to be inlined and to be optimised for small sizes known at compile time. Even changing it so that it tests an int at the start and then 16 bytes of memcmp, to avoid the unaligned worst case, doesn't speed it up much.
A:
If you're testing it, and then only going to use it if it's zero, then be aware you have a race-condition, because the method suggested by @Mark Byers doesn't have an atomic test/set operation. It'll be hard to get the logic correct in this case.
If you want to zero it if it's not already zero, then just set it to zero as that will be faster.
| {
"pile_set_name": "StackExchange"
} |
Q:
Elementary graph theory question
I found no one I graded so far had given a correct proof. The embarassing side is I also do not know how to find a simple proof. So I decided to ask. The question is:
Eight students in a class are asked how many of the other seven student they know. One student knows all the other students. But only two students know the same number of students. Show that these two students know each other.
A:
I don't know if this is simple enough, but here goes.
Everyone knows between zero and seven. Since someone knows seven, no one knows zero. Since only two know the same number, the degrees of the vertices in the acquaintanceship graph must be 1, 2, 3, 4, 5, 6, 7, with one repeat.
Since there's a 7 and a 6, there can't be two 1s. So there's a single 1.
Since there's a single 1 and a 2, there can't be two 6s. So there's a single 6.
Since there's a 7, a 6, and a 5, there can't be two 2s. So there's a single 2.
Since there's a single 1 and a single 2 and a 3, there can't be two 5s. So there's a single 5.
Since there's a 7, a 6, a 5, and a 4, there can't be two 3s. Now we've ruled out everything but two 4s.
The 7 knows everyone. The 6 knows all but the 1. The 5 knows all but the 1 and the 2. Each 4 knows all but the 1, 2, and 3. So, the 4s know each other.
| {
"pile_set_name": "StackExchange"
} |
Q:
Bug when collapsing a factor into groups, with forcats
I have the following data frame:
df = data.frame(a = 1:5) %>% as_tibble()
I want to collapse the values 1 and 3 into 'group1', 2 and 4 into 'group2' and the other values (e.g. 5) into 'Other'. I thought fct_collapse() would be the perfect function, but it does strange things...
df %>%
mutate(
a = as.character(a),
a_collapse = fct_collapse(a,
group1=c('1', '3'),
group2 = c('2', '4'),
group_other = TRUE))
Yet, the value 3 got 'group2' instead of 'group1'. Do you know why is this happening? I guess this has to do with the fact that the values of my factor are numerics but did not find a way to deal with that. Any idea?
Some posts deal with similar issues but did not help me in this case:
Replace factors with a numeric value
Joining factor levels of two columns
A:
A simple case_when ?
library(dplyr)
df %>%
mutate(a_collapse = factor(case_when(a %in% c(1, 3)~"group1",
a %in% c(2, 4) ~"group2",
TRUE ~ 'Other')))
# A tibble: 5 x 2
# a a_collapse
# <int> <fct>
#1 1 group1
#2 2 group2
#3 3 group1
#4 4 group2
#5 5 Other
As far as fct_collapse is concerned the issue seems to be from including group_other as referenced in this issue on Github. If we remove that it works as expected but not giving any value to other groups.
df %>%
mutate(
a = as.character(a),
a_collapse = forcats::fct_collapse(a,
group1=c('1', '3'),
group2 = c('2', '4')))
# A tibble: 5 x 2
# a a_collapse
# <chr> <fct>
#1 1 group1
#2 2 group2
#3 3 group1
#4 4 group2
#5 5 5
This bug has been fixed in the development version of forcats and would be available in the next release.
| {
"pile_set_name": "StackExchange"
} |
Q:
Linq.Js Group By with Count
I have the following array:
var data= [{ "Id": 1, "Name": "NameOne"}
{ "Id": 2, "Name": "NameTwo"}
{ "Id": 2, "Name": "NameTwo"}]
{ "Id": 3, "Name": "NameThree"}]
Using linq.js I would like to return the following array:
var data= [{ "Id": 1, "Name": "NameOne", Total: 1}
{ "Id": 2, "Name": "NameTwo", Total: 2}
{ "Id": 3, "Name": "NameThree", Total: 1}]
This means that I need to use GroupBy() with a Count(). I am not sure how to apply this using the linq.js reference.
A:
It's simple really:
var data = [
{ Id: 1, Name: 'NameOne' },
{ Id: 2, Name: 'NameTwo' },
{ Id: 2, Name: 'NameTwo' },
{ Id: 3, Name: 'NameThree' }
];
var query = Enumerable.From(data)
// GroupBy (keySelector, elementSelector, resultSelector, compareSelector)
.GroupBy(
null, // (identity)
null, // (identity)
"{ Id: $.Id, Name: $.Name, Total: $$.Count() }",
"'' + $.Id + '-' + $.Name"
)
.ToArray();
Use the overload of GroupBy() that includes the resultSelector, you'll want to grab the count of the grouped items (the second parameter).
| {
"pile_set_name": "StackExchange"
} |
Q:
Bootstrap dropdown submenu closing upstream submenu
I have a two-level dropdown that's working great, but when I add another level, the JS seems to be removing the open class from the previous submenu, which means that the desired third-level menu can't be seen, even though it does get the open class added.
I've tracked it down to this JS:
$(function() {
$('li.dropdown-submenu').on('click', function(event) {
event.stopPropagation();
if ($(this).hasClass('open')){
$(this).removeClass('open');
} else {
$('li.dropdown-submenu').removeClass('open');
$(this).addClass('open');
}
});
});
This is, I think, doing the undesired closing of the previous submenu. The HTML is very similar to this example.
Using an adaptation of the JS from that example, I get the third level, but then any given open submenu doesn't automatically close when clicking another submenu.
$(document).ready(function(){
$('.dropdown-submenu a').on("click", function(e){
$(this).next('ul').toggle();
e.stopPropagation();
e.preventDefault();
});
});
Need the best of both here!
A:
I think you almost had it, you just needed to look for the different clicks.
The approach I took below was to handle all a clicks but then check to see if it had a class of test which then followed your code verbatim or else, if it didn't have a class of test it then hides all the submenus and goes to it's default href.
<script>
$(document).ready(function(){
$('.dropdown-submenu a').on("click", function(e){
if ($(this).hasClass('test')) {
$(this).next('ul').toggle();
e.stopPropagation();
e.preventDefault();
} else {
$('.dropdown-submenu ul').hide();
}
});
});
</script>
Your updated working example: https://www.w3schools.com/code/tryit.asp?filename=FUB7ECWP20DA
| {
"pile_set_name": "StackExchange"
} |
Q:
Converting a list of digits to a number
I was wondering if there was a way to take a list of numbers (digits), and truncate the numbers together to be one large number (not addition) in Scheme. For example, I would want
(foo '(1 2 3 4))
;=> 1234
Does Scheme have a built in function to do this?
A:
There are a number of languages that are in the Scheme family, and there are a few versions of Scheme, too. If you're using one, e.g., Racket, that includes a left associative fold (often called foldl, fold, or reduce, though there are other variations, too), this is pretty straightfoward to implement in terms of the fold. Folds have been described in more detail in these questions and answers:
Finding maximum distance between two points in a list (scheme) This question includes a description of how fold can be viewed as an iterative construct (and in Scheme, which mandates tail call optimization, is compiled to iterative code), and also includes an implementation of foldl for Schemes that don't have it.
Flattening a List of Lists This question is about a somewhat unusual fold, and how it (or a standard fold) can be used to flatten a list.
scheme structures and lists This question has an example of how you might adjust the function that you pass to a fold to achieve slightly different behavior. (I also include an opinionated (but true ;), I assure you) comment about how Common Lisp's reduce provides a somewhat more convenient interface than what's provided in some of the Scheme libraries.
Here's what the code looks like in terms of foldl:
(define (list->num digits)
(foldl (lambda (digit n)
(+ (* 10 n) digit))
0
digits))
> (list->num '(1 2 3 4))
1234
If your language doesn't have it, foldl is pretty easy to write (e.g., my answer to the one of the questions above includes an implementation) and use the preceding code, or you can write the whole function (using the same approach) yourself:
(define (list->num-helper digits number-so-far)
(if (null? digits)
number-so-far
(list->num-helper (cdr digits)
(+ (* 10 number-so-far)
(car digits)))))
(define (list->num digits)
(list->num-helper digits 0))
You can make that a bit more concise by using a named let:
(define (list->num digits)
(let l->n ((digits digits)
(number 0))
(if (null? digits)
number
(l->n (cdr digits)
(+ (* 10 number)
(car digits))))))
| {
"pile_set_name": "StackExchange"
} |
Q:
mysql query doesn't work correctly in php on server unlike xampp server
I am working on a Persian site with utf8_persian_ci collation.
my PHP code :
<?php
header('Content-Type: text/html; charset=utf-8');
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
mysql_query("SET NAMES 'utf8'");
mysql_query("SET character_set_connection='utf8'", $dbhandle);
$selected = mysql_select_db("news",$dbhandle);
$str = 'فوتبال، فوتسال';
echo $str . '<br>';
$query = "SELECT * FROM news WHERE link_num='92051810161'";
$result = mysql_query($query);
if (mysql_num_rows($result) == 1) {
while ($row = mysql_fetch_array($result)) {
$from_db = $row{'category'};
echo $from_db . '<br>';
}
}
if ($str == $from_db) {
echo "string";
}
?>
the problem is that the last condition of code works in XAMP server and prints string but when I run this code on Server the result is so different!
Result on xamp server ( localhost ) :
فوتبال، فوتسال
فوتبال، فوتسال
string
Result on Server :
فوتبال، فوتسال
فوتبال، فوتسال
Also strpos() doesn't work on server but it works correctly in localhost!
I think the result of query on server is different with Xamp server on localhost, but I can't find the result.
Database Screenshot :
A:
I changed the Charset Encoding to Unicode(UTF-8) in browser and then changed the code in Server, I don't know what happened but the problem solved successfully!
| {
"pile_set_name": "StackExchange"
} |
Q:
Status Report sending using python
I used this script to sending status report to my team lead. It will read the status from the file Readme.md. Here i already wrote my status. if this script execute on target_time or greater than it will execute the mailer function otherwise ask for confirmation
# importing messagebox for confirmation diaglog box
import tkMessageBox
import smtplib
from time import gmtime, strftime
def mail_send():
target_time = 02
# By using strftime we only current time in hours, it returns string like
# "12"
current_Time = strftime("%H")
print current_Time
# convert str to number
cTime = int(current_Time)
def sub_mailer():
print "Mailer loading ...."
s = smtplib.SMTP('smtp.gmail.com', 587)
s.starttls()
s.login('[email protected]', 'anypass')
f = open('Readme.md', 'r')
filedata = f.read()
subject = "Today Update"
msg = 'Subject:{}\n\n{}'.format(subject, filedata)
s.sendmail('[email protected]', '[email protected]',
msg)
s.quit()
f.close()
# get time using time module
if target_time <= cTime:
sub_mailer()
else:
status = tkMessageBox.askquestion(
"Shift hours is not completed. Shall i send a mail", icon="warning")
if status == "yes":
sub_mailer()
else:
print "Mail sending process was canceled by user"
A:
First of all, Welcome to CodeReview!
Let's analyse the code to see what could be improved here.
current_Time = strftime("%H")
print current_Time
# convert str to number
cTime = int(current_Time)
A few things could be improved here:
Too many calls! current_Time = int(strftime("%H")) would have sufficed
the comment # convert str to number adds no real value to the code readability
s = smtplib.SMTP('smtp.gmail.com', 587)
Use better names, s does not make it clear what it does.
Avoid "magic" numbers-- it would have been better to have these as named constants
f = open('Readme.md', 'r')
Use context managers (with open ... as ...), see the docs
Some random thoughts
Use guards-- that way your script can be imported by other modules. Might not need it here, but I think it is good practice to always use them.
Consider upgrading your python-2.7 to python-3 and port all your code, since the Python 2 End Of Life is just 2 years away!
A:
Ludisposed probably deserves the accept, just wanted to point out a few other pet peeves of mine.
Never store credentials in your code.
This line:
s.login('[email protected]', 'anypass')
is a disaster waiting to happen. All it takes for the whole Internet to get your credentials is for for you to forget to sanitize it one time. Your code should read the credentials from a config file or something similar. See configparser (2.7, 3.x) module for one way to do it, or _winreg (2.7) / winreg (3.x) module if you're an all-Windows shop.
In fact a lot of your constants should be read from a config.
target_time, the mail server and port, the path to the file you're scanning, subject, from and to emails. Much easier to edit a config than to have to scan your code for the proper places to edit.
Functions should perform one job
Your mail_send() function takes no parameters and does all the work. It would be better for it to take parameters corresponding to all of the config items, and then have another function e.g. main() get the configuration details and then pass them as parameters to mail_send(). The general principle is called the single responsibility principle. This keeps functions shorter thus easier to understand. They also end up easier to test, debug, edit, reuse, etc. Ideally each function should be able to fit on your screen so you can take it in at a glance.
Inconsistent user interface
Some of your code uses print, others use a tk message box. What's the reason for this? If you have to pass this onto someone else, will they expect and be able to intuitively comprehend this?
I'm generally against print anyway, unless the function of the code is to generate output. For status messages (I believe all of your print) you ought to be using the logging (2.7, 3.x) module.
| {
"pile_set_name": "StackExchange"
} |
Q:
Accepted Answer with lot of Down Votes?
In this question, the accepted answer has lots of down votes. Should the community revise the accepted answer?
There may be other questions like the one I've linked to, that's just an example.
A:
The person who asked the question chose that as the answer that worked for them, which is their right. The community gets to decide whether that's the "best" answer by voting, which they've done. The answer the community voted as most useful is right underneath the answer that the person who asked the question thought was most useful (provided you've not done anything funny with the way you sort answers), so it's hardly difficult to find.
Also, note the comment by the person who asked the question where someone queried why he'd accepted the answer he did:
No need to be concerned. My final
solution went ahead with the
enterprise library for a few reasons,
firstly we were using a few other
features of the library, secondly I
liked the implementation and thirdly
it was powerful enough for our needs.
In other words, the answer met his needs, which is sort of the point of the site.
What's the problem?
| {
"pile_set_name": "StackExchange"
} |
Q:
How to replace data in array
Current array structure
array:2 [
"name" => "john"
"data" => array:3 [
0 => array:2 [
"id" => 191109
"ref_num" => "INV9002"
]
1 => array:2 [
"id" => 191110
"ref_num" => ""
]
]
I'm trying to copy id to ref_num if ref_num is null. So far I did try like
Code
$izero = //that data structure above
foreach($izero['data'] as $key => $value) {
if($value['ref_num'] === null) {
$value['ref_num'] = $value['id'];
}
$izero['data'] = $value;
}
$echo $izero
The result in izero missed the second array. It only keep the first array. Example if my data got 50 arrays, now it become the only one with first array.
The expected result should be like
array:2 [
"name" => "john"
"data" => array:3 [
0 => array:2 [
"id" => 191109
"ref_num" => "INV9002"
]
1 => array:2 [
"id" => 191110
"ref_num" => "191110"
]
]
A:
The other answers show how to fix this using a reference variable. If you want to assign to the array, you need to index it with $key:
foreach($izero['data'] as $key => $value) {
if($value['ref_num'] === null) {
$value['ref_num'] = $value['id'];
}
$izero['data'][$key] = $value;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Adding custom attributes to script tag via Scripts.Render
In my MVC application I would like to use require.js. I am trying to use following way;
@Scripts.Render("~/bundles/require")
in require.js documentation it is documented as;
<!--This sets the baseUrl to the "scripts" directory, and
loads a script that will have a module ID of 'main'-->
<script data-main="scripts/main.js" src="scripts/require.js"></script>
So I need to set data-main="scripts/main.js" section in MVC part.
How can I achive to add extra attributes via Scripts.Render function?
A:
Found out needs to use following way;
@Scripts.RenderFormat("<script type=\"text/javascript\" data-main=\"/JavaScript/main.js\" src=\"{0}\"></script>", "~/bundles/require")
| {
"pile_set_name": "StackExchange"
} |
Q:
Which image for steganography?
Which images are suitable for image steganography(Storing behind an image)?
In particular JPEG,BMP or TIFF?
As JPEG is lossy so is it possible to lose any data if it is hidden behind the image?(using LS*strong text* technique)
A:
Technically any of these can be used, but you are more likely to see jpeg in use in the wild. Because the steganography is a basically introducing imperfections in the image to hide a message, the imperfections will be less noticeable in an already lossy format, whereas if you had some off pixels in a bitmapped image, one is more likely to notice the discrepancy.
Your question about being lossy only applies if someone tries to resave the image. For example if I opened your image with a secret message hidden in it in photoshop and then saved it back out as a jpeg, the image would likely change and destroy your message. This is not the case when sending a file via e-mail or the web (except in the case of some ISPs that implement jpeg compression to speed up browsing speeds for slower connections like dialup).
| {
"pile_set_name": "StackExchange"
} |
Q:
How to set up two transaction managers?
I am working on a Spring application that has already set up a transaction manager.
In a configuration class it has already set up an entity manager reading from a persistence.xml and then sets up a JpaTransactionManager.
I am required to create a Spring Batch implementation and the problem is that, as I have found out from different posts, when using the @EnableBatchProcessing annotation it seems that a second transaction manager is registered and I cannot persist data inside my tasklets.
Is it possible to use two transaction managers or configure my application in a way that I will be able to persist my data?
Can you please provide me with sample code?
Thanks in advance.
EDIT:
This is the application config class, which already exists in the application:
@Configuration
@ComponentScan({
...
})
@EnableJpaRepositories("...")
@EnableTransactionManagement
@EnableJpaAuditing
@Import({SecurityConfig.class})
@PropertySource("classpath:application.properties")
public class ApplicationConfig {
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setPersistenceXmlLocation("classpath:/META-INF/persistence.xml");
return factory;
}
@Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
this is my batch config:
@Configuration
@EnableBatchProcessing
public class BatchConfig {
@Autowired
private JobBuilderFactory jobs;
@Autowired
private StepBuilderFactory steps;
@Autowired
@Qualifier("entityManagerFactory")
private LocalEntityManagerFactoryBean batchEntityManagerFactory;
}
from which I am getting an:
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.orm.jpa.LocalEntityManagerFactoryBean com.xxx.xxx.xxx.configuration.BatchConfig.batchEntityManagerFactory; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.orm.jpa.LocalEntityManagerFactoryBean] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.sp
ringframework.beans.factory.annotation.Qualifier(value=entityManagerFactory)}
EDIT 2:
This is what I have done:
@EnableJpaRepositories("xxx")
@Configuration
@EnableBatchProcessing
@PropertySource("classpath:application.properties")
public class BatchConfig {
@Autowired
private JobBuilderFactory jobs;
@Autowired
private StepBuilderFactory steps;
@Autowired
private ReportReaderProcessor reportReaderProcessor;
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setPersistenceXmlLocation("classpath:/META-INF/persistence.xml");
return factory;
}
@Bean
public BatchConfigurer batchConfigurer() {
return new DefaultBatchConfigurer() {
@Override
public PlatformTransactionManager getTransactionManager() {
JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
jpaTransactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return jpaTransactionManager;
}
};
}
@Bean
public JobRepository jobRepository() throws Exception {
MapJobRepositoryFactoryBean factory = new MapJobRepositoryFactoryBean();
factory.setTransactionManager(batchConfigurer().getTransactionManager());
return (JobRepository) factory.getObject();
}
@Bean
public SimpleJobLauncher simpleJobLauncher() throws Exception {
SimpleJobLauncher simpleJobLauncher = new SimpleJobLauncher();
simpleJobLauncher.setJobRepository(jobRepository());
return simpleJobLauncher;
}
@Bean
public Step readReports() {
return steps
.get("readReports")
.tasklet(reportReaderProcessor)
.build();
}
@Bean
public Job reportJob() {
return jobs
.get("submitReportJob")
.start(readReports())
.build();
}
}
but now I am getting an other error:
15:47:23,657 ERROR [stderr] (pool-36-thread-1) org.springframework.transaction.InvalidIsolationLevelException: DefaultJpaDialect does not support custom isolation levels due to limitations in standard JPA. Specific arrangements may be implemented in custom JpaDialect variants.
A:
There is an open issue for this case here: https://jira.spring.io/browse/BATCH-2294 which is fixed in version 4.1.0.M3. To use a custom transaction manager, you need to provide a BatchConfigurer in your application context, for example:
@Bean
public BatchConfigurer batchConfigurer() {
return new DefaultBatchConfigurer() {
@Override
public PlatformTransactionManager getTransactionManager() {
return new MyTransactionManager();
}
};
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Does this seem like discrimination?
I have 12+ years experience in call centers, I have started at the bottom and worked my way to the top over about 8 years. I have held every position there is in a call center. When I was on the phones as a sales rep I was consistently a top rep, I know how to sell and my resume shows it.
I live in Maine, in my area there are only so many call centers, so this company is pretty much the only game in town for this type of work. I applied once in June, had an interview which seemed to go great the guy told me the training class was starting in a week and he would call Wednesday with more info. When I get home I already had an email from them saying thanks but no thanks! This made no sense after what he had told me, I asked a friend to find out what he could and he said the guy thought I only wanted management but he would contact me now. Never heard from him..
Now its October, my unemployment is running out and I need a job badly, one of my past co-managers was a manager at this company now so he put in a good word, got me an interview the next day, it was with the same guy. So he told me the same thing again about before but I said no worries. So again the interview goes great he seems interested! So hes interested, i have a recommendation from a manager and a perfect resume for a call center job, I 'm thinking I am in! When I left the interview the guy said he was going to talk to the other manager (my friend) before he made the decision.
Again, when i got home already was an email saying thanks but no thanks! So obviously after our interview he talked to nobody, which I later confirmed with my friend, and immediately sent me the email.
I am disabled, I had a major brain injury in 2006 leaving me with long term memory problems and some short term however this never effected my ability on the phones!
I feel like I am being discriminated against for some reason because I know how call centers hire, they never tell anyone no unless they have a record, I have no record at all.
Do you think this could qualify as discrimination??
A:
From what you are saying, there is no way that manager could know that you had a brain injury in 2006 unless either you or your friend spilled the beans. Given that your short-term cognitive abilities are not affected, there is no way for that manager to suspect that you have a brain injury. If he doesn't know that you have a brain injury, how could he discriminate against you on the basis of a brain injury that he doesn't know you have?
I suggest you apply to other companies and that you use your friend as reference. Because as long as that manager is in there, you are not getting in.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to remove all alphabets, numbers '@' and '.' from a file in bash?
I have a data of email id's and i want to check if email id's contain any special character other than '@' and '.' so i want to remove all the alphabets, numbers, '@' and '.'. I know to remove all digits we can use following command:
sed 's/[0-9]*//g' input.txt > output.txt
Sample Input:
[email protected]
[email protected]
hira#[email protected]
shop@lov$echarms.jp
[email protected]
Sample Output:
-
#
$
-
Can anyone help me on this?
A:
with tr:
tr -d '[[:alnum:]].@' <filename
| {
"pile_set_name": "StackExchange"
} |
Q:
After submitting a comment, how can I get updates in my inbox?
I would like to know, if it is possible to have an update in the Global Inbox (top left) for questions where I only placed a comment.
Sometimes, I ask a question in a comment to the questioning person. And I would obviously like to know if he commented back to me.
One workaround is putting it as a favourite, but is it also possible to have a notification in my inbox after placing a comment?
Thanks in advance,
I hope I'm asking the right question on the right stackExchange =)
A:
In theory, if the person is replying to your comment they'll use @Marnix in it, which will add the comment to your inbox. If they don't do that it's assumed the comment wasn't meant for you, and you don't get bothered about it (notifying everyone in a comment thread every time anyone posts a comment would probably get annoying)
| {
"pile_set_name": "StackExchange"
} |
Q:
JavaScript / AJAX / Servlet compare Strings
I am trying to compare a string that is returned from servlet
Servlet page returns this:
out.println("pass");
JavaScript:
function Return() {
if (ajax.responseText === "pass") {
document.getElementById("pass").innerHTML = "This is valid number!";}
Now I have output the ("ajax.responseText") and it returns "pass" but I can't still validate it in the IF statement.
I tried using (.equal("pass") i tried with == and I even tried "var value = ajax.responseText; and then tried value === "pass")
Yes I also tried .toString()..
It just never validates it correctly it always goes to ELSE statement...
A:
println usually appends a line break at the end of the string (the "ln" in println stands for "line") and thus the string value returned by the server is actually "print\n" (or something similar), which is not equal to "pass".
If available, use
out.print("pass");
which doesn't append a line break.
Or trim the response before comparison.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get the java program completion status from unix shell script?
For example we are executing the below statement and we want to process further based on the status of java execution.
java -classpath $CLASSPATH com.heb.endeca.batch.BatchManager "param1" "param2" "param3"
A:
If your Java code exits with System.exit(status), you can get the status in Bash like this:
Java:
public class E {
public static void main(String[] args) {
System.exit(42);
}
}
Bash:
$ java E
$ echo $?
42
$? is the exit status of the last finished process.
| {
"pile_set_name": "StackExchange"
} |
Q:
FilterPane Grails Plugin: how to hide the combo box
I'm learning how to use the next search plugin: http://grails.org/plugin/filterpane
I'm executing the example project of the plugin: https://github.com/Grails-Plugin-Consortium/grails-filterpane-demo/
I want to hide the combo box:
For example, let say we want to filter as follow:
Is it possible with this plugin? Do you recommend to use another one? Do you recommend to do it manually without any plugin?
A:
You have to override filterpane template.
Create file grails-app/views/_filterpane/_filterpaneProperty.gsp
Insert original source.
Change select tag with a hidden field.
| {
"pile_set_name": "StackExchange"
} |
Q:
Uncaught ReferenceError: Rx is not defined
This my code HTML file
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app"></div>
<script src="../node_modules/rxjs/bundles/rxjs.umd.min.js"></script>
<script src="./Test.js"></script>
</body>
</html>
This my code Js file
const stream = Rx.Observable.create(...);
When I want to use Rx I get Error.
Uncaught ReferenceError: Rx is not defined
I can’t understand what the problem is.
A:
In RxJs 6 the object is called rxjs
const stream = rxjs.Observable.create(...);
or
const { Observable } = rxjs;
const stream = Observable.create(...);
If you are using npm then you need to import the parts you need as the main thing about RxJs 6 over 5 is that it is tree shakeable
import { Observable } from 'rxjs';
const stream = Observable.create(...);
| {
"pile_set_name": "StackExchange"
} |
Q:
Remove a row of ListView attached with AsyncTaskLoader
I have implemented a ListView with ListFragment which is attached with a AsyncTaskLoader. The data is populated from database. Each row has a menu button for PopUp which further has 2 options (Edit & Delete).
What I want is, when any of the option is clicked, that object is deleted from database.
How can I get id of the deleted object?
My Adapter:
public class ConferenceAdapter extends ArrayAdapter<Conference> implements View.OnClickListener, PopupMenu.OnMenuItemClickListener{
private Context context;
private final LayoutInflater mInflater;
public ConferenceAdapter(Context context) {
super(context, R.layout....);
this.context = context;
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void setData(List<Conference> data) {
clear();
if (data != null) {
addAll(data);
}
}
/**
* Populate new items in the list.
*/
@Override public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Conference conference = (Conference)getItem(position);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item_conference_fragment, parent, false);
holder = new ViewHolder();
...
holder.btnOverflow = (ImageButton)convertView.findViewById(R.id.btn_overflow);
...
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
holder.btnOverflow.setOnClickListener(this);
...
return convertView;
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.btn_overflow) {
PopupMenu pm = new PopupMenu(context, v);
Menu menu = pm.getMenu();
menu.add("Edit");
menu.add("Delete");
pm.show();
pm.setOnMenuItemClickListener(this);
}
}
@Override
public boolean onMenuItemClick(MenuItem item) {
OnPopUpListener listener = (OnPopUpListener)context;
if (item.getTitle().equals("Delete")) {
// What logic should I use here?
// How can I get current Object as I do not have a list?
listener.onDelete(...);
}
return false;
}
static class ViewHolder {
ImageButton btnOverflow;
...
}
}
A:
Sometimes, good coding practices may lead to difficult situation. Anyhow, I moved the event listeners inside getView(...) and I was able to access the object. May be helpful for someone in future.
/**
* Populate new items in the list.
*/
@Override public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
final Conference conference = (Conference)getItem(position);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item_conference_fragment, parent, false);
holder = new ViewHolder();
holder.btnOverflow = (ImageButton)convertView.findViewById(R.id.btn_overflow);
...
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
final ViewHolder finalHolder = holder;
holder.btnOverflow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finalHolder.btnOverflow.setTag(position);
PopupMenu pm = new PopupMenu(context, v);
Menu menu = pm.getMenu();
menu.add("Edit");
menu.add("Delete");
pm.show();
pm.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getTitle().equals("Delete")) {
conferenceTable.delete(conference.id);
} else if (item.getTitle().equals("Edit")) {
}
return false;
}
});
}
});
...
return convertView;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to run tests on every code change in IntelliJ IDEA from Scala sbt project?
I have a new Scala/sbt project set up in IntelliJ IDEA with ScalaTest and jUnit interface successfully installed as dependencies. I have one test that passes when I hit run or debug.
My problem is that it doesn't rerun if I change something. I have to hit run or debug again and then it runs and gives the expected response.
How do I set up IntelliJ IDEA (with or without sbt) to run all tests every time the code changes? Is it possible to run the tests related to the files that were changed only?
A:
As answered in comment by Boris the Spider you can run
> ~test
from sbt shell. Hopefully sbt and IntelliJ can integrate better via sbt server, but I don't think it's currently possible.
| {
"pile_set_name": "StackExchange"
} |
Q:
Swift iOS -How to manage Notification.Name.AVPlayerItemDidPlayToEndTime for different videos in multiple classes
My app plays video throughout several vcs using AVFoundation. For example FirstController plays a video then a user can push on SecondController which also plays a video then they can push on the ThirdController which also plays a video... The same thing would apply if their switching tabs. There's a video screen on TabOne, TabTwo, and TabThree.
Instead of setting up all the playLayer code associated with AVFoundation in each class I created one class that contains a AVPlayerViewController() and add that class to each vc using addChildViewController().
The problem is since I have one class that manages AVFoundation the Notification.Name.AVPlayerItemDidPlayToEndTime that gets notified when the player finishes playing can't distinguish one video on one vc from another video in a different vc. For example after a video finishes playing I show a replayButton. If the video in the first tab is playing, when I switch to TabTwo I pause that video, after the video on TabTwo finishes and the replayButton appears, if I switch back to TabOne, the replayButton will also appear on TabOne's screen (it should still show the pause button).
The problem is even though I have different instances of the AVFoundationManager, all the instances access the one showReplayButton() function that gets triggered when the notification fires.
How can I get around this?
I know I can check on the parent of the AVFoundationManager to find out which parent is managing it and use that inside the showReplayButton() function but I don't know which check to run on it.
AVFoundationManager:
class AVFoundationManager: UIViewController {
....
override func viewDidLoad() {
super.viewDidLoad()
configureAVPlayerController()
}
func configureAVPlayerController() {
let avPlayerVC = AVPlayerViewController()
avPlayerVC.player = player
avPlayerVC.view.frame = view.bounds
avPlayerVC.showsPlaybackControls = false
avPlayerVC.videoGravity = AVLayerVideoGravity.resizeAspectFill.rawValue
addChildViewController(avPlayerVC)
view.addSubview(avPlayerVC.view)
avPlayerVC.didMove(toParentViewController: self)
player?.replaceCurrentItem(with: playerItem!)
player?.play()
NotificationCenter.default.addObserver(self, selector: #selector(showReplayButton), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
playerItem?.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.status),
options: [.old, .new],
context: &itemContext)
}
@obj func showReplayButton(){
// if self.parent ... run a bool on the parent and enclose these two in the paranthesis?
pausePlayButton.isHidden = true
replayButton.isHidden = false
}
}
TabOneClass:
let avFoundationManager = AVFoundationManager()
addChildViewController(avFoundationManager)
avFoundationManager.didMove(toParentViewController: self)
TabTwoClass:
let avFoundationManager = AVFoundationManager()
addChildViewController(avFoundationManager)
avFoundationManager.didMove(toParentViewController: self)
FirstController (root) in TabThree:
let avFoundationManager = AVFoundationManager()
addChildViewController(avFoundationManager)
avFoundationManager.didMove(toParentViewController: self)
SecondController (child) in TabThree:
let avFoundationManager = AVFoundationManager()
addChildViewController(avFoundationManager)
avFoundationManager.didMove(toParentViewController: self)
A:
I got the answer from here
Inside the Notification, instead of setting the last argument object to nil set it to player.currentItem:
like this:
NotificationCenter.default.addObserver(self, selector: #selector(showReplayButton),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
object: player?.currentItem)
| {
"pile_set_name": "StackExchange"
} |
Q:
Compiling one .aar library file from multiple modules
Hello everyone I have library project that consists from multiple modules :
module 1
module 2
module 3
module 4
I want to export all four modules as one .aar library file so I'm thinking about generating .aar files for each module and including it to other .aar file I'm not sure if this is going to work or is this good practice so I want your opinions on that ? And what is the best way to compile one .aar file from multiple modules ?
EDIT :
I manages to find solution https://github.com/adwiv/android-fat-aar and to get all modules in one .aar file. But since I'm using dagger I get following error :
stack=java.lang.NoClassDefFoundError: Failed resolution of:
Ldagger/internal/Preconditions .... Caused by:
java.lang.ClassNotFoundException: Didn't find class
"dagger.internal.Preconditions" on path: DexPathList[[...
It's seems dependencies don't get included into .aar file.
A:
the "standard" way of doing it is to just direct use the modules in the compilation process that will generate the 1 aar.
So let's say module1 is the main part of the library, you'll have the following on it's build.gradle
apply plugin: 'com.android.library' // it's a library, generates aar
dependencies {
// the other modules are dependencies on this one
compile project(':module2')
compile project(':module3')
compile project(':module4')
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Why do browser vendors make their own css properties?
Why do browser vendors make their own
css properties, even they know these properties
will not pass the w3c validation before approved and added by w3c?
What is the purpose? Is for their own
testing, or for web developers, or to
demonstrate browser capabilities
to the world and to the W3C organizations
and to CSS development team of W3C?
is it like a beta version of
demonstration?
if i use any browser specific for now
can they remove that property's
support from future versions.will i have to edit my css in future
For example:
https://developer.mozilla.org/en/CSS_Reference/Mozilla_Extensions
A:
Responsible browser vendors (the big ones, excluding IE), know what the web will look a few years later. I don't know where you get the "not pass" part. They only implement things the browsers will support in a few years
It's about giving the tools to design the web for modern and future browsers.
Yeah, we can say it's a beta.
Yes and no, it's unlikely they will remove support for the extensions part.
What the W3C is thinking about is the syntaxis. Let's take gradient for an example:
-webkit-gradient(
linear,
left bottom,
left top,
color-stop(0.2, rgb(86,45,199)),
color-stop(0.6, rgb(112,72,239))
)
-moz-linear-gradient(
center bottom,
rgb(86,45,199) 20%,
rgb(112,72,239) 60%
)
Both these codes generate the same gradient. As you can see, there's no standard procedure, the syntaxis is both confusing and different for webkit and mozilla based browsers.
But let's imagine in two or three years, the implementation is done. Now you just have to add another line of code for the standard.
gradient: center bottom #colorFrom opacityFrom #colorTo opacityTo;
Now both engines will understand the gradient statment and if it's specified after the extension ones, this last one will be the one to interpret.
| {
"pile_set_name": "StackExchange"
} |
Q:
Image Saving issue from Windows application c#
I have developed a win apps which save images in a specific folder from where our exe run from. The below I used to save images
protected string GetPath(string strFileName)
{
string strPath=System.Environment.CurrentDirectory+@"\UPS\LabelImages\";
if (!System.IO.Directory.Exists(strPath))
{
System.IO.Directory.CreateDirectory(strPath);
}
strPath = strPath + strFileName;
return strPath;
}
the issue is some time win apps throwing execption like
Access to path 'C:\Windows\system32\UPS\LabelImages\' denied
suppose my application is installed inside c:\programfiles32 and then throw this kind of error my c# exe file. so tell me what would be the best option to save image files as a result no user get the exception or error like Access to path 'C:\Windows\system32\UPS\LabelImages\' denied
Looking for suggestion.
A:
I'd recommend saving those files in a safer location, such as the special folder for application data:
var safeFilePath = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.ApplicationData), @"UPS\LabelImages");
From the Environment.SpecialFolder doc:
ApplicationData: The directory that serves as a common repository for application-specific data for the current roaming user.
You could easily use another location too, as you see fit (i.e. MyDocuments or MyPictures).
Some locations on disk are a bad place to try saving files because of the potential for access errors like you're seeing, such as "System32", "Program Files", or the root C: directory, among others.
| {
"pile_set_name": "StackExchange"
} |
Q:
C++ Program size in Memory
I'm trying to make a c++ program print out its own memory footprint.
Whats a good way to print out the KB of memory a c++ program is using at the current time?
I would need it for Linux and windows...so something platform independent....
Thank you,
MS
A:
I dont think there is a mutli-platform way of doing this.
But you could use macros to do it like:
#ifdef __GCC__
//linux code
#else
//windows code
#endif
heres a link for the windows method:
How to get memory usage under Windows in C++
and one for a linux method:
How to get memory usage at run time in c++?
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to create anonymous objects from abstract classes / interfaces in VB.NET?
Is it also possible to create anonymous objects of interfaces and abstract classes?
For example, in Scala, I can do:
trait Something {
val someProperty: Int
}
val mySomething = new Something() {
override val someProperty: Int = 42
}
Is this possible in VB.net, too, and if yes, how do I do this?
Searching this issue did not yield any usable results, or I just did not hit the correct keywords. The only results I got were about anonymous types like this documentation page and this tutorial on MSDN. However this does not seem to work as expected when I do something like:
Public MustInherit Class Something
Public MustOverride ReadOnly Property SomeProperty as Integer
End Class
and where I want to use it:
Dim mySomething As New Something
With mySomething
' I expect to provide an implementation for the property here
End With
The compiler complains that 'New' cannot be used on a class that is declared 'MustInherit'.
Is such an approach not possible in VB.net or do I do something wrong?
A:
No, in VB if you want a class that implements an interface or inherits from a particular base class, it's up to you to actually define such a class.
You've found the closest feature already - anonymous types - but you don't get to choose their base type nor have them implement any interfaces.
| {
"pile_set_name": "StackExchange"
} |
Q:
check_mysql_query cannot connect to mysql, but works from the command line
I have Nagios 3 running on Debian Wheezy. I am able to run the query the following query from the command line. The credentials for the mysql db are stored in ~nagios/.my.cnf
nagios@intranet:~$ /usr/lib/nagios/plugins/check_mysql_query -H 'myhost.mydomain.com' -q "SELECT cast(AVG(availability)*100 AS DECIMAL(5,2) ) FROM crm.api_clients;" -w 70:100 -c 40:100
QUERY OK: 'SELECT cast(AVG(availability)*100 AS DECIMAL(5,2) ) FROM crm.api_clients;' returned 100.000000
But when the same command is invoked from Nagios, it can't connect to the database.
The relevant sections of the command and service definition are
define command{
command_name check_proxy
command_line /usr/lib/nagios/plugins/check_mysql_query -H 'myhost.mydomain.com' -q "SELECT cast(AVG(availability)*100 AS DECIMAL(5,2) ) FROM crm.api_clients;" -w '$ARG1$' -c '$ARG2$'
}
define service{
use generic-service ; Name of service template to use
host_name rds_read_replica
service_description Proxy availability
check_command check_proxy!70:100!40:100
}
In the web console, I see the following error against the service:
QUERY CRITICAL: Access denied for user 'nagios'@'172.33.13.112' (using password: NO)
It works the console when I pass the username and password to the command. But I would like to have the check_mysql_query use the credentials stored in .my.cnf. How can I achieve this?
A:
Nagios will run the plugins with no ENV, and therefore no $HOME set. You can simulate this with env -i for manual testing.
You can change your check command to something like HOME=/home/nagios && /usr/lib/nagios/plugins/check_mysql_query ... (or whatever the path is).
If you can't get that to work, wrap that whole check_command in a shell script that sets HOME before calling the real plugin. Also be sure to grab the return code and pass it through the wrapper script too.
| {
"pile_set_name": "StackExchange"
} |
Q:
HT Access IP restriction and htpasswd
Is there a way to require the use of htpasswd if the user is not in a certain IP range?
EDIT:
K I have this right now
Order Deny,Allow
Deny from all
AuthName "Htacess"
AuthUserFile /var/www/Test/.htpasswd
AuthType Basic
Require valid-user
Allow from 111.111.111.111
Satisfy Any
But its giving me a 500 error
A:
Figured it out
AuthName "Htaccess"
AuthUserFile /var/www/test/.htpasswd
AuthType Basic
Satisfy Any
<Limit GET POST>
Order Deny,Allow
Deny from all
Allow from 111.111.111.111
Require valid-user
</Limit>
| {
"pile_set_name": "StackExchange"
} |
Q:
Can not infer schema for type:
I have the following Python code that uses Spark:
from pyspark.sql import Row
def simulate(a, b, c):
dict = Row(a=a, b=b, c=c)
df = sqlContext.createDataFrame(dict)
return df
df = simulate("a","b",10)
df.collect()
I am creating a Row object and I want to save it as a DataFrame.
However, I am getting this error:
TypeError: Can not infer schema for type: <type 'str'>
It occurs on this line:
df = sqlContext.createDataFrame(dict)
What am I doing wrong?
A:
It is pointless to create single element data frame. If you want to make it work despite that use list: df = sqlContext.createDataFrame([dict])
| {
"pile_set_name": "StackExchange"
} |
Q:
ListView in ScrollView potential workaround
I've done all of the research on the matter. I know that Google thinks it's pointless and that the developers, know that it's not. I also know that there is no known workaround, but I know that I am close to making one. The user DougW posted this code:
public class Utility {
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
// pre-condition
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
}
Which almost gets the job done for me. But when I try it, I get a NullPointer exception at the listItem.measure(0, 0) line. The listItem itself is initialized, but the method throws the exception anyway. Please tell me how I can fix this.
Here is my code:
public class ExpenseReportsActivity extends Activity {
private ListView lvReports;
private ExpenseReportListAdapter adapter;
private Button btnSend;
private Button btnCancel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.expensereports);
lvReports = (ListView)findViewById(R.id.lv_reports);
lvReports.setBackgroundResource(R.drawable.shape_expense_report_list);
ColorDrawable cd = new ColorDrawable(0xFFffffff);
lvReports.setDivider(cd);
lvReports.setDividerHeight(1);
adapter = new ExpenseReportListAdapter(this);
lvReports.setAdapter(adapter);
int totalHeight = 0;
for (int i = 0; i < adapter.getCount(); i++) {
View listItem = adapter.getView(i, null, lvReports);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = lvReports.getLayoutParams();
params.height = totalHeight + (lvReports.getDividerHeight() * (adapter.getCount() - 1));
lvReports.setLayoutParams(params);
}
}
Another workaround I am working on is using my custom view's onWindowFocusChanged method. It tells the exacts height of the view. The problem is that the event isn't fired while I am still in my Activiy's onCreate method, nor in my Activity's onWindowFocusChanged method. I tried a custom event, but it never fired (it was placed inside my custom view's onWindowFocusChanged method and the listener was in my Activity's onWindowFocusChanged method).
A:
Ok, as far as I got your needs I think you may just use the ListView.addFooterView(View v) method:
http://developer.android.com/reference/android/widget/ListView.html#addFooterView(android.view.View)
It will allow you to have all your list items + "a few buttons" footer to be scrolled as a single block.
So the code should be smth like that:
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
public class YourActivity extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater factory = getLayoutInflater();
LinearLayout footer =
(LinearLayout) factory.inflate(R.layout.your_a_few_buttons_footer, null);
getListView().addFooterView(footer);
String[] array = new String[50];
for (int i = 0; i < 50;) { array[i] = "LoremIpsum " + (++i); }
setListAdapter(
new ArrayAdapter<String>(this, R.layout.list_item, array)
);
}
}
Note, the doc says addFooterView() should be called BEFORE the setListAdapter().
UPDATE: to add a View at the top of the list use ListView.addHeaderView(View v). Note that, for instance, LinearLayout is also a View. So you can put anything you want as a header or a footer and it'll be scrolled with the list as an indivisible block.
| {
"pile_set_name": "StackExchange"
} |
Q:
Method overloading in Python: more overloading
this question is not a duplicate of the other overloading question because I am attempting to reference self.args in the function. The answer given in that question does not satisfy, since if I implement that answer, I will get an error. However, in other languages, this is easily done through method overloading...so this question is highly related to the other question.
So I have a method,
class learner():
def train(a ton of arguments):
self.argA = argA,
etc.
And I want to call train with just one value, and have it use all the self calls to populate the other arguments...but it is a circular reference that python doesn't seem to support. Ideally, I would write:
class learner():
def train(self, position, data = self.data, alpha = self.alpha, beta = etc):
...do a bunch of stuff
def roll_forward(self,position):
self.alpha += 1
self.beta += 1
self.train(position)
How would I do this? In other languages, I could just define a second train function that accessed the internal variables...
currently, I have a janky hack where I do this:
class learner():
def train(...):
....
def train_as_is(self,position):
self.train(position,self.alpha,self.beta, etc.)
But this is a pretty big class, and a ton of functions like that are turning my code into spaghetti...
A:
An enhancement on other answers is to use a defaults dictionary:
def train(self, position, **kwargs):
defaults = {
'a': self.a,
'b': self.b,
...etc...
}
defaults.update(kwargs)
... do something with defaults
def roll_forward(self,position):
self.alpha += 1
self.beta += 1
self.train(position)
A:
Not sure if I follow your question 100% but usual pattern is to use None as a default value:
class Foo(object):
def __init__(self):
self.a = ...
self.b = ...
...
def foo(self, position, a=None, b=None, ...):
if a is None:
a = self.a
if b is None:
b = self.b
...
You can simplify that by using or:
def foo(self, position, a=None, b=None, ...):
a = a or self.a
b = b or self.b
...
however that is not as reliable in case you will try to pass falsy values like 0 the or part will kick in
| {
"pile_set_name": "StackExchange"
} |
Q:
How to setup rebound?
I have fancy new full-suspension bike and both shocks have this strange setting, called Rebound. It's a red dial, beside the blue CTD lever.
Increasing it makes the shock less responsive to small obstacles. Thus, pedal bob is reduced. However, if I max it out, the shock becomes so stiff, that even jumping onto the saddle (the bike is stationary) from quite some height doesn't move it a bit.
What are some guidelines to tune my fork and rear shock for the terrain that I ride in and for my mass?
My rear shock has CTD. Why would I ever want to limit the travel and sustain high pedal bob, when I can just increase the rebound and enjoy efficient pedaling?
It is known from Linear systems, that a suspension can roughly be modeled by
m*a + b*v + c*s = Fs, where
m - mass
a - second derivative of position with respect to time
b - damping coefficient
v - first derivative of position
c - spring coefficient
s - position
Fs - fore on the suspension element.
Is rebound the same as the coefficient b above?
A:
Rebound is close to b in your equations above. The guides I've seen and used recommend the following procedure for setting rear shock rebound.
Ride over a sidewalk curb ( ie. 4-5 inch drop ) and adjust the rebound until you have only one bounce. I.e. you want the shock to be able to absorb a hit, but not keep rebounding to cause you to lose control.
Setting the rebound on the front fork is similar, but not as straight forward. Find a short bumpy descent and keep doing it until you feel like you've got the best control. It's a balance between absorbing the hit and keeping control of the front wheel. If the front shock is "bouncing" more than once after the hit you are don't have control during the up phase.
If you set the rebound too high, the shock won't be able to function as designed to absorb the terrain. If you think of it as a wave form, you want the rebound to not significantly damp out the initial height of the wave, but to damp out the oscillations as quickly as possible.
As you get better and faster you will likely need to tweak the rebound. The trick is to always find that balance between absorbing the hit and sustaining the hit through oscillations.
A:
Rebound.
Increasing it makes the shock less responsive to small obstacles.
Thus, pedal bob is reduced. However, if I max it out, the shock
becomes so stiff, that even jumping onto the saddle (the bike is
stationary) from quite some height doesn't move it a bit.
I think you are refering to compression. Rebound is damping when the fork travel tries to return to original length. Compression is damping when the fork travel is being reduced (in high or low speed) due to a bump, a root, a landing.
You cannot have a single rebound setting that will be the best for you in all terrains. Thus you'll either want to find a generally good setting that will work in the most places you ride at, or fiddle with it whenever you change terrain or riding style (dh vs dirt jumps). I suggest you aim for the first, at least for 6-12 months of riding with your new hardware.
A middle setting generally is a safe start. Count the clicks you have and just set it at the middle. In that setting start riding in trails that you know well so you can get a feel of the suspensions. If it seems to work well then leave it like that.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I paste the audioinfo of a music file?
I want to be able to update a text box with the audioinfo of a sound file.
The current solution I have gives me an error
info = audioinfo('music1.mp3');
set(handles.edit1,'String',info);
Running info in the console gives me all the information about the sound file and stores it in the workspace to the right of MATLAB. I want all that information to update a textbox (edit1).
Error:
While setting the 'String' property of 'UIControl':
String should be char, numeric or cell array datatype.
Can anyone help?
A:
I would recommend using a uitable rather than an 'edit' uicontrol object. 'edit' uicontrol objects can only be one line so they can't be used anyway, and the alternative, 'listbox' can only be one column so you would need to sprintf/fprintf the data to get it to fit.
For example:
% Generate audio file
load handel.mat
filename = 'handel.wav';
audiowrite(filename,y,Fs);
clear y Fs
% Build dummy GUI
f = figure('ToolBar', 'none');
T = uitable('Parent', f, 'Units', 'Normalized', 'Position', [0.1 0.1 0.8 0.8]);
% Read data and add to table
info = audioinfo(filename);
T.RowName = fieldnames(info);
T.Data = struct2cell(info);
Results in the following UI:
Which also allows you to easily manipulate the data (e.g. copy, edit, etc.)
| {
"pile_set_name": "StackExchange"
} |
Q:
Вычислить разницу между датами
Есть таблица Mysql, в ней столбец "data" с типом datetime.
Нужно взять текущую дату и время и посчитать разницу с табличным значением и вывести результат в формате dd-hh-mm
SELECT SEC_TO_TIME(UNIX_TIMESTAMP(now())-UNIX_TIMESTAMP(users.data)) from users where UserId=999929921;
пробовал вот так, все работает до тех пор, пока разница между датами не больше 1 дня, далее выводится ошибка, так как SEC_TO_TIME работает в интервале 24 часов к сожалению.
Собственно вопрос, как правильно написать запрос?
A:
Можно например как нибудь так:
concat(lpad(floor((@h:=time_format(@tm:=timediff(now(), users.data), '%H'))/24), 2, '0'),
'-',
lpad(@h % 24, 2, '0'),
'-',
time_format(@tm, '%i'))
Вопрос в том, а стоит ли делать такие громоздкие конструкции в SQL, если на клиенте обычно гораздо больше средств для форматирования времени.
Пример на SQLFiddle.com
| {
"pile_set_name": "StackExchange"
} |
Q:
mysql Delete and Database Relationships
If I'm trying to delete multiple rows from a table and one of those rows can't be deleted because of a database relationship, what will happen?
Will the rows that aren't constrained by a relationship still be deleted? Or will the entire delete fail?
A:
If it's a single delete statement, then the entire delete will fail.
| {
"pile_set_name": "StackExchange"
} |
Q:
iframe disable on hover effect
i couldnot disable effect of the element within iframe attribute when you hover on it. are there any alternatives to solve the current problem ??
here is my code and raw solution:
iframe id="clock1" src="http://free.timeanddate.com/clock/i52azneg/n2253/szw110/szh110/hbw0/hfc000/cf100/hgr0/fav0/fiv0/mqcfff/mql15/mqw4/mqd94/mhcfff/mhl15/mhw4/mhd94/mmv0/hhcbbb/hmcddd/hsceee" frameborder="0" width="110" height="110"></iframe>
script>
$("iframe#clock1").contents().find("#hov").hide();
/script>
A:
This hover effect is coming from the original website.
You can solve this using following code.
<div title="Your title Here">
<iframe id="clock1" src="http://free.timeanddate.com/clock/i52azneg/n2253/szw110/szh110/hbw0/hfc000/cf100/hgr0/fav0/fiv0/mqcfff/mql15/mqw4/mqd94/mhcfff/mhl15/mhw4/mhd94/mmv0/hhcbbb/hmcddd/hsceee" frameborder="0" width="110" height="110" style="pointer-events: none;"></iframe>
</div>
Anyway I don't recommend this because the message is to give credit for the developer. This is not ethically correct.
| {
"pile_set_name": "StackExchange"
} |
Q:
wpf combobox binding
Hi I´m trying to bind a List<> to a combobox.
<ComboBox Margin="131,242,275,33" x:Name="customer" Width="194" Height="25"/>
public OfferEditPage()
{
InitializeComponent();
cusmo = new CustomerViewModel();
DataContext = this;
Cusco = cusmo.Customer.ToList<Customer>();
customer.ItemsSource = Cusco;
customer.DisplayMemberPath = "name";
customer.SelectedValuePath = "customerID";
customer.SelectedValue = "1";
}
I become no Error but the Combobox is always empty.
Cusco is the Property of my List.
I have no idea whats wrong with this code.
Can you help me?
Greets
public class Customer
{
public int customerID { get; set; }
public string name { get; set; }
public string surname { get; set; }
public string telnr { get; set; }
public string email { get; set; }
public string adress { get; set; }
}
this is the Customer Class which is my model.
public class CustomerViewModel
{
private ObservableCollection<Customer> _customer;
public ObservableCollection<Customer> Customer
{
get { return _customer; }
set { _customer = value; }
}
public CustomerViewModel()
{
GetCustomerCollection();
}
private void GetCustomerCollection()
{
Customer = new ObservableCollection<Customer>(BusinessLayer.getCustomerDataSet());
}
}
and this is the ViewModel.
A:
Try setting the ItemsSource property with an actual Binding object
XAML Method (recommended):
<ComboBox
ItemsSource="{Binding Customer}"
SelectedValue="{Binding someViewModelProperty}"
DisplayMemberPath="name"
SelectedValuePath="customerID"/>
Programmatic method:
Binding myBinding = new Binding("Name");
myBinding.Source = cusmo.Customer; // data source from your example
customer.DisplayMemberPath = "name";
customer.SelectedValuePath = "customerID";
customer.SetBinding(ComboBox.ItemsSourceProperty, myBinding);
Also, the setter on your Customer property should raise the PropertyChanged event
public ObservableCollection<Customer> Customer
{
get { return _customer; }
set
{
_customer = value;
RaisePropertyChanged("Customer");
}
}
If the above does not work, try moving the binding portion from the constructor to the OnLoaded override method. When the page loads, it may be resetting your values.
A:
As an expansion on Steve's answer,
You need to set the datacontext of your form.
Currently you have this:
InitializeComponent();
cusmo = new CustomerViewModel();
DataContext = this;
It should be changed to this:
InitializeComponent();
cusmo = new CustomerViewModel();
DataContext = cusmo;
Then as Steve noted you will need another property on the viewmodel to store the selected item.
| {
"pile_set_name": "StackExchange"
} |
Q:
What does it mean when multimeter accuracy is marked as: ±0,03%+10Digit?
I have a digital multimeter and its accuracy for VDC is marked like this:
±0,03%+10Digit
This multimeter has maximum display of 80000. So in the 80 V range it can show for example 79.999V.
0.03% of 80V is 0.024V - that is clear for me. But what does the +10Digit mean?
The device in question in Digitek DT-80000.
A:
The 1 digit means that the least significant digit can be off by +/- 1. In this resolution 1 digit would mean +/- 0.001V. 10 digit means that basically of your 79.999V displayed, it could also be 79.989V (not including the 0,03%!)
So basically in your range the 10 digit specification means that +/- 0.03% + 0,01V is your error. For measuring 79.999V it means an absolute maximum error or +/- 79.999*0.03% + 10*0.001V = 0.034V.
A:
Like Hans says +/-1 digit means that the last digit can be 1 off. +/-10 digits means it can be 10 digits off, or 1 digit in the one but last position. It shows how relative 5 digits (actually 4 3/4) of resolution are: while you get 5 digits, only 4 are significant, the last one is not reliable. This may not look too bad, 10 in 80000 is 0.01%, to be added to the 0.03% basic accuracy. However, while the 0.03% is relative to the measured value, the 10 digits are absolute, and they weigh more if your reading is lower. 10 in 80000 was 0.01%, if your reading is 20000 this error will be 0.05%, or larger than the relative error.
A:
If a meter with the indicated specifications is set for the 0-to-80-volt range, small values would be accurate to within 10mv, while larger values could be off by an additional 24mv. On such a meter, the last digit will generally not be meaningful when taking a single reader in isolation, but is provided for use in situations where one is interested in the differences among readings that are taken very close together. For example, if measures two voltages in fairly quick succession, and then repeats those measurements, and the readings are:
Item1 Item2
49.123V 49.569V -- Initial measurements
49.125V 49.568V -- Repeated measurements
one then the difference between the two items' voltages could be safely said to be somewhere between 442 and 445 mV. One wouldn't know where the first voltage was within the range 49.10V and 49.15V, nor where the second was within the range 49.55V and 49.59V, but one would know the difference with a precision much greater precision than one knew either voltage individually.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.