text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
css targeting div instead of form
I have the following html code:
<div class="formDiv">
<form id="searchForm">
<input type="text" name="weathersearch" placeholder="Search places">
</form>
</div>
With the following css, it looks like this
.formDiv {
background-color: red;
max-width: 400px;
margin-left: auto;
margin-right: auto;
}
I wish to have a larger search box, not a larger div. But targeting either the form id or the div gave me the same results, shown below. How would I make the form itself larger (i.e bigger horizontally and vertically).
#searchForm {
width: 300px;
height: 100px;
}
A:
If you'd like to size the input element relative to .searchForm or .formDiv, do:
.searchForm input {
height: 100%;
}
Otherwise, just set the height on the input element directly:
.searchForm input {
height: 400px;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
get id from db and display contents in another page
Basically I have a db with a table called apartments and I'm using this code to output the contents on one page:
$connect = mysqli_connect("localhost","root","","db_dice");
$query = "SELECT * FROM apartment ORDER BY ID DESC";
$records = mysqli_query($connect,$query);
//check connection
if ($connect->connect_error) {
die('Connection failed: ' . $conn->connect_error);
echo 'err';
}
while($show=mysqli_fetch_array($records)){
echo '<div class="div-recentupdate" style="background-color:white">';
echo '<a href="apartment.php">'.$show['apartment name'].' Bedroom:'.$show['bedroom'].' Price:$'.$show['price'].' <br></a>';
echo '</div>';
}
The question is simple (I'm used to mvc so that's why I don't know this, I'm sorry).
What I want is to output the contents of the db (apartment name, bedroom etc) on another page called the apartment.php
I think I'm supposed to use
<a href="apartment.php?id=(variable of the id of the chosen link)">
but I have no idea how.
Please help.
A:
"I think I'm supposed to use <a href apartment.php?id= (variable of the id of the chosen link)>"
Correct, and make sure there are no spaces after the = sign.
First we need to use an ?id in order to fetch the record from the database (and passed to the second page) while assigning it to the id row using:
$show['ID'] inside the href in your first page using your existing code that you posted.
Then on the second page, you would then use a WHERE clause using the fetched id from the variable and check if the assignment is set.
Sidenote: Your ID must be an int type in order for this to work properly.
In your first page:
Replace your current href line that's being echo'd with:
echo '<a href="?id='.$show['ID'].'">'.$show['apartment name'].' Bedroom:'.$show['bedroom'].' Price:$'.$show['price'].' <br></a>';
Then on your second page:
Sidenote: Using (int) for (int)$_GET['id'] makes it a safe array.
if(isset($_GET['id'])){
$id = (int)$_GET['id'];
$query_fetch = mysqli_query($connect,"SELECT * FROM apartment WHERE ID = $id");
while($show = mysqli_fetch_array($query_fetch)){
echo "ID: " . $show['ID'] . " " . $show['apartment name']. " Bedroom:".$show['bedroom']." Price:$".$show['price']." <br></a>";
} // while loop brace
} // isset brace
else{
echo "It is not set.";
}
Another sidenote:
You can also use the following instead of (int):
$id = filter_var($_GET['id'], FILTER_SANITIZE_NUMBER_INT);
Footnotes:
I noticed you have a space here $show['apartment name'] between apartment and name.
Be careful with that, since spaces can cause problems if used in a query where you did not escape it using ticks.
I.e.: This would fail and cause a syntax error:
SELECT * FROM apartment WHERE ID = $id AND apartment name = 'apartment 101'
You would need to do and notice the ticks around the apartment name name:
SELECT * FROM apartment WHERE ID = $id AND `apartment name` = 'apartment 101'
It's best to use underscores as word seperators, just saying.
Error checking:
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
as well as or die(mysqli_error($connect)) to mysqli_query().
References:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/function.error-reporting.php
Another thing I spotted, you are using the incorrect variable here:
$conn->connect_error)
it should be $connect, and not $conn.
Then your echo"err"; will never happen, since you've used die().
From the manual:
http://php.net/manual/en/function.die.php
This language construct is equivalent to exit(). http://php.net/manual/en/function.exit.php
"exit — Output a message and terminate the current script"
| {
"pile_set_name": "StackExchange"
} |
Q:
Detect all certain substrings in Python sequence
The code below demonstrates Penney's Game - the probability of one sequence of heads and tails appearing before another. In particular, I wonder about the efficiency of while not all(i in sequence for i in [pattern1, pattern2]):, and more globally about coding this optimally in Python. Is this a reasonable attempt in Python, or is the a better more efficient way. The more I think I know about Python, the more I believe there's always a better way!
import random
pattern1 = 'TTT'
pattern2 = 'HTT'
pattern1Wins = 0
pattern2Wins = 0
trials = 1000
for _ in range(trials):
sequence = ''
while not all(i in sequence for i in [pattern1, pattern2]):
sequence += random.choice(['H','T'])
if sequence.endswith(pattern1):
pattern2Wins += 1
else:
pattern1Wins += 1
print pattern1, 'wins =', pattern1Wins
print pattern2, 'wins =', pattern2Wins
print str((max([pattern1Wins, pattern2Wins]) / float(trials) * 100)) + '%'
A:
Create your sequence with three calls to choice originally then just add the last two and a new choice looping until one of the patterns appears:
pattern1 = 'TTT'
pattern2 = 'HTT'
trials = 1000
d = {pattern1: 0, pattern2: 0}
for _ in range(trials):
sequence = random.choice("HT") + random.choice("HT") + random.choice("HT")
while sequence not in {pattern1, pattern2}:
sequence = sequence[-2:] + random.choice("HT")
d[sequence] += 1
print pattern1, 'wins =', d[pattern1]
print pattern2, 'wins =', d[pattern2]
print str((max([d[pattern1], d[pattern2]]) / float(trials) * 100)) + '%'
Some timings with random.seed:
In [19]: import random
In [20]: random.seed(0)
In [21]: %%timeit
....: pattern1 = 'TTT'
....: pattern2 = 'HTT'
....: trials = 1000
....: patterns = {'TTT': 0, 'HTT': 0}
....: for _ in range(trials):
....: sequence = ''
....: while True:
....: sequence += random.choice('HT')
....: for pattern in patterns:
....: if sequence.endswith(pattern):
....: patterns[pattern] += 1
....: break
....: else:
....: continue
....: break
....:
100 loops, best of 3: 7.28 ms per loop
In [22]: %%timeit
....: pattern1 = 'TTT'
....: pattern2 = 'HTT'
....: trials = 1000
....: d = {pattern1: 0, pattern2: 0}
....: for _ in range(trials):
....: sequence = random.choice("HT") + random.choice("HT") + random.choice("HT")
....: while sequence not in {pattern1, pattern2}:
....: sequence = sequence[-2:] + random.choice("HT")
....: d[sequence] += 1
....:
100 loops, best of 3: 4.95 ms per loop
In [23]: %%timeit
pattern1 = 'TTT'
pattern2 = 'HTT'
pattern1Wins = 0
pattern2Wins = 0
trials = 1000
for _ in range(trials):
sequence = ''
while True:
sequence += random.choice('HT')
if sequence.endswith(pattern1):
pattern2Wins += 1
elif sequence.endswith(pattern2):
pattern1Wins += 1
else:
continue
break
....:
100 loops, best of 3: 6.65 ms per loop
| {
"pile_set_name": "StackExchange"
} |
Q:
how to know video format or type
i am getting list of video files from web services and playing in Videoview . Some video getting played .for example mp4. While some video are not for example .mov file.So I want to check the format of video so that i can handle in error listner in android. My question is how to know format another question-I am playing the video in videoview and doing manually streaming. I am buffering some amount and then playing the video simulataneously. video is getting played but after some time it raising warning like media cannot be played .I think that because of unavailibilty of media in file it saying like that because when total amount of video is present in file then it playing total video without warning . My 2 question is- what is your opinion .what is the reason for this .how can i correct it
A:
Intent intent=anyPlayer(urlstring);
startactivity(intent);
public static Intent anyPlayer(String DestAddr)
{
Uri uri = Uri.parse(DestAddr.toString());
Intent i = new Intent("android.intent.action.VIEW");
i.setDataAndType(uri, "video/*");
return i;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Highcharts fill map based on data values with React TypeScript
I'm trying to fill colours in countries based on each country's data. Something similar to this map. Something similar to the function formatter in tooltip.
I've tried different approaches, including using zones (like it's described here, here and here) but couldn't do it.
import mapDataWorld from '@highcharts/map-collection/custom/world.geo.json';
import worldMapData from '../data/WorldMapData';
const options: Highcharts.Options = {
series: [{
type: 'map',
mapData: mapDataWorld,
data: worldMapData,
// Zones don't seem to work for point value
zones: [{
value: 2,
color: '#f7a35c'
}]
}],
tooltip: {
headerFormat: '',
formatter: function () {
const country = this.point;
const info = `The value for ${country.name} is ${country.value}`
return info;
}
}
}
A:
You can use colorAxis
const options: Highcharts.Options = {
colorAxis: {
dataClasses: [{
to: 10,
color: "red"
}, {
from: 10,
to: 20,
color: "orange"
}, {
from: 20,
to: 50,
color: "yellow"
}]
}
.
.
.
more about colorAxis
| {
"pile_set_name": "StackExchange"
} |
Q:
Mail bounced during relay via Google account
I want to all mails form my server to be relay through my private google email account.
But all email are bounced and the return mail stands:
I got info: <[email protected]>: host smtp.gmail.com[173.194.69.109]
said: 530-5.5.1 Authentication Required. Learn more at 530 5.5.1
support.google.com/mail/bin/answer.py?answer=14257 fc7sm2465531bkc.3 - gsmtp
(in reply to MAIL FROM command) - so in such configuration MAIL FROM must be
included in relay definition. How can I do it?
How and in which file i have to add line to define MAIL FROM parameter.
Below my main.cf file
readme_directory = /usr/share/doc/postfix/README_FILES
html_directory = /usr/share/doc/postfix/html
sendmail_path = /usr/sbin/sendmail.postfix
setgid_group = postdrop
command_directory = /usr/sbin
manpage_directory = /usr/share/man
daemon_directory = /usr/lib/postfix
data_directory = /var/lib/postfix
newaliases_path = /usr/bin/newaliases
mailq_path = /usr/bin/mailq
queue_directory = /var/spool/postfix
mail_owner = postfix
# listen on localhost only
inet_interfaces = 127.0.0.1
smtpd_banner = $myhostname ESMTP $mail_name
biff = no
mynetworks = 192.168.0.0/24
# appending .domain is the MUA's job.
append_dot_mydomain = no
#Uncomment the next line to generate "delayed mail" warnings
delay_warning_time = 4h
relayhost = [smtp.gmail.com]:587
smtp_use_tls = yes
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options = noanonymous
And how to make port 25 (at this moment nmap show it is not open) be active to receive mail from my local network?
A:
inet_interfaces = 127.0.0.1 says to only listen on localhost. Change that as appropriate to get it listening on port 25.
I'm going to guess that /etc/postfix/sasl_passwd isn't quite right, but I'll need to see the contents to be sure. Make sure to mask out your real password! :)
| {
"pile_set_name": "StackExchange"
} |
Q:
Performance benefit to pre-compiling web application project set to be updateable?
Is there any performance benefit to pre-compiling an asp.net web application if it's set to be updateable? By setting the pre-compiler updateable flag it doesn't pre-compile the aspx, ascx, etc. so those still have to be compiled at run-time on the first page load. Everything else in an ASP.NET Web Application Project is already compiled anyways though, so what is the point of running the pre-compiler on a WAP with the updateable flag set to true?
A:
From what I can tell in this specific case there isn't a performance benefit to pre-compiling a WAP when it's set to updateable for the reasons listed in the question.
| {
"pile_set_name": "StackExchange"
} |
Q:
Unexpected End of stream retrofit while receiving response from esp8266
The Arduino Code is:
#define ASCII_0 48
#define ESP8266 Serial3
String SSID = "baghairat";
String PASSWORD = "abc12345";
int packet_len;
char *pb;
int LED = 13;
boolean FAIL_8266 = false;
String strHTML1 = "<!doctype html>\
<html>\
<body>\
";
String strHTML2 = "</body>\
</html>";
//String strHTML = "arduino-er.blogspot.com";
#define BUFFER_SIZE 128
char buffer[BUFFER_SIZE];
void setup() {
pinMode(LED, OUTPUT);
digitalWrite(LED, LOW);
delay(300);
digitalWrite(LED, HIGH);
delay(200);
digitalWrite(LED, LOW);
delay(300);
digitalWrite(LED, HIGH);
delay(200);
digitalWrite(LED, LOW);
do{
Serial.begin(115200);
ESP8266.begin(115200);
//Wait Serial Monitor to start
while(!Serial);
Serial.println("--- Start ---");
ESP8266.println("AT+RST");
delay(1000);
if(ESP8266.find("ready"))
{
Serial.println("Module is ready");
ESP8266.println("AT+GMR");
delay(1000);
clearESP8266SerialBuffer();
ESP8266.println("AT+CWMODE=1");
delay(2000);
//Quit existing AP, for demo
Serial.println("Quit AP");
ESP8266.println("AT+CWQAP");
delay(1000);
clearESP8266SerialBuffer();
if(cwJoinAP())
{
Serial.println("CWJAP Success");
FAIL_8266 = false;
delay(3000);
clearESP8266SerialBuffer();
//Get and display my IP
sendESP8266Cmdln("AT+CIFSR", 1000);
//Set multi connections
sendESP8266Cmdln("AT+CIPMUX=1", 1000);
//Setup web server on port 80
sendESP8266Cmdln("AT+CIPSERVER=1,80",1000);
Serial.println("Server setup finish");
}else{
Serial.println("CWJAP Fail");
delay(500);
FAIL_8266 = true;
}
}else{
Serial.println("Module have no response.");
delay(500);
FAIL_8266 = true;
}
}while(FAIL_8266);
digitalWrite(LED, HIGH);
//set timeout duration ESP8266.readBytesUntil
ESP8266.setTimeout(1000);
}
void loop(){
int connectionId;
if(ESP8266.readBytesUntil('\n', buffer, BUFFER_SIZE)>0)
{
Serial.println("Something received");
Serial.println(buffer);
if(strncmp(buffer, "+IPD,", 5)==0){
Serial.println("+IPD, found");
sscanf(buffer+5, "%d,%d", &connectionId, &packet_len);
if (packet_len > 0) {
pb = buffer+5;
while(*pb!=':') pb++;
pb++;
if (strncmp(pb, "GET /on", 7) == 0) {
Serial.println("connectionId: " + String(connectionId));
delay(1000);
clearESP8266SerialBuffer();
// sendHTTPResponse(connectionId, strHTML1);
sendHTTPResponse(connectionId, "{\"message\":true}");
//sendHTTPResponse(connectionId, strHTML2);
//Close TCP/UDP
String cmdCIPCLOSE = "AT+CIPCLOSE=";
cmdCIPCLOSE += connectionId;
sendESP8266Cmdln(cmdCIPCLOSE, 1000);
}
else{
Serial.println("connectionId: " + String(connectionId));
delay(1000);
clearESP8266SerialBuffer();
sendHTTPResponse(connectionId, strHTML1);
sendHTTPResponse(connectionId, "{\"message\":false}");
sendHTTPResponse(connectionId, strHTML2);
//Close TCP/UDP
String cmdCIPCLOSE = "AT+CIPCLOSE=";
cmdCIPCLOSE += connectionId;
sendESP8266Cmdln(cmdCIPCLOSE, 1000);
}
}
}
}
}
void sendHTTPResponse(int id, String response)
{
String cmd = "AT+CIPSEND=";
cmd += id;
cmd += ",";
cmd += response.length();
Serial.println("--- AT+CIPSEND ---");
sendESP8266Cmdln(cmd, 1000);
Serial.println("--- data ---");
sendESP8266Data(response, 1000);
}
boolean waitOKfromESP8266(int timeout)
{
do{
Serial.println("wait OK...");
delay(1000);
if(ESP8266.find("OK"))
{
return true;
}
}while((timeout--)>0);
return false;
}
boolean cwJoinAP()
{
String cmd="AT+CWJAP=\"" + SSID + "\",\"" + PASSWORD + "\"";
ESP8266.println(cmd);
return waitOKfromESP8266(10);
}
//Send command to ESP8266, assume OK, no error check
//wait some time and display respond
void sendESP8266Cmdln(String cmd, int waitTime)
{
ESP8266.println(cmd);
delay(waitTime);
clearESP8266SerialBuffer();
}
//Basically same as sendESP8266Cmdln()
//But call ESP8266.print() instead of call ESP8266.println()
void sendESP8266Data(String data, int waitTime)
{
//ESP8266.print(data);
ESP8266.print(data);
delay(waitTime);
clearESP8266SerialBuffer();
}
//Clear and display Serial Buffer for ESP8266
void clearESP8266SerialBuffer()
{
Serial.println("= clearESP8266SerialBuffer() =");
while (ESP8266.available() > 0) {
char a = ESP8266.read();
Serial.write(a);
}
Serial.println("==============================");
}
And the Android Code is:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.protocol+Constants.IP)
.addConverterFactory(GsonConverterFactory.create())
.build();
ServerApis service = retrofit.create(ServerApis.class);
Call<ResponseBody> call = service.left();
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {
Toast.makeText(MainActivity.this,"Left Done.",Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Throwable t) {
System.out.print(t.getMessage());
}
});
I am getting "Unexpected end of stream" error on receiving the response from the Arduino Mega 2560 server on my Android client. I am using an ESP8266 WiFi module, and I am using Retrofit for the Android. Any hints?
A:
I figured it out. now i am sending this respond from arduino and it is working perfectly
sendHTTPResponse(connectionId, "HTTP/1.1 200 OK\nContent-Type: application/json;charset=utf-8\nConnnection: close\n\n{\"message\":true}");
| {
"pile_set_name": "StackExchange"
} |
Q:
C# Mono - Low Level Keyboard Hook
I'm using code that I found on the CodeProject.com for a low-level keyboard hook. The only problem is it uses external DLL calls that don't work in mono. I was wondering if anyone knew of a way to accomplish the same thing as that code, but will run in both Windows using .net, and Linux using mono?
Edit: Clarifying what I'm trying to do:
I'm making a Dashboard like application. The program sits in the system tray and when the user presses the hot-key, it will pop up all the gadgets. So the program doesn't have focus, so typically it won't catch any keystrokes, so I'm using the low-level keyboard hook and I hook the two keys that the user defines as the hot-keys. But I'm using a Windows DLL call for that, which doesn't work in Linux using mono. So I'm wondering if there's a way to do the same thing, but will run in Linux using mono?
A:
Without knowing what you are trying to capture, it's hard to be sure what will work for you. You may want to look at using Application.AddMessageFilter.
An example is here: http://dn.codegear.com/article/30129
A:
It's not possible to get this behavior using only .Net. You have to use a binary driver for each platform you run on (Windows, Linux, Mac OS). It might be possible to use only P/Invoke (detect what OS you are running on, call appropriate system libraries) so that you won't have to distribute any "extra" dll/so/dylib.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I get the Eclipse version programmatically?
I need to get the Eclipse version programmatically but I've not found a way
to get that version.
Could anyone have a suggestion, please?
Thanks in advance for your time.
A:
There are lots of versions in Eclipse, the nearest to what you want is probably the org.eclipse.platform version. So try
Version version = Platform.getBundle("org.eclipse.platform").getVersion();
| {
"pile_set_name": "StackExchange"
} |
Q:
JavaScript GetDate not working across regions
I have some JS code which takes in the client's date/time and passes it to the server like so:
function SetPostbackValues() {
//Function that gets the client machine datetime and stores it in a hidden field
// so it may be used in code behind.
var date = new Date();
var day = date.getDate(); // yields day
if (day < 10)
day = '0' + day;
var month = date.getMonth() + 1; // yields month
if (month < 10)
month = '0' + month;
var year = date.getFullYear(); // yields year
var hour = date.getHours(); // yields hours
if (hour < 10)
hour = '0' + hour;
var minute = date.getMinutes(); // yields minutes
if (minute < 10)
minute = '0' + minute;
var second = date.getSeconds(); // yields seconds
if (second < 10)
second = '0' + second;
var time = day + "/" + month + "/" + year + " " + hour + ':' + minute + ':' + second;
var hiddenControl = '<%= hfDateTime.ClientID %>';
document.getElementById(hiddenControl).value = time;
}
My problem is that the code works fine when the client time zone settings are set to a UK standard, dd/MM/yyyy but when a US client connects, the conversion to DateTime throws an error saying it is not of the right format.
Because I am getting each month, day, year separately and combining them, I do not understand why it does not work across different zone settings.
The error occurs when trying to insert datetime into SQL:
using (SqlCommand cmd = new SqlCommand("Remove", con))
{
string test = (this.Master.FindControl("hfDateTime") as HiddenField).Value;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@RemovalDate", SqlDbType.DateTime).Value = (this.Master.FindControl("hfDateTime") as HiddenField).Value; //Get the client's datetime.
con.Open();
insertedRecordID = (int)cmd.ExecuteScalar();
}
The error is {"Failed to convert parameter value from a String to a DateTime."}
The value of test is: "19/02/2016 10:55:45" which does not look wrong to me.
A:
I think you should use this:
function SetPostbackValues() {
var date = new Date();
var hiddenControl = '<%= hfDateTime.ClientID %>';
document.getElementById(hiddenControl).value = date.toISOString();
}
And change codebehind to
cmd.Parameters.Add("@RemovalDate", SqlDbType.DateTime).Value = DateTime.Parse((this.Master.FindControl("hfDateTime") as HiddenField).Value);
| {
"pile_set_name": "StackExchange"
} |
Q:
C++ Dynamic float dies in the constructer?
i need a float array in my field class.
Everything worked fine, and now i wanted to make my heighmap a bit more dynamic.
I just figured out that it dies while im doing this:
*highMap = new float[mapWidth];
for (int x = 0; x<GFX_Rx; x++)
{
*highMap[x]=30;
}
and highmap in the headerfile
float* highMap[];
Thank you
A:
There are a few problems in your code. First you can't declare an array with dynamic size, it shouldn't even compile. Second, you can't dereference a pointer without knowing it points to some valid location, you'll get seg fault.
If you don't want to use std::vector, you can do the following:
#include <iostream>
const int mapWidth = 5;
float** highMap;
int GFX_Rx=5;
int main()
{
highMap = new float*[mapWidth];
for (int x = 0; x<GFX_Rx; x++)
{
highMap[x]=new float(30);
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
ActionController::RoutingError: No route matches {:controller=>"vendors", :action=>"vendors"}?
In my test, I'm trying to call
get :vendors
but the error I get is
ActionController::RoutingError: No route matches {:controller=>"vendors",
:action=>"vendors"}
I do have the following in routes.rb
match '/vendors', :to => 'vendors#index'
so I don't get why it's looking for the (non-existent) "vendors" action instead of using "index" like it's matched. Can anyone explain this to me?
A:
Because you told it to?
The test is already contextualized, presumably with describe VendorsController, so saying get :vendors tells it to get the Vendors#vendors action. It isn't saying "get the /vendors URL", it's going straight to the controller.
In general, you run get :action not get :controller nor get :matched_route_name
| {
"pile_set_name": "StackExchange"
} |
Q:
VPN into multiple LAN Subnets
I need to figure out a way to allow access to two LAN subnets on a SonicWall NSA 220 through the built-in SonicWall GlobalVPN server. I've Googled and tried everything I can think of, but nothing has worked. The SonicWall NSA management web interface is also very unorganized; I'm probably missing something simple/obvious.
There are two networks, called Network A and Network B for simplicity, with two different subnets. A SonicWall NSA 220 is the router/firewall/DHCP Server for Network A, which is plugged into the X2 port. Some other router is the router/firewall/DHCP server for Network B. Both of these networks need to be managed through a VPN connection.
I setup the X3 interface on the SonicWall to have a static IP in the Network B subnet and plugged it in. Network A and Network B should not be able to access each other, which appears the be the default configuration. I then configured and enabled VPN.
The SonicWall currently has the X1 interface setup with a subnet of 192.168.1.0/24 with a DHCP Server enabled, although it is not plugged in. When I VPN into the SonicWall, I get an IP address supplied by the DHCP Server on the X1 interface and I can access Network A remotely although I do not have access to Network B.
How can I allow access to both Network A and Network B to VPN clients although keep devices on Network B from accessing Network A and vice-versa.
Is there some way to create a VPN-only subnet (something like 10.100.0.0/24) on the SonicWall that can access Network A and Network B without changing the current network configuration or allowing devices on both netorks "see" each other? How would I go about setting this up?
Diagram of the network: (Hopefully this kind of helps)
WAN1 WAN2
| |
[ SonicWall NSA 220 ]-(X3)-----------------[ Router 2 ]
| |
(X2) 192.168.2.0/24
10.1.1.0/24
Any help would be greatly appriciated!
A:
The problem was not that VPN clients could not access the X3 network, any LAN device on the Sonicwall could not access the X3 network. Once a NAT entry was created to properally translate the source/destination of the packets destined for the X3 network everything worked fine. This is also described in a bit more detail in this question: Sonicwall routing between multiple subnets on multiple interfaces
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create Spatial Reference System in QGIS?
I have some Attribute and the coordinate and the coordinate reference system. I want to create a DBmanagamet form my spatial data. To do that I want to create one table with name Spa_ref_sys, but I don't know how to populate my table. The point of this is that I want to connect my spatial data with QGIS. How to do that?
A:
When you create a PostGIS database using
create extension postgis
the "spatial_ref_sys" table is created automatically. I don't see any use case where you would want to do that by hand.
If you are new to the technology, you really need to read some basic literature. Just asking about random details here won't get you anywhere. See for example Getting started with PostGIS.
| {
"pile_set_name": "StackExchange"
} |
Q:
Where should I ask a question about APIs?
In which Stack Exchange site should I ask a question about which APIs to use for a certain problem, pricing, and the logistics (financial, and technical) of using them for my app?
A:
Software Recommendations has some questions requesting for APIs. You might be able to get help there, but be sure to read their guidelines before posting. Without enough information, your question will be closed quickly.
| {
"pile_set_name": "StackExchange"
} |
Q:
It lags when i am using android studio
my laptop is i7 4510U , 4GB ram , Intel HD graphics 2gb , Nvidia GeForce 840m 4GB
why it's so laggy when Iam using android studio?
A:
Your 4GB of ram is to blame,
to use well Android Studio, you need at least 8GB of RAM (more if intend to use emulators), just note that the GPU have no use here, and even the processor you just need a mid range processor to work well, but when compiling the more powerful processor you have the better.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to change Eclipse Git location and point it to Source tree embedded Git?
I want to change default Eclipse Git executable location with SourceTree installed embedded Git executable.
But in eclipse where is the configuration to change git path ?
Reason I am doing this is ,Source Tree has latest Git but separate installed version is not latest (As I don't have installation right and Through Source Tree I can update Embedded version easily).
A:
Eclipse uses EGit which relies on JGit (a java implementation of Git).
That is why you don't see a git.exe path to set. (As opposed to SourceTree, which can use an embedded or a "system" Git)
You can only specify a Git path in order for EGit to respect your Git system config.
| {
"pile_set_name": "StackExchange"
} |
Q:
Automatic conversion of evtx to plaintext logs
I have a Windows Server 2008 running MicroSoft Exchange. The Audit Logs are stored in evtx and I am trying to export the logs to a 3rd party collector. The agents we have used (Snare Epilog, open source among them) do not recognized the evtx format and do not forward them to the collecting server.
I am attempting to implement a workaround via Powershell and Task Scheduler. The problem I am facing is that while I can access the evtx and save it as a .txt, I am reparsing the entire log every time. However, I would like to only send the new events every 5 minutes or less.
The code I am using is this:
$File = "C:\text.txt; Get-WinEvent -Path C:\test.evtx | Format-Table -AutoSize | Out-File $File -append -width 750
I really appreciate the help!
A:
You could use Get-EventLog, rather than Get-WinEvent, then use the After parameter to only get the last five minutes of events or better still keep track of the most recent event message you have seen.
Here's how to get the last five minutes of the Application log.
Get-EventLog -LogName Application -After $((Get-Date).AddMinutes(-5))
| {
"pile_set_name": "StackExchange"
} |
Q:
How to set the layout directly in designer?
I would like to set up the layout for a widget directly, as I didn't find a way to do it in the UI editor, I often turns to:
ui->tab->setLayout (ui->verticalLayout)
But that looks stupid to me.
Is there anyway to do that without extra coding?
A:
Select the widget you want in your editor and choose the layout you want to use in the menu :
There is no need to add a layout inside a widget in the editor.
| {
"pile_set_name": "StackExchange"
} |
Q:
Connect to Server Db using msql command prompt
I am using mySql command prompt. A username and password is created(root,root), in my local.Now i want to coonect to server db(existing one) which has different username and password.How?
Thanks
A:
At the command line, type the following command, replacing USERNAME with your username:
mysql -u USERNAME -p
At the Enter Password prompt, type your password. When you type the correct password, the mysql> prompt appears.
To display a list of databases, type the following command at the mysql> prompt:
show databases;
To access a specific database, type the following command at the mysql> prompt, replacing DBNAME with the database that you want to access:
use DBNAME;
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I get the current url in Gatsby?
I am currently creating share buttons with Gatsby and would like to share content based on the current url, which changes depending on the environment and the current page. With GoHugo this can be called with {{ .Permalink }}. Does anyone know how to do this with Gatsby?
I have a ShareButtons component, which is a child of BlogPostTemplate.
A:
You can get the current url using the location prop from the @reach/router Location component.
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { Location } from '@reach/router';
class SomeComponent extends Component {
static propTypes = {
location: PropTypes.object.isRequired
}
render() {
const { location } = this.props;
return <div>{JSON.stringify(location)}</div>;
}
}
export default props => (
<Location>
{locationProps => <SomeComponent {...locationProps} {...props} />}
</Location>
);
A:
Gatsby uses react-router behind the scene meaning location information is available in props. This information can be used in a conditional statement or passed into styled-components like so:
<Component isIndex={this.props.location.pathname === '/'}>
| {
"pile_set_name": "StackExchange"
} |
Q:
How to remove the two last characters of a column in a TSV file using awk, perl or sed?
I would like to go from file A to file B using awk , sed or perl :
File A (tab separated) :
target_id length eff_length est_counts tpm
ENSORLT00000000001.1 1614 1663.8 266 2.69411
ENSORLT00000000002.8 1641 1724.36 62.1756 0.607613
ENSORLT00000000003.1 1389 1363.82 68.8244 0.850394
ENSORLT00000000004.3 537 484.396 2 0.0695767
ENSORLT00000000005.2 520 374.865 0 0
ENSORLT00000000007.1 1809 2083.96 699 5.65227
ENSORLT00000000008.4 1098 1099.36 423.548 6.49226
File B (tab separated) :
target_id length eff_length est_counts tpm
ENSORLT00000000001 1614 1663.8 266 2.69411
ENSORLT00000000002 1641 1724.36 62.1756 0.607613
ENSORLT00000000003 1389 1363.82 68.8244 0.850394
ENSORLT00000000004 537 484.396 2 0.0695767
ENSORLT00000000005 520 374.865 0 0
ENSORLT00000000007 1809 2083.96 699 5.65227
ENSORLT00000000008 1098 1099.36 423.548 6.49226
Each id in the first column has the same number of characters (except the column header).
I tried with sed 's/ENSORLT*.*\..\t/ENSORLT*/g' FileA > FileB but I think there is a problem with the *.
A:
sed 's/\..//' file
................
| {
"pile_set_name": "StackExchange"
} |
Q:
Python logging module prints unnecessary messages
Please consider this dummy code.
$ cat dummy.py
import logging
import time
from boto3.session import Session
# Logging Configuration
fmt = '%(asctime)s [%(levelname)s] [%(module)s] - %(message)s'
logging.basicConfig(level='INFO', format=fmt, datefmt='%m/%d/%Y %I:%M:%S')
logger = logging.getLogger()
def main():
session = Session(region_name='us-west-2')
client = session.client('ec2')
response = client.describe_instances(InstanceIds=['i-11111111111111111'])
logger.info('The instnace size is: %s', response[
'Reservations'][0]['Instances'][0]['InstanceType'])
if __name__ == '__main__':
main()
Output:
$ python3 dummy.py
03/03/2017 08:47:00 [INFO] [credentials] - Found credentials in shared credentials file: ~/.aws/credentials
03/03/2017 08:47:01 [INFO] [connectionpool] - Starting new HTTPS connection (1): ec2.us-west-2.amazonaws.com
03/03/2017 08:47:02 [INFO] [dummy] - The instnace size is: t2.micro
Question:
How to avoid below lines from being printed?
03/03/2017 08:47:00 [INFO] [credentials] - Found credentials in shared credentials file: ~/.aws/credentials
03/03/2017 08:47:01 [INFO] [connectionpool] - Starting new HTTPS connection (1): ec2.us-west-2.amazonaws.com
If I change logging.basicConfig(level='INFO',... to logging.basicConfig(level='WARNING',... then Those messages are not printed, but then all my messages get logged with WARNING severity.
I just want the logging module to print the messages that I explicitly write using logger.info .... and nothing else. Hence I need any pointers on how to avoid the unnecessary messages from being printed.
A:
Solution:
import logging
import time
from boto3.session import Session
# Logging Configuration
fmt = '%(asctime)s [%(levelname)s] [%(module)s] - %(message)s'
logging.basicConfig(format=fmt, datefmt='%m/%d/%Y %I:%M:%S')
logger = logging.getLogger('LUCIFER')
logger.setLevel(logging.INFO)
def main():
COUNTER = 3
session = Session(region_name='us-west-2')
client = session.client('ec2')
response = client.describe_instances(InstanceIds=['i-0a912622af142b510'])
logger.info('The instnace size is: %s', response[
'Reservations'][0]['Instances'][0]['InstanceType'])
if __name__ == '__main__':
main()
Output:
$ python3 dummy.py
03/03/2017 10:30:15 [INFO] [dummy] - The instnace size is: t2.micro
Explanation:
Earlier, I set the INFO level on root logger. Hence, all other loggers who do not have a level set, get this level propagated and start logging. In the solution, I am specifically enabling this level on a logger LUCIFER.
Reference:
from: https://docs.python.org/3/howto/logging.html
Child loggers propagate messages up to the handlers associated with their ancestor loggers. Because of this, it is unnecessary to define and configure handlers for all the loggers an application uses. It is sufficient to configure handlers for a top-level logger and create child loggers as needed. (You can, however, turn off propagation by setting the propagate attribute of a logger to False.)
AND
In addition to any handlers directly associated with a logger, all handlers associated with all ancestors of the logger are called to dispatch the message (unless the propagate flag for a logger is set to a false value, at which point the passing to ancestor handlers stops).
| {
"pile_set_name": "StackExchange"
} |
Q:
Rails: cache_classes => false still caches
It seems like cache_classes => false still caches them, and I have to shut down and restart the server to see any changes. Any ideas? I'm really stuck, and it's a very annoying problem.
My development.rb looks like this:
Total::Application.configure do
config.cache_classes = false
config.whiny_nils = true
config.threadsafe!
# Add the fonts path
config.assets.paths << Rails.root.join('app', 'assets', 'fonts')
# Precompile additional assets
config.assets.precompile += %w( .svg .eot .woff .ttf )
config.serve_static_assets = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# config.eager_load = false
config.action_mailer.default_url_options = { :host => 'lvh.me:3000' }
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default :charset => "utf-8"
config.action_mailer.smtp_settings = {
address: "smtp.gmail.com" # ETC
}
config.active_support.deprecation = :log
config.action_dispatch.best_standards_support = :builtin
config.active_record.mass_assignment_sanitizer = :strict
config.assets.compress = false
config.assets.debug = true
end
Any help would be great. Thanks.
A:
If anyone else has this problem the solution was the order: config.threadsafe! has to come before config.cache_classes. Reorder it like this to fix it:
...
config.threadsafe!
config.cache_classes = false
...
Update
It's simply because config.threadsafe! does this:
def threadsafe!
@preload_frameworks = true
@cache_classes = true
@dependency_loading = false
@allow_concurrency = true
self
end
See here for what thread safety does.
| {
"pile_set_name": "StackExchange"
} |
Q:
What method was used to kill an animal being sacrificed by a priest?
I know that it was very important to drain the blood of a sacrificed animal so that it could be spattered on the altar.
When imagining the priest taking on the task of killing a bull or a goat it seems that simply approaching the animal and using a knife or spear to inflict a blood draining wound would be dangerous. That is why modern slaughterhouses and people who butcher at home usually stun or kill the animal before letting the blood.
Is there any ancient writings describing the methodology of sacrificing animals?
A:
This is the method of shechitah (ritual slaughtering used today. We are commanded that the method of slaughtering used for animals (for regular eating) must be the same method as used for the altar. This is explained in Talmud Bavli Masechet Chulin 38a. See the Rashi below.
To explain in more detail, the talmud says that we use the method of shechita which is cutting the throat of the animal using a knife to sever more than 50% of both the esophagus and windpipe.
Note that puncturing the animal as with the point of a knife or a spear, invalidates the shechita. Killing or stunning the animal prior to the shechitah invalidates the procedure. The second temple had rings set in the floor to hold the animal in place.
Birds were slaughtered using a different procedure called melikah (using the fingernail to sever the back of the neck). Torah.org cites Vayikra 5:8
8 He shall bring them to the kohen, who shall first offer up that
[bird] which is [designated] for the sin offering. He shall cut its
head [by piercing with his nail] opposite the back of its head, but
shall not separate [it].
Rashi
but shall not separate [it]: He cuts only one organ [either the esophagus or the trachea]. — [Chul. 21a]
This would not be valid for regular (non-sacrificial) slaughter of a bird for eating.
The details of shechita are explained by the Rambam in The Mishna Torah, Sefer Kedusha, Hilchos Shechita Chapter 1. English
Halacha 4
The slaughter which the Torah mentions without elaboration must be
explained so that we know: a) which place in the animal is
[appropriate] for ritual slaughter?, b) what is the measure of the
slaughtering process?, c) with what do we slaughter?, d) when do we
slaughter?, e) in which place [on the animal's neck] do we slaughter?
f) how do we slaughter, g) what factors disqualify the slaughter? h)
who can slaughter?
Ramabam answers these questions in the following halachos.
chabad.org also gives a summary of the method used.
The procedure consists of a rapid and expert transverse incision with
an instrument of surgical sharpness (a chalaf), which severs the major
structures and vessels at the neck. This causes an instant drop in
blood pressure in the brain and immediately results in the
irreversible cessation of consciousness.
Deuteronymy 12:21
כא כִּי יִרְחַק מִמְּךָ הַמָּקוֹם אֲשֶׁר יִבְחַר יְהֹוָה אֱלֹהֶיךָ
לָשׂוּם שְׁמוֹ שָׁם וְזָבַחְתָּ מִבְּקָרְךָ וּמִצֹּאנְךָ אֲשֶׁר נָתַן
יְהֹוָה לְךָ כַּאֲשֶׁר צִוִּיתִךָ וְאָכַלְתָּ בִּשְׁעָרֶיךָ בְּכֹל
אַוַּת נַפְשֶׁךָ
21 If the place the Lord, your God, chooses to put His Name there,
will be distant from you, you may slaughter of your cattle and of your
sheep, which the Lord has given you, as I have commanded you, and
you may eat in your cities, according to every desire of your soul.
Rashi
וזבחת וגו' כאשר צויתך: למדנו שיש צווי בזביחה היאך ישחוט, והן הלכות שחיטה שנאמרו למשה בסיני
you may slaughter… as I have commanded you: We learn [from here] that there is a commandment regarding slaughtering, how one must
slaughter. [Since this commandment is not written in the Torah we
deduce that] these are the laws of ritual slaughtering given orally to
Moses on [Mount] Sinai. — [Sifrei ; Chul. 28a]
| {
"pile_set_name": "StackExchange"
} |
Q:
How to know which section header is on the top when use ListView?
I want to get the y position value when each section header is on the top.
For instance, A、B、C are my header title, when A is on the top y value is 100, B is 500, C is 1200.
My react native project version is 0.44.2, so I use ListView to achieve SectionList.
Here is my ListView code from FaceBook source code:
'use strict';
var ListView = require('ListView');
var Dimensions = require('Dimensions');
var Platform = require('Platform');
var StyleSheet = require('StyleSheet');
var React = require('React');
var View = require('View');
type Rows = Array<Object>;
type RowsAndSections = {
[sectionID: string]: Object;
};
export type Data = Rows | RowsAndSections;
type RenderElement = () => ?ReactElement;
type Props = {
data: Data;
renderEmptyList?: ?RenderElement;
minContentHeight: number;
contentInset: { top: number; bottom: number; };
contentOffset: { x: number; y: number; };
};
type State = {
contentHeight: number;
dataSource: ListView.DataSource;
};
// FIXME: Android has a bug when scrolling ListView the view insertions
// will make it go reverse. Temporary fix - pre-render more rows
const LIST_VIEW_PAGE_SIZE = Platform.OS === 'android' ? 20 : 1;
class PureListView extends React.Component {
props: Props;
state: State;
static defaultProps = {
data: [],
contentInset: { top: 0, bottom: 0 },
contentOffset: { x: 0, y: 0 },
// TODO: This has to be scrollview height + fake header
minContentHeight: 0, //Dimensions.get('window').height,
// renderSeparator: (sectionID, rowID) => <View style={styles.separator} key={rowID} />,
};
constructor(props: Props) {
super(props);
let dataSource = new ListView.DataSource({
getRowData: (dataBlob, sid, rid) => dataBlob[sid][rid],
getSectionHeaderData: (dataBlob, sid) => dataBlob[sid],
rowHasChanged: (row1, row2) => row1 !== row2,
sectionHeaderHasChanged: (s1, s2) => s1 !== s2,
});
this.state = {
contentHeight: 0,
dataSource: cloneWithData(dataSource, props.data),
};
(this: any).renderFooter = this.renderFooter.bind(this);
(this: any).onContentSizeChange = this.onContentSizeChange.bind(this);
}
componentWillReceiveProps(nextProps: Props) {
if (this.props.data !== nextProps.data) {
this.setState({
dataSource: cloneWithData(this.state.dataSource, nextProps.data),
});
}
}
render() {
const {contentInset} = this.props;
const {contentOffset} = this.props;
// console.log('ESDebug:content offset');
// console.log(contentOffset);
const bottom = contentInset.bottom +
Math.max(0, this.props.minContentHeight - this.state.contentHeight);
var removeSubviews = false;
if (Platform.OS === 'android') {
removeSubviews = true;
}
return (
<ListView
initialListSize={5}
pageSize={LIST_VIEW_PAGE_SIZE}
{...this.props}
ref="listview"
dataSource={this.state.dataSource}
renderFooter={this.renderFooter}
contentInset={{bottom, top: contentInset.top}}
contentOffset={contentOffset}
onContentSizeChange={this.onContentSizeChange}
scrollEventThrottle={1000}
decelerationRate ={'normal'}
removeClippedSubviews={true}
/>
);
}
onContentSizeChange(contentWidth: number, contentHeight: number) {
if (contentHeight !== this.state.contentHeight) {
this.setState({contentHeight});
}
}
scrollTo(...args: Array<any>) {
this.refs.listview.scrollTo(...args);
}
getScrollResponder(): any {
return this.refs.listview.getScrollResponder();
}
renderFooter(): ?ReactElement {
if (this.state.dataSource.getRowCount() === 0) {
return this.props.renderEmptyList && this.props.renderEmptyList();
}
return this.props.renderFooter && this.props.renderFooter();
}
}
function cloneWithData(dataSource: ListView.DataSource, data: ?Data) {
if (!data) {
return dataSource.cloneWithRows([]);
}
if (Array.isArray(data)) {
return dataSource.cloneWithRows(data);
}
return dataSource.cloneWithRowsAndSections(data);
}
var styles = StyleSheet.create({
separator: {
backgroundColor: '#eeeeee',
height: 1,
},
});
module.exports = PureListView;
And here is my components code about ListView:
var PureListView = require('../../common/PureListView');
render() {
return (
<PureListView
ref={(pureListView) => { this.pureListView = pureListView; }}
style = {{marginTop:0, backgroundColor:'white'}}
contentContainerStyle = {{flexDirection: 'row',flexWrap: 'wrap'}}
data= {this.state.sectionData}
renderEmptyList={this.renderEmptyList}
renderSectionHeader={this._renderSectionHeader}
onScroll={this._onScroll}
renderRow={this._renderRow}
navigator={this.props.navigator}
/>
);
}
I get the y position value from _onScroll function, but I have no idea how to get the y position value when A or B or C header title is on the top.
_onScroll(event) {
let offset = event.nativeEvent.contentOffset;
console.log(offset.y); // y position value
}
Any help would be appreciated.
A:
You can use onLayout to get A, B and C initial y positions, for example in your onScroll check when y position of scroll - A.y is 0, then this would be the current header at top
here's the method:
https://facebook.github.io/react-native/docs/view#onlayout
| {
"pile_set_name": "StackExchange"
} |
Q:
Jython: include custom java class [oanda]
>>> import sys
>>> sys.path.append("/usr/local/oanda_fxtrade.jar") # add the jar to your path
>>>
>>> import com.oanda.fxtrade.api.test.Example1 as main1
>>> import com.oanda.fxtrade.api.test.Example2 as cancel
main1("JPY",9,'-1')
TypeError: main1("JPY",9,'-1'): expected 0 args; got 3
This seems no error - but really i need some args
cancel()
Thread[Thread-0,5,main]
Inside java class
public final class Example1 extends Thread {
private Example1() {
super();
}
public static void main(String[] args) throws Exception {
FXClient fxclient = API.createFXGame();
String username = "foo";
String password = "foo";
String sel=args[0];
String str1=args[1];
String str2=args[2];
main1.main("JPY 9 -1")
TypeError: main(): 1st arg can't be coerced to String[]
Ok I think I went to the next level
A:
After
import com.oanda.fxtrade.api.test.Example1 as main1
main1 is the class. In java executing the class will run main but that doesn't mean you can pass args to the class.
Try:
main1.main(["JPY","9","-1"])
EDIT:
There were two separate issues here.
For the subsequent error Could not initialize class com.oanda.fxtrade.api.API... it looks like you should review this question: Why does Jython refuse to find my Java package?
calling sys.path.append to add the jar does not allow the package scanner operate which happens at load time. You should try either importing the required modules/classes manually or perhaps adding the jar to the CLASSPATH before invoking jython.
from here I think the jython answer is in and it becomes a com.oanda.fxtrade.api question with is probably outside SO scope.
| {
"pile_set_name": "StackExchange"
} |
Q:
PostgreSQL: cancel query from C/C++ program
I'm using PostgreSQL 8.3, and writing a program in C++ that uses the libpq API. I execute commands asynchronously with the PQsendQuery() function. I'm trying to implement a timeout processing feature. I implemented it by calling PQcancel() when the timeout expires. I tested it with a query that returns 100 000 rows (it lasts about 0.5 s) with a timeout of 1 ms, and found that instead of cancelling the command, PQcancel() blocks until the server finishes execution, then returns with a successful query.
I understand that the documentation says that even with a successful cancel request the query may still be executed. My problem is that PQcancel() blocks my thread of execution, which is not acceptable because I use asynchronous processing (using the Boost Asio framework) so my program, which may have other tasks to do other than executing the SQL query, runs only on one thread.
Is it normal that PQcancel() blocks? Is there any way to make a non-blocking cancel request?
A:
I looked at the implementation of PQcancel. It creates a separate TCP connection to the server, that's why it is blocking. This code part is exactly the same in the newest version of PostgreSQL too. So I concluded that there is no way to make it nonblocking other than starting the cancel in a separate thread. This is also the preferred way of using this feature, as the cancel object is completely independent from the connection object thus it is completely thread safe to use.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I install wide-plank solid hardwood over radiant floor heat?
I've been planning to replace my living room carpet with hardwood. I have radiant heating under the floor (boiler and pex piping). I was originally looking at 3/4" thick 3" to 5" wide boards, but after looking into how to DIY, I ended up with more questions than answers.
The recommended method of installation is nailing, but I have radiant heat, that sounds like a bad idea. Other advice I found recommended not to glue or float the boards. I'm in a cold climate as well, and saw advice not to use wide boards because they would warp. Is it really a good idea to put hardwood over radiant heat? And if so, what's the recommended method of installing it?
I used to have engineered beech (plywood backing) in my 2nd floor bathroom which was floating and the boards were glued to each other, and it held up well for over 10 years aside from water damage around the shower. I have laminate in one room and it was ruined when the roof leaked while we were on vacation (ice dam that formed in a spot that had never leaked before), so I'm not fond of anything that is MDF backed. I have pets and kids so its possible liquids could sit unnoticed on the floor.
I ordered various samples of solids and engineered woods. To my horror, some of the samples of engineered hardwood were MDF backed, and the 5" wide 1/2" thick plywood backed samples were slightly warped.
Whatever I install, I want it to last. Can I go with 3" hardwood and short nails or glue the boards together and float it? Or is engineered really the best way to go?
A:
There are lots of resources covering this topic, and since your question is rather broad I'm inclined to refer mostly to them. In general, you can install hardwood over floor heat if:
Subfloor temperatures are reasonable (say within 15 degrees of room air temperature)
You stick to quartersawn wood species that are known to handle heat well, or
You go with an engineered floor
More on that
| {
"pile_set_name": "StackExchange"
} |
Q:
Java heap out of space : after -XmX1G
I am trying to read a lot of data(10k-20k records) from files (10 threads running for 10 mins). I get an exception:
Exception in thread "main" Exception in thread "Thread-26" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOfRange(Unknown Source)
at java.lang.String.<init>(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
I get the above error message for the code snippet below.
I have been trying to debug this : and the closest I have come is to use CharSequence. But I still get the heap exception. (At this point - can anyone help me understand why CharSequence would be better? => It seems it'll load smaller amount of data in main memory, but eventually all the data needs to be in the main memory).
I am able to run the code if for 1 min. But anything near 10 mins explodes. Is there an efficient way to read the files?
**This code is part of a research and I am still re-factoring it, so a lot of inefficient code does exist.
try{
for(int i=0; i<threadCount; i++){
fstream = new FileInputStream(dir+"//read"+machineid+"-"+i + ".txt");
// Use DataInputStream to read binary NOT text.
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String line;
// Read File Line By Line
String[] tokens;
while ((line = br.readLine()) != null) {
tokens = line.split(",");
logObject record = new logObject(tokens[0], tokens[1], tokens[2],tokens[3], tokens[4], tokens[5], tokens[6], tokens[7], "", tokens[8]);
toBeProcessed[toBeProcessedArraySz] = record;
toBeProcessedArraySz++;
if(readToValidate == toBeProcessedArraySz){
try {
semaphore.acquire();
} catch (InterruptedException e) {
e.printStackTrace(System.out);
}
//create thread to process the read records
ValidationThread newVThread = new ValidationThread(props,toBeProcessed, updateStats, initCnt, semaphore, finalResults, staleSeqSemaphore, staleSeqTracker, seqTracker, seenSeqSemaphore, toBeProcessedArraySz, freshnessBuckets,bucketDuration);
vThreads.add(newVThread);
toBeProcessedArraySz = 0;
toBeProcessed = new logObject[readToValidate];
semaphore.release();
newVThread.start();
}
}
br.close();//remove to test
fstream.close();
}
}catch(Exception e){
e.printStackTrace(System.out);
}
A:
Do not simply increase the heapsize if you do not understand the problem. Increasing the heapsize does not solve your problem. It only postpones it till it's worse (taking longer to occur).
The problem is that your program does not wait with reading in data when the heap is full. This is a simple problem. There is nothing in your algorithm which stops the reading thread from filling the heap further and further. If the processing threads can not keep up with the reading speed, the OOME must occur at some point. You have to change this: For the data reading thread, add some way that it pauses reading if a maximum number of processing threads are active, and to resume reading data when the number of processing threads goes below this threshold again.
Moreover:
Maybe one of your files is corrupted and contains a very long line, e.g. > 500MB at one line. Find out if the OOME always occurs in the same line (this is very likely the case) and then check the line. What line delimeter does it have at the end, \n or \r\n? Or \r?
| {
"pile_set_name": "StackExchange"
} |
Q:
Evaluate the Determinants A?
Evaluate the Determinants
$$A=\left(\begin{matrix}
1 & 1 & 0 & 0 & 0\\
-1 & 1 & 1 & 0 & 0\\
0 & -1& 1 & 1 & 0\\
0& 0 & -1 & 1 & 1\\
0 & 0 & 0 & -1 & 1\\
\end{matrix}\right)$$
My attempst : I was thinking abouts the
Schur complement https://en.wikipedia.org/wiki/Schur_complement
$\det \begin{pmatrix}
A&B\\
C&D
\end{pmatrix}= \det (A-BD^{-1}C)\det D
$
As i not getting How to applied this formula and finding the Determinant of the Given question,,
Pliz help me or is There another way to find the determinant of the matrix.
Thanks u
A:
Given $A=\left(\begin{matrix}
1 & 1 & 0 & 0 & 0\\
-1 & 1 & 1 & 0 & 0\\
0 & -1& 1 & 1 & 0\\
0& 0 & -1 & 1 & 1\\
0 & 0 & 0 & -1 & 1\\
\end{matrix}\right)$
To find the determinant you need to find the upper triangular matrix and then multiply the diagonal elements of the matrix.
$$=\begin{vmatrix}
1 & 1 & 0 & 0 & 0\\
-1 & 1 & 1 & 0 & 0\\
0 & -1& 1 & 1 & 0\\
0& 0 & -1 & 1 & 1\\
0 & 0 & 0 & -1 & 1\\
\end{vmatrix}_{R_2->R_2+R_1}$$
$$=\begin{vmatrix}
1 & 1 & 0 & 0 & 0\\
0 & 2 & 1 & 0 & 0\\
0 & -1& 1 & 1 & 0\\
0& 0 & -1 & 1 & 1\\
0 & 0 & 0 & -1 & 1\\
\end{vmatrix}_{R_3->R_3+\dfrac12R_1}$$
$$=\begin{vmatrix}
1 & 1 & 0 & 0 & 0\\
0 & 2 & 1 & 0 & 0\\
0 & 0& \dfrac32 & 1 & 0\\
0& 0 & -1 & 1 & 1\\
0 & 0 & 0 & -1 & 1\\
\end{vmatrix}_{R_4->R_4+\dfrac23R_3}$$
$$=\begin{vmatrix}
1 & 1 & 0 & 0 & 0\\
0 & 2 & 1 & 0 & 0\\
0 & 0& \dfrac32 & 1 & 0\\
0& 0 & 0 & \dfrac53 & 1\\
0 & 0 & 0 & -1 & 1\\
\end{vmatrix}_{R_5->R_5+\dfrac35R_4}$$
$$=\begin{vmatrix}
1 & 1 & 0 & 0 & 0\\
0 & 2 & 1 & 0 & 0\\
0 & 0& \dfrac32 & 1 & 0\\
0& 0 & 0 & \dfrac53 & 1\\
0 & 0 & 0 & 0 & \dfrac85\\
\end{vmatrix}_{R_5->R_5+\dfrac35R_4}$$
Now the determinant $=1\times 2\times \dfrac32\times \dfrac53 \times \dfrac85=8$
| {
"pile_set_name": "StackExchange"
} |
Q:
AC compressor diagnosis - failed or failed with shrapnel?
What is the best way to diagnose if the compressor has simply failed versus self destructed with metal fragment release? I'd like to determine that myself before purchasing parts to make sure I buy exactly what I need before getting started. Also, I assume gas removal has to take place first. Will it be obvious to whoever I take it to for gas removal?
fyi: 2002 Toyota Camry v6
In my opinion, the contents of the compressor looked clean, but I can't say immaculate. I replaced the compressor, dryer and vac'd it for 30 minutes, then charged. I have cold air now... but for how long. We shall see.
Update: It has been about a year and the system is still going.
A:
The first thing to check is if the compressor turns by hand and if it does how smooth it turns.
The only way to tell if the there is metal leaving the compressor is to remove the hose fittings for the compressor output line and visually inspect the inside of the fittings. A word of caution is that metal may have moved through the system and not be visible in any one connection. I pull apart as many as I can and get a good look with a strong light.
Even small metal particles can lodge in the expansion valve and cause the system to not function.
A:
In addition to Fred's answer I just want to add that the system must be fully evacuated before attempting to disassemble any A/C connection! Also, take a q-tip and swab the inside of these fittings. The q-tip should not have any grey color to it after swabbing. Sometimes compressor failure isn't catastrophic enough to send large metal chunks into the system but rather fine metal shavings. If your a/c system has any UV dye in it you will notice the oil in the system has a bright green color. This isn't anything to worry about.
| {
"pile_set_name": "StackExchange"
} |
Q:
Java - From a String Type name how to initialize an ArrayList of that Type
May be many of you have several times wanted to do this. Right now I am trying to do it but stuck.
Say, I have a method like this:
private Object getList(String nameofType) {
return new ArrayList<Type>();
/**e.g. It returns ArrayList<java.lang.Double> if nameofType is "java.lang.Double",
/*ArrayList<java.io.File> if nameofType is "java.io.File"**/
}
How can I init an ArrayList like this?
A:
The closest thing to what you want to do, might be this:
private List getList(String nameofType) {
List list = null;
try {
Class clazz = Class.forName(nameofType); //must be fully qualified, example: "java.lang.Integer"
list = Collections.checkedList(new ArrayList(), clazz);
} catch (ClassNotFoundException e) {
// log exception, etc.
}
return list;
}
This will return an effectively type-checked list, that will throw an exception if you try to insert an object of different type than specified.
You can check it four yourself:
List list = getList("java.lang.Integer");
System.out.println("Inserting Integer");
list.add(new Integer(1));
System.out.println("List: "+ list);
System.out.println("Inserting Long");
list.add(new Long(1));
System.out.println("List: "+ list);
Output:
Inserting Integer
List: [1]
Inserting Long
Exception in thread "main" java.lang.ClassCastException: Attempt to insert class java.lang.Long element into collection with element type class java.lang.Integer
| {
"pile_set_name": "StackExchange"
} |
Q:
Email validation in Vue.js
I have been working with Vue for 24 hours now, so forgive the ignorance. I have searched around and I'm getting close, but I'm sure it's my lack of understanding and basic principles.
I have a modal that opens when a button is clicked. This modal displays a form with an email input. I managed to get the modal working, but nothing happens when I type in an incorrect email.
Here's my code for the component:
<template>
<div>
<!-- Aside -->
<aside class="aside">
<button class="aside__btn button" @click="showModal = true">
Send Me The Tips
</button>
</aside>
<!-- Modal -->
<div class="modal" v-if="showModal">
<div class="modal-container">
<a href="#" class="close" @click="showModal = false"></a>
<p class="modal__steps">Step 1 of 2</p>
<div class="relative">
<hr class="modal__divider" />
</div>
<div class="modal__heading-container">
<p class="modal__heading">Email Your Eail To Get <span class="modal__heading-span">Free</span>
</p>
<p class="modal__heading">iPhone Photography Email Tips:</p>
</div>
<form>
<input for="email" type="email" placeholder="Please enter your email here" required v-model="email">
<span class="floating-placeholder" v-if="msg.email">{{msg.email}}</span>
<!-- <span class="floating-placeholder">Please enter your email here</span> -->
<button class="modal__button button">Send Me The Tips</button>
</form>
</div>
</div>
</div>
</template>
<script>
export default ({
data () {
return {
showModal: false,
email: '',
msg: [],
}
},
watch: {
email(value) {
// binding this to the data value in the email input
this.email = value;
this.validateEmail(value);
}
},
methods: {
validateEmail(value){
if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(value))
{
this.msg['email'] = '';
} else{
this.msg['email'] = 'Please enter a valid email address';
}
}
}
})
</script>
I'm using Laravel if that's of importance.
A:
I would delete the watch and add an event listener on blur like so:
<input for="email" type="email" placeholder="Please enter your email here" required v-model="email" @blur="validateEmail" >
and update the validateEmail method like so :
validateEmail() {
if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(this.email)) {
this.msg['email'] = 'Please enter a valid email address';
} else {
this.msg['email'] = '';
}
}
You could also change the event listener to change @change if it serves your needs better.
| {
"pile_set_name": "StackExchange"
} |
Q:
Commercial satellite retrieval - possible?
I know that the space shuttle was originally designed with the capability to retrieve satellites from space, but I'm wondering if in the commercial market right now if there are services that allow the retrieval?
I've seen companies that do space junk clean up etc, but wondering if when companies or governments use SpaceX or one of the other launch companies to launch a satellite, do they also have the ability to go and get that satellite too?
A:
Defining "retrieval" as "returning a commercial satellite to earth" then as of this moment there is no known capability to do that. (Ground-ruling out capsules like Dragon that return themselves with internal cargo).
As you mention Shuttle was designed for that but it was decades since it performed that function.
One could speculate about the X-37 and SpaceX has mentioned using their proposed vehicles in this role. But as of right now...no.
| {
"pile_set_name": "StackExchange"
} |
Q:
Change styles based on dark or light mode
I want to have a dark and a light theme on my Vue app.
I can create dark.scss file and change classes styles and use !important property to override styles defined in components.
Or I can use props in my components and change className with v-if based on the theme.
e.g. set class to className__light when theme is light otherwise set to className__dark.
which one is better in all situations like performance or time needed to do it?
A:
Well i would not do it with classes. I would create CSS variables with either SCSS or you create CSS variables in :root
If you do it with the :root method then it should look something like this:
:root {
--background: red;
}
Then you can access it in any component like this for example:
.class {
background: var(--background); // the background will appear red
}
Now you can change the background color with just 1 CSS variables.
To change the variable with Javascript you just write following:
root.style.setProperty('--background', "green");
The problem here is that it isnt supported in IE if you care about browser support.
So you should create an fallback like this:
.class {
background: red; //fallback
background: var(--background); // the background will appear red
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Python suds error "'NoneType' object has no attribute 'promotePrefixes'"
I have an ASP.NET webservice running on a Windows 7 box. I have two Linux boxes (Ubuntu 12.04) that I'm trying to hit the webservice from, using Python 2.7.3 and Suds 0.4. The script I'm trying to execute is as follows:
from suds import client
from suds.transport.https import WindowsHttpAuthenticated
url = "https://webserver.mydomain.com/webservice/services.asmx?WSDL"
ntlm = WindowsHttpAuthenticated(username = "user", password = "pwd")
c = client.Client(url, transport = ntlm)
resp = c.service.GetData()
On one of my Linux boxes, this code executes perfectly and resp will contain the expected data returned from the web service. On the other Linux box, I get the following error message:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/var/www/dev/local/lib/python2.7/site-packages/suds/client.py", line 542, in __call__
return client.invoke(args, kwargs)
File "/var/www/dev/local/lib/python2.7/site-packages/suds/client.py", line 602, in invoke
result = self.send(soapenv)
File "/var/www/dev/local/lib/python2.7/site-packages/suds/client.py", line 643, in send
result = self.succeeded(binding, reply.message)
File "/var/www/dev/local/lib/python2.7/site-packages/suds/client.py", line 678, in succeeded
reply, result = binding.get_reply(self.method, reply)
File "/var/www/dev/local/lib/python2.7/site-packages/suds/bindings/binding.py", line 149, in get_reply
soapenv.promotePrefixes()
AttributeError: 'NoneType' object has no attribute 'promotePrefixes'
I need some ideas on what settings, etc. could be causing this difference in behavior between the two machines. Thanks in advance!
A:
I added lines to output additional logging information, and found that the problem had nothing to do with the Python error being thrown, but was instead due to the web service rejecting my connection. Here are the lines I added to the script posted in the question:
import logging
logging.basicConfig(level=logging.INFO)
logging.getLogger('suds.client').setLevel(logging.DEBUG)
With these lines added, my script then produced the following output (partial):
<body>
<div id="header"><h1>Server Error</h1></div>
<div id="content">
<div class="content-container"><fieldset>
<h2>403 - Forbidden: Access is denied.</h2>
<h3>You do not have permission to view this directory or page using the credentials that you supplied.</h3>
</fieldset></div>
</div>
</body>
From here I shifted my focus from the clients to the server, and was able to quickly identify the problem (which has nothing to do with my original question!).
| {
"pile_set_name": "StackExchange"
} |
Q:
Convert Coordinates of ASC File
I am trying to put the Solar Radiation data into QGIS with my current projection of EPSG:27700 but even when I change the projection, the data is well off the mark. The data comes from here: http://re.jrc.ec.europa.eu/pvgis/download/solar_radiation_classic_laea_download.html
The website states the data is in the map projection: Lambert Azimuthal Equal Area, ellipsoid WGS84
A:
The site you linked mentions these projection parameters:
Map projection: Lambert Azimuthal Equal Area, ellipsoid WGS84
Center point: 48° N, 18° E.
So you have to build a custom CRS in QGIS. As a reference, search for lambert in the list of EPSG codes to find:
North_Pole_Lambert_Azimuthal_Equal_Area EPSG:102017
+proj=laea +lat_0=90 +lon_0=0 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs
Copy the string to clipboard, goto Settings -> Custom CRS tab, paste it into the parameters field, and change the center as needed:
+proj=laea +lat_0=48 +lon_0=18 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs
Provide a name foor the projection (e.g. JRC laea) and hit OK.
Now you can drag and drop the asc file to the table of content. But beware, QGIS wrongly assings a false CRS, so rightclick on the layer -> Set Layer CRS, and select the custom CRS you just cretaed by searching for its name.
Once done, you can assign the project CRS to the same, and add a natural Earth shapefile as a reference:
Once you found it is correct, you can use Raster -> Projections -> Warp to reproject to any other CRS. Make sure you provide the source SRS and target SRS, because gdalwarp is an external command, and does not know what CRS you have assigned to the asc file inside the QGIS GUI. The asc file itself has no SRS information, like Geotoff or other formats have.
| {
"pile_set_name": "StackExchange"
} |
Q:
getting background to randomize on load?
So yeah I'm not very good at getting this page to do this. I had the goal to make a background apply a random color. So I put some colors into an array and decided to select a random one from it. This was my attempt, but it didn't tahe affect.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<script>
var r = Math.floor((Math.random()*4)+1);
var colors=["red", "blue", "green", "yellow", "pink"];
bodyObject.bgColor=colors[r].toString();
</script>
</body>
</html>
A:
Try this...
<script>
window.onload = function(){
var r = Math.floor((Math.random()*4)+1);
var colors=["red", "blue", "green", "yellow", "pink"];
document.body.style.backgroundColor =colors[r];
}
</script>
A:
I would use this code as it's most resilient to alteration;
var colors=["red", "blue", "green", "yellow", "pink"];
var r = Math.floor((Math.random()*colors.length-1)+1);
document.getElementsByTagName("body")[0].bgColor=colors[r];
Note that I originally suggested that you give your body tag an id "bodyObject", which is in fact the easiest way to fix the code as you'd written it, and was the cause of your bug, but that suggestion was poorly received.
Note here however, that I've also re-ordered a couple of lines allowing you to use the length property which is more robust to the numbers of items in your array.
You could also generate colours from scales of RGBs, but I'm not sure what effect you're going for.
| {
"pile_set_name": "StackExchange"
} |
Q:
Message persistence in Message Queues
I have looked into several message queues as referenced in this link. Several of the larger and more popular ones are in memory only.
I can understand the need for this in some situations however in a large architecture this makes little sense to me. For instance if I have a series of work that needs to be performed such as user calculations, object updates, info refresh, and then the MQ crashes all work is lost.
If this is imperative the lost work could be loaded again however why would I want to?
I would imagine there is vital and then regular pieces of information however if I use a non-persistence MQ then all my data would be regular and that doesn't seem valid.
A:
Consider a client that wishes to push a message to a queue. The queue manager would typically send a message acknowledgement to the client to signify that the message was successfully delivered to the queue. A persistent MQ would first need to write the message to persistent storage which for most storage media would be an expensive IO operation relative to memory operations.
The cost of persistence in message queues is a factor that may play into a decision to go for non-persistent message queues.
The drawbacks of non-persistent message queues are essentially that you must contend with potential data loss in the event of a partial or complete outage of a machine, however this isn't always necessarily true if you opt for distributed non-persistent message queues in a cloud based infrastructure across multiple data centers. This would ensure that even a complete data center outage for a cloud hosting provider would not result in loss of the message, at least one other node is guaranteed to still have the message.
Of course if potential for message loss is not a serious concern for your application then you don't even need such a complex solution. It becomes a comparison of quality attributes, Performance vs. Reliability.
| {
"pile_set_name": "StackExchange"
} |
Q:
Unable to run Spring Boot WebMVC with Thymeleaf support
I have search a lot but I did not find answer to my question, So I am posting my question here. Please look and suggest me the solution where I am mistaken.
I have created spring boot web mvc project with thymeleaf support using Spring Tool Suite(STS). When I run it give me "Whitelabel Error Page" page. Which means mapping not found.
Efforts:
WebConfig.java
package com.springthymeleaf.config;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
@Configuration
@ComponentScan("com.springthymeleaf")
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Bean
ServletRegistrationBean servletRegistration(){
ServletRegistrationBean registrationBean = new ServletRegistrationBean();
registrationBean.addUrlMappings("/console/*");
return registrationBean;
}
//start Thymeleaf specific configuration
@Bean(name ="templateResolver")
public ServletContextTemplateResolver getTemplateResolver() {
ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
// templateResolver.setPrefix("/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("XHTML");
return templateResolver;
}
@Bean(name ="templateEngine")
public SpringTemplateEngine getTemplateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(getTemplateResolver());
return templateEngine;
}
@Bean(name="viewResolver")
public ThymeleafViewResolver getViewResolver(){
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(getTemplateEngine());
return viewResolver;
}
//end Thymeleaf specific configuration
@Bean(name ="messageSource")
public MessageSource getMessageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("/WEB-INF/i18/thymeleafResource");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
}
SecurityConfiguration.java
package com.springthymeleaf.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeRequests().antMatchers("/").permitAll();
}
}
ServletInitializer.java
package com.springthymeleaf;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SpringThymeLeafApplication.class);
}
}
SpringThymeLeafApplication.java
package com.springthymeleaf;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringThymeLeafApplication {
public static void main(String[] args) {
SpringApplication.run(SpringThymeLeafApplication.class, args);
}
}
IndexController.java
package com.springthymeleaf.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class IndexController {
@RequestMapping("/")
public String index(){
return "index";
}
}
I have created index.html file in resources/templates folder. Still I am getting that error. I have searched a lot on web, but did not get clue. Please somebody help me.
A:
Actually Spring Boot configures Thymeleaf out of the box. It should work with the following setup:
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
@Override
protected void configure(HttpSecurity http) throws Exception
{
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").defaultSuccessUrl("/").permitAll() // http://docs.spring.io/spring-security/site/docs/4.0.3.RELEASE/reference/htmlsingle/#jc-form
.and()
.logout().permitAll(); // http://docs.spring.io/spring-security/site/docs/4.0.3.RELEASE/reference/htmlsingle/#jc-logout
}
@Override
public void configure(WebSecurity web) throws Exception
{
web
.ignoring()
.antMatchers("/resources/**"/*, ... */);
}
}
@Controller
public class LoginController
{
@RequestMapping("/login")
static String login(Model model)
{
return "login";
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Update project from older CUDA version
In my older CUDA project I had the globals:
__device__ uint8_t dev_intersect
__constant__ uint8_t dev_flags
... and used them this way:
cudaGetSymbolAddress((void**)&ptr_dev_intersect,"dev_intersect")
cudaMemcpyToSymbol("dev_flags",&flags,sizeof(flags))
Now, since CUDA 5.0 (and newer) the symbols must be passed directly (without string), so I define the globals this way:
__device__ uint8_t *dev_intersect
__constant__ uint8_t *dev_flags
...and call the functions this way:
cudaGetSymbolAddress((void**)&ptr_dev_intersect,dev_intersect)
cudaMemcpyToSymbol(dev_flags,&flags,sizeof(flags))
Am I doing it right so far? I'm asking you, because when I update the code, I start getting other errors, which makes me kinda suspicious. Thanks for any help.
A:
Switching from a POD variable to a pointer is probably not what you want.
If you didn't make changes elsewhere in your code to account for that difference, I would expect things to break.
To update your cuda function calls, leave your variables as-is:
__device__ uint8_t dev_intersect;
__constant__ uint8_t dev_flags;
And just drop the quotes from your cuda API functions that use those variables:
cudaGetSymbolAddress((void**)&ptr_dev_intersect,dev_intersect);
cudaMemcpyToSymbol(dev_flags,&flags,sizeof(flags));
Here is a complete worked example:
$ cat t524.cu
#include <stdio.h>
typedef unsigned char uint8_t;
__device__ uint8_t dev_intersect;
__constant__ uint8_t dev_flags;
__global__ void mykernel(uint8_t *d1_ptr){
printf("data 1 = %c\n", *d1_ptr);
printf("dev_flags = %c\n", dev_flags);
}
int main(){
uint8_t *ptr_dev_intersect;
uint8_t flags = 'X';
uint8_t dev_intersect_data = 'Y';
cudaGetSymbolAddress((void**)&ptr_dev_intersect,dev_intersect);
cudaMemcpyToSymbol(dev_flags,&flags,sizeof(flags));
cudaMemcpyToSymbol(dev_intersect,&dev_intersect_data,sizeof(dev_intersect_data));
mykernel<<<1,1>>>(ptr_dev_intersect);
cudaDeviceSynchronize();
return 0;
}
$ nvcc -arch=sm_20 -o t524 t524.cu
$ cuda-memcheck ./t524
========= CUDA-MEMCHECK
data 1 = Y
dev_flags = X
========= ERROR SUMMARY: 0 errors
$
| {
"pile_set_name": "StackExchange"
} |
Q:
Kafka Streams KTable configuration error on Message Hub
This issue is now solved on Message Hub
I am having some trouble creating a KTable in Kafka. I am new to Kafka, which is probably the root of my problem, but I thought I could ask here anyway. I have a project where I would like to keep track of different IDs by counting their total occurrence. I am using Message Hub on IBM Cloud to manage my topics, and it has worked splendid so far.
I have a topic on Message Hub that produces messages like {"ID":"123","TIMESTAMP":"1525339553", "BALANCE":"100", "AMOUNT":"4"}, for now, the only key of relevance is ID.
My Kafka code, along with the Streams configuration, looks like this:
import org.apache.kafka.streams.StreamsConfig;
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, appId);
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());
props.put(StreamsConfig.REPLICATION_FACTOR_CONFIG, "3");
props.put("security.protocol","SASL_SSL");
props.put("sasl.mechanism","PLAIN");
props.put("ssl.protocol","TLSv1.2");
props.put("ssl.enabled.protocols","TLSv1.2");
String saslJaasConfig = "org.apache.kafka.common.security.plain.PlainLoginModule required username=\"USERNAME\" password=\"PASSWORD\";";
saslJaasConfig = saslJaasConfig.replace("USERNAME", user).replace("PASSWORD", password);
props.put("sasl.jaas.config",saslJaasConfig);
StreamsBuilder builder = new StreamsBuilder();
KStream<String, String> Kstreams = builder.stream(myTopic);
KTable<String, Long> eventCount = Kstreams
.flatMapValues(value -> getID(value)) //function that retrieves the ID
.groupBy((key, value) -> value)
.count();
When I run the code, I get the following error(s):
Exception in thread "KTableTest-e2062d11-0b30-4ed0-82b0-00d83dcd9366->StreamThread-1" org.apache.kafka.streams.errors.StreamsException: Could not create topic KTableTest-KSTREAM-AGGREGATE-STATE-STORE-0000000003-repartition.
Followed by:
Caused by: java.util.concurrent.ExecutionException: org.apache.kafka.common.errors.PolicyViolationException: Invalid configuration: {segment.index.bytes=52428800, segment.bytes=52428800, cleanup.policy=delete, segment.ms=600000}. Only allowed configs: [retention.ms, cleanup.policy]
I have no idea why this error occurs, and what could be done about it. Is the way I have built the KStream and KTable incorrect somehow? Or perhaps the message hub on bluemix?
Solved:
Adding an extract from the comments below the answer I have marked as correct. Turned out my StreamsConfig was fine, and that there (for now) is an issue on Message Hub's side, but there is a workaround:
It turns out Message Hub has an issue when creating repartition topics with Kafka Streams 1.1. While we work on a fix, you'll need to create the topic KTableTest-KSTREAM-AGGREGATE-STATE-STORE-0000000003-repartition by hand. It needs as many partitions as your input topic (myTopic) and set the retention time to the max. I'll post another comment once it's fixed
Many thanks for the help!
A:
Message Hub has some restrictions on the configurations that can be used when creating topics.
From the PolicyViolationException you received, it looks like your Streams application tried to use a few configs we don't allow:
segment.index.bytes
segment.bytes
segment.ms
I'm guessing you set those somewhere in your Streams configuration and they should be removed.
Note that you also need to set StreamsConfig.REPLICATION_FACTOR_CONFIG to 3 in your config to work with Message Hub as mentioned in our docs.
| {
"pile_set_name": "StackExchange"
} |
Q:
Mvc - How to stream large file in 4k chunks for download
i was following this example, but when download starts it hangs and than after a minute it shows server error. I guess response end before all data id sent to client.
Do you know another way that i can do this or why it's not working?
Writing to Output Stream from Action
private void StreamExport(Stream stream, System.Collections.Generic.IList<byte[]> data)
{
using (BufferedStream bs = new BufferedStream(stream, 256 * 1024))
using (StreamWriter sw = new StreamWriter(bs))
{
foreach (var stuff in data)
{
sw.Write(stuff);
sw.Flush();
}
}
}
A:
Can you show the calling method? What is the Stream being passed in? Is it the Response Stream?
There are many helpful classes to use that you don't have to chuck yourself because they chunk by default. If you use StreamContent there is a constructor overload where you can specify buffer size. I believe default is 10kB.
From memory here so it my not be complete:
[Route("download")]
[HttpGet]
public async Task<HttpResponseMessage> GetFile()
{
var response = this.Request.CreateResponse(HttpStatusCode.OK);
//don't use a using statement around the stream because the framework will dispose StreamContent automatically
var stream = await SomeMethodToGetFileStreamAsync();
//buffer size of 4kB
var content = new StreamContent(stream, 4096);
response.Content = content;
return response;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
C# FormatException double.parse(), Why isn't 0.89 parsing?
class Program
{
static void Main(string[] args)
{
string str = "0.898";
double dbl = Double.Parse(str);
dbl++;
Console.WriteLine(dbl);
Console.ReadLine();
}
}
All other formats that I need to work, like "100" works. But as soon as I add a 'dot' I have a FormatException error.
A:
maybe try:
double dbl = double.Parse(str , CultureInfo.InvariantCulture);
check here at ideone
Your problem is that your culture does not allow dot's. Invariant culture is not the only solution, you can also specify your culture and use it's separators. If your current culture accepts only commas as separators it could also be a solution to replace dot with comma. Not specifying culture explicitly will effect in problems with parsing numbers in different machines running different cultures.
Everything that is culture specific is always tricky and should be defined as precise as it's possible. If you know excatly which double format you will use, define it. If you know which date format you will use, specify it etc.
| {
"pile_set_name": "StackExchange"
} |
Q:
Store referring keyword in a PHP Session
I'd like to store the keyword that customers use to visit my website in a PHP Session.
Can someone explain how this is done?
So if a customer types 'football laces' and clicks on my site in the list of results, my script would store this data in a session.
Is it universal or would it change depending on Google/Bing/Yahoo search engine.
UPDATE This looks good for me: http://www.liamdelahunty.com/tips/php_google_referer.php
Thanks for the input with the answers. Much appreciated.
Many thanks
A:
You could use $_SERVER['HTTP_REFERER'] to see where a user came from. Google does for example put the keywords in the URL.
| {
"pile_set_name": "StackExchange"
} |
Q:
A problem with Vivek's vcam of directshow
CVCam::CVCam(LPUNKNOWN lpunk, HRESULT *phr) :
CSource(NAME("Virtual Cam"), lpunk, CLSID_VirtualCam)
{
ASSERT(phr);
CAutoLock cAutoLock(&m_cStateLock);
// Create the one and only output pin
m_paStreams = (CSourceStream **) new CVCamStream*[1];
m_paStreams[0] = new CVCamStream(phr, this, L"Virtual Cam");
}
What's the reason to instantiate m_paStreams twice?
Does CAutoLock cAutoLock(&m_cStateLock); work for separate request(by different application) to this filter?
A:
I have no idea what this code is about, but I can assure you that m_paStreams is only initialized once in what you've posted.
It appears that m_paStreams is intended to be an array of pointers to CSourceStream objects. Presumably, it's possible to have more than one of these objects, hence, the array. Your code simply creates an array of size 1, and then for the first element of the array, creates the CVCamStream object.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why do characters and enemies in Rayman Origins swell up like balloons when they die?
I know that the characters in Rayman Origins are inhabitants of a kind of dreamland but why do they swell up like balloons before they explode? Is there a precedent for this or is merely a stylistic thing? I don't recall this happening in the original Rayman.
A:
From a plot point of view, the world is affected by the dreams / nightmares of the Bubble Dreamer (the guy with the beard below), so I guess he dreams about bubbles a lot.
In terms of gameplay, this blog entry on the Rayman website describes the thinking behind bubbles:
A health bar didn’t feel right in a game where you might lose all those hard earned “health points” by falling into a pit. So it was natural to limit those, and a great opportunity to get rid of the GUI. Instead we took the bubblizing approach. If you take a hit or fall into a pit you turn into a bubble. You can be revived by one of your co-op partners with a simple punch or jump.
...
in co-op mode. If your friend is running ahead, you are left with fewer opportunities to kick ass. So Michel came up with the idea to bubblize enemies. It was great, because all of a sudden lagging players could finish those bad guys, and earn one of those happy lums too.
| {
"pile_set_name": "StackExchange"
} |
Q:
Detecting suppressed auras
The various Realms of Power books describe how an aura can be suppressed by a stronger (or equal-level Divine) aura; but I can't see anything definitive that says that either:
You can't detect the suppressed aura (until it ceases being suppressed)
You can detect it, and here's how.
Can anyone provide a pointer to something I've missed?
A:
To begin with some quotes:
RoP:D, p10 has this to say about Dominiating Divine Auras:
More so than other auras, the
Dominion regularly conflicts and challenges the auras from other realms.
During the expansion of Christianity,
Islam, and the kingdom of Israel, the
Dominion abutted and pressed against
Magic and Faerie auras. Due to the purpose and nature of the Dominion, when it
comes to influence in an area with another realm’s aura of equal strength, the Dominion will trump the opposing aura; a more-powerful aura will still overwhelm
the Dominion, however.
Exempli Gratia: A church with a
Dominion rating of 4 is built
upon an ancient pagan temple to
Pan with a Faerie aura of 4. The
Dominion will preside during
the day. At night (when the
Dominion decreases to 3) and
on holy days to Pan (when the
Faerie aura increases to 5), the
Faerie aura emerges.
Thus, the faerie aura doesn't go away, it just isn't influencing the world. While, over time, this will result in the creation of a faerie regione, depending on the nature of the faeries and the stories they are telling.
RoP:M p13:
Magic regiones can also arise due to the
impingement of a stronger foreign aura, but
this is significantly rarer, at least for cov-
enants. The foreign aura compresses the
area of the Magic aura so strongly that the
Magic appears to vanish. Usually the Magic
aura has indeed vanished, but sometimes it
will instead move up into a regio, leaving the
lower level in contact with the foreign aura.
However, both of these are refinements and restatements of the core rules, p183:
Two realms may have influence over the
same place. When this is the case, only the
stronger can hold sway at any one time. A
change in the relative strengths of the two
realms can cause an area to switch from the
influence of one to the other.
Therefore, there is no reason why the presiding of the divine dominion aura prevents detection via the ImVi 1 guidelines, save if God wills it. However, if we presume the aura is "eliminated" we can merely treat it much like negative magnitudes of spell residues (HoH:TL 74) and increase the magnitude of the effect needed to discover the aura.
| {
"pile_set_name": "StackExchange"
} |
Q:
React Native with Redux: mapStateToProps()-function is not updating
I am working at a React Native and Redux project with several reducers, that are combined through combineReducers().
I have one component, that doesn't dispatches any actions but only shows information from the redux state. It is connected to this state with the connect function:
class MyComponent extends React.Component {
componentWillMount() {
// some code
}
render() {
return(
<Text>
{ this.props.value }
</Text>
)
}
}
function mapStateToProps(state) {
return {
value: state.updaterReducer.value,
}
}
export default connect(
mapStateToProps,
) (MyComponent);
There's another part/component in the project, that changes the redux state and value:
import { makeUpdate } from './updater.actions.js';
import configureStore from '@redux/configureStore.js';
const store = configureStore();
// This function is can be called by some buttons in the app:
export default function update() {
console.log('Update function called');
store.dispatch(makeUpdate());
}
And here's my problem: when update is called, the updater-action and the updater-reducer are both called, so that the redux state changes, but 'MyComponent' never updates.
A:
I could solve the problem on my own: The solution was very easy in the end, but couldn't be found on the basis of the code in the original question: Every time I needed the redux-store, I used a configureStore-function from a web-tutorial to create it on basis of the reducers. So I created multiple times the 'same' store. Unfortunately these stores were not connected to each other...
Sometimes that worked in the project, because a mapStateToProps-function and a mapDispatchToProps-function both were in the the same component and used one store, but sometimes (like in the example in the question) those functions used different stores and couldn't influence each other.
| {
"pile_set_name": "StackExchange"
} |
Q:
django - "auth_files_fileid_id" is an index
I have the following models.py
class FileIndex(models.Model):
filename = models.CharField(max_length=256)
filetype = models.CharField(max_length=16)
vendorid = models.IntegerField()
vendorname = models.CharField(max_length=256)
tablename = models.CharField(max_length=256)
class Meta:
db_table = 'file_index'
verbose_name = 'File/Vendor Index'
verbose_name_plural = 'File/Vendor Indicies'
def __str__(self):
return self.filename
class UserFile(models.Model):
userid_id = models.ManyToManyField(User)
fileid_id = models.ManyToManyField(FileIndex)
grant_date = models.DateTimeField()
revoke_date = models.DateTimeField(blank=True)
class Meta:
db_table = 'auth_files'
verbose_name = 'User File Matrix'
verbose_name_plural = 'User File Matricies'
def get_userids(self):
return "\n".join([u.pk for u in self.userid_id.all()])
def get_fileids(self):
return "\n".join([f.pk for f in self.fileindex.all()])
I then run the following view in my views.py -
class ExampleView(APIView):
model = cdx_composites_csv
serializer_class = cdx_compositesSerializer
def get(self, request, format=None):
if UserFile.objects.filter(fileid_id=1, userid_id=2).exists():
content = {
'status': 'Request Successful.'
}
return Response(content)
else:
content = {
'status': 'Request Failed.'
}
return Response(content)
It fails with the following error message -
"auth_files_fileid_id" is an index
The SQL it's trying to run is the following -
u'SELECT (1) AS "a" FROM "auth_files"
INNER JOIN "auth_files_fileid_id" ON ( "auth_files"."id" = "auth_files_fileid_id"."userfile_id" )
INNER JOIN "auth_files_userid_id" ON ( "auth_files"."id" = "auth_files_userid_id"."userfile_id" )
WHERE ("auth_files_fileid_id"."fileindex_id" = 1 AND "auth_files_userid_id"."user_id" = 2 ) LIMIT 1'
If I were to write the query in the DB this is how it would look - for some reason the query is waaaaaay off and I'm unsure why it's registering like above.
select * from auth_files af
inner join auth_user on au.id = af.userid
inner join fileindex fi on fi.id = af.fileid
where fi.id = 1 and au.id = 2
Looking at the query that Django is creating it's trying to inner join on itself I have no idea why.
This is ultimately what I want the query to be -
select fi.filename from auth_files af
inner join auth_user on au.id = af.userid
inner join fileindex fi on fi.id = af.fileid
where fi.filename = 'filename' and au.username = 'testuser'
A:
If you want those queries, then you have the wrong relationship type (not to mention your extremely odd field names). You're describing a foreign key relationship, but you have declared a many-to-many. M2M relationships require a linking table, which Django automatically names with the source table + fieldname - but apparently this conflicts with an index you have defined.
I would change those very strange fieldnames into something more standard ("users" and "fileindexes" would do fine) and recreate the database.
Edited As confirmed by the comments, you do have the wrong field type here. UserFile is already the linking table of a many-to-many relationship, so you need to use ForeignKey fields to both User and File. Again, though, you should use sensible names: each UserFile can only relate to one of each, so these names should be "user" and "file".
The many-to-many relationship is really from FileIndex to User, going through FileIndex, so you should declare it like that.
class UserFile(models.Model):
user = models.ForeignKey(User)
file = models.ForeignKey(FileIndex)
...
class FileIndex(models.Model):
users = models.ManyToManyField(User, through=UserFile)
| {
"pile_set_name": "StackExchange"
} |
Q:
If The Knights and Knaves got together
If the island of knights and knaves got together and there were n people, including a joker, how many questions would it take for all of the knights and knaves found the joker?
Nobody knows who each other is. When the knight finds the joker, he/she may tell the others, if a knave finds a knight/another knave the knave will do so. Only 1 person asks a question at once. The knave can not always exclaim he/she found a joker when they find a knight/knave. Let's assume a 50-50 chance of telling the others.
What's the least amount of questions needed to guarantee everybody knows who the joker is for sure?
The joker don't just randomly tell truth/lie. He can also exclaim that he found the joker himself.
Standard rules apply, nobody had any knowledge about eachother, or what they would have answered. You can not silence them, if you do they will kill you (very violent knights and knaves huh?)
A:
First, I am not trying to find the smallest number of questions. Let's just find an answer and then try to optimize it.
If you ask to each person the question "Are you the joker?", the knights would answer "no" and the knaves would answer "yes". This easily separates them, but leaves the joker in any of the two groups.
Lets suppose that the joker answered "no", so he is in the knights group. Since he does not want to be caught and is presumably smart, he would pose himself as a knight, always giving the answers that a knight would give.
Now, lets suppose that the joker answered "yes", so he is in the knaves group. Since he does not want to be caught and is presumably smart, he would pose himself as a knave, always giving the answers that a knave would give.
Since nobody (except the joker himself) knows if somebody else is or is not the joker and nobody can give a proof that he is not the joker, we have a situation that if the joker answered "yes", he can't be distinguished from a knight. If he answered "no", he can't be distinguished from a knave.
Asking a knight "Do you know who is the joker", he would answer "No". The knave would answer "Yes". The joker would follow saying what a knight or a knave would say accordingly to his previous answers. No information is gained here.
Asking a knight if somebody else is or is not the joker would produce the answer "I don't know" or something similar. If you ask this to a knave, he could not answer "yes", "no" or "I don't know", so he would answer "I know the answer, but I can't tell you" or something similar. The joker would follow the answers from the group he chose. This is essentially the same as the previous question, so again, no information is gained here.
If the question is changed to "Is the joker among/not among that X group?" the same "I don't know" and "I know the answer, but I can't tell you" answers will follow from the same people for any arbitrary definition of group X, and no information gain would be produced. There is an exception for trivial cases where X is an empty group, a group with everybody or a group with everybody except who is being asked, which would not produce any information gain either.
If you change the question to "what would the person X answer if I asks him if person Y is the joker?", the pattern gets a bit more complicated, but this would not produce any information gain either.
So, in all the ways, except if the joker blunders by producing an incoherent answer somewhere, it is impossible to solve the puzzle only with the provided information, even if we knew what the joker answered to the "are you the joker?" question (and yet, we don't).
But I have a lateral thinking answer: To not be caught, when the joker decides to pose himself definitely either as a knight or a knave, he essentially becomes a knight or a knave, so we have no joker anymore, and thus the puzzle is solved: Nobody is the joker and the least amount of questions is zero!
| {
"pile_set_name": "StackExchange"
} |
Q:
Filtering for NULL on a joined table
I have this query:
select t1.l_id, coalesce(t2.o_id,0) from t1 left join t2 using(l_id);
which gives me a result, with 0 in the second column. However, when I put a where on the column, it gives me no results:
select t1.l_id, coalesce(t2.o_id,0) from t1 left join t2 using(l_id)
where t2.o_id = null;
How can I select records that have no joined record?
A:
Use:
WHERE t2.o_id IS NULL;
instead of:
WHERE t2.o_id = NULL;
If t2.o_id is NULL then the second predicate evaluates to NULL not true as one might expect. This is the so-called three-valued logic of SQL.
| {
"pile_set_name": "StackExchange"
} |
Q:
Making one project a sub-project of another project in coq?
I am testing a coq project called corn, which requires another project MathClasses as a dependency. I was able to compile the dependency project MathClasses via a sudo make install kind-of process.
However, there are certain features in the make install process that I don't like.
Firstly, if I do a make again, coq seem to be confused about what's already installed somewhere in the system and what's currently being compiled.
Secondly, the project did not provide a remove or uninstall method in the make file. And I suspect this might cause me problems when I upgrade to a new version of coq.
So my questions are:
Is it possible (and how) to make the dependency project (i.e. MathClasses) a sub-project of CoRN, so that I can compile the whole thing by issuing one command from the top project (CoRN)?
After I make a coq project, can I load it into coqtop without install it into the system directories? (i.e. How can I modify and test the project locally).
Thanks in advance.
-- EDIT --
@Arthur Azevedo De Amorim : You mentioned
Plus, OPAM makes it possible to work with your own local version of a package
Any further pointers about this?
Thanks again
A:
Setting up sub-projects
You can always set up the load path in the project Makefile, so that it finds exactly the version of the library you want.
Suppose that your copy MathClasses lives in /path/to/MathClasses. You can then add the following line to the Make.in file in the CoRN distribution:
-R path/to/MathClasses/ MathClasses
After doing that, the compilation process should be able to find the MathClasses files.
That being said, installing a package directly is not such a big deal. I find it strange that Coq is getting confused about which files to use when you hit make; could you include which error messages you are getting? While upgrading Coq by yourself can cause problems with the libraries that are already installed, removing the problematic files is just a matter of removing the corresponding directory (MathClasses, in your case) under the user-contribs directory of your Coq library path.
Also, managing your Coq install is probably easier with OPAM. There is a GitHub repository with updated Coq packages that can be used with OPAM, including MathClasses and CoRN; using it would make the whole Coq update problem go away. Plus, OPAM makes it possible to work with your own local version of a package (see here), which seems what you want to do with CoRN.
Loading packages
If you are using Emacs and Proof General, you can configure a project's load path directly, as explained here.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to submit a string array in a form Rails 4.2
I have a model message with a string array attribute recipients. Here's what my messages_controller.rb looks like:
def new
@message = Message.new
@message.attachments = params[:attachments]
end
def create
@message = Message.new(create_params)
@message.user_id = current_user.id
@message.attachments = params[:message][:attachments]
@message.recipients = params[:message][:recipients]
save_message or render 'new'
end
private
def create_params
params.require(:message).permit(:object, :content,
:recipients,
:attachments)
end
And the _fields.html.erb looks like this:
<%= render 'shared/error_messages', object: f.object %>
<%= f.label :object %>
<%= f.text_field :object, class: "form-control" %>
<%= f.label :recipients %>
<%= f.text_field :recipients, multiple: true, class: "form-control" %>
<%= f.label :attachments %><br>
<%= f.file_field :attachments, multiple: true, class: 'form-control' %><br />
<%= f.label :content %>
<%= f.text_area :content, class: "form-control" %>
The problem is that it saves the recipients array like this:
["recipient_1, recipient_2"]
instead of
["recipient_1", "recipient_2"]
I want to be able to retrieve recipient[0] = recipient_1 and not recipient[0] = whole array.
It's probably something simple, but I can't find the fix.
All inputs appreciated.
Thanks
A:
It is returning a single string because the input is a text field. If you want to utilize a text field for this then just expect that the input will be comma-separated and split the input:
@message.recipients = params[:message][:recipients].split(',')
# or, if it's wrapped in an array
# @message.recipients = params[:message][:recipients][0].split(',')
| {
"pile_set_name": "StackExchange"
} |
Q:
Should questions that answer themselves answer themselves in the answer section of the post
For example, if I discover that a compiler has an error, would posting the question and answer to that question in the question section of the post be considered a bad thing to do in this site? Should I post the question and answer separately instead?
A:
would posting the question and answer to that question in the question section of the post be considered a bad thing to do in this site?
Yes. The question is where you ask a question, not where you post an answer.
Should I post the question and answer separately instead?
Yes, just be sure that both the question and the answer are of high quality when evaluated independantly. It's not okay to ask a bad question just because you're answering it, and a bad answer isn't automatically good just because it's the question author that answered it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is the ring of integers initial in Ring?
In Algebra Chapter 0 Aluffi states that the ring $\Bbb{Z}$ of integers with usual addition and multiplication is initial in the category Ring. That is for a ring $R$ with identity $1_{R}$ there is a unique ring homomorphism $\phi:\Bbb{Z}\rightarrow{R}$ defined by $\phi(n)\mapsto{n\bullet1_{R}}$ $(\forall{n\in\Bbb{Z}})$which makes sense for rings such as $\Bbb{Q},\Bbb{R},\Bbb{C}$ which have $\Bbb{Z}$ as a subring but I fail to see how $\phi$ holds when the codomain is a ring which doesn't contain $\Bbb{Z}$. If someone could provide examples of ring homomorphisms from $\Bbb{Z}$ to rings other than the rings mentioned above I would appreciate it.
A:
In every ring (with unit) $R$ you have a $1$. And you have thus $1+1$, and $1+1+1$, &c. You can consider the collection of all these elements and their additive inverses, $-(1+1), -(1+1+1)$, &c. For $n>0$ call these elements $n1$ and set $(-n)1=-(n1)$, if $n=0$; $n1=0$. You should convince yourself that $m1+n1=(m+n)1$ for any pair of integers $n,m$, and $n1\cdot m1=(nm)1$. Of course $1\cdot 1=1$. This means the collection of such elements is a subring of $R$. It looks like $\Bbb Z$, since every element is just a sum of $1$ (or difference), but note that these elements needn't be distinct. For example, in $\Bbb Z/3\Bbb Z$, $2\cdot 1=-1\cdot 1$.
At any rate, now we can define a function $f:\Bbb Z\to R$ for any ring $R$ with unit that sends the integer $n$ to $n1$, as defined above. What you checked above is precisely the claim that $f(n)f(m)=f(mn)$ and $f(n+m)=f(n)+f(m)$, $f(1)=1$. This means $f$ is a morphism of rings. Since $R$ was arbitrary, we have shown that every ring $R$ admits a morphism of rings $f:\Bbb Z \to R$.
It remains to see that $f$ is unique. Now if $g:\Bbb Z\to R$ is another morphism of rings, we know that $g(1)=1$ (i.e. $g$ sends the unit of $\Bbb Z$ to the unit of $R$), hence $g(-1)=-1$ (why?). But any nonzero integer is $n$ is $1+\dots+1$ ($n$ times) or $-1-\cdots-1$ ($n$ times), so using $g$ is $\Bbb Z$-linear ($g(a+b)=g(a)+g(b)$) gives $g$ sends $n$ to $f(n)$ as defined above, i.e. $f=g$.
A:
Take the ring $\mathbb{Z}_2$ (also known as $\mathrm{GF}_2$) with two elements, and define $$\phi(n)=\begin{cases}1&\text{if $n$ is odd}\\0&\text{if $n$ is even}\end{cases}$$
To learn something from this example, prove that this is the only homomorphism.
| {
"pile_set_name": "StackExchange"
} |
Q:
grub2 wont load Ubuntu on dual boot
Having an issue with a dual boot setup that is being run from Windows boot manager. I can successfully load into grub2 from Windows boot manager, however it seems that grub2 cannot locate to the Kernel or something, as it is dropping me right into a shell with the following output:
[ Minimal BASH-like line editing is suported. For the First word, TAB
list the posible command completion. Anywhere else tab list the posible
completions of a device/filename,]
grub>
I have used Easybcd in the past and successfully loaded a Linux grub through Windows bootloader, but this was when both operating systems were on the same partition, but since my OS installationd are now on separate partitions it seems EasyBcd cant work its magic.
ONe encouragement is that I was able to get Easybcd to load a working Grub if I used the Neo grub bootloader and edit the confg with:
title Ubuntu 14.04
find --set-root /boot/vmlinuz-3.19.0-61-generic
kernel /boot/vmlinuz-3.19.0-61-generic ro root=/dev/sdc
initrd /boot/initrd.img-3.19.0-61-generic
however this loads in Grub4DOS which is very slow, and as of today this method stopped working See THIS POST for details).
Here is the output of EasyBcd Settings for all the different methods I have tried for the Ubuntu 14.04 installation:
Default: Windows 7
Timeout: 30 seconds
Boot Drive: C:\
Entry #1
Name: Windows 7
BCD ID: {current}
Drive: C:\
Bootloader Path: \Windows\system32\winload.exe
Entry #2
Name: Ubuntu 14.04 Legacy
BCD ID: {a4f127cf-3150-11e6-8aaf-408d5cb9e442}
Drive: C:\
Bootloader Path: \NST\nst_linux.mbr
Entry #3
Name: Ubuntu 14.04 Grub2
BCD ID: {a4f127d0-3150-11e6-8aaf-408d5cb9e442}
Drive: C:\
Bootloader Path: \NST\AutoNeoGrub0.mbr
Entry #4
Name: Ubuntu Neo Grub
BCD ID: {a4f127d1-3150-11e6-8aaf-408d5cb9e442}
Drive: C:\
Bootloader Path: \NST\NeoGrub.mbr
*It seems that none of the paths seen above are pointing to my dev/sdc2/ partition which would be considered DISK1 on my Windows Volume manager.
EDIT - In the confusion of attempting to get a working bootmanager for Ubuntu/Windows, you will see that grub and Windows Boot manager have all been installed in numerous locations. Below are the present locations and contents of all bootmanager & Grub installations:
dev/sdb Windows7 drive
/dev/sdb1 - 512 MB fat32 partition which is currently empty
/dev/sdb2 - 110 GB ntfs partition containing Windows7 installation. This partition contains a 'Boot' folder which contains BCD files and a whole wack of langauage folders. THIS IS The FOLDER THAT WINDOWS BOOTLOADER uses.
/dev/sdb4 - 121.53 ntfs partition containing storage for media
dev/sdd - Ubuntu Drive
dev/sdd1 - 512 MB partition containing a 'EFI' folder, inside of which are two folders 'grub' and 'Ubuntu', both of which contain the exact same files (grub.cfg, grubx64.efi, MokManager.efi, shium64.efi)
dev/sdd2 - 48.83 GB ext4 partition that contains the '/' folder and Ubuntu instalation.
dev/sdd3 - 69.91 GB ntfs partition containing storage for media
what do I need to do so that the Grub shell I am being dropped into will load up Ubuntu? HOw can I get this machine to dual boot out of Grub?
A:
I was finally able to get grub2 to load at startup with a Windows 7 entry however it took a lot of trial and error.
What I did was remove all Grub entries from all the different locations that it had been installed on the numerous drives, and then remove all of the EasyBcd Grub entries.
After this I booted into Boot repair Disk and restored the MBR to allow Windows to boot normally, rebooted back into Boot Disk Repair, and then reinstalled Grub2 (on all drives). I then went into my BIOS, changed boot Disk and booted into Ubuntu and typed sudo update-grub
it was only after performing this command that Windows was recognised in the Grub2 bootloader. It did not end here though because Windows Bootloader was still coming up after choosing Windows in the Grub2 menu (essentially adding another step), so I used EasyBCD to disable the Windows bootloader menu so that Grub simply loads straight into Windows without waiting for input from the WIndows bootloader.
I was then able to change the boot order in Grub2 with grub-customizer
sudo add-apt-repository ppa:danielrichter2007/grub-customizer
sudo apt-get update
sudo apt-get install grub-customizer
I am going to reward the bounty to the first answer as it was the only answer, and also I am happy that the author took time to be thorough in their explanation.
| {
"pile_set_name": "StackExchange"
} |
Q:
Documentation for old versions of Clojure java.jdbc?
The [Using java.jdbc] documentation is very sparse and the clojure.java.jdbc - JDBC-based SQL Interface 0.3.0 API documentation is only for the latest version. [I imagine the title of that last link will change when a new version is released.]
I'm using version 0.2.3 – where can I find the API documentation for that vesion? Or where can I find the info that likely would have been in the API docs for that version?
A:
You can read the docs in the proper tagged branch in GitHub.
Table dropping in your example.
If those docs are not enough you can always refer to the properly tagged source code of that version.
| {
"pile_set_name": "StackExchange"
} |
Q:
NSAttributedString freeze UITableView
Application really freeze while scrolling with NSAttributedString (When I use NSString it works fine), so there my method:
- (void)setSubtitleForCell:(TTTableViewCell *)cell item:(TTPhotoPost *)item
{
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:
[item.caption dataUsingEncoding:NSUnicodeStringEncoding]
options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
documentAttributes:nil
error:nil];
[cell.descriptionLabel setAttributedText:attributedString];
}
Any mistakes there? or some way to make att.string faster?
A:
I'd suggest creating the NSAttributedString from HTML once asynchronously, and storing the attributed string in your model. That way you won't have to do the HTML -> attributed string conversion on every cell reuse, which happens a lot when you're scrolling.
| {
"pile_set_name": "StackExchange"
} |
Q:
SSIS Control Flow - set a precedent constraint on entire group of Data Flow tasks
I have about 20 data flow tasks arranged into a group in my control flow window. I'm fine with them executing in parallel; in fact I prefer it.
But I need to add an Execute SQL Task and I need it to run completely before any of my data flow tasks begin. It doesn't look like I can connect a precedence constraint from the Execute SQL Task to the group of data flow tasks (I was really hoping it would be that easy.)
Is my only option to create a precedence constraint from my Execute SQL Task to EACH of the data flow tasks? Seems like there should be a simpler solution.
(SQLServer 2005)
A:
You can take advantage of a Sequence Container. Add a Sequence container to your task flow. Then move (drag and drop will do it) all of your data flow tasks into the container. Now you can create a single precedence constraint from your Execute SQL Task to the Sequence container. Everything in the Sequence Container will not execute until the rules of the Precedence Constraint are met.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to forward sub-json object to splunk indexer
My application writes log data to disk file. The log data is one-line json as below. I use the splunker-forwarder to send the log to splunk indexer
{"line":{"level": "info","message": "data is correct","timestamp": "2017-08-01T11:35:30.375Z"},"source": "std"}
I want to only send the sub-json object {"level": "info","message": "data is correct","timestamp": "2017-08-01T11:35:30.375Z"} to splunk indexer, not the whole json. How should I configure splunk forwarder or splunk indexer?
A:
You can use sedcmd to delete data before it gets written to disk by the indexer(s).
Add this to your props.conf
[Yoursourcetype]
#...Other configurations...
SEDCMD-removejson = s/(.+)\:\{/g
This is an index time setting, so you will need to restart splunkd for changes to take affect
| {
"pile_set_name": "StackExchange"
} |
Q:
laravel 4.2 and ignore global scope
I have a Model Eloquent called (TicketModel),
I add a global scope for take all tickets for a user , but sometimes , I want to use Ticket without this scope how can do it? how can ignore this scope
this is the model
<?php
class TicketModel extends Eloquent{
public $timestamps = false;
public static function boot()
{
static::addGlobalScope(new TicketScope);
}
}
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\ScopeInterface;
class TicketScope implements ScopeInterface {
public function apply(Builder $builder)
{
$builder->where('user_id', '=', Auth::user()->id_user);
}
public function remove(Builder $builder){}
}
A:
What about having a child class for the cases you need the scope?
Here's an example:
class TicketModel extends Eloquent
{
// Your model stuff here
}
class UserTicketModel extends TicketModel
{
public static function boot()
{
static::addGlobalScope(new TicketScope);
}
}
The idea is not to ignore the scope sometimes, it's to use it when you need it.
If you really want the model without the scope to be the exception, let a SimpleTicketModel inherit from TicketModel and override boot() method so that it does not use the scope, like this:
class TicketModel extends Eloquent
{
public static function boot()
{
static::addGlobalScope(new TicketScope);
}
}
class SimpleTicketModel extends TicketModel
{
public static function boot()
{
// Do nothing else
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
back button on Angular2 is broken
UPDATED **
I'm writing my first Angular2 app using routing. A simple quiz application.
Clicking the back button triggers the problem behavior, the template does not render properly with data from the model.
I have a routing scheme where you can go between a series of questions in a quiz using a URL pattern like /question/:n.
My component implements OnReuse, OnActivate, and CanReuse.
My model is attached to the component via a property.
This Plunker has a simplified version of my app.
You can see that clicking the Next button goes to the next question and updates the URL. Clicking the browser's back button does change the URL back, but the template does not actually render.
What am I missing?
A:
If it's a base href issue then it is difficult to diagnose with Plunker. So I am not sure if this is the issue, but please give it a try.
Try changing this:
<script>document.write('<base href="' + document.location + '" />');</script>
To This:
<base href="/">
within your index.html. If it's already set to to the latter please comment and I will update this response.
| {
"pile_set_name": "StackExchange"
} |
Q:
Could the Supreme Court prohibit abortion? (And other misconceptions about overturning Roe v Wade)
Here's my layman's understanding of Roe v Wade:
A state had a law prohibiting abortion;
That law was challenged all the way up to the Supreme Court;
The Supreme Court found a right to abortion in the 14th Amendment;
The right to abortion was thus determined to be constitutionally protected;
The Constitution takes precedence over both state and federal law;
Therefore, neither the states nor the federal government may pass any law abridging the right to abortion.
If Roe v Wade were to be overturned by some future Supreme Court, it would mean that the right to abortion is not found in the Constitution, and therefore not constitutionally protected. Thus, the states and the federal government would be free to pass laws banning abortion, if they so choose.
I think many Americans would be surprised to learn that if Roe v Wade were overturned, it wouldn't mean abortion is automatically outlawed throughout the land. It means every state and the federal government would have the opportunity to make its own laws about it. (Get ready for 50+1 more battles, I guess.)
But could a future Supreme Court not only overturn Roe v Wade, but also find that abortion is prohibited by the Constitution, thereby preventing the states from making their own laws about it? Does the Supreme Court ever rule that something is prohibited, or only protected/not protected?
Not exactly sure how this could go down anyway. The Supreme Court doesn't write laws, and a prohibition on abortion would have to involve not only the prohibitory statement itself, but also exact definitions, sentencing mandates, parole guidelines, etc. This sounds more like the state legal codes on homicide (first-degree murder, premeditated murder, vehicular homicide, manslaughter, accidental homicide, accessory to murder, etc.) than a Supreme Court ruling.
A:
There is no higher court which can overturn a SCOTUS decision, so in theory (or, imaginarily) they can rule any way they please. The ruling could then be overturned by a later court, as happened in these cases. However, justices of the Supreme Court can be impeached (impeachment is not subject to judicial review), so the individuals responsible for such a ruling could be impeached. Or, if the sitting president is favorable and the enabling legislation has been passed, additional members of the Supreme could be added, as was unsuccessfully attempted during the Roosevelt administration.
The court could not write specific enforceable statutes defining the crime and imposing a penalty. They could rule that there is such-and-such right which is protected by the Cconstitution, and that that right must be protected by the states (for instance, a state may not pass a law that prohibits practicing the Pastafarian religion). It would be unprecedented, though, for SCOTUS to order a legislature to pass particular legislation. That would not mean that a ruling could not be written which mandated that, but it would be a huge break from tradition and a clear breach of the separation of powers. Legislatures could respond "they have made their decision; now let them enforce it".
Decades ago, existing state death penalty laws were declared unconstitutional as defective with respect to the 8th Amendment, meaning that there was no death penalty in many states for some time. Homicide statutes could likewise be struck down en masse, perhaps as an Equal Rights violation, which would means that either homicide is now legal, or the Equal Rights violation in those statutes must be eliminated. All that SCOTUS would have to do is rule that a fetus is a person. Recall Roe v. Wade:
If this suggestion of personhood is established, the appellant's case,
of course, collapses, for the fetus' right to life would then be
guaranteed specifically by the Amendment.
A model for how this might take place is McCleary v.Washington, where the Washington Supreme Court ordered the legislature to act to fund public education, on constitutional grounds that the legislature has an obligation to do certain things. The leverage imposed by the court was a large daily contempt fine that went up to over $100 million. However this was symbolic (lifted when the legislation was passed), and it took 3 years to implement the order.
| {
"pile_set_name": "StackExchange"
} |
Q:
Como colocar um texView dentro de um Circulo
Senhores eu gostaria de deixar mais rico um textView deixando-o dentro de um Circulo, é uma Lista de Produto com o nome do produto e o valor e este que estaria dentro do circulo, tentei fazer um shape e usa-lo como background mais não ficou legal, como podem ver o meu rounded_shape.xml baixo
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" android:padding="2dp">
<solid android:color="@color/amarelo2"/>
<stroke android:color="@color/branco" android:width="2dp"/>
<corners android:radius="2dp"/>
e fazendo uso dele
<TextView
android:textColor="@color/colorPrimarytext"
android:id="@+id/tv_valor"
android:background="@drawable/rounded_shape"
Mais o efeito foi horrivel
A:
layout_rounded_background.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<solid android:color="#694CA7"/>
<stroke android:width="1dp" android:color="#694CA7" />
<corners android:radius="100dp" />
<padding android:bottom="10dp" android:left="10dp" android:right="10dp" android:top="10dp" />
</shape>
</item>
</selector>
Para editar a cor mude a linha: <solid android:color=".." e também não se esqueça da borda ou, se preferir, você pode removê-la.
Depois de ter criado a drawable aplique como background de um container:
<FrameLayout
android:background="@drawable/rounded"
android:layout_width="56dp"
android:layout_height="56dp">
<TextView
android:id="@+id/tv_valor"
android:text="LC"
android:textSize="14sp"
android:textColor="#fff"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</FrameLayout>
Resultado
| {
"pile_set_name": "StackExchange"
} |
Q:
Selecting data from an array as an Object
var myObj = [
{"a":"1", "b":"2"},
{"c":"3", "c":"4"},
{"d":"5", "e":"6"}
];
What is the best solution to pick one of the rows? I have this function below which convert the Object to array, but it returns indexes, though I need the full row.
var array = $.map(myObj, function(value, index) {
return value;
});
return array;
}
A:
var myObj = [{
"a": "1",
"b": "2"
}, {
"c": "3",
"c": "4"
}, {
"d": "5",
"e": "6"
}];
var reformattedArray = myObj.map(function(value, index, array) {
return Object.values(value);
});
console.log(reformattedArray);
| {
"pile_set_name": "StackExchange"
} |
Q:
Como implementar un Sidenav en mi sitio web?
Disculpen la molestia.La verdad es que me mandarían a buscar a Google al leer mi pregunta,pero ya he buscado y buscado y no encuentro un código para implementarlo en mi sitio ya que hacer una cosa así de avanzada esta fuera de mi alcance.
Lo que busco es un sidenav para ponerlo al lado derecho de mi web,el cual ha de ocultarse/mostrarse mediante un botón.
Para ser sincero ya tengo uno.Este sidenav lo he conseguido en la web w3school,pero me da error así:
"Cannot read property 'style' of null".
El sidenav que busco, es del tipo que no arrastra el contenido de la pagina,sino que se sobrepone.Osea de tipo "overlay"
Aquí les dejo el link.
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_sidenav
¿Alguien podría darme algún link de alguno,pero que no sea usando Angular?
function openNav() {
document.getElementById("mySidenav").style.width = "250px";
document.getElementById("main").style.marginRight = "250px";
}
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
document.getElementById("main").style.marginRight= "0";
}
#wrapper-tabs-o{
width: 220px;
}
#wrapper-tabs-o li{
color: #B0B0B0 ;
}
.sidenav {
height: 100%;
width: 0;
position: fixed;
z-index: 1;
right: 0;
background-color: #292F33;
overflow-x: hidden;
transition: 0.5s;
}
.sidenav a {
padding: 8px 8px 8px 32px;
text-decoration: none;
font-size: 25px;
color: #818181;
display: inline;
transition: 0.3s
}
.sidenav a:hover, .offcanvas a:focus{
color: #f1f1f1;
}
.sidenav .closebtn {
position: absolute;
top: 0;
right: 25px;
font-size: 36px;
margin-right: 50px;
}
#main {
transition: margin-right .5s;
padding: 16px;
}
/*@media screen and (max-height: 450px) {
.sidenav {padding-top: 15px;}
.sidenav a {font-size: 18px;}
}*/
<div id="mySidenav" class="sidenav">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">x</a>
<div id="wrapper-tabs-o">
<ul class="tabs2">
<li class="tab-link current" data-tab="tab-1"><i class="fa fa-list"
aria-hidden="true"></i></li>
<li class="tab-link" data-tab="tab-2"><i class="fi-comment"></i></li>
<div class="div_search"></div>
</ul>
</div>
</div>
Por cierto este codigo lo tengo en un archivo aparte llamado sidenav.php,el cual esta incrustado en la pagina principal mediante un include("")
A:
No necesitas grandes conocimientos para hacer lo que quieres. Te recomiendo encarecidamente aprender los conceptos básicos de HTML, CSS y JS e ir avanzando progresivamente para poder realizar las cosas por tí mismo.
Para hacer un menú lateral tipo overlay solo necesitas tener en cuenta lo siguiente:
Cómo trasladar el menú. Para esto puedes usar left o transform.
Tipo de animación y tiempo de duración
Extras como sombras, animaciones del ícono burguer, etc.
Ejemplo
document.addEventListener('DOMContentLoaded', function () {
let burguer = document.getElementById('burguer');
let sidebar = document.getElementById('sidebar');
burguer.addEventListener('click', function () {
sidebar.classList.toggle('visible');
});
});
@import url('https://fonts.googleapis.com/css?family=Barrio');
*,
*:before,
*:after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
background-color: #fff;
}
.navigation {
background-color: #f5f7fb;
box-shadow: 0 4px 6px 0 rgba(0,0,0,.2);
height: 100vh;
left: -231px;
width: 230px;
padding: 12px 20px;
position: fixed;
transition: all .5s cubic-bezier(.39,.575,.565,1);
top: 0;
}
.navigation.visible {
left: 0;
}
.navigation.visible .burguer span:first-child {
transform: rotate(45deg);
}
.navigation.visible .burguer span:nth-child(2) {
opacity: 0;
visibility: hidden;
}
.navigation.visible .burguer span:last-child {
transform: rotate(-45deg) translate(10px, -10px);
}
.burguer {
background-color: transparent;
border: none;
cursor: pointer;
left: 10px;
outline: none;
position: fixed;
top: 10px;
}
.burguer span {
background-color: #555;
display: block;
height: 2px;
margin: 5px 0;
transition: all .35s cubic-bezier(.39,.575,.565,1);
width: 25px;
}
.menus {
list-style: none;
margin-top: 50px;
}
.menu a {
border-bottom: 1px dashed #aaa;
color: #333;
display: block;
font-family: 'Barrio';
padding: 15px 0;
text-decoration: none;
}
<aside id="sidebar" class="navigation">
<button id="burguer" class="burguer">
<span></span>
<span></span>
<span></span>
</button>
<ul class="menus">
<li class="menu">
<a href="#">Principal</a>
</li>
<li class="menu">
<a href="#">Blog</a>
</li>
<li class="menu">
<a href="#">Portafolio</a>
</li>
</ul>
</aside>
En el código anterior hay algunos aspectos interesantes como la animación del ícono del menú. Esto se logra simplemente rotando las líneas extremas y desvaneciendo la intermedia.
| {
"pile_set_name": "StackExchange"
} |
Q:
Avoid nested subscribe call
I have a button, clicking it will make a service call. Finally I want to inform the user by email. The email will be made by another service call.
public submitForm = (data, selected = {} ) => {
console.log(data);
this.service['submit'].post({body: data}).subscribe(
() => { null },
error => {
console.log(error);
};
() => {
// second subscribe
this.service['email']['post']({ body: theForm.value }).subscribe(
() = > {
// data processing
}
);
}
);}
You see it is the nested subscribe. I use angular 5 and rxjs 5.5. How to avoid it?
UPDATE:
By the comment, I added the service code
public readonly service: SwaggerService
The actually all services are in asp.net web api, for example
[HttpPost]
[Route("email")]
public ActionResult postEmail([FromBody]EmailBody email)
{}
A:
You can use switchMap to avoid nested subscription like this:
public submitForm = (data, selected = {} ) => {
console.log(data);
this.service['submit'].post({body: data})
.switchMap(() => {
return this.service['email']['post']({ body: theForm.value })
.catch(err => {
//handle your error here
//HERE YOU NEED TO DO YOUR SELF; MAKE SURE TO RETURN AN OBSERVABLE FOR HERE.
//I ON RXJS 6.4; So I am not sure what is `of` operator in rxjs 5.5
//I guss it is Observable.of
return Observable.of(err);
});
})
.catch(err => {
//handle your error here
//HERE YOU NEED TO DO YOUR SELF; MAKE SURE TO RETURN AN OBSERVABLE FOR HERE.
//I ON RXJS 6.4; So I am not sure what is `of` operator in rxjs 5.5
//I guss it is Observable.of
return Observable.of(err);
})
.subscribe((resultOfSecondCall) => {
//do your processing here...
console.log(resultOfSecondCall);
});
}
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the proper usage of HasColumnType and Database generated
I'm migrating a substantial EF model of ~80 entites from EF4 to EF6, and I'm also changing it from a Designer EDMX-generated database, to a Code First database.
Right now I'm configuring the entity relationships using EF fluent-api, and I'm not certain I'm doing it correctly.
It's type in the SQL Server database is varchar(50), so should I be configuring it like this?
mb.Entity<SomeObject>()
.Property(so => so.Type)
.IsUnicode(false)
.HasColumnName("Type")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsRequired()
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
or like this, without the HasMaxLength(50)?
mb.Entity<SomeObject>()
.Property(crt => crt.Type)
.IsUnicode(false)
.HasColumnName("Type")
.HasColumnType("varchar(50)")
.IsRequired()
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Additionally, say I have another object with a GUID ID:
mb.Entity<AnotherObject>()
.Property(ao => ao.ID)
.HasColumnName("ID")
.HasColumnType("uniqueidentifier")
.IsRequired()
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
In the database it has a default of newsequentialid(), should I be configuring it with DatabaseGeneratedOption.None, DatabaseGeneratedOption.Identity, or DatabaseGeneratedOption.Computed?
What is the difference between those options?
Additionally, in the code GUIDs are mostly being assigned at object instantiation, like so:
Guid ID = new Guid.NewGuid()
Is that appropriate?
A:
varchar(50) is not a column type itself, 'varchar' is a data type while (50) is the maximum length of characters in a string.
you have to do it like this
mb.Entity<SomeObject>()
.Property(so => so.Type)
.IsUnicode(false)
.HasColumnName("Type")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsRequired()
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
for your second question, if you dont give GUID, it will be set to default value of GUID in the settings of the database, if you want to set it, use the GUID generator class.
| {
"pile_set_name": "StackExchange"
} |
Q:
Do bank conflicts occur on non-GPU hardware?
This blog post explains how memory bank conflicts kill the transpose function's performance.
Now I can't but wonder: does the same happen on a "normal" cpu (in a multithreaded context)? Or is this specific to CUDA/OpenCL? Or does it not even appear in modern CPUs because of their relatively large cache sizes?
A:
There have been bank conflicts since the earliest vector processing CPUs from the 1960's
It's caused by interleaved memory or multi-channel memory access.
Interleaved memory access or MCMA solves the problem to slow RAM access, by phasing access to
each word of memory from different banks or via different channels. But there is a side effect, memory access from the same bank takes longer than accessing memory from the adjacent bank.
From Wikipedia on the 1980's Cray 2 http://en.wikipedia.org/wiki/Cray-2
"Main memory banks were arranged in quadrants to be accessed at the same time, allowing programmers to scatter their data across memory to gain higher parallelism. The downside to this approach is that the cost of setting up the scatter/gather unit in the foreground processor was fairly high. Stride conflicts corresponding to the number of memory banks suffered a performance penalty (latency) as occasionally happened in power-of-2 FFT-based algorithms. As the Cray 2 had a much larger memory than Cray 1's or X-MPs, this problem was easily rectified by adding an extra unused element to an array to spread the work out"
| {
"pile_set_name": "StackExchange"
} |
Q:
Multipanel table titles
I´m trying to make a table with two panels. I need something like this:
But I have this:
I am having problems with the numbers in the titles and their positions, I would also like to remove those [t]. This is my code:
\\\begin{table}[!hbt]
\centering
\caption{Panel A: Descriptive statistics}
\begin{subtable}[t]{\linewidth}
\centering
\vspace{0pt}
\begin{tabular}{@{\extracolsep{5pt}} l|ccc}
\toprule
Observations & 594\\
Mean & 0.00313\\
Median & 0.00453\\
Maximum & 0.22762\\
Minimun & -0.18917\\
Std. Dev. & 0.04886\\
Skewness & -0.10910 \\
Kurtosis & 2.22092\\
\bottomrule
\end{tabular}
\caption{Panel A: Unit root tests}
\end{subtable}
\begin{subtable}[t]{\linewidth}
\centering
\begin{tabular}{@{\extracolsep{5pt}} l|ccc}
\toprule
ADF & -7.7912*** \\
PP & -604.93*** \\
\bottomrule
\end{tabular}
\caption{Descriptive statistics and unit root tests}
\end{subtable}
\end{table}
Thanks for your help!
A:
You can achieve the desired output by using the subcaption package as follows:
\documentclass{article}
\usepackage{booktabs}
\usepackage{subcaption}
\captionsetup[subtable]{labelformat=simple, labelsep=colon}
\renewcommand{\thesubtable}{Panel~\Alph{subtable}}
\begin{document}
\begin{table}[!hbt]
\centering
\begin{subtable}{\linewidth}
\centering
\caption{Unit root tests}
\begin{tabular}{@{\extracolsep{5pt}} lc}
\toprule
Observations & 594\\
Mean & 0.00313\\
Median & 0.00453\\
Maximum & 0.22762\\
Minimun & -0.18917\\
Std. Dev. & 0.04886\\
Skewness & -0.10910 \\
Kurtosis & 2.22092\\
\bottomrule
\end{tabular}
\end{subtable}
\vspace{0.75\baselineskip}
\begin{subtable}{\linewidth}
\caption{Unit root tests}
\centering
\begin{tabular}{@{\extracolsep{5pt}} lc}
\toprule
ADF & -7.7912*** \\
PP & -604.93*** \\
\bottomrule
\end{tabular}
\end{subtable}
\caption{Descriptive statistics and unit root tests}
\end{table}
\end{document}
Additionall, I have removed superfluous columns (the table originally had four while only two are needed) as well as the vertical lines (which are incompatible with booktabs' horizontal lines).
For some further improvement, you might be interested in using the siunitx package's S type column in order to align the numbers with respect to the decimal separator:
\documentclass{article}
\usepackage{booktabs}
\usepackage{subcaption}
\captionsetup[subtable]{labelformat=simple, labelsep=colon}
\renewcommand{\thesubtable}{Panel~\Alph{subtable}}
\usepackage{siunitx}
\begin{document}
\begin{table}[!hbt]
\centering
\caption{Descriptive statistics and unit root tests}
\begin{subtable}{\linewidth}
\centering
\caption{Unit root tests}
\begin{tabular}{@{\extracolsep{5pt}} lS[table-format=3.5]}
\toprule
Observations & 594\\
Mean & 0.00313\\
Median & 0.00453\\
Maximum & 0.22762\\
Minimun & -0.18917\\
Std. Dev. & 0.04886\\
Skewness & -0.10910 \\
Kurtosis & 2.22092\\
\bottomrule
\end{tabular}
\end{subtable}
\vspace{0.75\baselineskip}
\begin{subtable}{\linewidth}
\sisetup{
table-format = -3.4,
table-space-text-post = ***,
table-align-text-post = false
}
\caption{Unit root tests}
\centering
\begin{tabular}{@{\extracolsep{5pt}} lS}
\toprule
ADF & -7.7912*** \\
PP & -604.93*** \\
\bottomrule
\end{tabular}
\end{subtable}
\end{table}
\end{document}
| {
"pile_set_name": "StackExchange"
} |
Q:
Subsetting a data.frame based on factor levels in a second data.frame
I have two data.frames:
df.1 <- data.frame(A=runif(10), B=runif(10), C=runif(10), D=runif(10))
df.2 <- data.frame(Var=factor(c("A", "B", "C", "D")), Info=c("X1", "X2", "X1", "X2"))
In df.1, i want to select all columns which are associated with one factor level in df.2$Info
i can only do this in a very clumsy way by merging the two data.frames first, then subsetting, then rearraging the desired output:
tmp <- as.data.frame(t(df.1))
tmp$Var=row.names(tmp)
tmp.m <- merge(tmp, df.2, by="Var")
df.X1 <- tmp.m[tmp.m$Info == "X1", ]
df.X1$Info <- factor(df.X1$Info) # drop unused factor levels
desired.output <- as.data.frame(t(df.X1))
names(desired.output) <- lapply(desired.output[1, ], as.character)
desired.output <- desired.output[-c(1,11),]
My question is if there is a better, faster and less complicated way (i am sure there is!). Thank you.
A:
df.1[,unique(df.2$Var[which(df.2$Info=="X1")])]
A C
1 0.8924861 0.7149490854
2 0.5711894 0.7200819517
3 0.7049629 0.0004052017
4 0.9188677 0.5007302717
5 0.3440664 0.9138259818
6 0.8657903 0.2724015017
7 0.7631228 0.5686033906
8 0.8388003 0.7377064163
9 0.0796059 0.6196693045
10 0.5029824 0.8717568610
| {
"pile_set_name": "StackExchange"
} |
Q:
Jquery tabs - how to makes it work?
Im using code of http://jsfiddle.net/syahrasi/us8uc/.
HTML:
<div id="tabs-container">
<ul class="tabs-menu">
<li class="current"><a href="#tab-1">Tab 1</a></li>
<li><a href="#tab-2">Tab 2</a></li>
<li><a href="#tab-3">Tab 3</a></li>
<li><a href="#tab-4">Tab 4</a></li>
</ul>
<div class="tab">
<div id="tab-1" class="tab-content">
<p>c</p>
</div>
<div id="tab-2" class="tab-content">
<p>b</p>
</div>
<div id="tab-3" class="tab-content">
<p>a</p>
</div>
</div>
JS:
$(document).ready(function() {
$(".tabs-menu a").click(function(event) {
event.preventDefault();
$(this).parent().addClass("current");
$(this).parent().siblings().removeClass("current");
var tab = $(this).attr("href");
$(".tab-content").not(tab).css("display", "none");
$(tab).fadeIn();
});
});
CSS:
In the link at top, too long to paste it here.
It works perfectly, but I need to make divs with same tabs many time on my site.
With this code, doing anything on 1st tab, making other tabs to colapse.
I was trying do this with other classes/id but it doesnt work, and my js skill is too poor to invent way to fix it.
TIA
A:
A workaround way without changing too much:
HTML:
<div class="tabs-container">
<ul class="tabs-menu">
<li class="current"><a href=".tab-1">Tab 1</a></li>
<li><a href=".tab-2">Tab 2</a></li>
<li><a href=".tab-3">Tab 3</a></li>
<li><a href=".tab-4">Tab 4</a></li>
</ul>
<div class="tab">
<div class="tab-content tab-1">
<p>A</p>
</div>
<div class="tab-content tab-2">
<p>B</p>
</div>
<div class="tab-content tab-3">
<p>C</p>
</div>
<div class="tab-content tab-4">
<p>D</p>
</div>
</div>
</div>
<div class="tabs-container">
<ul class="tabs-menu">
<li class="current"><a href=".tab-1">Tab 1</a></li>
<li><a href=".tab-2">Tab 2</a></li>
<li><a href=".tab-3">Tab 3</a></li>
<li><a href=".tab-4">Tab 4</a></li>
</ul>
<div class="tab">
<div class="tab-content tab-1">
<p>E</p>
</div>
<div class="tab-content tab-2">
<p>F</p>
</div>
<div class="tab-content tab-3">
<p>G</p>
</div>
<div class="tab-content tab-4">
<p>H </p>
</div>
</div>
</div>
JS:
$(document).ready(function() {
$(".tabs-menu a").click(function(event) {
event.preventDefault();
$(this).parent().addClass("current");
$(this).parent().siblings().removeClass("current");
var tab = $(this).attr("href");
$(this).parents().eq(2).find(".tab-content").not(tab).css("display", "none");
$(this).parents().eq(2).find(tab).fadeIn();
});
});
And in the CSS, change the #tab-1 to .tab-1.
Basically, in order to make more than 2, copy and paste the tabs-container div and everthing inside, then just change the content.
Demo: http://jsfiddle.net/Us8uc/6272/
| {
"pile_set_name": "StackExchange"
} |
Q:
how to retrieve HTML form fields in JavaFX application
<html lang="en">
<head>
<title>WebView</title>
</head>
<body>
<form action="">
<input type="text" name="tb1" id="ib1">
<button id="btn">Submit</button>
</form>
</body>
</html>
package webviewsample;
public class WebViewSample extends Application {
private Scene scene;
@Override
public void start(Stage stage) {
stage.setTitle("Web View");
scene = new Scene(new Browser(), 750, 500, Color.web("#666970"));
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
class Browser extends Region {
private HBox toolBar;
private static String[] imageFiles = new String[]{
"help.png"
};
private static String[] captions = new String[]{
"Help"
};
private static String[] urls = new String[]{
WebViewSample.class.getResource("help.html").toExternalForm()
};
final ImageView selectedImage = new ImageView();
final Hyperlink[] hpls = new Hyperlink[captions.length];
final Image[] images = new Image[imageFiles.length];
final WebView browser = new WebView();
final WebEngine webEngine = browser.getEngine();
final Button showPrevDoc = new Button("Toggle Previous Docs");
final WebView smallView = new WebView();
final ComboBox comboBox = new ComboBox();
private boolean needDocumentationButton = false;
public Browser() {
//apply the styles
getStyleClass().add("browser");
for (int i = 0; i < captions.length; i++) {
// create hyperlinks
Hyperlink hpl = hpls[i] = new Hyperlink(captions[i]);
Image image = images[i] =
new Image(getClass().getResourceAsStream(imageFiles[i]));
hpl.setGraphic(new ImageView(image));
final String url = urls[i];
final boolean addButton = (hpl.getText().equals("Documentation"));
// process event
hpl.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
needDocumentationButton = addButton;
webEngine.load(url);
}
});
}
webEngine.setOnAlert((WebEvent<String> event) -> {
System.out.println("ALERT!!!! " + event.getData());
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Information Dialog");
alert.setHeaderText(null);
alert.setContentText(event.getData());
alert.showAndWait();
JSObject jso = (JSObject) webEngine.executeScript("window");
jso.setMember("bridge", new Bridge());
});
comboBox.setPrefWidth(60);
// create the toolbar
toolBar = new HBox();
toolBar.setAlignment(Pos.CENTER);
toolBar.getStyleClass().add("browser-toolbar");
toolBar.getChildren().add(comboBox);
toolBar.getChildren().addAll(hpls);
toolBar.getChildren().add(createSpacer());
//set action for the button
showPrevDoc.setOnAction(new EventHandler() {
@Override
public void handle(Event t) {
webEngine.executeScript("toggleDisplay('PrevRel')");
}
});
smallView.setPrefSize(120, 80);
//handle popup windows
webEngine.setCreatePopupHandler(
new Callback<PopupFeatures, WebEngine>() {
@Override public WebEngine call(PopupFeatures config) {
smallView.setFontScale(0.8);
if (!toolBar.getChildren().contains(smallView)) {
toolBar.getChildren().add(smallView);
}
return smallView.getEngine();
}
}
);
//process history
final WebHistory history = webEngine.getHistory();
history.getEntries().addListener(new
ListChangeListener<WebHistory.Entry>(){
@Override
public void onChanged(Change<? extends Entry> c) {
c.next();
for (Entry e : c.getRemoved()) {
comboBox.getItems().remove(e.getUrl());
}
for (Entry e : c.getAddedSubList()) {
comboBox.getItems().add(e.getUrl());
}
}
});
//set the behavior for the history combobox
comboBox.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent ev) {
int offset =
comboBox.getSelectionModel().getSelectedIndex()
- history.getCurrentIndex();
history.go(offset);
}
});
// process page loading
webEngine.getLoadWorker().stateProperty().addListener(
new ChangeListener<State>() {
@Override
public void changed(ObservableValue<? extends State> ov,
State oldState, State newState) {
toolBar.getChildren().remove(showPrevDoc);
if (newState == State.SUCCEEDED) {
JSObject win =
(JSObject) webEngine.executeScript("window");
win.setMember("app", new JavaApp());
if (needDocumentationButton) {
toolBar.getChildren().add(showPrevDoc);
}
}
}
}
);
// load the home page
webEngine.load("http://www.oracle.com/products/index.html");
//add components
getChildren().add(toolBar);
getChildren().add(browser);
}
// JavaScript interface object
public class JavaApp {
public void exit() {
Platform.exit();
}
}
private Node createSpacer() {
Region spacer = new Region();
HBox.setHgrow(spacer, Priority.ALWAYS);
return spacer;
}
@Override
protected void layoutChildren() {
double w = getWidth();
double h = getHeight();
double tbHeight = toolBar.prefHeight(w);
layoutInArea(browser,0,0,w,h-tbHeight,0,HPos.CENTER,VPos.CENTER);
layoutInArea(toolBar,0,h-tbHeight,w,tbHeight,0,HPos.CENTER,VPos.CENTER);
}
@Override
protected double computePrefWidth(double height) {
return 750;
}
@Override
protected double computePrefHeight(double width) {
return 600;
}
}
I will render this HTML page in JavaFX application, I will enter something in textbox and hit submit button. I want to get entered textbox value inside JavaFX application. Can some one please tell me how can I achieve this?
I want entered textbox value inside my Java class. Thanks again
A:
index.html
<fieldset>
<legend>LoginForm</legend>
USERNAME: <input type="text" id="uname" name="uname">
PASSWORD: <input type="password" id="password" name="password">
<button onclick="app.submit(document.getElementById('uname').value)">Submit</button>
</fieldset>
public class JavaApp {
public void submit(String userName) {
System.out.println("Inside exist application method");
System.out.println("userName-->"+userName);
//Platform.exit();
}
}
JSObject win = (JSObject) webEngine.executeScript("window");
win.setMember("app", new JavaApp());
I did like this and able to have the textfield value inside my Java Class, Can some one please let me know is this the correct way?
| {
"pile_set_name": "StackExchange"
} |
Q:
How you write these lines in Intel syntax?
How do you translate these lines from Linux assembly to Intel assembly?
pushl cb_queue
pushl %eax
popl (%eax)
jg .FOR_end0
.FOR_end0:
sete (%esp)
pushl $.rte_isqrt
.rte_isqrt:
.string "isqrt returns no value"
A:
Running intel2gas -g (the switch reverses the direction of translation) produces:
push dword [cb_queue]
push eax
pop dword [eax]
jg .FOR_end0
.FOR_end0:
sete [esp]
push dword .rte_isqrt
.rte_isqrt:
db 'isqrt returns no value'
(It's normally called AT&T syntax, not Linux assembly.)
| {
"pile_set_name": "StackExchange"
} |
Q:
jquery accordion image
I am trying to include the arrow icon into my accordion...
i dont know how to write css for this combined images
here is my image links http://code.jquery.com/ui/1.9.1/themes/base/images/ui-icons_454545_256x240.png
here is my js code
http://jsfiddle.net/Uf7Nj/3/
/*!
* Vallenato 1.0
* A Simple JQuery Accordion
*
* Designed by Switchroyale
*
* Use Vallenato for whatever you want, enjoy!
*/
$(document).ready(function()
{
//Add Inactive Class To All Accordion Headers
$('.accordion-header').toggleClass('inactive-header');
//Set The Accordion Content Width
var contentwidth = $('.accordion-header').width();
$('.accordion-content').css({'width' : contentwidth });
// The Accordion Effect
$('.accordion-header').click(function () {
if($(this).is('.inactive-header')) {
$('.active-header').toggleClass('active-header').toggleClass('inactive-header').next().slideToggle().toggleClass('open-content');
$(this).toggleClass('active-header').toggleClass('inactive-header');
$(this).next().slideToggle().toggleClass('open-content');
}
else {
$(this).toggleClass('active-header').toggleClass('inactive-header');
$(this).next().slideToggle().toggleClass('open-content');
}
});
return false;
});
A:
just extract needed icon positions from jquery-ui css:
CSS:
.ui-icon {
width: 16px;
height: 16px;
background-image: url("http://code.jquery.com/ui/1.9.1/themes/base/images/ui-icons_454545_256x240.png");
}
.ui-icon-arrowthick-1-n { background-position: 0 -48px; }
.ui-icon-arrowthick-1-ne { background-position: -16px -48px; }
.ui-icon-arrowthick-1-e { background-position: -32px -48px; }
.ui-icon-arrowthick-1-se { background-position: -48px -48px; }
.ui-icon-arrowthick-1-s { background-position: -64px -48px; }
.ui-icon-arrowthick-1-sw { background-position: -80px -48px; }
.ui-icon-arrowthick-1-w { background-position: -96px -48px; }
.ui-icon-arrowthick-1-nw { background-position: -112px -48px; }
.ui-icon-arrowthick-2-n-s { background-position: -128px -48px; }
.ui-icon-arrowthick-2-ne-sw { background-position: -144px -48px; }
.ui-icon-arrowthick-2-e-w { background-position: -160px -48px; }
.ui-icon-arrowthick-2-se-nw { background-position: -176px -48px; }
sample
to get a name of icon go to theme rolling page
hover on icon you need, open css file, find a names for icon there, copy code to your new css.
| {
"pile_set_name": "StackExchange"
} |
Q:
mysql query retrieving number of records for each day for the last 15 days
I have a database table with user registration records. Table: [USER]
One of my columns is named created_on with type int and holds a timestamp for the registration date and time.
How should I compose my query so I can have the number of registered users for each day?
I want results like this:
21/11 : 150 users
22/11 : 200 users
23/11 : 50 users
24/11 : 150 users
A:
Using FROM_UNIXTIME() and simple date functions.
SELECT MONTH(FROM_UNIXTIME(created_on)) AS "month",
DAY(FROM_UNIXTIME(created_on)) AS "day", COUNT(created_on)
FROM `user`
WHERE YEAR(FROM_UNIXTIME(created_on)) = 2012
GROUP BY MONTH(FROM_UNIXTIME(created_on)), DAY(FROM_UNIXTIME(created_on))
You can do your string formatting using PHP.
| {
"pile_set_name": "StackExchange"
} |
Q:
Listview onitemclick in Fragment
I want to listview with clickable new activities. When i add the onitemclick program was stopped. Logcat says:
07-13 09:09:18.873: E/AndroidRuntime(1790): java.lang.IllegalStateException: Content view not yet created
Before the onitemclick listview worked . I create all xml files and add intens in manifest file. How can i fix the issue?
Here is my main java code:
public class FragmentThree extends ListFragment {
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
setListAdapter(new MyAdapter(getActivity(), android.R.layout.simple_list_item_1, R.id.mech ,getResources().getStringArray(R.array.parts)));
ListView listView = getListView();
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = null;
switch(position) {
case 0:
intent = new Intent(getActivity(), FragmentThreeOne.class);
startActivity(intent);
break;
case 1:
intent = new Intent(getActivity(), FragmentThreeTwo.class);
startActivity(intent);
break;
case 2:
intent = new Intent(getActivity(), FragmentThreeThree.class);
startActivity(intent);
break;
case 3:
intent = new Intent(getActivity(), FragmentThreeFour.class);
startActivity(intent);
break;
case 4:
intent = new Intent(getActivity(), FragmentThreeFive.class);
startActivity(intent);
break;
case 5:
intent = new Intent(getActivity(), FragmentThreeSix.class);
startActivity(intent);
break;
case 6:
intent = new Intent(getActivity(), FragmentThreeSeven.class);
startActivity(intent);
break;
case 7:
intent = new Intent(getActivity(), FragmentThreeEight.class);
startActivity(intent);
break;
case 8:
intent = new Intent(getActivity(), FragmentThreeNine.class);
startActivity(intent);
break;
case 9:
intent = new Intent(getActivity(), FragmentThreeTen.class);
startActivity(intent);
break;
case 10:
intent = new Intent(getActivity(), FragmentThreeEleven.class);
startActivity(intent);
break;
default:
}
}
});
View rootView = inflater .inflate(R.layout.fragment_three, container, false);
return rootView;
}
private class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context context, int resource,
int textViewResourceId, String[] strings) {
super(context, resource, textViewResourceId, strings);
// TODO Auto-generated constructor stub
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater =(LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.list_item_one, parent, false);
String[] items = getResources().getStringArray(R.array.parts);
ImageView iv = (ImageView) row.findViewById(R.id.mechres);
TextView tv = (TextView) row.findViewById(R.id.mech);
tv.setText(items[position]);
if(items[position].equals("itemone")){
iv.setImageResource(R.drawable.one);
}
else if (items[position].equals("itemtwo")){
iv.setImageResource(R.drawable.twp);
}
else if (items[position].equals("itemthree")){
iv.setImageResource(R.drawable.three);
}
else if (items[position].equals("itemfour")){
iv.setImageResource(R.drawable.four);
}
else if (items[position].equals("itemfive")){
iv.setImageResource(R.drawable.five);
}
else if (items[position].equals("itemsix")){
iv.setImageResource(R.drawable.six);
}
else if (items[position].equals("itemseven")){
iv.setImageResource(R.drawable.seven);
}
else if (items[position].equals("itemeight")){
iv.setImageResource(R.drawable.eight);
}
else if (items[position].equals("itemnine")){
iv.setImageResource(R.drawable.nine);
}
else if (items[position].equals("itemten")){
iv.setImageResource(R.drawable.ten);
}
else if (items[position].equals("itemeleven")){
iv.setImageResource(R.drawable.eleven);
}
return row;
}
}
}
A:
Move all the setListAdapter and all that ListView creation logic over to the onActivityCreated(). In your onCreateView() method just inflate and return the rootView.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using variables in DOM elements
Is there any way to make this work in IE8?:
spacer = 0.5;
elem.setAttribute("style", "margin: 0%" + spacer + "%");
It works in Chrome, FireFox, and even in IE.11, but works in IE8 if the variable is not used:
elem.setAttribute("style", "margin: 0% 0.5%");
Thank you.
A:
You can use equivalent
elem.style.margin = '0 ' + spacer + '%';
Just for info, your problem was in missing space.
| {
"pile_set_name": "StackExchange"
} |
Q:
Extracting a large number (about 300) documents from a firebase firestore db collection
I am trying to get data from firestore. The code is working fine in FutureBuilder ListView.I tried printing all the entries to console. The code below is working fine but only printing first 10 or so entries.
Future getP() async {
var firestore = Firestore.instance;
var q = await firestore.collection('place_list').getDocuments();
List<Map<String, dynamic>> list = q.documents.map((DocumentSnapshot doc) {
return doc.data;
}).toList();
print(list);
return q.documents;
}
I want to get all 300 entries to be printed in console. Can anyone help me out in this?
A:
Try this debugPrint instead of print
debugPrint(list.toString(), wrapWidth: 1024);
or add this method and
void printWrapped(String text) {
final pattern = new RegExp('.{1,800}'); // 800 is the size of each chunk
pattern.allMatches(text).forEach((match) => print(match.group(0)));
}
call
printWrapped(list.toString());
Check this for further information.
| {
"pile_set_name": "StackExchange"
} |
Q:
Return Max value with LINQ Query in VB.NET?
I have a method that takes in an id, a start date, and and end date as parameters. It will return rows of data each corresponding to the day of the week that fall between the date range. The rows are all doubles. After returning it into a DataTable, I need to be able to use LINQ in VB.NET to return the maximum value. How can I achieve this? Here is the initial setup?
Dim dt as DataTable = GetMaximumValue(1,"10/23/2011","11/23"/2011")
'Do linq query here to return the maximum value
The other alternative is to just return a Maximum value just given an id which would be slightly easier to implement, so the method would look like this:
Dim dt as DataTable = GetMaximumValue(1)
'Do linq query here to return maximum value
Important
What if I want to query against a DataRow instead of a DataTable and the column names are not the same, they are something like MaxForMon, MaxForTue, MaxForWed`, etc... and I need to take the Maximum value (whether it is MaxForMon, MaxForTue, or some other column). Would an option for this be to alias the column returned in the stored proc? The other thing I thought about was instead of doing this in LINQ, I probably should just handle it in the T-SQL.
A:
You can use the DataSet Extensions for Linq to query a datatable.
The following query should help.
Dim query = _
From value In dt.AsEnumerable() _
Select value(Of Double)("ColumnName").Max();
If you don't now in which column will hold the maximum you could use: (C#)
var result = from r in table.AsEnumerable()
select r.ItemArray.Max();
| {
"pile_set_name": "StackExchange"
} |
Q:
How to return values from nested promise?
I have a set of IDs of movies in Redis: [1,2,3,4] and a set of hashes with the actual data. Now, I want to fetch all the movie data for the IDs in once.
I am trying to use bluebird promisses, but I got stuck. So far, I have:
function allMovies() {
var movies, movieIds;
return client.smembersAsync('movies.ids').then(function(ids) {
movieIds = ids;
movies = _.map(movieIds, function(id) {
var movie;
return client.hmgetAsync("movies:" + id, 'title', 'description', 'director', 'year').done(function(data) {
movie = data;
return {
title: data[0],
description: data[1],
director: data[2],
year: data[3]
};
});
return movie;
});
})
The problem is from what I try, that I always get back a new promise, while I am just interested in a JSON after all operations have finished.
Anyone here can shed some light into this?
A:
In bluebird, there is a more sugary way of doing this:
function allMovies() {
return client.smembersAsync("movies.ids").map(function(id){
return client.hmgetAsync( "movies:" + id, 'title', 'description', 'director', 'year');
}).map(function(data){
return {
title: data[0],
description: data[1],
director: data[2],
year: data[3]
};
});
}
| {
"pile_set_name": "StackExchange"
} |
Q:
TestNG BeforeMethod with groups
I am wondering about @BeforeMethod's usage with groups. In http://testng.org/javadoc/org/testng/annotations/BeforeMethod.html it says:
alwaysRun: If set to true, this configuration method will be run regardless of what groups it belongs to.
So I have the following class:
public class BeforeTest {
private static final Logger LOG = Logger.getLogger(BeforeTest.class);
@BeforeMethod(groups = {"g1"}, alwaysRun = false)
public void setUpG1(){
sleep();
LOG.info("BeforeMethod G1");
}
@Test(groups = {"g1"})
public void g1Test(){
sleep();
LOG.info("g1Test()");
}
@BeforeMethod(groups = {"g2"}, alwaysRun = false)
public void setUpG2(){
sleep();
LOG.info("BeforeMethod G2");
}
@Test(groups = {"g2"})
public void g2Test(){
sleep();
LOG.info("g2Test()");
}
private void sleep(){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Which outputs:
BeforeMethod G1
BeforeMethod G2
g1Test()
BeforeMethod G1
BeforeMethod G2
g2Test()
Aside the fact that I think awaysRun is false by default, can anyone explain to me why both before methods are called before each test, disregarding the groups? Something like @Test(skipBeforeMethod = "setUpG1") would work too.
I am using IntelliJ IDEA CE 10.5.2. I've run it with gradle 1.0-milestone-3, too.
A:
How are you invoking TestNG? Are you running any groups?
If you run none, both @BeforeMethods will run. If you run "g1", only setupG1 will run, etc...
| {
"pile_set_name": "StackExchange"
} |
Q:
Who could I be?
I am kind, compassionate and cruel
I am just and unfair
I am quick and I am slow
I am known and unknown
I am friend and foe
Who am I?
A:
Possible answer (very meta)
A riddle
I am just and unfair
When solving a riddle, everyone approaches the puzzle from a unique perspective based on individual background, this makes it inherently unfair as certain "thinking styles" or creative perspectives are more likely to succeed at riddles. The fact that this perspective-discrimination is essentially random makes it just.
I am quick and I am slow
Riddle solutions can be arrived at quickly or slowly
I am known and I am unknown
Some people know the answer (the person posing the riddle) and some people don't (the participants)
I am friend and foe
A friend can be judged by the net improvement he/she adds to your life. A riddle can be intellectually stimulating like a friend. Sometimes the quest to solve riddle can be all-consuming or overstimulating, resulting it having a negative impact (foe).
A:
I say the answer is
Death
I am kind, compassionate and cruel
For those who are suffering death can be compassionate. For others it can be cruel
I am just and unfair
Death can be seen as just for murderers and unfair for good people
I am quick and I am slow
Some people die suddenly while others suffer slow deaths
I am known and unknown
People see others die all the time but no one knows what happens after death
I am friend and foe
Death is a friend to those who are suffering but a foe to those who have a lot of life to live
| {
"pile_set_name": "StackExchange"
} |
Q:
Identify Short Story about a Man/Computer trying to hack into a casino in Mars
This is a short story I read back in the 80's (but it could be older). It centered around a man who was artificially augmented with a computer that could be plugged directly to his spine. The story opens in a casino in Mars where he has won a large sum of money using his hidden computer processing power to calculate odds. He is later approached by a woman who offers him a job: hack into the computer systems of the highly secretive owner of the casino by plugging himself into it. In the process he discovers that the shadowy owner is in fact the computer system itself that has gained sentience.
I no longer remember what the story was called. Or even what language it was originally written in (the version I read was translated to Arabic). Though I seem to remember the words "fire" and "ship" somewhere in the title. Ring any bells?
A:
You have, in fact, remembered the title. It's Fireship by Joan D. Vinge.
| {
"pile_set_name": "StackExchange"
} |
Q:
Clipboard erased when quitting Blender on Ubuntu
If you highlight text in Blender and press CTLC to copy it, then quit Blender, you can no longer paste that text.
Why not?
A:
I posted a bug report on this, but apparently it's not Blender's fault.
As Sergey explained in the bug report, Blender only instructs the clipboard manager to save the text, but in Ubuntu, this is a bug that affects many programs. You can read more about why it happens here.
Going to the Ubuntu Software Center and installing the application Parcellite, which is an alternative clipboard manager has fixed the problem for me.
EDIT: I also had some problems with Parcellite and Blender working together. You could try a different clipboard manager.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I log HTTP::Async communication in Perl?
I have a Perl code that use threads and HTTP::Async with multiple outbound IP addresses >>
use threads ( 'yield',
'exit' => 'threads_only',
'stack_size' => 2*16384 );
use strict;
use warnings;
no warnings 'threads';
use threads::shared;
use LWP::UserAgent;
use HTTP::Request;
use HTTP::Async;
...
my $async = HTTP::Async->new( ... );
...
foreach (@list) {
$thread = threads->create( sub {
local $SIG{KILL} = sub { threads->exit };
...
$ua->local_address($ip);
$request->url($url);
$async->add($request);
while ($response = $async->wait_for_next_response) {
...
}
}, $_);
}
...
I need to generate some basic application logs that would include url and outbound IP information.
How can I log HTTP::Async communication?
A:
You are not actually using LWP in that code, you are just loading it. Likewise from your code example it's not clear why you are using threads. HTTP::Async takes care of doing multiple HTTP requests "at once".
It doesn't look like HTTP::Async has any built-in debug mechanisms, but it'd be relatively straightforward to add a 'debug' flag in that module and some warn statements at the appropriate places if you need help seeing what it's doing. You could also add the debug code in your own code that's using HTTP::Async.
| {
"pile_set_name": "StackExchange"
} |
Q:
d3 Tree - drag and relocate nodes in d3 graphs is possible?
Is it possible to use D3 Trees and draw graph. Then let the user to rearange the nodes without changing their relationships?
A:
I used d3 Tree functions to have the location of nodes and used my current forced directed graph. This way I could keep my current functionalities, and also having more than one parent for nodes, and user could move the nodes around. However, once user moves the node, I do not let d3 to rearrange the node when nodes is expanded. I want the node stays in the location that user moved and wants.
| {
"pile_set_name": "StackExchange"
} |
Q:
Building open street routing machine (osrm)
I'm doing a project on openstreetmap, thus for the purpose of implementing routing mechanism I tried to implement osrm referring 1, but when I tried out mkdir -p build; cd build; cmake .., I got an error saying:
"CMake Error: The source directory "/home/user1" does not appear to
contain CMakeLists.txt".
What should I do to resolve this!
A:
After running the git clone command, you first need to go to your cloned branch directory by typing cd osrm-backend/. After that continue with mkdir -p build; cd build; cmake ..; make.
Here's the directory layout assumed by cmake, to make things a bit clearer.
/home/user1
/home/user1/osrm-backend
/home/user1/osrm-backend/build
| {
"pile_set_name": "StackExchange"
} |
Q:
Creating SafeArray with user defined type objects
I am using Interoperability concept between Delphi and c#. I created classes in c#, and imported those classes to delphi project as com objects.
The class declaration in c# code
public class HotelAvailNotifRQ : IHotelAvailNotifRQ
{
[MarshalAs(UnmanagedType.LPArray)]
public IAvailStatusMessage[] AvailStatusMessagesField;
public IAvailStatusMessage[] AvailStatusMessages
{
get { return AvailStatusMessagesField; }
set { AvailStatusMessagesField = value; }
}
}
And when I import this class as com object to delphi that will be like
IHotelAvailNotifRQ = interface(IDispatch)
['{2F7C57D7-256A-3102-A4C6-FD081C8342B4}']
function Get_AvailStatusMessages: PSafeArray; safecall;
procedure Set_AvailStatusMessages(pRetVal: PSafeArray); safecall;
property AvailStatusMessages: PSafeArray read Get_AvailStatusMessages write Set_AvailStatusMessages;
end;
I can create IAvailStatusMessage object successfully. But, while I am putting this object into the PSafeArray by using function
SafeArrayPutElement(HotelAvailNotifRQ.AvailStatusMessages, Idx, AvailStatusMessage)
I am getting the error like "the parameter is incorrect". Please help me to solve this problem.
A:
After a day of struggling found the solution for the problem. After chaning the both sides code as,
Delphi side code
var
varAvailStatusMessages : Variant;
begin
varAvailStatusMessages := VarArrayCreate([0, AvailStatusMessages.Count], varDispatch);
varAvailStatusMessages[asmIdx] := AvailStatusMessage;
Result.AvailStatusMessages := PSafeArray(TVarData(varAvailStatusMessages).VArray);
end;
.Net side code
public class HotelAvailNotifRQ : IHotelAvailNotifRQ
{
[MarshalAs(UnmanagedType.Interface)]
public IAvailStatusMessage[] AvailStatusMessagesField;
public IAvailStatusMessage[] AvailStatusMessages
{
get { return AvailStatusMessagesField; }
set { AvailStatusMessagesField = value; }
}
}
Thanks for the reference,
http://blog.virtec.org/2008/07/the-mysteries-of-psafearray/
| {
"pile_set_name": "StackExchange"
} |
Q:
Locally flat coordinate and Locally inertial frame
I am having some doubts on myself regarding the above concepts in General Relativity.
First, I want to point out how I understand them so far.
A male observer follows a timelike worldline ($\gamma$) in spacetime (because he must have a proper time). He has a frame for himself.
A coordinate is a sets of numbers the observer uses to describe the spacetime in his frame (which is another way to say the spacetime in his view).
The locally flat coordinate of an observer at a time ($s\in\gamma$) is the coordinate (of his frame, of course) in which he sees the metric tensor at a neighborhood of his position be the flat metric (Christoffel symbols vanish):
$$g_{\mu\nu}(s)=\eta_{\mu\nu}$$
$$\Gamma_{\mu\nu}^\rho(s)=0$$
This coordinate depends on and is used naturally by the observer.
Now a locally inertial frame is a frame of any freely falling observer, or any observer following a geodesic ($l$). He may use or may not use the locally flat coordinate of himself. But he has a very special coordinate which is locally flat at every point is his worldline:
$$\forall s\in l:$$ $$g_{\mu\nu}(s)=\eta_{\mu\nu}$$ $$\Gamma_{\mu\nu}^\rho(s)=0$$
Do I have any misunderstanding or wrong use of terminology?
Now there should be an freely falling observer $A$ (with his special coordinate) and his wordline crosses the wordline of another (not freely falling) observer $B$. And at the cross point can I believe that the two coordinate (of two frames) may be chosen to be locally identical (or equal) (that is, there exists a linear transformation locally transform one to other)?
A:
In the most general case described by general relativity, it is not possible to find a $neighbourhood$ covered by coordinates $x^\mu$ such that $g^{\mu\nu} = \eta^{\mu\nu}$ in all U. If it were so, you have a zero Riemann tensor, hence the space-time would be flat in all U. You may have space-times with such flat pieces (I think there is no problem in gluing this piece with non-flat pieces, but I may be wrong), but is not the most general case and not what is meant when we say that space-time is locally flat.
What we mean is that the tangent space, in any point is the Minkowski space-time.
This mean that, for any point p, you can find a basis for the tangent space at p (and associated "exponential" coordinates) so that the metric is diag(-,+,+,+) in these coordinates at this point p and the connession coefficients vanish at this point (not in a neighbourhood!)
You can think of these coordinates as those of a inertial observer. Note that there exists several possible coordinates, which are related by a Lorentz transform at the tangent space, and are associated to different observers.
In what sense you can think of these coordinates as those of a inertial observer? In the sense that as long as you are covering a sufficiently small neighbourhood of p, whose dimension will be "smaller the larger the Riemann tensor is at p", you may describe everything happening here as if you were in special relativity. One above all, the geodesics are of the form $d/dt^2 x(\tau) = 0$ and do not accelerate with respect to each other.
Of course, actually they do, but these effects are small if you consider small neighbourhood of p and small Riemann at p.
Analogously, Earth is flat at a point in the sense that you can "confuse" the flat tangent space with the actual neighbourhood because the differences are difficult to detect if you zoom enough.
A:
In light of our clarifying discussions, I believe the answer is yes.
I found a nice section on Fermi Normal coordinates here (Section 9):
http://relativity.livingreviews.org/Articles/lrr-2011-7/fulltext.html
This seems to be what you mean by "Locally inertial coordinates" - the tetrad is orthonormal with one direction along the curve, and the others along spacelike curves orthogonal to the curve.
Since you can define Fermi normal coordinates anywhere on a timelike geodesic, define them on the intersection of two geodesics. These define a flat metric, so there's no reason why you couldn't pick that metric to be the tetrad for the other observer at the same point.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to set the height for a flexbox container so it uses the "remaining space"
I'm struggling to understand how flexbox containers interact with other blocks. With just a flexbox on my page, I can do what I want. But when I mix in other page elements, things get weird. The problem seems to be space allocation.
My flexbox container seems to need an explicit height. If I don't specify that, I don't get the wrapping behavior. I'm not sure how to specify the height of the flexbox container.
If I set the height of the flexbox container to 100%, it wraps as desired but I am stuck with a scrollbar to nowhere: I've allocated more than 100% of height. I want to allocate 100px above the flexbox container. So I need to make the flexbox container height something like 100% - 100px. I can't mix absolute and relative measurements. And looking down the road, I would prefer not to have to do this math at all, it will become a maintenance hassle.
Below is an example of where things go wrong for me. I want to have some instructions at the top of the page. The instructions should span the width of the page. In the space below, I want a collection of buttons. The buttons should wrap to use multiple columns, as needed.
I can make it work by button the instructions inside the flexbox container. But then, it won't have 100% with like I want, it will get jumbled up with my buttons.
<html>
<head>
<style>
* {
margin: 0;
padding: 0;
border: 1px solid #A00;
}
.instructions {
height: 100px;
background: linear-gradient(to bottom, #ffffff 0%, #999 100%);
}
.container {
display: flex;
flex-direction: column;
flex-wrap: wrap;
height: 80%;
}
.button {
width: 200px;
height: 50px;
margin: 10px;
background: linear-gradient(to bottom, #ffffff 0%, #BBB 100%);
border: 1px solid #CCC;
text-align: center;
}
</style>
</head>
<body>
<div class="instructions">Instructions go here.</div>
<div class="container">
<div class="button">This is Button 1</div>
<div class="button">Thar be Button 2</div>
<div class="button">Yarr, button 3</div>
<div class="button">Hey that is a nice looking button.</div>
<div class="button">Click Me!</div>
</div>
</body>
</html>
A:
You have to give the section a height to limit it to cause the buttons to wrap, otherwise the flex element will just grow to fit the height of whatever's inside of it.
I would use height: calc(100vh - 100px) on the flex container to make it take up all of the available space.
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.instructions {
height: 100px;
background: linear-gradient(to bottom, #ffffff 0%, #999 100%);
}
.container {
display: flex;
flex-direction: column;
flex-wrap: wrap;
height: calc(100vh - 100px);
}
.button {
width: 200px;
height: 50px;
margin: 10px;
background: linear-gradient(to bottom, #ffffff 0%, #BBB 100%);
border: 1px solid #CCC;
text-align: center;
}
<div class="instructions">Instructions go here.</div>
<div class="container">
<div class="button">This is Button 1</div>
<div class="button">Thar be Button 2</div>
<div class="button">Yarr, button 3</div>
<div class="button">Hey that is a nice looking button.</div>
<div class="button">Click Me!</div>
</div>
Alternatively, you could limit the height of body to 100vh, make it display: flex; flex-direction: column and set flex-grow: 1 on .container so it will take up the available space.
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
display: flex;
flex-direction: column;
height: 100vh;
}
.instructions {
height: 100px;
background: linear-gradient(to bottom, #ffffff 0%, #999 100%);
}
.container {
display: flex;
flex-direction: column;
flex-wrap: wrap;
flex-grow: 1;
}
.button {
width: 200px;
height: 50px;
margin: 10px;
background: linear-gradient(to bottom, #ffffff 0%, #BBB 100%);
border: 1px solid #CCC;
text-align: center;
}
<div class="instructions">Instructions go here.</div>
<div class="container">
<div class="button">This is Button 1</div>
<div class="button">Thar be Button 2</div>
<div class="button">Yarr, button 3</div>
<div class="button">Hey that is a nice looking button.</div>
<div class="button">Click Me!</div>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
How can a flying wing style airplane recover from a spin without a vertical stabilizer?
I fly a Cessna C-172, and if I have any bank when stalling, I have to use rudder to level the airplane. If I use aileron, the bank angle will increase and bring the airplane into a spin.
My question is, if there is no rudder or vertical stabilizer, like a B-2 bomber for example, how could a plane recover from a stall?
This question is different from others because this is not focus on the stability or control of 6 freedom. I would like more discussion on the recovery of spin and stall.
A:
The answer depends on the type of flying wing aircraft.
Drag rudders
The B2 for example is an example of a flying wing aircraft with rudders. It's just that it doesn't use conventional boat style rudders attached to vertical stabilisers since it doesn't have any vertical stabilisers. Instead it uses drag rudders.
There are several different types of drag rudders. The B2 uses one of the most effective designs as proven by countless experiments: the split elevon (sometimes called duckerons since they look sort of like duck bills). If you look at pictures of B2 landing you can clearly see them open at the wingtips.
Regardless of the type of drag rudders, they work via 2 principles:
The simple to understand one whereby if you increase the drag on one wing you make it advance slower than the other wing thus inducing a yaw.
The less obvious principle of shifting the center of drag backwards. This is the same principle of how badminton shuttlecocks work. Indeed, this is the same principle of how vertical stabilizers work. If the center of gravity is in front of the center of drag you get a weathervaning effect where the draggy part would swivel to the rear. The B2 achieves this by opening both drag rudders. In effect the B2 is creating a less efficient, more draggy, virtual vertical stabilizer. In practice you'd only need this extra stability when flying slow. At cruise speeds the drag rudders would be mostly closed (especially if you have them gyro stabilized, if you don't have computer controls and gyros you'd keep them partially open for stability).
Wing twist/washout
Some flying wings don't have drag rudders. Instead the wing is twisted to achieve a lift distribution that would cause the wing to have proverse yaw. The Dunne series of flying wings were promoted as inherently stable aircraft because they didn't experience adverse yaw. If you have proverse yaw you can simply use your ailerons to turn the plane without rudders.
The big disadvantage designs that don't use drag rudders or any vertical stabilizers is that you depend on banking in order to yaw. This makes landing on straight runways impractical so most such planes land on grass fields which allows the pilot to choose landing direction so that crosswind is not an issue. A lot of Dunne flying wings were seaplanes.
A:
Stall Recovery
Similar to the vertical tail on your Cessna, a flying wing produces only little lift or even a downforce over the rear part of its wing. A swept flying wing uses washout for the same effect. In all cases, the idea is to produce relatively more lift increase with an angle of attack increase in the rear parts of the wing (or the tail in conventional configurations) so the aircraft stabilizes itself.
This also means that the center of lift is ahead of the quarter chord point of the wing, and the same goes for the center of mass. At high angle of attack you need to create a pitch-up moment with the elevons in order to trim the high angle, and once the wing stalls, this pitch-up moment is reduced. As a consequence, the flying wing will pitch down and recover. Again, this is very similar to what happens on your Cessna, only that the function of the tail is performed by the rear part of the wing.
Wing sweep helps a lot to pull the aircraft into the wind, and the yaw inertia of the big wing helps to keep rate changes down. Stalling in banking flight produces a very similar reaction as a straight and level stall while the airplane continues to turn. Of course, pulling too hard and preventing the wing from correcting the high angle of attack itself will risk to force the flying wing into a spin.
Spin Recovery
Flying wings have only a steep spin mode. Flat spins are not possible because the flying wing lacks the lengthwise mass distribution of conventional airplanes which creates a strong pitch-up moment in a spin. If the flying wing has no fuselage protruding in front, it also lacks the stabilizing nose vortices which are a contributing factor for flat spins.
Spinning the SB-13 was quite harrowing: The nose points almost straight down and the aircraft loses about 100 m in one turn. But ending the spin was simple: Just pitch down and stop the rolling motion by allowing the roll damping of the wing to kick in.
| {
"pile_set_name": "StackExchange"
} |
Q:
Which enemies take extra damage from sword attacks?
I have noticed that Ranger sword attacks do different amounts of damage to different enemies. For example, attacking with the basic sword against ADVENT troopers deals 3-5 damage, but attacking Sectoids deals 6-8 damage. Which other enemies are more vulnerable to sword attacks?
A:
It's just Sectoids against which swords have +3, sadly.
| {
"pile_set_name": "StackExchange"
} |
Q:
linux reading file line by line and passing to another program
I have an input file of this form:
Some text here
Another text here
Something else here
Now I want to write a linux script picks one line at a time from input file and creates a separate file which stores just the line received. After this I want to pass this file to a program (for which I have just binary file). Is it possible to write such a linux script. I am used to programming in C++ I know it is possible there. But I want to know if something like this is possible using linux script. Basically I intend to do the following:
read inputfile.txt line by line
store line read in inputFileInside.txt
./myprogram paramater1 inputFileInside.txt //run my C++ binary file which I usually run as (root$./myprogram parameter1 inputFileInside.txt)
sudo sh -c \"sync; echo 3 > /proc/sys/vm/drop_caches\"
exit when the input file has been read
A:
you can read line by line like this using for loop
while read x
do
echo $x > inputFileInside.txt;
# do whatever you want
done < inputfile.txt
this may hep you to loop, $x is line read one by one till it reach end of file
while read x
do
echo $x > $2;
./myprogram paramater1
#your other command
done < $1;
save the above file as any name like prog.sh, then give execute permission and run ur program with argument
chmod u+x prog.sh
./prog.sh inputfile.txt inputFileInside.txt
here $1 is inputfile.txt and $2 is inputFileInside.txt
| {
"pile_set_name": "StackExchange"
} |
Q:
Cannot use javascript screen width inside css background image style also being set by javascript
Here is my code:
<div id="newprofileimg_<xsl:value-of select+"position()"/></div>
<script>
var width=screen.width;
var d=document.getElementById("newprofileimg_<xsl:value-of select="position()"/>");
d.style.backgroundImage="url(/services/resizeimage/<xsl:value-of select="./mediaid"/>/"+width+"/500);";
</script>
The backgroundImage URL parses correctly, just for some reason the JavaScript isn't affecting the div being mutated.
A:
Looks like there is nothing in your div, that's why the height of the div is 0px; You should add css to the div.
var div = document.getElementById("test")
div.style.backgroundImage = "url('http://via.placeholder.com/200/200')"
div.style.width = "200px"
div.style.height = "200px"
<div id="test"></div>
| {
"pile_set_name": "StackExchange"
} |
Q:
DataTemplate only shows Canvas for the last record
I'm using the following DataTemplate
<DataTemplate x:Key="platform_resources">
<StackPanel Orientation="Horizontal">
<Viewbox Width="30" Height="30" ToolTip="Network Domain Count" Stretch="Uniform">
<ContentControl DataContext="{Binding}" Focusable="False" Content="{DynamicResource appbar_server}" />
</Viewbox>
<TextBlock Margin="0,7,0,0" Text="{Binding Path=workload_count}"/>
<Separator Style="{StaticResource {x:Static ToolBar.SeparatorStyleKey}}" />
<Viewbox Width="30" Height="30" ToolTip="Logical Network Count" Stretch="Uniform">
<ContentControl Focusable="False" Content="{DynamicResource appbar_network_server_connecting}" />
</Viewbox>
<TextBlock Margin="0,7,0,0" Text="{Binding Path=vlan_count}"/>
<Separator Style="{StaticResource {x:Static ToolBar.SeparatorStyleKey}}" />
<Viewbox Width="30" Height="30" ToolTip="Network Domain Count" Stretch="Uniform">
<ContentControl Focusable="False" Content="{DynamicResource appbar_network}" />
</Viewbox>
<TextBlock Margin="0,7,0,0" Text="{Binding Path=networkdomain_count}"/>
</StackPanel>
</DataTemplate>
The template displays all the relevant data with separators but only shows the images on the last record. It's leaves spaces where the images are supposed to be, but no images.
A:
Make sure you add x:Shared="False" property to your resources.
Example:
<Canvas x:Key="appbar_server" x:Shared="False">
<!-- ... -->
</Canvas>
| {
"pile_set_name": "StackExchange"
} |
Q:
Understanding the Product Topology
This is pretty basic, but I just learned about the product topology in class, and it seems to me that it doesn't agree with how it is defined - obviously, I'm wrong, but I was hoping someone could explain to me exactly where my thoughts are going wrong.
Working in the simple case of two sets for illustrative purposes: Let $(X,T_x)$ and $(Y,T_y)$ be topological spaces. Then we define the product topology on $X \times Y$ to be $T_{X \times Y} = \{U \times V: U \in T_x, V \in T_y\}$. This is supposed to be the weakest topology on $X \times Y$ such that the projection operator $p_i$ is continuous for all $i$. However, let us take the case $P \times Q \subset X \times Y$ such that $P \in T_x$ but $Q \notin T_y$. By the definition of product topology this isn't an open set. Then, $p_1[P \times Q] = P \in T_x$. Since $P$ is an open set, but $p_1^{-1}[P]$ isn't an open set, wouldn't this mean that $p_1$ is not continous, in contradition to the definition of the product topology?
A:
No, we do not define the product topology to be $\{U\times V:U\in T_X,V\in T_Y\}$
we define it to the the topology with basis
$\{U\times V:U\in T_X,V\in T_Y\}$.
In all cases, if $U\in T_X$ then $p^{-1}(U)=U\times Y$ which is open in $X\times Y$.
A:
The set $\mathcal{B}:= \{ U \times V: U \in \mathcal{T}_X, V \in \mathcal{T}_Y\}$ is not the product topology (it's not closed under unions) but it is a base for that topology: all product-open sets are unions of sets from this family.
This makes all projections continuous: $(p_X)^{-1}[U] = U \times Y$ and $(p_Y)^{-1}[V] = X \times V$, for all open $U$ in $X$ and open $V$ in $Y$, and these products are all in $\mathcal{B}$, of course, hence open.
If $\mathcal{T}$ is any topology on $X \times Y$ that makes both projections continuous, then for any open $U$ in $X$ and any open $V$ in $Y$, $(p_X)^{-1}[U] \cap (p_Y)^{-1}[V]$ must be open in $\mathcal{T}$. And clearly $$(p_X)^{-1}[U] \cap (p_Y)^{-1}[V] = U \times V$$
which shows that then we know that $\mathcal{B} \subseteq \mathcal{T}$. So any topology that makes the projections continuous at least has all of $\mathcal{B}$ as open sets. So taking that collection as a base (which we can do, as it's closed under intersections, e.g.) gives us the smallest such topology.
Your set $P \times Q$ is not of the form $p^{-1}[O]$ for a projection $p$ and some open set so not a contradiction to continuity of such projections.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.