source
sequence | text
stringlengths 99
98.5k
|
---|---|
[
"rus.stackexchange",
"0000447137.txt"
] | Q:
Пунктуация при "двойной" прямой речи
Подскажите, пожалуйста, как верно расставить знаки препинания в следующих предложениях.
1) У вас могут возникнуть мысли: «А почему это я должен что-то делать, а не мой партнер?» - или страхи: «Ага, сейчас я уступлю, а потом он мне на шею сядет!»
2) Вместо того чтобы сказать тебе: «Давай подумаем, вместе мы найдем решение!» - тебе говорили: «Решай сам, не маленький!»
3) Она сказала: «Ну хорошо, пусть будет по-вашему» - и тихо добавила: «Как же вы мне надоели».
Интересуют места между репликами. Верно ли поставлены тире и вторые двоеточия?
Напишите, пожалуйста, как будет правильно.
A:
У Розенталя есть тема "Прямая речь внутри слов автора". Это схема А—П—А. В Вашем случае схема А—П—А—П, но я думаю, что добавление второй прямой речи на оформление не влияет.
http://old-rozental.ru/punctuatio.php?sid=159#pp159
1) У вас могут возникнуть мысли: «А почему это я должен что-то делать, а не мой партнер?» или страхи: «Ага, сейчас я уступлю, а потом он мне на шею сядет!»
Розенталь: Не говорить же: «Эй, собака!» или «Эй, кошка!» — две реплики, разделенные неповторяющимся союзом или;
2) Вместо того чтобы сказать тебе: «Давай подумаем, вместе мы найдем решение!» — тебе говорили: «Решай сам, не маленький!»
Розенталь: И только когда он шептал: «Мама! Мама!» — ему становилось как будто легче (Ч.) — тире после вопросительного/восклицательного знака, которым заканчивается прямая речь;
Комментарий: Если бы не было восклицательного знака в прямой речи, то на месте тире ставилась бы запятая (это как бы "встроенная" прямая речь)
3) Она сказала: «Ну хорошо, пусть будет по-вашему» — и тихо добавила: «Как же вы мне надоели».
Розенталь: Она сказала: «Нынче, говорят, в университете уже мало занимаются науками» — и подозвала свою собачку Сюзетку (Л. Т.) — тире перед союзом и при однородных сказуемых;
|
[
"stackoverflow",
"0062865567.txt"
] | Q:
How select multiple value in one record in mysql?
I have a table with many column. one of this contain multiple argument, How can I select a field with one of this argument. for example my query is :
select name from product where product='carpet' and selling='new';
selling column contain 'new' , 'discounted', ..
A:
You are looking for FIND_IN_SET
Returns a value in the range of 1 to N if the string str is in the
string list strlist consisting of N substrings. A string list is a
string composed of substrings separated by , characters
mysql> DESCRIBE products;
+---------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+------------------+------+-----+---------+----------------+
| id | int(11) unsigned | NO | PRI | NULL | auto_increment |
| product | varchar(255) | YES | | NULL | |
| selling | varchar(255) | YES | | NULL | |
+---------+------------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
mysql> SELECT * FROM products;
+----+---------+---------------------------+
| id | product | selling |
+----+---------+---------------------------+
| 1 | carpet | new,discounted,hello,worl |
| 2 | fork | used,other |
| 3 | plate | new |
| 4 | spoon | NULL |
+----+---------+---------------------------+
4 rows in set (0.00 sec)
mysql> SELECT * FROM products
-> WHERE product='carpet' AND FIND_IN_SET('new', selling) <> 0;
+----+---------+---------------------------+
| id | product | selling |
+----+---------+---------------------------+
| 1 | carpet | new,discounted,hello,worl |
+----+---------+---------------------------+
1 row in set (0.00 sec)
|
[
"stackoverflow",
"0032177375.txt"
] | Q:
How to draw on canvas and convert to bitmap?
I'm tring to draw some line and shapes on canvas and then convert it to bitmap on ImageView. I'm usin a custom class that extands "View" and on "OnDraw method i'm drawing the lines. here is my code(this class only draw simple lines) :
public class finalDraw extends View {
public finalDraw(Context context) {
super(context);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
paint.setColor(Color.BLUE);
for (int i = 0; i <100; i++) {
canvas.drawLine(xStart * i + 50 , yStart , stopX + 30 , stopY,paint);
}
invalidate();
}
}
How can i get the drawing result and show it on ImageView?
Thanks!
A:
Found this article may help: http://www.informit.com/articles/article.aspx?p=2143148&seqNum=2
draw.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Bitmap imageBitmap = Bitmap.createBitmap(imageView.getWidth(), imageView.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(imageBitmap);
float scale = getResources().getDisplayMetrics().density;
Paint p = new Paint();
p.setColor(Color.BLUE);
p.setTextSize(24*scale);
canvas.drawText("Hello", imageView.getWidth()/2, imageView.getHeight()/2, p);
imageView.setImageBitmap(imageBitmap);
}
});
|
[
"stackoverflow",
"0033601177.txt"
] | Q:
Minimax Algorithm: Why make rating negative?
/* finds the best move for the current player given the state of the game.
* depth parameter and MAX_DEPTH are used to limit the depth of the search for games
* that are too difficult to analyze in full detail (like chess)
* returns best move by storing an int in variable that rating points to.
* we want to make the move that will result in the lowest best move for the position after us(our opponent)
*/
moveT findBestMove(stateT state, int depth, int &rating) {
Vector<moveT> moveList;
generateMoveList(state, moveList);
int nMoves = moveList.size();
if (nMoves == 0) cout << "no move??" << endl;
moveT bestMove;
int minRating = WINNING_POSITION + 1; //guarantees that this will be updated in for loop
for (int i = 0; i < nMoves && minRating != LOSING_POSITION; i++) {
moveT move = moveList[i];
makeMove(state, move);
int curRating = evaluatePosition(state, depth + 1);
if (curRating < minRating) {
bestMove = move;
minRating = curRating;
}
retractMove(state, move);
}
rating = -minRating;
return bestMove;
}
/* evaluates the position by finding the rating of the best move in that position, limited by MAX_DEPTH */
int evaluatePosition(stateT state, int depth) {
int rating;
if (gameIsOver(state) || depth >= MAX_DEPTH) {
return evaluateStaticPosition(state);
}
findBestMove(state, depth, rating);
return rating;
}
This is my code for implementing a minimax algorithm to play a perfect game of tic tac toe against a computer. The code works and there are many other helper functions not show here. I understand the nature of the algorithm, however I am having a hard time fully wrapping my head around the line at the end of the findBestMove() function:
rating = -minRating;
This is what my book says: The negative sign is included because the perspective has shifted: the positions were evaluated from the point- of-view of your opponent, whereas the ratings express the value of a move from your own point of view. A move that leaves your opponent with a negative position is good for you and therefore has a positive value.
But when we call the function initially, it is from the computers perspective. I guess when we evaluate each position, this function is being called from our opponent's perspective and that is why? Could someone give me more insight into what is going on recursively and exactly why the rating needs to be negative at the end.
As always thank you very much for your time.
A:
Imagine two positions, A and B, where A is better for player a and B is better for player b. When player a evaluates these positions, eval(A) > eval(B), but when play b does, we want eval(A) < eval(B), but don't. If b instead compares -eval(A) with -eval(B), we get the desired result, for the very reasons your book says.
|
[
"stackoverflow",
"0040235464.txt"
] | Q:
Bitmasking conversion of CPU ids with Go
I have a mask that contains a binary counting of cpu_ids (0xA00000800000 for 3 CPUs) which I want to convert into a string of comma separated cpu_ids: "0,2,24".
I did the following Go implementation (I am a Go starter). Is it the best way to do it? Especially the handling of byte buffers seems to be inefficient!
package main
import (
"fmt"
"os"
"os/exec"
)
func main(){
cpuMap := "0xA00000800000"
cpuIds = getCpuIds(cpuMap)
fmt.Println(cpuIds)
}
func getCpuIds(cpuMap string) string {
// getting the cpu ids
cpu_ids_i, _ := strconv.ParseInt(cpuMap, 0, 64) // int from string
cpu_ids_b := strconv.FormatInt(cpu_ids_i, 2) // binary as string
var buff bytes.Buffer
for i, runeValue := range cpu_ids_b {
// take care! go returns code points and not the string
if runeValue == '1' {
//fmt.Println(bitString, i)
buff.WriteString(fmt.Sprintf("%d", i))
}
if (i+1 < len(cpu_ids_b)) && (runeValue == '1') {
//fmt.Println(bitString)
buff.WriteString(string(","))
}
}
cpuIds := buff.String()
// remove last comma
cpuIds = cpuIds[:len(cpuIds)-1]
//fmt.Println(cpuIds)
return cpuIds
}
Returns:
"0,2,24"
A:
What you're doing is essentially outputting the indices of the "1"'s in the binary representation from left-to-right, and starting index counting from the left (unusal).
You can achieve the same using bitmasks and bitwise operators, without converting it to a binary string. And I would return a slice of indices instead of its formatted string, easier to work with.
To test if the lowest (rightmost) bit is 1, you can do it like x&0x01 == 1, and to shift a whole number bitwise to the right: x >>= 1. After a shift, the rightmost bit "disappears", and the previously 2nd bit becomes the 1st, so you can test again with the same logic. You may loop until the number is greater than 0 (which means it sill has 1-bits).
See this question for more examples of bitwise operations: Difference between some operators "|", "^", "&", "&^". Golang
Of course if we test the rightmost bit and shift right, we get the bits (indices) in reverse order (compared to what you want), and the indices are counted from right, so we have to correct this before returning the result.
So the solution looks like this:
func getCpuIds(cpuMap string) (r []int) {
ci, err := strconv.ParseInt(cpuMap, 0, 64)
if err != nil {
panic(err)
}
count := 0
for ; ci > 0; count, ci = count+1, ci>>1 {
if ci&0x01 == 1 {
r = append(r, count)
}
}
// Indices are from the right, correct it:
for i, v := range r {
r[i] = count - v - 1
}
// Result is in reverse order:
for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return
}
Output (try it on the Go Playground):
[0 2 24]
If for some reason you need the result as a comma separated string, this is how you can obtain that:
buf := &bytes.Buffer{}
for i, v := range cpuIds {
if i > 0 {
buf.WriteString(",")
}
buf.WriteString(strconv.Itoa(v))
}
cpuIdsStr := buf.String()
fmt.Println(cpuIdsStr)
Output (try it on the Go Playground):
0,2,24
|
[
"stackoverflow",
"0032380326.txt"
] | Q:
mysql order by group with with alphabetical order
example in database:
felhasznalonev tipus
TOM 1
DICK 2
HARRY 1
I have asking
SELECT elsotabla.felhasznalonev, elsotabla.tipus
GROUP BY elsotabla.tipus
but this query return me tom 1 as first and I will hawing it in ordered by group and in group type the names in alphabetical order. Can somebody me help?
Thank.
A:
SELECT elsotabla.felhasznalonev, elsotabla.tipus
ORDER BY elsotabla.felhasznalonev ASC;
That would order the query by some field in ascending order.
|
[
"stackoverflow",
"0060366838.txt"
] | Q:
Okhttp sending http request after proxy connection is closed
I'm tunneling my requests through a proxy that it seems like it closes the connection every 10-15 seconds. So if the client request a website and it takes some time the connection might be closed and therefore the okhttp library throws a "unexpected end of stream". Even though the connection is closed and the library throws that exception, the request has been successfully received by the server but the client couldn't check the answer. If I try to request the same url without proxy I have no problem and I receive the answer successfully.
Here you can see it wireshark:
wireshark capture
In the photo you can see at the end a request made by the client at 19:27:54,980 and then after 10 seconds, the client receives the FIN tcp packet. So after that Okhttp throws this exception:
java.io.IOException: unexpected end of stream on Connection{m.apuestas.codere.es:443, proxy=HTTP @ /185.163.232.127:58542 hostAddress=/185.163.232.127:58542 cipherSuite=TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA protocol=http/1.1}
at okhttp3.internal.http1.Http1Codec.readResponseHeaders(Http1Codec.java:208)
at okhttp3.internal.http.CallServerInterceptor.intercept(CallServerInterceptor.java:88)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at com.telecobets.http.HTTPClient$LoggingInterceptor.intercept(HTTPClient.java:219)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:45)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at com.telecobets.http.HTTPClient$AddHeadersInterceptor.intercept(HTTPClient.java:199)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
at okhttp3.RealCall.execute(RealCall.java:77)
at retrofit2.OkHttpCall.execute(OkHttpCall.java:188)
at com.main(Main.java:375)
Caused by: java.io.EOFException: \n not found: limit=0 content=…
at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:237)
at okhttp3.internal.http1.Http1Codec.readHeaderLine(Http1Codec.java:215)
at okhttp3.internal.http1.Http1Codec.readResponseHeaders(Http1Codec.java:189)
... 26 more
It is not the server who closes the connection because I've been doing different requests simultaneously to different servers and suddenly at the same time the connections got closed.
So my question is, is there a way to receive that answer even if the connection was closed by the proxy server?
Whole wireshark capture is here
Proxy IP: 185.163.232.127:58542
A:
The proxy server provider was disconnecting connections every 10 seconds.
|
[
"stackoverflow",
"0004085297.txt"
] | Q:
Rails: display @cars as a comma-separated list
Based on this query:
@cars = Car.where("manufacturer_id IN ?", @mfts.select("id")).limit(30).select("id")
How can I display the cars' IDs in the view like this (or do I need to rewrite my query)?
3,2,5,12,15,24,34,63,64,65,66,85
Thanks a lot - I've looked for this but couldn't find the right question/answer.
One solution is to do:
#view
<% @cars.each do |c| %><%= c.id %>,<% end %>
I don't know if there's a better way to go about it - this obviously leaves a stray comma at the end of the list (which isn't a dealbreaker). Any more elegant solutions?
A:
One line:
<%= @cars.map(&:id).join(",") %>
A:
If writing &:id seems confusing, there's another way that's a little more readable.. If y'all want to access a method or attribute, it might look better to inline a block.
<%= @cars.map { |car| car.id }.join(", ") %>
P.S... another name for map is collect.. that's what it's called in Smalltalk.
Lookin' good!
A:
With Rails 3.0+ you can now write:
<%= @cars.map { |car| car.id }.to_sentence %>
Rails will appropriately add the comments and the word 'and' between the last two elements.
|
[
"stackoverflow",
"0056512223.txt"
] | Q:
Why we don't need suffix after conversion but during declaration we need it?
Float is not accepting suffix f when converting from string to float using C#. I want to convert string to float & my string already has "F" suffix within it. but the float is not accepting suffix f when converting from string to float & throws an exception.
static void Main()
{
string any_str = "123.45F";
float f = float.Parse(any_str);
Console.WriteLine(f);
Console.ReadLine();
}
A:
Basically float.Parse can't do anything with that f suffix. float.Parse will just take a string representing a numerical value, any extra nonnumerical characters will throw an exception. The f suffix is just for use, by you, in your code itself. So as fahime and Norse said you'll need to get rid of that 'f' before using float.Parse.
|
[
"superuser",
"0000802653.txt"
] | Q:
What are the impact on underpowering my motherboard/graphic card?
I recently had to change my PSU and the one that was given to me has not enough power cables to fully plug every plug in the motherboard and the graphic card. It seems to work just fine though, and it's been going on for over a year now.
I was just wondering if it had any impact on performance, durability, or anything else to underpower my hardware like that?
The PSU has a lower power limit (600 vs 750) than the older one, and therefore has less power cables. Games run fine (though i can't really compare, i didn't have the old one for long), everything is good, and i've never really had bluescreens or anything of the sort.
What happens if I run a stress test? is it risky? or will it just slow down? I've been told that it might burn because the motherboard would ask for more energy than the cable can supply. I have absolutly no clue on what can happen and on top of being curious, i'd like to know if i'm taking risks with my hardware here ^^
Thanks for your time ! Looking forward to your answers !
A:
The PSU should be protected against overload. The worst (practical) thing that can happen is that you blow a fuse on the PSU. The worst theoretical thing is that your PC can catch fire, or blow a fuse in your house's electical system. Most likely the PSU will just switch off when it detects an overload, but it depends on the model. However, the PSU might deliver more than enough power for your particular setup.
One reason to ship with a more powerful PSU is because most PSU's work most efficient at around 80% load. If, for example your PC's maximum power usage is 590W, a 600W PSU would still work, but not be as efficient as a 750W.
|
[
"stackoverflow",
"0040136858.txt"
] | Q:
how to display a dialog box in response to a field value change in an infopath form
I have a situation where I need to display a dialog box when a specific field value is changed by the user in an InfoPath form.
I have a field called STATUS in the InfoPath form. When this field is set to a particular value, a dialog box needs to show up and the user needs to have to enter the value of some other fields (field1, field2 fields3) .
So basically the intent is to force the user to enter values in field1, field2 and field3 when he sets the STATUS field to a particular value.
How can I do this in InfoPath 2010 BROWSER form ?
UPDATE: this is an InfoPath list form (based on customizing a SharePoint list), so it seems like there is no way to add code (using the developer tab in InfoPath) to such forms. So is this thing possible using something like JavaScript or something like that?
A:
You can't have custom dialog boxes in InfoPath
On of the ways is to be creative to come close to your demand...
You can build something with show en hide sections.
Just put in the fields of you dialog box in a section and the rest of your form in another section. By default hide the "dialog box"-section.
Then activivate by rules to show it when needed, while show the "dialog box"-section just hide the rest of the form to force to fill in the dialog section. When done toggle hide/show of the sections.
|
[
"stackoverflow",
"0062586105.txt"
] | Q:
While iterating the array, the records are not completely displaying in react hooks page
While iterating using map function in react-hooks, array data is not properly displaying in the page, I could see the array has got 3 records, but while iterating it is displaying only two records and that too same image got displayed twice. Could someone please help me to identify the issue here ?
I can see a warning error logged in console:
import React, { useRef, useEffect, useState } from "react";
const [dailyStatusPlayers, setDailyStatusPlayers] = useState([]);
const isMounted = useRef(false);
useEffect(() => {
isMounted.current = true;
return () => isMounted.current = false;
}, []);
useEffect(() => {
const fetchData = async () => {
try {
const res = await axios.get('http://localhost:8000/service/availability');
if (isMounted.current) {
setDailyStatusPlayers(res.data.dailyStatus);
}
} catch (e) {
console.log(e);
}
}
fetchData();
}, []);
return (
<div className="availability_wrapper">
<h4>In: <span className="displayInCount">20</span></h4>
<div className="wrap">
<div className="container">
<div className="dailystatus_section">
<span className="playerdailyrecord">
<h4>Player Daily Status:</h4>
<div className="row">
{
dailyStatusPlayers.map(([{id, photo, position, dailystatus}]) =>(
<div key={id} className="playerdailyrecord_main">
<span className="dailstatus_playerphoto"><img className="dailstatus_playerImage" key={photo} src={photo}></img></span>
<span className="dailstatus" key={dailystatus}>{dailystatus}</span>
<span className="dailstatus_playerposition" key={position}>{position}</span>
</div>
))
}
</div>
<button className="OverlayDailyStatus" onClick={displayAvailabilityStatus}>Enter</button>
</span>
</div>
</div>
</div>
<DailyStatusDialog
onSubmit={onSubmit}
open={deleteDialog}
onClose={() => setDeleteDialog(false)}
/>
</div>
);
const Availability = () =>{
const [team1, setTeam1] = useState([]);
const [team2, setTeam2] = useState([]);
const [deleteDialog, setDeleteDialog] = useState(false);
const [playerId, setPlayerId] = useState("");
const [helperText, setHelperText] = useState('');
const loginUserEmail = localStorage.getItem('loginEmail');
const [dailyStatusPlayers, setDailyStatusPlayers] = useState([]);
const [teamData, setTeamData] = useState([]);
//const [dailyinput, setDailyInput] = useState('');
const [inCount, setInCount] = useState("");
const isMounted = useRef(false);
const c_day = moment().format('dddd');
const c_date = moment().format('DD-MM-YYYY');
useEffect(() => {
isMounted.current = true;
return () => isMounted.current = false;
}, []);
const displayAvailabilityStatus = () =>{
setDeleteDialog(true);
}
useEffect(() => {
const fetchData = async () => {
try {
const res = await axios.get('http://localhost:8000/service/availability');
if (isMounted.current) {
setDailyStatusPlayers(res.data.dailyStatus[0]);
//setTeamData(res.data.dailyStatus[0]);
console.log("Complete array:"+res.data.dailyStatus[0]);
}
} catch (e) {
console.log(e);
}
}
fetchData();
}, []);
let i = 0;
const tempTeam1 = [];
const tempTeam2 = [];
while(teamData.length > 0) {
const random = Math.floor(Math.random() * teamData.length);
i%2 === 0 ? tempTeam1.push(teamData[random]) : tempTeam2.push(teamData[random]);
teamData.splice(random, 1);
i++;
}
useEffect(() => {
setTeam1(tempTeam1);
setTeam2(tempTeam2);
},[]);
const onSubmit = (dailyinput) =>{
console.log("Here Daily:"+ dailyinput);
const dailyStatus = async () => {
try {
const params = {
email: loginUserEmail,
};
const res = await axios.post('http://localhost:8000/service/availability', { dailystatus: dailyinput }, {params} );
console.log("Dailystatus update" + res.data.success);
if (res.data.success) {
setDeleteDialog(false);
}
else {
console.log(res.data.message);
setHelperText(res.data.message);
}
} catch (e) {
setHelperText(e.response.data.message);
}
}
dailyStatus();
}
return (
<div className="availability_wrapper">
<div className="displayCurrentDate">
<b>{c_day}</b>, {c_date}
</div>
<h4>In: <span className="displayInCount">20</span></h4>
<div className="wrap">
<div className="container">
<div className="dailystatus_section">
<span className="playerdailyrecord">
<h4>Player Daily Status:</h4>
<div className="row">
{
dailyStatusPlayers.map(({id, photo, position, dailystatus}) =>(
<div key={id} className="playerdailyrecord_main">
<span className="dailstatus_playerphoto"><img className="dailstatus_playerImage" key={photo} src={photo}></img></span>
<span className="dailstatus" key={dailystatus}>{dailystatus}</span>
<span className="dailstatus_playerposition" key={position}>{position}</span>
</div>
))
}
</div>
<button className="OverlayDailyStatus" onClick={displayAvailabilityStatus}>Enter</button>
</span>
</div>
</div>
<div>
<div className="container">
<div className="playerdistribution_section">
<h4>Team Selection</h4>
<div className="wrap">
<div className="left_col">
{
team1.map(({id, name, image}) =>(
<div>
<span key={name}>{name}</span>
</div>
))
}
</div>
<div className="right_col">
{
team2.map(({id, name, image})=>(
<div>
<span key={name}>{name}</span>
</div>
))
}
</div>
</div>
</div>
</div>
<div className="container">
<div className="weeklycount_graph_section">
<span className="avail_newImageback">
<img className="avail_newsImagesection" src="images/greenplayer.png"></img>
</span>
</div>
</div>
</div>
</div>
<DailyStatusDialog
onSubmit={onSubmit}
open={deleteDialog}
onClose={() => setDeleteDialog(false)}
/>
</div>
);
}
export default Availability;
A:
The issue is that the array passed in from the server is being duplicated. Until the code on the server is fixed, you can simply pass in the first value of the array by calling setDailyStatusPlayers(res.data.dailyStatus[0]) inside of the second useEffect.
Should also change dailyStatusPlayers.map(([{id, photo, position, dailystatus}]) to remove the wrapping array. So it should become dailyStatusPlayers.map(({id, photo, position, dailystatus}).
Here is a Codesandbox with a working example.
|
[
"travel.stackexchange",
"0000050266.txt"
] | Q:
Can I withdraw CHF on a Mastercard pre loaded with euros?
I have a pre-loaded "travel wallet" Mastercard issued by a bank in South Africa. When I loaded it I specified an amount in euro and they issued me a different card for GBP. Can I use the euro card to withdraw Swiss francs in Switzerland, even if that attracts a higher fee? Assume that I cannot use my normal credit card (I did not expect a Switzerland stop so I did not tell the bank that I would be using the other cards there).
OUTCOME: At the main train station in Geneva I was able to draw Francs at an ATM which even had the option to debit my card in Euros.
A:
Yes, you can. Maestro Cards work with every ATM in Switzerland. The currency of the card doesn't matter. The fees depends on the issuing institute (bank). ATMs of the Swiss Post (the yellow ones) charge an extra fee.
|
[
"stackoverflow",
"0030536244.txt"
] | Q:
Select (dplyr) operator with '-'
How to use SELECT (dplyr library) operator with name containing '-'? For example:
AdultUCI %>% select(capital-gain)
caused:
A:
Try this
data.frame(`a-b` = 1, c = 2, check.names = FALSE) %>%
select(`a-b`)
# a-b
# 1 1
|
[
"ru.stackoverflow",
"0000879810.txt"
] | Q:
Авторизация пользователей NTML
Разрабатываю способ авторизации на сайте для небольшого проекта на Python и Flak и возник вопрос авторизации пользователей. Поскольку в сети имеется контролер домена, но решил использовать LDAP. После долго поиска в сети я так и не нашел ни какого способа сверить пароль введенный пользователем с тек, который сохранен в учетной записи AD. После прочтения нескольких статей я понял что этот протокол применяется для доступа к службе каталогов предприятия, а для авторизации пользователей нужно использовать NTLM или Kerberos, но что то у меня так и не получилось найти ни одной подходящей статьи. Возможно кто-то сталкивался с подобной проблемой?
A:
Аутентификацию с AD можно реализовать разными путями.
1. Аутентификация по логину-паролю
Если предполагается заставлять вводить логин-пароль пользователя в формочке на сайте, то тут достаточно стандартных LDAP функций от стандартного LDAP-модуля.
#!/usr/bin/python
import ldap
ldap_server = '192.169.0.100'
user = "vasya" + "@YOUR-DOMAIN.LOC"
password = "Sup3rVasy@"
connect = ldap.open(ldap_server)
try:
connect.bind_s(user, password)
print('Success')
except ldap.LDAPError:
print('Invalid credentials')
Где "@YOUR-DOMAIN.LOC" - это имя (realm) вашего AD.
2. NTLM/Kerberos
Этот тип аутентификации обычно (но не обязательно) используют для "прозрачного" входа на сайт. Предполагается, что ПК юзера заджойнен в домен. Юзер с этого ПК открывает некий интранет-сайт. И попадает на/в него уже авторизованным на основе своих доменных реквизитов. Т.е. логин-пароль вводить не надо.
Данный тип аутентификации осуществляет веб-сервер после предварительных настроек.
Примеры конфигураций:
Apache + NTLM
Apache + Kerberos
Apache + Kerberos + PHP
В этом типе аутентификации веб-сервер определяет "валидность" юзера, инициализируя переменную REMOTE_USER, которую в последствии можно обработать в движке сайта.
|
[
"stackoverflow",
"0003633060.txt"
] | Q:
Hibernate one to many mapping
I have two tables:
<class name="Content" table="language_content" lazy="false">
<composite-id>
<key-property name="contentID" column="contentID"/>
<key-property name="languageID" column="languageID"/>
</composite-id>
<property name="Content" column="Content" />
</class>
and
<class name="SecretQuestion" table="secretquestions" lazy="true">
<id name="questionID" type="integer" column="QuestionID">
<generator class="increment"></generator>
</id>
<property name="question" column="Question"/>
<property name="isUsing" column="IsUsing"/>
<bag name="contents" inverse="true" cascade="all,delete-orphan">
<key column="question" />
<one-to-many class="Content" />
</bag>
</class>
I'm trying to map the "question" property of SecretQuestion to the "contentID" property of Content but Eclipse throwing out an exception:
org.hibernate.exception.SQLGrammarException: could not initialize a collection: [com.sms.model.entity.SecretQuestion.contents#1]
If I replace the <key column="question" /> with <key column="contentID" />, it can run but mapping the wrong data (actually, as far as I see, it maps the questionID with the contentID of Content)
Anyone know how to do what I'm trying to achieve here?
Thanks.
UPDATE
Okey, after modifying as Pascal said, here is the new error:
javax.servlet.ServletException: org.hibernate.MappingException: Foreign key (FKB65C9692FCD05581:language_content [contentID,languageID])) must have same number of columns as the referenced primary key (secretquestions [QuestionID])
This error means I have to have a composite primary key for secretquestions table which I don't want :(
UPDATE
I will give an example to clearer what I trying to do:
Table SecretQuestion
questionID* question answer
1 4 a
2 5 a
3 6 a
Table Content
contentID* languageID* content
1 1 a
1 2 b
2 1 c
2 2 d
3 1 e
3 2 f
4 1 g
4 2 h
5 1 i
5 2 j
6 1 k
6 2 l
Now I want to map question 4, 5, 6 to content ID 4, 5, 6.
A:
Looks like this approach cannot work and is not supported by Hibernate (the Content table have composite primary key while I want to mapping it to only one field in the Question table), thus I use a workaround that I only map the question to the contentID and I use a ContentGetter class that will get the content depend on the languageID.
|
[
"es.stackoverflow",
"0000259715.txt"
] | Q:
¿Cómo insertar datos al segundo intento?
Cómo puedo insertar los datos al segundo intento de dar clic en iniciar sesión de igual forma insertar los datos pero solo redireccionar al segundo intento.
$msg = "";
if (isset($_POST['new_account'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($_POST['username'])) {
$msg = "Por favor, ingresé su usuario";
}
$stmt = $con->prepare("INSERT INTO data_users (email, password) VALUES (?, ?)");
$stmt->bind_param("ss", $username,$password);
if($stmt->execute()){
header('location: index.php');
exit;
}
}
Formulario
<form method="post" autocomplete="off" action="#">
<input name="username" type="email" value="" placeholder="[email protected]" autocomplete="off"/>
<input name="password" type="password" placeholder="Contraseña" autocomplete="off"/>
<input type="submit" value="Iniciar sesión" name="new_account">
</form>
A:
Esta sería una forma de controlar los clicks del botón.
He cambiando el elemento, en vez de input a button, porque así podemos usar el value para actualizar la cantidad de clicks que se hacen en él.
En el código Javascript se escuchan los clicks del botón, se aumente el valor en 1 cada vez y cuando sean dos se imprime un mensaje. En ese bloque lanzarías tu petición Ajax, que llamaría al archivo PHP que procesa los datos.
OJO: Ajax es algo mucho mejor y más avanzado. Si quieres, podrías evitar incluso la redirección, actualizando la misma página del formulario. Pero, dado que es un proyecto, no sé cuáles son las limitaciones, ni qué se puede hacer o no hacer.
Otro vacío que no queda claro en tu pregunta es: ¿qué pasa al tercer click, al cuarto, al quinto? Ese tipo de situaciones hay que cubrirlos. Se podría por ejemplo desactivar el botón desde el bloque del segundo click o algo así. Todo depende de la lógica de tu programa. Lo señalo aquí para que lo tengas en cuenta...
Espero te sirva. Si necesitas ayuda con Ajax (para mandar a ejecutar el código de PHP) lo dices y te pongo un ejemplo.
$(function() {
$("#btnSession").click(function(e) {
e.preventDefault();
this.value++;
console.log(`Haz hecho click ${this.value} veces`);
if (this.value == 2) {
console.log('Aquí llamamos al servidor');
} else {
console.log('Aquí hacemos otra cosa');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" autocomplete="off" action="#">
<input name="username" type="email" value="" placeholder="[email protected]" autocomplete="off" />
<input name="password" type="password" placeholder="Contraseña" autocomplete="off" />
<button id="btnSession" type="submit" value="0" name="new_account">Iniciar sesión</button>
</form>
|
[
"stackoverflow",
"0041844475.txt"
] | Q:
How to use Ionic2 Events
I'm getting inconsistent results from the login event created in my Login service. When the user logs in or logs out the event is not getting picked up on the subscription pages changing the links on the page accordingly.
UPDATE
After more testing I've found that each page does pick up on the subscription but only after it has been entered first. In other words if I go to pageWithLink.ts before logging in then the page will correctly read the subscription update but if I login before going to the page it will ignore the subscription update.
tabs.ts
import { Component } from '@angular/core';
import { NavParams } from 'ionic-angular';
import { page1 } from '../page1';
import { page2 } from '../page2';
import { page3 } from '../page3';
@Component({
templateUrl: 'tabs.html'
})
export class Tabs {
index:any;
tab1Root: any = page1;
tab2Root: any = page2;
tab3Root: any = page3;
constructor(public navParams: NavParams) {
if(navParams.get('index') === undefined || navParams.get('index') === null){
this.index = "0";
} else {
this.index = navParams.get('index');
}
}
}
app.module.ts
import { NgModule, ErrorHandler } from '@angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { Tabs } from '../tabs';
import { page1 } from '../page1';
import { page2 } from '../page2';
import { page3 } from '../page3';
import { LoginService } from '../services/loginService';
@NgModule({
declarations: [
page1,
page2,
page3,
Tabs
],
imports: [
IonicModule.forRoot(MyApp, {
swipeBackEnabled: true
})
],
bootstrap: [IonicApp],
entryComponents: [
page1,
page2,
page3,
Tabs
],
providers: [LoginService]
})
export class AppModule {}
loginService.ts
import { Injectable } from '@angular/core';
import { Events } from 'ionic-angular';
import { AlertController, NavController, ViewController, Events, App } from 'ionic-angular';
import { Tabs } from '../tabs';
import { page1 } from '../page1';
@Injectable()
export class LoginService {
userStatus: boolean;
constructor(public events:Events, public alertController:AlertController, public navController: NavController, public viewController:ViewController, public app:App){}
sendUserStatus(statusOfUser) {
this.events.publish('login:Status', statusOfUser);
}
login(){
//login successful
this.sendUserStatus(true)
}
logout(){
//logout successful
this.sendUserStatus(false)
}
}
pageWithLink.ts
import { Component } from '@angular/core';
import { Events } from 'ionic-angular';
@Component({
selector: 'pageWithLink',
templateUrl: 'pageWithLink.html',
providers: [LoginService]
})
export class pageWithLink {
person: any;
constructor(public events:Events){
this.events.subscribe('login:Status', login => {
this.person = login;
})
}
}
pageWithLink.html
<ion-header class="opaque">
<ion-buttons end>
<button ion-button icon-only *ngIf="person" (click)="signout()">
<ion-icon name="log-out"></ion-icon>
</button>
<button ion-button icon-only *ngIf="!person" (click)="openModal()">
<ion-icon name="log-in"></ion-icon>
</button>
</ion-buttons>
</ion-header>
A:
Set
providers: [LoginService]
in app.module.ts within ngModule.
Currently you have set LoginService as provider for each page. So a new service is created for every component. For your events to work LoginService needs to be singleton.
@NgModule({
//declarations,imports etc.
providers:[LoginService]
})
and remove provider from all other pages.This way only one event is published for the single service and will be picked by every page.
The
No provider for navcontroller
is because you are injecting Navcontroller into a service.
Check this answer for explanation
A:
@suraj had most of it which led to several other fixes adjustments including:
1) making much of what goes into my constructors private as appropriate
2) what got the fix for me was adding a login in check to each of pages to provide a beginning state in case a user logged in already.
New loginService.ts
import { Injectable } from '@angular/core';
import { Events } from 'ionic-angular';
import { AlertController, Events, App } from 'ionic-angular';//don't use NavController or ViewController in Injectables!
import { Tabs } from '../tabs';
import { page1 } from '../page1';
@Injectable()
export class LoginService {
userStatus: boolean;
constructor(private events:Events, private alertController:AlertController, private app:App){}
sendUserStatus(statusOfUser) {
this.events.publish('login:Status', statusOfUser);
}
login(){
//login successful
this.sendUserStatus(true)
}
logout(){
//logout successful
this.sendUserStatus(false)
}
}
new pageWithLink.ts
import { Component } from '@angular/core';
import { Events } from 'ionic-angular';
@Component({
selector: 'pageWithLink',
templateUrl: 'pageWithLink.html'//no provider for LoginService, that's all in app.module.ts!
})
export class pageWithLink {
person: any;
constructor(private events:Events){
if(UserExists){//this is a condition stating the current login status
this.person = true;
}
this.events.subscribe('login:Status', login => {
this.person = login;
})
}
}
|
[
"biology.stackexchange",
"0000045202.txt"
] | Q:
Does the creation of memory involve mRNAs crossing the synaptic gap?
There is a diagram from a book titled "Teaching with the brain in mind". The diagram shows
The diagram appears to show that the "creation of memory" involves "messages coded by RNA" moving through an axon and being released into the synaptic gap, whereupon they presumably bind to the receptors on the other side of the synapse.
Unfortunately the book does not seem to provide any sources for this and I have not been able to find any sources corroborating this claim. Can anyone provide any references?
A:
I have never heard of this pathway. Memory is usually assoiciated with synaptic plasticity by ‘Long-term potentiation’ (LTP), which has glutamate as a neurotransmitter. Neuroscience Exploring the brain (Bear, et al,. 2007), has a pretty good explanation of this process, if you're interrested. Motor patterns have more mechanisms than LTP, and are not as well understood.
|
[
"ru.stackoverflow",
"0001113552.txt"
] | Q:
Интерактивная форма на ajax не работает
<div class="col-md-6 col-xl-4">
<div class="input-field">
<form id="callphone">
<!-- Hidden Required Fields -->
<input type="hidden" name="project_name" value="a">
<input type="hidden" name="admin_email" value="b">
<input type="hidden" name="form_subject" value="c">
<!-- END Hidden Required Fields -->
<input id="phone-email" name="phoneemail" class="form-control" type="text"size="40" required>
<label for="phone-email" class="animated-label">введите ваш email или номер телефона</label>
</form>
</div>
</div>
<div class="col-md-6 col-xl-4">
<div class="buttons">
<div id="sub" class="callback">
<p>заказать<br> обратный звонок</p>
</div>
<div class="send-email">
<p>отправить<br> e-mail </p>
</div>
</div>
</div>
//form email+call
$('#sub').click(function () {
$('#callphone').submit(function () {
let th = $(this);
$.ajax({
type: "POST",
url: "./mail.php",
data: th.serialize()
}).done(function() {
alert("www");
setTimeout(function() {
// Done Functions
th.trigger("reset");
}, 1000);
});
return false;
})
});
A:
Нажимая на #sub, вы всего лишь регистрируете обработчик формы #callphone по событию submit. Регистрация обработки этого события должна происходить до клика, а на клике вызываться метод submit()
как-то так, к примеру:
$(function() {
$('#callphone').submit(function () {
let th = $(this);
$.ajax({
type: "POST",
url: "./mail.php",
data: th.serialize()
}).done(function() {
alert("www");
setTimeout(function() {
// Done Functions
th.trigger("reset");
}, 1000);
});
return false;
})
})
$('#sub').click(function () {
$('#callphone').submit()
return false;
});
|
[
"stackoverflow",
"0042321378.txt"
] | Q:
str_replace doesn't work as expected - multi byte character set?
I have a problem with spaces within array $a2. I would like to replace " " with "".
I tried
$a2 = str_replace(" ", "", $a2);
and even :
function str_replace_json($search, $replace, $subject) {
return json_decode(str_replace($search, $replace, json_encode($subject)), true);
}
$a2 = str_replace_json(" ", "", $a2);
But it trims spaces only before and after number (not inside).
My array:
$a2 = array( $rowData[3][1],
$rowData[3][2],
$rowData[3][3],
$rowData[3][4],
$rowData[3][5],
$rowData[3][6],
$rowData[3][7]
);
var_dump of my array:
array(7) { [0]=> string(54) " 155 808.00 "
[1]=> string(54) " 131 256.00 "
[2]=> string(54) " 106 008.00 "
[3]=> string(53) " 60 600.00 "
[4]=> string(53) " 41 520.00 "
[5]=> string(52) " 5 880.00 "
[6]=> string(52) " 6 744.00 "
}
What might be a reason for that?
EDIT
When I declere my array this way:
$a2 = array(
" 155 808.00 ",
" 131 256.00 ",
" 106 008.00 ",
" 60 600.00 ",
" 41 520.00 ",
" 5 880.00 ",
" 6 744.00 "
);
I can easily trim all the spaces (including those inside numbers).
This is how i create $rowData
include_once ("includes/php/simple_html_dom.php");
$html = file_get_html('https://gaz.tge.pl/pl/rdn/gas/index/index/');
$table = $html->find("table[@class=t-02]",0);
$rowData = array();
foreach($table->find('tr') as $row) {
$data = array();
foreach($row->find('td') as $cell) {
$data[] = $cell->plaintext;
}
$rowData[] = $data;
}
array_unshift($rowData[0], "RDNpg");
var_dump of $rowData:
array(7) { [0]=> array(8) { [0]=> string(5) "RDNpg" [1]=> string(68) " Pn. 13/02 " [2]=> string(68) " Wt. 14/02 " [3]=> string(69) " Śr. 15/02 " [4]=> string(68) " Cz. 16/02 " [5]=> string(68) " Pt. 17/02 " [6]=> string(68) " So. 18/02 " [7]=> string(67) " N. 19/02 " } [1]=> array(1) { [0]=> string(40) " TGEgasDA " } [2]=> array(8) { [0]=> string(8) "PLN/MWh " [1]=> string(44) " 92.56 " [2]=> string(44) " 91.36 " [3]=> string(44) " 89.51 " [4]=> string(44) " 87.62 " [5]=> string(44) " 88.01 " [6]=> string(44) " 84.63 " [7]=> string(44) " 84.90 " } [3]=> array(8) { [0]=> string(4) "MWh " [1]=> string(54) " 155 808.00 " [2]=> string(54) " 131 256.00 " [3]=> string(54) " 106 008.00 " [4]=> string(53) " 60 600.00 " [5]=> string(53) " 41 520.00 " [6]=> string(52) " 5 880.00 " [7]=> string(52) " 6 744.00 " } [4]=> array(1) { [0]=> string(40) " TGEsgtDA " } [5]=> array(8) { [0]=> string(8) "PLN/MWh " [1]=> string(40) " - " [2]=> string(40) " - " [3]=> string(40) " - " [4]=> string(40) " - " [5]=> string(40) " - " [6]=> string(40) " - " [7]=> string(40) " - " } [6]=> array(8) { [0]=> string(4) "MWh " [1]=> string(40) " - " [2]=> string(40) " - " [3]=> string(40) " - " [4]=> string(40) " - " [5]=> string(40) " - " [6]=> string(40) " - " [7]=> string(40) " - " } } array(7) { [0]=> string(54) " 155 808.00 " [1]=> string(54) " 131 256.00 " [2]=> string(54) " 106 008.00 " [3]=> string(53) " 60 600.00 " [4]=> string(53) " 41 520.00 " [5]=> string(52) " 5 880.00 " [6]=> string(52) " 6 744.00 " }
And json_encode($rowData);
[["RDNpg"," \t Pn. \t 13\/02 \t "," \t Wt. \t 14\/02 \t "," \t \u015ar. \t 15\/02 \t "," \t Cz. \t 16\/02 \t "," \t Pt. \t 17\/02 \t "," \t So. \t 18\/02 \t "," \t N. \t 19\/02 \t "],[" \t TGEgasDA \t "],["PLN\/MWh "," \t 92.56 \t "," \t 91.36 \t "," \t 89.51 \t "," \t 87.62 \t "," \t 88.01 \t "," \t 84.63 \t "," \t 84.90 \t "],["MWh "," \t 155 808.00 \t "," \t 131 256.00 \t "," \t 106 008.00 \t "," \t 60 600.00 \t "," \t 41 520.00 \t "," \t 5 880.00 \t "," \t 6 744.00 \t "],[" \t TGEsgtDA \t "],["PLN\/MWh "," \t - \t "," \t - \t "," \t - \t "," \t - \t "," \t - \t "," \t - \t "," \t - \t "],["MWh "," \t - \t "," \t - \t "," \t - \t "," \t - \t "," \t - \t "," \t - \t "," \t - \t "]]
EDIT 2 I used bin2hex() to see what is realy inside $a2 array. I got:
20200920202020202020202020202020202020313535266e6273703b3830382e30302020200920202020202020202020202020202020
20200920202020202020202020202020202020313331266e6273703b3235362e30302020200920202020202020202020202020202020
20200920202020202020202020202020202020313036266e6273703b3030382e30302020200920202020202020202020202020202020
202009202020202020202020202020202020203630266e6273703b3630302e30302020200920202020202020202020202020202020
202009202020202020202020202020202020203431266e6273703b3532302e30302020200920202020202020202020202020202020
2020092020202020202020202020202020202035266e6273703b3838302e30302020200920202020202020202020202020202020
2020092020202020202020202020202020202036266e6273703b3734342e30302020200920202020202020202020202020202020
Am I right that mysterious space is no-break space and that is why trim function with normal space doesn't work?
A:
Use array_map. The code will look like this:
$originalArray = json_decode($jsonText, true);
$data = array_map(function($value){
return str_replace(" ", '', $value);
}, $originalArray);
var_dump($data);
Later Edit:
Looks like the requirements of the problem got changed and the same the input data.
This changes everything as well.
You can see here http://php.net/array_map how it works, it's simpler and cleaner.
So, having the array with this data (let's take only the first key-value)
// this is the actual data from the array
$a = "20200920202020202020202020202020202020313535266e6273703b3830382e30302020200920202020202020202020202020202020";
// make it readable
$b = hex2bin($a);
// see what is inside
var_dump($b);
var_dump will return something like:
string(54) " 155 808.00 "
So, you have which is 6 characters written and displayed only one.
What solution I see in this case would be to use trim function to remove the spaces from the beginning and the end of the string, and then to use preg_replace to remove all non digit characters and dots.
$b = trim($b);
$b = preg_replace("/([^0-9\.]+)/", '', $b);
The result will be then:
string(9) "155808.00"
So, the end result will look like this:
$data = array_map(function($value){
$value = trim($value);
return preg_replace("/([^0-9\.]+)/", '', $value);
}, $originalArray);
|
[
"stackoverflow",
"0055795498.txt"
] | Q:
How to fix that at filtering an multidimensional array, the array gets more elements?
I have an multidimensional array called "Places" like this:
0: Array [ 1, 1 ]
1: Array [ 1, 2 ]
2: Array [ 1, 3 ]
3: Array [ 1, 4 ]
4: Array [ 1, 5 ]
5: Array [ 2, 1 ]
6: Array [ 2, 2 ]
7: Array [ 2, 3 ]
8: Array [ 2, 4 ]
9: Array [ 2, 5 ]
10: Array [ 3, 1 ]
11: Array [ 3, 2 ]
12: Array [ 3, 3 ]
13: Array [ 3, 4 ]
and so on until [ 5, 5 ]
I have also another array (called "occupied"):
0: Array [ 1, 5 ]
And I have a for-in loop that creates an new array ("unOccupied") with all the things in "Places" except the things that are also in "occupied".
This is the code:
for(var arr in Places){
for(var filtered in occupied){
if(Places[arr][0] !== occupied[filtered][0] || Places[arr][1] !== occupied[filtered][1]){
unOccupied.push(Places[arr]);
}
}
}
What I expected, is that unOccupied becames something like this:
0: Array [ 1, 1 ]
1: Array [ 1, 2 ]
2: Array [ 1, 3 ]
3: Array [ 1, 4 ]
4: Array [ 2, 1 ]
5: Array [ 2, 2 ]
and so on until [ 5, 5 ]
So, this is a copy of "Places", but without the elements of "occupied".
If "occupied" contains 1 element, everything works well, and "unOccupied" contains 24 elements. But if "occupied" contains for example 2 elements, "unOccupied" does have 48 elements, and everything that "Places" haves, is double, except the elements that are also in "occupied".
If "occupied" contains more elements, "unOccupied" contains also much more elements. But why? And how to fix it?
Thanks in advance!
A:
Your loop is incomplete:
What is happening?
for(var arr in Places){
for(var filtered in occupied){
if(Places[arr][0] !== occupied[filtered][0] || Places[arr][1] !== occupied[filtered][1]){
unOccupied.push(Places[arr]);
}
}
}
It works well with only one element in occupied due to it only iterates one time over the current place arr. when you have more items in occupied you iterate n-times over the same place arr inserting it n-times if the condition is valid.
So you need to define when a place must be added to unoccupied this is when a place is not in occupied.
for(var arr in Places){
let isOccupied = false;
for(var filtered in occupied){
if(Places[arr][0] === occupied[filtered][0] || Places[arr][1] === occupied[filtered][1]){
isOccupied = true;
break;
}
}
!isOccupied && unOccupied.push(Places[arr]);
}
Also you can improve this by:
const unoccupied = Places.filter(place => occupied.every(occ => occ[0] !== place[0] || occ[1] !== place[1]))
|
[
"stackoverflow",
"0035460784.txt"
] | Q:
"ionic run ios" How to add provisioning profiles
I wish to use Ionic to run my app on my iOs device with livereload enabled. According to the docs this should be easy:
ionic run ios --device -l
Of course I have to add provisioning profiles, but how am I supposed to do it?
I have the .mobileprovision and the .p12 of the certificate, but no matter what I do I still get this error when running the command:
No matching provisioning profiles found: No provisioning profiles with a valid signing identity (i.e. certificate and private key pair) matching the bundle identifier “<MyBundleID>” were found
How am I supposed to add my provisioning profiles? I'm not able to find any info about this in the framework docs.
Note: I can reploy the project using Xcode, but then I don't get the livereload. Plus I'd prefer doing everything from the CLI.
A:
You need to go into XCode and add those provisioning profiles to your device.
Set those provisioning profiles into the build process and add the profile to the device as well.
Though you may not be using Visual Studio, their explanation on the setup works for all methods of building Ionic apps.
The documentation is here, but to tell you what's going on:
Make sure you have a developer account to make provisioning profiles.
You would sign into Itunes Connect to add your device as a testing device
Create an App ID
Create a provisioning profile associated to that App ID
Download the provisioning file into Xcode
Add the provisioning file to your device via Xcode
Run ionic run ios --device -l
That should do the trick.
Follow the setup guide by Microsoft starting at create your provisioning profile.
|
[
"physics.stackexchange",
"0000065274.txt"
] | Q:
Is there a one-to-one relationship between colour theories and our trichromatic vision?
This has started to bug me more and more… it involves:
colour theory
the trichromatic properties of our eyes through cone cells
and light.
Is there a one-to-one relationship between colour theories and our trichromatic vision? Are colour theories — the subtractive and additive properties of colour — strictly a by-product of our trichromatic vision?!
Could our colour theories also hold some truth in, say tetrachromatic vision (if both vision had an identical electromagnetic radiation range)?
Imagining we had perfect RGB screen technology, capable of reproducing all the colours within our visible spectrum range (400nm—700nm). Could you, if you had tetrachromatic vision, use the same RGB screen and still see all the colours in your "visible spectrum" of the same range?
Could you use this perfect RGB screen technology if, while trichromatic, your cone cells were "tuned" to different frequencies (but still covered the identical "visible light" range)?!
Math can be applied regardless of the base you're using (binary, octal, decimal, hexadecimal, etc.). I would like to think colour has a similar beauty to it.
A:
Colour theory has a lot to do with how the brain processes the signals from the retina, as well as the physics of how light is detected in the eyes. But broadly speaking, the additive and subtractive properties of colour result from the physics of light and its interaction with pigments, so if we were tetrachromatic we would experience them similarly. The main difference is that a tetrochromat would experience four primary colours rather than three. This would change some aspects of colour theory (I guess you'd have something more like a "colour sphere" than the colour wheel, for example) but the basics would be the same.
Imagining we had perfect RGB screen technology, capable of reproducing all the colours within our visible spectrum range (400nm—700nm). Could you, if you had tetrachromatic vision, use the same RGB screen and still see all the colours in your "visible spectrum" of the same range?
Such a screen is actually kind of impossible. There are colours that we trichromats can see that cannot be reproduced by an RGB screen. The range of colours a three-colour screen can produce are only a subset of the colours we can see. This is due to the way our cone cells respond to more than one light frequency at once. It's a fundamental thing, it's not just due to deficiencies in the screen. But the subset of colours that an RGB screen can produce is a pretty big one, so we generally don't notice.
But aside from that point, no, a tetrochromat could not use a three-colour screen and still see most of the colours in its visible range. There would simply be a primary colour missing. It would be like trying to reproduce all the colours a trichromat can see using only two light frequencies. If you use red and cyan for example, then you can get red, white, cyan and black, but you can't get blue or green.
Could you use this perfect RGB screen technology if, while trichromatic, your cone cells were "tuned" to different frequencies (but still covered the identical "visible light" range)?!
No, you couldn't, for similar reasons. Most likely, it would still cover a large proportion of the colours you can perceive, but there would certainly be some colours you can see that it wouldn't be able to produce.
|
[
"gis.stackexchange",
"0000118172.txt"
] | Q:
How do I display my roads in Tilemill?
First, I'm new to TileMill, Ubuntu, and OpenStreetMap so I may be overlooking something basic.
I have a Postgres/PostGIS database with my OSM data. I created a new project in TileMill and added a layer for my OSM data in Postgres.
The query selects everything in planet_osm_line. When I click the Features icon in the Layers box, a grid is displayed with my linear features (roads, bike paths, transmission lines, etc.) To me, this indicates data is being returned from the database to TileMill. The next step is displaying it.
I'm trying to use the roads.mss style from https://github.com/gravitystorm/openstreetmap-carto but nothing is displayed.
When I simplify my styles to the following, the screen color changes but still no linework.
@water-color: #b5d0d0;
@land-color: #f2efe9;
Map {
background-color: @water-color;
}
What am I missing?
A:
Check out the CartoCSS documentation.
You're missing layer definitions for any layer except Map. The syntax is:
#layerName {
propertyName: propertyValue;
}
So try something like:
#roads{
line-color: #ccc;
line-width: 1;
line-join: round;
}
for each of your layers, being sure to match #layerName to the actual name of the layers in the layer panel (bottom left-most button).
|
[
"webmasters.stackexchange",
"0000064858.txt"
] | Q:
Does paid traffic improve SEO?
In Fiverr there is a complete subcategory to "Get Traffic". Some of the descriptions in the category claim that "these traffic will boost your ranking or your biz". Is it true? How new traffic could improve a website rankings?
A:
I have never seen any evidence that Google uses traffic to a website as a ranking signal. There is certainly a bunch of speculation about it in this thread on WebmasterWorld.
If they did, they would have to very careful about it. Google is the main traffic source for most websites. Using website traffic as a signal would have to exclude traffic that Google itself sends, otherwise it would be a self-reinforcing feedback loop where Google sends more traffic and sees the website has more traffic, so it sends even more.
There is also the issue of where Google would get the data about which websites have traffic. Google has several possible sources for this data:
Google Toolbar
Google Chrome Browser
Google Analytics
Google's malware blacklist
Google's DNS servers
However, they might be missing out on certain demographics such as Internet Explorer users.
You could certainly make the case that Google should be ranking sites better because the are getting users. Having users seems like it could be a sign of quality. A couple years ago I remember reading about an online retailer with a huge ad budget that was trying to make the case that their large ad budget should be considered a sign of quality that Google considers in its rankings.
|
[
"apple.stackexchange",
"0000167332.txt"
] | Q:
Process named after website executing?
While looking at Activity Monitor processes, I noticed a process whose name started with "http://".
Shortly after observing and screenshoting the process disappeared. This morning, it briefly re-appeared and then died.
lsof and dtracte indicate the process is looking at standard system libraries, one of which is /private/var/db/mds/messages/se_SecurityMessages.
Any ideas on:
Whether this is a normal process?
How to find where and how it's launched? (Mac doesnt have /proc...?)
How to investigate what its doing?
A:
This is Normal in the way Safari now operates.
Each process is part of Safari sandboxing.
If you go to the View menu in Activity Monitor and down to the 'All Processes Hierarchically'
You will see that they all gathered and are owned by Safari.
Also this is a known feature: apple.com/safari
Sandboxing for websites.
Sandboxing provides built-in protection against malicious code and
malware by restricting what websites can do. And because Safari runs
web pages in separate processes, any harmful code you come across in
one page is confined to a single browser tab, so it can’t crash the
whole browser or access your data.
|
[
"stackoverflow",
"0022999120.txt"
] | Q:
Uncaught SyntaxError: Unexpected string in my JavaScript
I'm getting the Uncaught SyntaxError: Unexpected string error in my JavaScript and I honestly can't figure out what's wrong with the code. I have looked at the similar questions, but I'm unable to find a solution. The error is coming in the line highlighted with an asterisk below.
$("#items1").change(function () {
if ($(this).data('options') === undefined) {
$(this).data('options', $('#items2 option').clone());
}
var checkval = $(this).val();
/* this line: */ var options = $(this).data('options').filter('[value='"+ checkval +"']');
$('#items2').html(options);
});
The code is taken from Use jQuery to change a second select list based on the first select list option
I've added the extra quotes around the checkval to get rid of another error, this might be the problem, but if I change it, the other error returns.
A:
The problem is this:
'[value=' "+ checkval +"']'
^ ^ ^ ^^
1 2 3 45
At 1, you're starting a string; at 2, you're ending it. That means when we reach 3, the start of a new string using double quotes, it's an unexpected string.
You probably want:
'[value="' + checkval + '"]'
^ ^^ ^^ ^
1 23 45 6
At 1, we start the string. 2 is just a " within the string, it doesn't end it. 3 ends it, then we append checkval, then we start a new string (4) with a " in it (5) followed by a ] and then the end of the string (6).
A:
It should be:
var options = $(this).data('options').filter('[value="' + checkval + '"]');
The double quotes need to be inside the single quotes.
A:
'[value=' "+ checkval +"']'
should be
'[value="' + checkval + '"]'
You have the quotations in the wrong place, so the double-quotation mark is not being included in your string.
|
[
"stackoverflow",
"0057366191.txt"
] | Q:
laravel pagination returns different page
I am working on a laravel project, where I get data from an API then I want to display it on pages. I want the return to be spread out across 4 pages, each page with 10 results each. What I have so far, seems like it should work, but I am missing one piece, so any advice and help would be appreciated. So this is how it is suppose to work with code:
1) The users types in a book title in a search box.
<form method=POST action='/search'>
@csrf
<input type="text" name="search_term"/>
<input type="submit" value="Search"/>
</form>
2) there input is then sent to my controller, which queries the google books api.
class search extends Controller {
public function search(){
$current_page = LengthAwarePaginator::resolveCurrentPage();
echo $current_page;
$term = request('search_term');
$term = str_replace(' ', '_', $term);
$client = new \Google_Client();
$service = new \Google_Service_Books($client);
$params = array('maxResults'=>40);
$results = $service->volumes->listVolumes($term,$params);
$book_collection = collect($results);
$current_book_page = $book_collection->slice(($current_page-1)*10,10)->all();
$books_to_show = new LengthAwarePaginator($current_book_page,count($book_collection),10,$current_page);
return view('library.search')->with(compact('books_to_show'));
}
}
3) the results are then displayed on my blade
@extends('home')
@section('content')
@foreach($books_to_show as $entries)
<div class="row">
<div class="col-sm-auto">
<img class="w-50 img-thumbnail" src={{$entries['volumeInfo']['imageLinks']['smallThumbnail']}}/>
</div>
<div class="col-sm">
{{$entries['volumeInfo']['title']}}<br/>
@if($entries['volumeInfo']['authors']!=null)
by:
@foreach($entries['volumeInfo']['authors'] as $authors)
{{$authors}}
@endforeach
@endif
</div>
</div>
@endforeach
{{$books_to_show->links()}}
@endsection
This all works fine and as expected. I get 10 results on the view, and then I have a bar at the bottom which give shows me 4 different pages to choose from.
When I first type in a search term such as "William Shakespeare" My page url is:
localhost:8000/search
But, when I click on any of the pages my url becomes:
http://localhost:8000/?page=2
I understand that the ?page=* is how the pagination determines which page you are viewing, and that should be sent back to the controller. But, I am missing something on sending it back to the controller I think.
Still kind of fresh to this, so any advice is more then greatly appreciated.
A:
LengthAwarePaginator accepts a 5th parameter in its constructor: an array of options.
the path option
$books_to_show = new LengthAwarePaginator($current_book_page, count($book_collection), 10, $current_page, [
// This will fix the path of the pagination links
'path' => LengthAwarePaginator::resolveCurrentPath()
]);
By the way, on a totally different matter, Laravel makes your life easier by slicing the collection for you, check it out:
$current_book_page = $book_collection->forPage($current_page, 10);
Hope it helps :)
|
[
"gaming.stackexchange",
"0000237026.txt"
] | Q:
StarCraft Brood War online?
Is it still possible to play Star Craft Brood War online on Battle.net?
What do I need aside from the original game?
Do I need to pay a subscription fee on Battle.net?
A:
You do not need to pay a fee.
Battle.Net is currently still free. You need to sign up for an account, apply all the patches (it is done automatically when you try to access battle.net), and that's it.
|
[
"stackoverflow",
"0053808417.txt"
] | Q:
Win 10 CMD. Using IF GEQ to compare, getting bad results
I've been writing a CMD BATCH file to draw some stuff on the screen with ascii chars. I wrote a pretty simple setup to make circles on the screen using a variant of the distance formula. BUT the results aren't quite right.
While it draws circles (mostly), the top and left side have some weirdness going on. To attempt to debug this, I spit out the actual results of the set /A into a .csv and it looks like the math is being done right, and it's getting the correct result. BUT when it uses an if !variable! geq number, it's not reliably evaluating correctly (just MOST of the time).
Here is a stripped down version of the code that is still having the issue:
SETLOCAL ENABLEDELAYEDEXPANSION
@ECHO OFF
CLS
MODE CON: COLS=100 LINES=102
COLOR 0A
IF EXIST OUTPUT.MAP DEL OUTPUT.MAP
IF EXIST MATHCHECK.CSV DEL MATHCHECK.CSV
SET STATUSLINE=-
FOR /L %%Y IN (2,1,79) DO (
FOR /L %%X IN (2,1,79) DO (
SET DRAWCHAR%%X%%Y=.
)
CLS
ECHO !STATUSLINE!
SET STATUSLINE=!STATUSLINE!-
)
SET STATUSLINE=-
FOR /L %%Y IN (2,1,79) DO (
FOR /L %%X IN (2,1,79) DO (
SET /A "SQDISTANCE=((405-%%X*10)*(405-%%X*10))+((405-%%Y*10)*(405-%%Y*10))"
IF !SQDISTANCE! GEQ 129600 SET DRAWCHAR%%X%%Y=^^
ECHO 129600,^^^^,%%X,%%Y,!SQDISTANCE!,!DRAWCHAR%%X%%Y!>>MATHCHECK.CSV
)
CLS
ECHO !STATUSLINE!
SET STATUSLINE=!STATUSLINE!-
)
SET STATUSLINE=-
FOR /L %%Y IN (2,1,79) DO (
FOR /L %%X IN (2,1,79) DO (
SET /A "SQDISTANCE=((405-%%X*10)*(405-%%X*10))+((405-%%Y*10)*(405-%%Y*10))"
IF !SQDISTANCE! GEQ 144400 SET DRAWCHAR%%X%%Y=M
ECHO 144400,M,%%X,%%Y,!SQDISTANCE!,!DRAWCHAR%%X%%Y!>>MATHCHECK.CSV
)
CLS
ECHO !STATUSLINE!
SET STATUSLINE=!STATUSLINE!-
)
SET STATUSLINE=-
FOR /L %%Y IN (2,1,79) DO (
SET DRAWLINE%%Y=-
FOR /L %%X IN (2,1,79) DO (
SET DRAWLINE%%Y=!DRAWLINE%%Y!!DRAWCHAR%%X%%Y!
)
SET DRAWLINE%%Y=!DRAWLINE%%Y:~1,79!
ECHO !DRAWLINE%%Y!>>OUTPUT.MAP
CLS
ECHO COMPILING OUTPUT...
ECHO !STATUSLINE!
SET STATUSLINE=!STATUSLINE!-
)
CLS
ECHO +------------------------------------------------------------------------------+-------------------+
FOR /L %%D IN (2,1,79) DO (
ECHO ^|!DRAWLINE%%D!^|! ^|
)
ECHO +------------------------------------------------------------------------------+-------------------+
PAUSE
Here's the results I'm getting:
https://drive.google.com/open?id=1Rwp2YCBwJCArkVunqBNXa3CDuJhTSVSm
That SHOULD look like a square of Ms with a circle of ^s in it and then a circle of .s in that. It's mostly right but those extra jags of Ms and ^s on the top and left shouldn't be there.
Math formula SHOULD be right. it's just A^2+B^2=C^2.
For figuring this out, I'm spitting out a mathcheck.csv file that has:
The test value
The char to print if geq the test value
The x and y coord
The calculated squared distance from center
The resulting character the program said to use.
If you scroll through that file, you can see instances where the results are that the calculated value is greater than the test value even when they are NOT.
I've tried all sorts of stuff: using lss instead of geq (and flipping values), looking up and tweaking the set /a command, lookin up and tweaking the if, "drawing" in a different order (if you draw all Ms, then draw smaller circles on top instead of starting with .s and putting rings over that you get a very similar error in the same general area).
Pretty sure at this point I've either boneheaded up something obvious in the code OR that if comparisons of numbers just aren't reliable enough for this to work? that doesn't seem possible though. It HAS to be a code error.
A:
The main problem with XY coordinates is that if you don't separate them, you can have multiple values appear to be the same location. For example, [638] is either [6,38] or [63,8]. Unfortunately, if you don't separate them, batch will overwrite any existing values. Using a standard array syntax !DRAWCHAR[%%X][%%Y]! resolves this issue.
SETLOCAL ENABLEDELAYEDEXPANSION
@ECHO OFF
CLS
MODE CON: COLS=100 LINES=102
COLOR 0A
IF EXIST OUTPUT.MAP DEL OUTPUT.MAP
IF EXIST MATHCHECK.CSV DEL MATHCHECK.CSV
SET STATUSLINE=-
FOR /L %%Y IN (2,1,79) DO (
FOR /L %%X IN (2,1,79) DO (
SET DRAWCHAR[%%X][%%Y]=.
)
CLS
ECHO !STATUSLINE!
SET STATUSLINE=!STATUSLINE!-
)
SET STATUSLINE=-
FOR /L %%Y IN (2,1,79) DO (
FOR /L %%X IN (2,1,79) DO (
SET /A "SQDISTANCE=((405-%%X*10)*(405-%%X*10))+((405-%%Y*10)*(405-%%Y*10))"
IF !SQDISTANCE! GEQ 129600 SET DRAWCHAR[%%X][%%Y]=^^
ECHO 129600,^^^^,%%X,%%Y,!SQDISTANCE!,!DRAWCHAR[%%X][%%Y!]>>MATHCHECK.CSV
)
CLS
ECHO !STATUSLINE!
SET STATUSLINE=!STATUSLINE!-
)
SET STATUSLINE=-
FOR /L %%Y IN (2,1,79) DO (
FOR /L %%X IN (2,1,79) DO (
SET /A "SQDISTANCE=((405-%%X*10)*(405-%%X*10))+((405-%%Y*10)*(405-%%Y*10))"
IF !SQDISTANCE! GEQ 144400 SET DRAWCHAR[%%X][%%Y]=M
ECHO 144400,M,%%X,%%Y,!SQDISTANCE!,!DRAWCHAR[%%X][%%Y]!>>MATHCHECK.CSV
)
CLS
ECHO !STATUSLINE!
SET STATUSLINE=!STATUSLINE!-
)
SET STATUSLINE=-
FOR /L %%Y IN (2,1,79) DO (
SET DRAWLINE[%%Y]=-
FOR /L %%X IN (2,1,79) DO (
SET DRAWLINE[%%Y]=!DRAWLINE[%%Y]!!DRAWCHAR[%%X][%%Y]!
)
SET DRAWLINE[%%Y]=!DRAWLINE[%%Y]:~1,79!
ECHO !DRAWLINE[%%Y]!>>OUTPUT.MAP
CLS
ECHO COMPILING OUTPUT...
ECHO !STATUSLINE!
SET STATUSLINE=!STATUSLINE!-
)
CLS
ECHO +------------------------------------------------------------------------------+-------------------+
FOR /L %%D IN (2,1,79) DO (
ECHO ^|!DRAWLINE[%%D]!^|! ^|
)
ECHO +------------------------------------------------------------------------------+-------------------+
PAUSE
|
[
"stackoverflow",
"0029478216.txt"
] | Q:
TraceBack (most recent call last), and GPIO.setmode(GPIO.BOARD) or GPIO.setmode(GPIO.BCM) errors
I have been struggling with a script that will turn a Pi's BCM pins 17, 27, and 10 on for 1 second then off for 1 second sequentially 100ish times. When I run the script LED1 will turn on and then it turns off and the program shuts down with this error:
Traceback (most recent call last):
File "LedBlink.py", line 47, in <module>
LED2Blink()
File "LedBlink.py", line 27, in LED2Blink
GPIO.setup(LED2, GPIO.OUT)
RuntimeError: Please set pin numbering mode using GPIO.setmode(GPIO.BOARD) or GPIO.setmode(GPIO.BCM)
import RPi.GPIO as GPIO
import time
LED1 = 17
LED2 = 27
LED3 = 10
GPIO.setmode(GPIO.BCM)
def LED1Blink():
GPIO.setup(LED1, GPIO.OUT)
GPIO.output(LED1,True)
time.sleep(1)
GPIO.output(LED1,False)
time.sleep(1)
GPIO.cleanup()
def LED2Blink():
GPIO.setup(LED2, GPIO.OUT)
GPIO.output(LED2,True)
time.sleep(1)
GPIO.output(LED2,False)
time.sleep(1)
GPIO.cleanup()
def LED3Blink():
GPIO.setup(LED3, GPIO.OUT)
GPIO.output(LED3,True)
time.sleep(1)
GPIO.output(LED3,False)
time.sleep(1)
GPIO.cleanup()
i = 0
while i < 100:
LED1Blink()
LED2Blink()
LED3Blink()
i + 1
else:
print "finished loop"
A:
The problem is that you are calling GPIO.cleanup() at the end of each methods. As stated in the documentation, Note that GPIO.cleanup() also clears the pin numbering system in use. What you want is GPIO.cleanup(channel) instead, where channel corresponds to LED1, LED2, LED3 in your script.
The best practice is to setup and cleanup the channels ONLY ONCE, e.g.
import RPi.GPIO as GPIO
import time
LED1 = 17
LED2 = 27
LED3 = 10
GPIO.setmode(GPIO.BCM)
GPIO.setup(LED1, GPIO.OUT)
GPIO.setup(LED2, GPIO.OUT)
GPIO.setup(LED3, GPIO.OUT)
def LED1Blink():
GPIO.output(LED1,True)
time.sleep(1)
GPIO.output(LED1,False)
time.sleep(1)
def LED2Blink():
GPIO.output(LED2,True)
time.sleep(1)
GPIO.output(LED2,False)
time.sleep(1)
def LED3Blink():
GPIO.output(LED3,True)
time.sleep(1)
GPIO.output(LED3,False)
time.sleep(1)
i = 0
if i < 100:
LED1Blink()
LED2Blink()
LED3Blink()
i + 1
else:
GPIO.cleanup()
print "finished loop"
|
[
"math.stackexchange",
"0003061451.txt"
] | Q:
compound interest when interest is a random variable
Say you are investing, and you on average get $2$% interest per bet, with a standard deviation of $3$%.
How can I get, within a confidence interval, an average amount I will have after 100 bets, if interest compounds?
A:
This is actually a stochastic differential equation. See https://en.wikipedia.org/wiki/Geometric_Brownian_motion.
Say your bet starts at $S_0$, and we model it as $S_t$ over time. Then we can write
$$dS_{t}=\mu S_{t}\,dt+\sigma S_{t}\,dW_{t}$$
where $\mu=.02$, $\sigma=.03$. Here $W$ represents random brownian motion, so $dW$ is simply a draw from the standard normal. So letting each $dt = 1$, your interest rate is $dS_{t}=\mu+\sigma dW_{t}$. The analytic solution to this equation is
$$S_{t}=S_{0}\exp \left(\left(\mu -{\frac {\sigma ^{2}}{2}}\right)t+\sigma W_{t}\right)$$
The pdf of Brownian Motion $W_t$ is Normal with mean $0$ and variance $t$
$${\displaystyle f_{W_{t}}(x)={\frac {1}{\sqrt {2\pi t}}}e^{-x^{2}/(2t)}}$$
We want the pdf of $S_t$, $f_{S_{t}}(x)$. Because $S_{t} = g(W_{t})$ with
$$g(x) = S_{0}\exp \left(\left(\mu -{\frac {\sigma ^{2}}{2}}\right)t+\sigma x\right)$$
we can use the change of variable formula
$$f_{S_{t}}(x)=f_{W_{t}}(g^{-1}(x))|\frac{dg^{-1}(x)}{dx}|$$
We have
$$g^{-1}(x) = \frac{\ln{\frac{y}{S_0}}-(\mu-\frac{\sigma^2}{2})t}{\sigma}$$
and
$$\frac{dg^{-1}(x)}{dx} = \frac{1}{\sigma y}$$
Thus
$$f_{S_{t}}(x) = \frac{1}{\sigma y \sqrt{2\pi t}} \exp{\frac{-(\frac{\ln{\frac{y}{S_0}}-(\mu-\frac{\sigma^2}{2})t}{\sigma})^2}{2t}}$$
This is the general solution, plug in your values of $t=100$, $\mu=.02$, and $\sigma=.03$ and you have the pdf for your question!
Funnily enough after all that I'm not sure how to analytically find the mean and standard deviation of $f_{S_{t}}(x)$. But numerically it has mean $\approx 7.244S_0$ and standard deviation $\approx 2.176S_0$.
|
[
"stackoverflow",
"0047673830.txt"
] | Q:
what is the es5 equivalent of this code
function handleDeposit (accountNumber, amount) {
type: 'DEPOSIT',
accountNumber,
amount
}
it returns undefined when invoked. I'm not sure what feature of es6 is being used here
is it equivalent to...
function handleDeposit (accountNumber, amount) {
return {
type: 'DEPOSIT',
accountNumber: accountNumber,
amount: amount
}
}
A:
You need to wrap the properties in an object structure with short hand properties as ES6 example for the given ES5 result.
function handleDeposit (accountNumber, amount) {
return {
type: 'DEPOSIT',
accountNumber,
amount
};
}
Your given code
function handleDeposit (accountNumber, amount) {
type: 'DEPOSIT',
accountNumber,
amount
}
has no object inside, but a label type, some comma operators and ends with no return neither some value.
You get the standard return value of a function with undefined.
A:
I'm not sure what feature of es6 is being used here
None. Passing the function through Babel with the es2017 preset results in nothing more than a reformating of the code.
This is just a function (which takes two arguments) containing a label, followed by a string literal, then two arguments, each separated by comma operators.
There is no return statement.
The function does nothing, returns nothing, and is ES5.
|
[
"stackoverflow",
"0026385995.txt"
] | Q:
When should I use parametrized constructor and default constructor
Suppose there is a class that has n properties. While creating its objects I have to create by using following syntax
Way 1
ClassName c = new ClassName();
and assing values like
c.p1 = someValue1;
c.p2 = someValue2;
c.p3 = someValue3;
c.p4 = someValue4;
or
Way 2
ClassName c = new ClassName(someValue1,someValue2,someValue3,someValue4);
if class has a parametrized constructor like
private CalssName(DataType1 prop1,DataType2 prop2,DataType3 prop3,DataType4 prop4)
{
p1 = prop1;
p2 = prop2;
p3 = prop3;
p4 = prop4;
}
Which ways will suit for which siuation?
A:
Using either depends on the requirement.
If you want your class object to have some state (properties assigned) at the time of instantiation then use parametrized constructor. If your class doesn't have a default constructor (no parameters) then there will be no way for the user to instantiate a class without any state.
By default each class would have a default constructor (without any parameter), but once you define a parametrized constructor, there will be no default constructor unless you provide one explicitly.
Imagine if you have class like:
public class ClassName
{
public int ID { get; set; }
public string Name { get; set; }
public ClassName(int id, string name)
{
ID = id;
Name = name;
}
}
Since you have provided a parametrized constructor, User can't instantiate an object without passing ID and Name values. (ignoring reflection)
ClassName obj = new ClassName(); //This will error out
This is useful in scenarios where it is compulsory for an object to have some values at the time of instantiation.
Consider the DirectoryInfo class provided by the .Net framework, you can't instantiate an object of DirectoryInfo without parameter
DirectoryInfo dirInfo = new DirectoryInfo();//This will error out
Since DirectoryInfo requires the object to have a path pointing to the directory, It would be of no use without a path, therefore it is provided with only a parametrized constructor
DirectoryInfo dirInfo = new DirectoryInfo(@"C:\Somefolder");
|
[
"stackoverflow",
"0019328425.txt"
] | Q:
ember not working on jsfiddle
For some reason ember won't work in jsfiddle at the moment. And, I mean it won't work for my simple example, it won't work for other fiddles such as this starter kit, or this one, or either of the fiddles in this post.
I've tried this on Chrome and Firefox on two different machines. And, on my example, I've tried a range of CDNs, methods of including the libraries, versions, body declarations and actual code.
I must be doing something dumb because I keep getting different errors depending on which example I look at, which seems to indicate something fundamentally wrong but I assume jsfiddle works (or worked) in general.
Is anyone else seeing the same thing as me?
Apparently, posts with links to jsfiddle must be accompanied by code now? I've seen other posts with jsfiddle links and no code? Isn't this the whole point of jsfiddle? Well, here's the code.
A:
Add the app initialization script:
var App = Ember.Application.create();
and wrap your handlebars in the correct <script> tags:
<script type="text/x-handlebars" data-template-name="application">
....
</script>
Updated JSFiddle
|
[
"stackoverflow",
"0011999758.txt"
] | Q:
How to pivot column values of the below table?
TableA:
Brand Product
------------------
A X
A XX
A XXX
B Y
B YY
C Z
I need data as shown in Table below:
A B C
-------------------
X Y Z
XX YY NULL
XXX NULL NULL
How to do that in Sql Server 2008 ?
A:
I dont beleive a PIVOT is what you are looking for here.
From what I can see you are looking at using the entries in order to generate the rows?
Also, PIVOTs make use of aggregate functions, so I cant see this happening.
What you can try, is something like
DECLARE @Table TABLE(
Brand VARCHAR(10),
Product VARCHAR(10)
)
INSERT INTO @Table SELECT 'A','X '
INSERT INTO @Table SELECT 'A','XX'
INSERT INTO @Table SELECT 'A','XXX'
INSERT INTO @Table SELECT 'B','Y'
INSERT INTO @Table SELECT 'B','YY'
INSERT INTO @Table SELECT 'C','Z'
;WITH Vals AS (
SELECT *,
ROW_NUMBER() OVER(PARTITION BY Brand ORDER BY (SELECT NULL)) RID
FROM @Table
)
, RIDs AS (
SELECT DISTINCT
RID
FROM Vals
)
SELECT vA.Product [A],
vB.Product [B],
vC.Product [C]
FROM RIDs r LEFT JOIN
Vals vA ON r.RID = vA.RID
AND vA.Brand = 'A' LEFT JOIN
Vals vB ON r.RID = vB.RID
AND vB.Brand = 'B' LEFT JOIN
Vals vC ON r.RID = vC.RID
AND vC.Brand = 'C'
|
[
"stackoverflow",
"0020378930.txt"
] | Q:
SVG path to Bézier Path in Android
I am working on SVG and Bézier paths. It is very new to me . I want to make Bézier Path Animations from SVG Paths. Requirement is to animate any shape or letter like "A" "B" "C" and onward . Now i did not know that is it possible to make SVG path from some drawing tools and give these paths or files to Bézier paths (convert) in android..
Any help will be appreciated
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
View v = new SVGTest(this);
setContentView(v);
}
}
A:
the below method "readPath" is an ABSOLUTE MINIMUM to converd SVG's path "d" attribute to android
Path, it supports only M, L, C and z commands but still i often use it with the output created by
Inkscape program:
class SVGTest extends View {
private Path mPath;
private Paint mPaint;
private Path mTransformedPath;
public SVGTest(Context context) {
super(context);
mPath = new Path();
mTransformedPath = new Path();
String d = "M 30,11 C 30,20 20,25 15,30 C 11,24 1,19 1,11 C 1,3 13,1 15,10 C 15,1 30,3 30,11 z";
readPath(d, mPath);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setStyle(Style.STROKE);
mPaint.setColor(0xff00aa00);
mPaint.setStrokeWidth(20);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
RectF src = new RectF();
mPath.computeBounds(src, true);
RectF dst = new RectF(30, 30, w-30, h-30);
Matrix matrix = new Matrix();
matrix.setRectToRect(src, dst, ScaleToFit.FILL);
mPath.transform(matrix, mTransformedPath);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(mTransformedPath, mPaint);
}
private void readPath(String data, Path p) {
try {
String[] tokens = data.split("[ ,]");
int i = 0;
while (i < tokens.length) {
String token = tokens[i++];
if (token.equals("M")) {
float x = Float.valueOf(tokens[i++]);
float y = Float.valueOf(tokens[i++]);
p.moveTo(x, y);
} else
if (token.equals("L")) {
float x = Float.valueOf(tokens[i++]);
float y = Float.valueOf(tokens[i++]);
p.lineTo(x, y);
} else
if (token.equals("C")) {
float x1 = Float.valueOf(tokens[i++]);
float y1 = Float.valueOf(tokens[i++]);
float x2 = Float.valueOf(tokens[i++]);
float y2 = Float.valueOf(tokens[i++]);
float x3 = Float.valueOf(tokens[i++]);
float y3 = Float.valueOf(tokens[i++]);
p.cubicTo(x1, y1, x2, y2, x3, y3);
} else
if (token.equals("z")) {
p.close();
} else {
throw new RuntimeException("unknown command [" + token + "]");
}
}
} catch (IndexOutOfBoundsException e) {
throw new RuntimeException("bad data ", e);
}
}
}
test it by placing the following code in Activity.onCreate method:
View v = new SVGTest(this);
setContentView(v);
|
[
"stackoverflow",
"0028110810.txt"
] | Q:
Using local packages
I have an Elm package (source + all build artifacts) in a local directory, and I would like to use it from another Elm package, without publishing the library. So my directory setup looks like this:
/
my-lib/
elm-package.json
my-app/
elm-package.json
First of all, running elm-package install in the library package's directory doesn't seem to do anything more than just building the package; it doesn't get installed in any global directory as far as I can tell.
I've added my-lib to my-app/elm-package.json as such:
"dependencies": {
"elm-lang/core": "1.0.0 <= v < 2.0.0",
"my-vendor/my-lib": "0.0.1 <= v <= 0.0.1"
}
So when I run elm-make in the dependent package's directory, it complains
There are no versions of package my-vendor/my-lib on your computer.
elm-package install complains about the same thing.
The only workaround I've found is to create the following symlinks in my-app:
/
my-app/
elm-stuff/
packages/
my-vendor/
my-lib/
0.0.1@ -> /my-lib/
build-artifacts/
my-vendor@ -> /my-lib/build-artifacts/my-vendor
I also had to add the following to /my-app/elm-stuff/exact-dependencies.json:
"my-vendor/elm-lib": "0.0.1"
Clearly, all of the above should be taken care of automatically by elm-package, if only I could point it at /my-lib/ from /my-app/. So how do I do that?
A:
In 2017 ( elm 0.18 ) you can do the following:
Overwrite a published package with a local cloned version
If you've got a dependency to a published package that you'd like to make local, remove your dependency e.g:
"dependencies": {
"rtfeldman/elm-css": "8.2.0 <= v < 9.0.0"
}
Then do a elm-make of your project (this should remove the package from your elm-stuff directory otherwise it will use the cached version of the package. Then you clone and reference the package locally as per steps below.
Reference a local package
You can reference any elm project locally by adding it to source-directories like this:
"source-directories": [
".",
"src",
"../elm-css/src"
],
Add the locally referenced package's dependencies to your elm-package.json
elm-css has these dependencies:
"rtfeldman/elm-css-util": "1.0.2 <= v < 2.0.0",
"rtfeldman/hex": "1.0.0 <= v < 2.0.0"
So add these to your elm-package.json as well.
You're done!
A:
Easier use of local packages is on the todo list. I'm afraid your current approach is the state of the art. Either do it like your doing it now or copy over the code from the package (or maybe symlink modules folders/.elm files from my-lib/src in my-app/src?)
Most recent thread on the mailing list about this issue: https://groups.google.com/d/topic/elm-discuss/i51Bor6Uers/discussion
A:
You can track the status of this feature in this enhancement request.
|
[
"stackoverflow",
"0026867435.txt"
] | Q:
Can a std::map rebalance during the invocation of a const function?
I have a const std::map<std::string, std::vector<double>> member variable and a function const std::vector* foo(). I'd like this function to sometimes return a pointer to an element of this map. But I'm concerned that the map might rebalance - even during a std::map function marked const - so invalidating my returned pointer. I know that any subsequent modification of the map will invalidate my pointers but that cannot happen as I've marked the member variable const.
I can't return a reference as on occasions, foo needs to return nullptr.
Is what I'm doing safe?
A:
The standard is quite clear: the only thing that can invalidate
an iterator or a pointer or reference into a map is removing the
element it points to. You can even insert other elements
without invalidating your pointer. See §23.2.4/9:
The insert and emplace members shall not affect the validity of
iterators and references to the container, and the erase members shall
invalidate only iterators and references to the erased elements.
A:
Fortunately the C++11 standard makes this clear:
§23.2.2/1:
For purposes of avoiding data races (17.6.5.9), implementations shall
consider the following functions to be const: begin, end, rbegin,
rend, front, back, data, find, lower_bound, upper_bound, equal_range,
at and, except in associative or unordered associative containers,
operator[].
So you are safe. The map cannot rebalance when calling a const function.
|
[
"stackoverflow",
"0057318335.txt"
] | Q:
Create 2 publicIPs and assign to nics
I am trying to create 2 public ips and then assign one each to nics
for($i=1; $i -lt 3; $i++)
{
New-AzPublicIpAddress -Name "publicIP$i" -ResourceGroupName $resourceGroup.ResourceGroupName -Location $location -AllocationMethod Dynamic
New-AzNetworkInterface -Name "nic$i" -ResourceGroupName $resourcegroup.ResourceGroupName -Location $location -SubnetId $vnet.subnets[0].Id -PublicIpAddressId "publicIP$i.Id" -NetworkSecurityGroupId $nsg.Id
}
I want to assign the output of new-azPublicIpAddress to a variable and then use that variable's id to assign to -pulicIpAddressId.
like this $pip$i = New-AzPublicIpAddress -Name "publicIP$i" -ResourceGroupName $resourceGroup.ResourceGroupName -Location $location -AllocationMethod Dynamic but this does not work
A:
You cannot set a variable with a '$' inside it.
The following is a correct sample.
$pip = New-AzPublicIpAddress -Name "publicIP$i" -ResourceGroupName $resourceGroup.ResourceGroupName -Location $location -AllocationMethod Dynamic
Considering your requirement, I suggest you use an array:
$pipArr = New-Object 'Object[]' 2;
$nicArr = New-Object 'Object[]' 2;
for($i=0; $i -lt 2; $i++)
{
$pipArr[$i] = New-AzPublicIpAddress -Name "publicIP$i" -ResourceGroupName $resourceGroup.ResourceGroupName -Location $location -AllocationMethod Dynamic
$nicArr[$i] = New-AzNetworkInterface -Name "nic$i" -ResourceGroupName $resourcegroup.ResourceGroupName -Location $location -SubnetId $vnet.subnets[0].Id -PublicIpAddressId $pipArr[$i].Id -NetworkSecurityGroupId $nsg.Id
}
In this way, you can get your first public IP with "$pipArr[0]". As it is an array, you can use index with it.
|
[
"raspberrypi.stackexchange",
"0000073036.txt"
] | Q:
Custom menu GUI
I am trying to make a retro gaming console with the Pi Zero W. The first thing I want to happen is a custom menu screen show up. I know how to make a custom Tkinter GUI but I want it to show up when the desktop would usually load up. Any ideas?
A:
Following this link, .xinitrc in your home directory will be read and executed.
Otherwise, you can place your script under /etc/X11/xinit/xinitrc (I don't know what OS are you using). So, both ways are supposed to run the script when X server starts (again, don't know what OS you're using)
|
[
"poker.stackexchange",
"0000001123.txt"
] | Q:
Postflop play books references
I feel quite comfortable playing pre flop, but I feel that I am weak in post flop play. I lack the big picture of post flop play.
Can anyone give me a good reference for post flop play?
A:
As well as the link Toby has suggested above take a look a the following:
the simple psychology of postflop play
How to play after the flop
Post flop strategy
Post flop play after missing flop
Top 15 Poker - Post Flop strategy
Partypoker - Post flop play
Pokerstars Pokerschool - Post Flop quiz
The last one is a quiz. There are a lot of useful quizzes on this site. If you dont already have an account I would recommend that you sign up and give some of them a go.
Hope some of these links are useful
|
[
"stackoverflow",
"0023376971.txt"
] | Q:
R expanding out a data.table
I've the following situation. A data.table that looks as follows
x = data.table(
id1 = c('a','b','c'),
id2 = c('x','y','x'),
val = c(0.2,0.3,0.5))
I have two other data tables that give a mapping between the values in id1 and id2 which look like the following
id1.dt = data.table(
id1 = c('a','a','a','b','b','c'),
fid = c('1232','3224','3434','234','231','332')
)
and
id2.dt = data.table(
id2 = c('x','x','y','y'),
fid = c('334','443','344','24')
)
What I would like to be able to do is to expand out the above data.table x by preserving the values column such that I get a full cross join but by using the fid column. So the expected final table is
id1 id2 val
1232 334 0.2
1232 443 0.2
3224 334 0.2
3224 443 0.2
3434 334 0.2
3434 443 0.2
...
Basically, for each row in x I want to take all fid values of id1 and id2 from the other two tables and preserve the val value. I've tried using CJ but didn't get far with it. Any help appreciated.
A:
A bit awkward but this should do it:
setkey(x, id1)
(setkey(x[id1.dt], id2))[
id2.dt, allow.cartesian=T][
order(val), -(1:2)
]
Produces:
val fid fid.1
1: 0.2 1232 334
2: 0.2 3224 334
3: 0.2 3434 334
4: 0.2 1232 443
5: 0.2 3224 443
6: 0.2 3434 443
7: 0.3 234 344
8: 0.3 231 344
9: 0.3 234 24
10: 0.3 231 24
11: 0.5 332 334
12: 0.5 332 443
You can also try merge.data.table to achieve a similar result in a somewhat more intuitively graspable form:
merge(
merge(x, id1.dt, by="id1"),
id2.dt, by="id2", allow.cartesian=T
)[, -(1:2)]
|
[
"stackoverflow",
"0048427021.txt"
] | Q:
which user agent request library is using by default
I am developing Node-Js application and I am using Request library and I just want to know which user-agent by default Request library is using?
A:
You can use httbin.org for things like that:
const request = require('request');
request('https://httpbin.org/headers', (error, response, body) => {
console.log(body);
});
The output of the above script is the following:
"headers": {
"Connection": "close",
"Host": "httpbin.org"
}
So it seems like by default the request library doesn't send a "User-Agent" header at all...
|
[
"math.stackexchange",
"0003068107.txt"
] | Q:
Find all polynomials $p(x)$ such that $(p(x))^2 = 1 + x \cdot p(x + 1)$ for all $x\in \mathbb{R}$
Find all polynomials $p(x)$ such that $(p(x))^2 = 1 + x \cdot p(x + 1)$ for all $x\in \mathbb{R}$.
I assume that $O(p(x)=n)$ (Where O(p) denotes the order of p)
let $p(x)=a_nx^n+a_{n-1}x^{n-1}+a_{n-2}x^{n-2} \dots \dots +a_{1}x^{1}+a_{n-1}$ also $a_n \neq 0$
Then we have $a_n^2x^{2n} +\dots +a_0^2=1+a_nx^{n+1}+ \dots a_0x$
since $a_n \neq 0$ we must have $2n=n+1$ and hence $n=1$ hence the polynomial must be linear and hence there doesn't exist any solution(I proved assuming $p(x)=ax+b$)
Is it correct?
A:
Our OP SunShine has correctly deduced that $\deg p(x) = 1$, so that
$p(x) = ax + b; \tag 1$
we compute:
$p^2(x) = a^2x^2 + 2ab x + b^2; \tag 2$
$p(x + 1) = ax + a + b; \tag 3$
$xp(x + 1) = ax^2 + ax + bx; \tag 4$
$xp(x + 1) + 1 = ax^2 + ax + bx + 1; \tag 5$
$a^2 x^2 + 2ab x + b^2 = ax^2 + ax + bx + 1; \tag 6$
$(a^2 - a)x^2 + 2abx + b^2 = ax + bx + 1; \tag 7$
$a^2 = a, \; b^2 = 1, \; 2ab = a + b; \tag 8$
$a = 0, 1; \; b = \pm 1; \tag 9$
$b = 1 \Longrightarrow 2a = a + 1 \Longrightarrow a = 1 \in \{0, 1 \}; \tag{10}$
$b = -1 \Longrightarrow -2a = a - 1 \Longrightarrow a = \dfrac{1}{3} \notin \{0, 1 \}; \tag{11}$
thus the only solution is $a = b = 1$, so that
$p(x) = x + 1. \tag{12}$
CHECK:
$p^2(x) = (x + 1)^2 = x^2 + 2x + 1$
$= x(x + 2) + 1 = x((x + 1) + 1) + 1 = xp(x + 1) + 1; \tag{13}$
it thus appears that the only solution is
$p(x) = x + 1. \tag{14}$
A:
After observing that the degree is at most $1$ you can simplify the rest of the argument as follows: $p(0)^{2}=1$ from the equation, so $p(0)=\pm 1$. Also $p(-1)^{2}=1-p(0)$. By considering the cases $p(0)=1$ and $p(0)=-1$ separately it is quite easy to conclude that the only solution is $p(x)=x+1$.
|
[
"gis.stackexchange",
"0000346468.txt"
] | Q:
How to export raster of Mean Annual Land Surface Temp from Landsat Imagery?
I am using google earth engine to estimate Mean Annual land surface temp of a local scale from 1984 to 2019 from landsat Imagery.
I am having trouble determining a script for my goal, there are many example but the problem is that all of them are calculating the LST for one year.
I have tried this script but I think there is some thing wrong with it and I cannot export the raster of calculated Mean annual LST for my study.
I will be helpful, if anybody could help me to rectify the script. The GEE Code for Export raster of mean annual lsthere
A:
You can create a function calculating LST for a single year (you already have all the code for the function), invoke it for every year, finally combine the results to a single multi-band image.
function calculateLST(col) {
// ...
}
var annualLST = ee.ImageCollection(
years.map(function (year) {
var colForYear = col.filter(
ee.Filter.calendarRange(year, year, 'year')
)
return calculateLST(colForYear)
.rename(ee.String('LST_')
.cat(ee.Number(year).int()))
})
)
.toBands() // Convert ImageCollection to a single image
.regexpRename('.*_(LST.*)', '$1') // Get rid of 'n_' band name prefixes
Export.image.toDrive({
image: annualLST,
description: 'annualLST',
scale: 30,
region: geometry
});
https://code.earthengine.google.com/0bc544dd0048db04e713cd7f235e2309
|
[
"tex.stackexchange",
"0000046579.txt"
] | Q:
Do I really have to initialize xkeyval’s key manually?
If I define some (many) keys with xkeyval do I really have to initialize them to use them if the key is not set explicitly?
\documentclass{article}
\usepackage{xkeyval}
\makeatletter
\define@cmdkeys{fam}[my@]{%
fonta,
fontb,
% ...
% fontn
}[]
%\presetkeys{fam}{keya,keyb}{}
%\setkeys{fam}{
% fonta,
% fontb,
% % ...
% % fontn
%}
\newcommand{\mymacro}[2]{%
{\my@fonta #1} and {\my@fontb #2}
}
\makeatother
\begin{document}
\mymacro{Font A}{Font B}
\end{document}
This code shall become part of a new package.
Many of my keys should set a font, which is empty per default (i.i. if the user doesn’t sets a key-value pair for it). I want to use these font’s in macro definitions but I have to initialize all fonts manually as empty. As a result of this behavior I need to take care of two lists (\define@cmdkeys and \setkeys) in case of adding a new font.
In my understanding the above example should compile as it is but I need to uncomment the \setkeys lines to initialize the macros.
Certainly there are keys that must have a preset value and i must initialize them. For example savemode well be a boolean that is false in preset but should default to true if the user set the key without a value.
Extra What does \presetkeys do? I don’t understand the manual in this section. Is it better to post this as a new question?
A:
The xkeyval doesn't provide for auto-initialization of keys. Your best bets are the keyreader and ltxkeys packages; they provide commands that automatically initialize keys to their default values after the keys have been defined. The keyreader package is easier to follow than the ltxkeys package, but of course has fewer features. Here is an example based on the keyreader (and xkeyval) package.
\documentclass{article}
\usepackage{keyreader}
\usepackage{xcolor}
\makeatletter
\newdimen\shadowsize
\define@boolkey[KV]{shadowbox}[shb@]{frame}[true]{}
\define@boolkey[KV]{shadowbox}[shb@]{shadow}[true]{}
\define@cmdkey[KV]{shadowbox}[shb@]{framecolor}[black]{}
\define@cmdkey[KV]{shadowbox}[shb@]{shadecolor}[white]{}
\define@cmdkey[KV]{shadowbox}[shb@]{shadowcolor}[gray]{}
\define@cmdkey[KV]{shadowbox}[shb@]{boxwidth}[2cm]{}
\define@choicekey+[KV]{shadowbox}{align}[\val\nr]
{center,right,left,justified}[center]{%
\ifcase\nr\relax
\def\curralign##1{\hfil##1\hfil}%
\or
\def\curralign##1{\hfill##1}%
\or
\def\curralign##1{##1\hfill}%
\or
\let\curralign\@iden
\fi
}{%
\@latex@error{Erroneous value for a choice key}
{Invalid value '#1' for key 'align' of family '\XKV@tfam'}%
}
% The following keys could have been defined as command keys, but this is
% just an illustration:
\define@key[KV]{shadowbox}{framesize}{\def\currfboxrule{#1}}
\define@key[KV]{shadowbox}{shadowsize}{\shadowsize=\dimexpr#1\relax}
% Save the values of the following keys when they are being set:
\savevaluekeys[KV]{shadowbox}{frame,framecolor,framesize}
% 'Presetting keys' means set the following keys whenever \setkeys is called.
% These keys should be set BEFORE the keys listed in the current argument of
% \setkeys are set, provided that these keys aren't listed in the current
% argument of \setkeys. If these keys appear in the current argument of \setkeys,
% then obviously the user has new values for them or he wants the keys to be
% set with their default values.
% The command \presetkeys of the xkeyval package expects both 'head' and 'tail'.
% The keyreader package splits \presetkeys into two, hopefully less confusing,
% commands: \krdpresetkeys and \krdpostsetkeys.
\krdpresetkeys[KV]{shadowbox}{%
frame,framecolor=black,framesize=.8pt,boxwidth=2cm,align=center,
shadecolor=gray!15
}
% 'Postsetting keys' means set the following keys whenever \setkeys is called.
% These keys should be set AFTER the keys listed in the current argument of
% \setkeys are set, provided that these keys aren't listed in the current
% argument of \setkeys:
\krdpostsetkeys[KV]{shadowbox}{%
shadow=\usevalue{frame},shadowcolor=\usevalue{framecolor}!40,
shadowsize=\dimexpr\usevalue{framesize}*5\relax
}
\newcommand*\newshadowbox[2][]{%
\krdsetkeys[KV]{shadowbox}{#1}%
\begingroup
\ifshb@frame
\fboxrule=\dimexpr\currfboxrule\relax
\else
\fboxrule=0pt
\fi
\ifshb@shadow\else\shadowsize=0pt \fi
\sbox\z@{\fcolorbox{\shb@framecolor}{\shb@shadecolor}{%
\hb@xt@\shb@boxwidth{\curralign{#2}}%
}}%
\hskip\shadowsize
\color{\shb@shadowcolor}%
\rule[-\dp0]{\wd0}{\dimexpr\ht0+\dp0\relax}%
\llap{\raisebox{\shadowsize}{\box0\hskip\shadowsize}}%
\endgroup
}
\makeatother
\begin{document}
\noindent
\newshadowbox{tobi1}
\newshadowbox[framecolor=gray,shadecolor=blue!25,shadowsize=10pt,align=left]{tobi2}
\newshadowbox[shadow=false,boxwidth=1cm]{tobi3}
\newshadowbox[framesize=2pt,framecolor=red,shadowcolor=green]{tobi4}
\newshadowbox[frame=false,shadow,shadowsize=9pt,shadowcolor=violet!50,align=right]{tobi5}
\end{document}
% Using a feature of the keyreader package, all the above keys can be defined
% compactly as follows. The command \krddefinekeys will automatically initialize
% the keys after they have been defined.
\krddefinekeys*[KV]{shadowbox}[shb@]{%
bool/frame/true;
bool/shadow/true;
cmd/framecolor/black;
cmd/shadecolor/white;
cmd/shadowcolor/gray;
cmd/boxwidth/2cm;
ord/framesize/.5pt/\def\currfboxrule{#1};
ord/shadowsize/2pt/\shadowsize=\dimexpr#1\relax;
choice/align/center/
center.do=\def\curralign##1{\hfil##1\hfil},
right.do=\def\curralign##1{\hfill##1},
left.do=\def\curralign##1{##1\hfill},
justified.do=\let\curralign\@iden;
}
|
[
"math.stackexchange",
"0000878973.txt"
] | Q:
Polar form of a complex number
Question:
Write the polar form of $$\frac{(1+i)^{13}}{(1-i)^7}$$
Well its obviously impractical to expand it and try and solve it.
Multiplying the denominator by $(1+i)^7$ will simplify the denominator, and a single term in the numerator.
Answer I got:
$$(\frac{1}{\sqrt2}(cos(\frac{\pi}{4}) + sin(\frac{\pi}{4})i)^{20}$$
Is this correct?
A:
No, that's not correct. You must have made a couple of errors in your expansions.
\begin{align}
\frac{(1+i)^{13}}{(1-i)^7} &= \frac{(1+i)^{13}(1+i)^7}{(1-i)^7(1+i)^7} \\
&= \frac{1}{2^7}(1+i)^{20} \\
&= \frac{1}{2^7}\left(\sqrt{2}\left(\cos\frac{\pi}{4} + i \sin\frac{\pi}{4}\right)\right)^{20} \\
&= \frac{2^{10}}{2^7}\left(e^{i\pi/4}\right)^{20} \\
&= 8e^{5\pi i} \\
&= -8.
\end{align}
The polar form is $8(\cos\pi + i\sin\pi)$, or $(8,\pi)$.
|
[
"unix.stackexchange",
"0000316610.txt"
] | Q:
how to read ssh output from 'last' and 'who' command
I have just used the command 'last' to see who has logged into my server.
I am unsure how to read some of the output, particularly in Column 2 where it states pts/l and :0.
Instead of spoon feeding me the answer, could you point me in the direction of a good source or pdf's to read in order to become more familiar with this query and general ssh queries.
www.digitalocean.com has been useful up to this point.
Thanks guys( and girls).
A:
pts/1 is your pseudoterminal. A pseudoterminal provides processes with an interface that is identical to that of a real terminal.
http://linux.die.net/man/4/pts
:0 is your X11 Display
https://en.wikipedia.org/wiki/X_Window_System
|
[
"stackoverflow",
"0000488033.txt"
] | Q:
WMI Remote connection
I have an issue regarding WMI connection through asp.net from Computer A (windows 2003 server) to Computer B (Windows XP)..
The error is as follows:
RPC server is unavailable..
A:
There are a few steps that you must take in order to successfully leverage WMI connectivity. The basics are you must allow remote management on the target box of course. If you can’t RDP into it, chances are, you can’t remote manage anything else. This can also include Windows firewall issues too. Make sure your request can even get in at all.
Next, start simple. Can you even poll for the running processes on that box? Try to output all the running processes on the target box with System.Diagnostics.Process currentProcess = System.Diagnostics.Process.GetProcesses("machine-name"). If you can at least get some information on the box then the RPC message you are getting has to do with incorrect arguments being passed in, perhaps?
Anyways, I recently wrote a web application that allowed the users to find a server on the LAN and kill a target process there or start a new one. I did it in C# so the code snippet below is just what I used. It's not the best but its working in production right now:
public static class RemoteProcessAccess
{
public static void KillProcessByProcessID(string NameOfServer, string DomainName, string LogIn, string Password, int processID)
{
//#1 The vars for this static method
#region /// <variables> ...
string userName;
string password;
string machineName;
string myDomain;
Hashtable hs = new Hashtable();
ManagementScope mScope;
ConnectionOptions cnOptions;
ManagementObjectSearcher objSearcher;
ManagementOperationObserver opsObserver;
ManagementClass manageClass;
DirectoryEntry entry;
DirectorySearcher searcher;
DirectorySearcher userSearcher;
#endregion
//#2 Set the basics sent into the method
machineName = NameOfServer;
myDomain = DomainName;
userName = LogIn;
password = Password;
cnOptions = new ConnectionOptions();
cnOptions.Impersonation = ImpersonationLevel.Impersonate;
cnOptions.EnablePrivileges = true;
cnOptions.Username = myDomain + "\\" + userName;
cnOptions.Password = password;
mScope = new ManagementScope(@"\\" + machineName + @"\ROOT\CIMV2", cnOptions);
//#3 Begin Connection to Remote Box
mScope.Connect();
objSearcher = new ManagementObjectSearcher(String.Format("Select * from Win32_Process Where ProcessID = {0}", processID));
opsObserver = new ManagementOperationObserver();
objSearcher.Scope = mScope;
string[] sep = { "\n", "\t" };
//#4 Loop through
foreach (ManagementObject obj in objSearcher.Get())
{
string caption = obj.GetText(TextFormat.Mof);
string[] split = caption.Split(sep, StringSplitOptions.RemoveEmptyEntries);
// Iterate through the splitter
for (int i = 0; i < split.Length; i++)
{
if (split[i].Split('=').Length > 1)
{
string[] procDetails = split[i].Split('=');
procDetails[1] = procDetails[1].Replace(@"""", "");
procDetails[1] = procDetails[1].Replace(';', ' ');
switch (procDetails[0].Trim().ToLower())
{
//You could look for any of the properties here and do something else,
case "processid":
int tmpProc = Convert.ToInt32(procDetails[1].ToString());
//if the process id equals the one passed in....
//(this is redundant since we should have limited the return
//by the query where above, but we're paranoid here
if (tmpProc.Equals(processID))
{
obj.InvokeMethod(opsObserver, "Terminate", null);
}
break;
}//end process ID switch...
}//end our if statement...
}//end our for loop...
}//end our for each loop...
}//end static method
}
|
[
"stackoverflow",
"0057285152.txt"
] | Q:
Restrict file input type control to select only text files
The value text/* for the accept on the input element of type file does not restrict the selection in the Open file dialog to only text files, as it does for other types.
The dialog still shows *.* as the file filter.
<input type = "file" accept = "text/*" />
<input type = "file" accept = "image/*" />
If I do provide specific filters for text files (e.g. text/plain, text/html, I see the dialog restricted to those types, but not for the text/* filter.
How do I make it restrict its file filter to only text files?
Note: Please note that I have already got code to ensure I am not reading files that I want to filter out. I am only concerned with the file filter displayed in the Open dialog box in response to the value of the accept attribute on the input element.
A:
I tested this on various browsers and it appears to be a bug in that it differs from what is mentioned in the specification, and at best a difference in implementation across various browsers. Here are the behaviors for popular browsers.
Chrome and Opera display all types of text files in the file filter.
Chrome
Opera
Firefox
And just with every other feature, IE and Edge go their own way. They have their own, weird behavior. They display something like this:
Internet Explorer
Microsoft Edge
|
[
"stackoverflow",
"0044348396.txt"
] | Q:
How to make create and update use the same route
I have a route and form that looks like this:
<%= form_for @address, url: {action: "update_contact", controller: "checkouts"}, html: {class: ""} do |f| %>
My route looks like:
post "checkouts/:cart_token/update_contact" => "checkouts#update_contact", as: "checkouts_update_contact"
For updates the form is looking for a PATCH which I haven't defined, and so I get an error when the @address model already exists i.e. updates
How can I make my form always POST no matter what?
A:
Add method: :post
<%= form_for @address,
url: {action: "update_contact", controller: "checkouts"},
html: {class: ""},
method: :post do |f| %>
Without that Rails adds a hidden field which is used to fake a PATCH request when the form is used to update an object.
<input type="hidden" name="_method" value="patch" />
|
[
"stackoverflow",
"0043521022.txt"
] | Q:
external swf no longer loading in modern browsers - security issue?
Years ago, I created a swf that upon init, loads an external swf. It worked reliably for years. Now, it's been brought back, but no longer loads the swf in more modern browsers, like in its heyday. It now fails in Chrome 57 and IE11, but worked around IE8 and Chrome 20ish. I'm thinking this might be a security issue. I tried setting compatibility mode in IE but that didn't help. Am I missing a security setting somewhere?
A:
Crossdomain only matters between servers. If its not accessing the internet from hard drive then it cannot be any security issue...
Since it will run offline why involve browsers?
Just use the standalone Flash Player (see this other Answer for any useful hints).
If you have original source codes then just compile output as .exe instead of an .swf.
|
[
"stackoverflow",
"0016589111.txt"
] | Q:
"Primitive types" versus "built-in value types"
I recently caught an exception in C# while using the Array.SetValue(Int32) method. The exception was:
Cannot widen from source type to target type either because the source
type is a not a primitive type or the conversion cannot be
accomplished.
The reference to the word "primitive" surprised me a bit because I thought the tendency was to refer to these types as built-in types, also that the term "primitive type" was an informal term. What is the difference between "primitive" types and "built-in value types"? I don't find a definition of primitive types in the C# language specification.
A:
Primitive Types are not defined in the C# Language Specification. They are instead defined in .NET itself, and the best reference for primitive types is to look straight at Type.IsPrimitive on MSDN. Specifically, the Remarks section lists the primitive types that are available.
So that we've got a complete reference here, these are the primitive types defined in the CLI Spec (Section I.8.2.2):
Boolean
Byte
SByte
Int16
UInt16
Int32
UInt32
Int64
UInt64
IntPtr
UIntPtr
Char
Double
Single
Contrary to popular belief, just because a type has a corresponding keyword does not make it a primitive type, the best example is probably string.
Value types, on the other hand, may or may not be primitives also. There are lots of value types "built-in" to the .NET Framework in addition to those defined in the CLI Spec, but they are not classed as primitives. A good example is DateTime, which is a struct provided by the .NET Framework, by that definition it could be considered a "built-in value type". You can read more about value types (which will of course cover the built-in ones also) here.
|
[
"scifi.stackexchange",
"0000026874.txt"
] | Q:
Could Gaff have known about the unicorn without Deckard being a Replicant?
Or is that supposed to cinch it?
He appears to take the revelation rather calmly, doesn't he?
A:
Opinions are divided, even among the people with immediate creative input:
Philip K. Dick wrote the character Deckard as a human in the original novel.
Hampton Fancher (original screenwriter) has said that he wrote the character Deckard as a human, but wanted the film to suggest the possibility that he may be a replicant.
Ridley Scott stated in an interview in 2002 that he considers Deckard a replicant.
Harrison Ford considered Deckard to be human, at least originally (see details on Wiki).
Possible "human" explanations are that Deckard talked about the dream off-screen and Gaff somehow learned about it, or that it's a coincidence and Gaff intended it to symbolize Rachel.
If Deckard is a replicant, he may long have suspected it himself and is therefore not shocked.
|
[
"stackoverflow",
"0050289903.txt"
] | Q:
Bootstrap 4 - Flexbox examples not working
I am creating a simple Express webserver that serves a landing page made with bootstrap, but I can't get any Flexbox examples to work..
Below is my landing page, is there anything I am not seeing? I have checked that jQuery and Bootstrap links are working. I have also viewed the page in Firefox, Chrome and Edge.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Homepage</title>
<!-- STYLES -->
<link rel="stylesheet" href="../public/styleshee/bootstrap.min.css"/>
<link rel="stylesheet" href="../public/stylesheets/main.css" />
</head>
<body>
<div class="d-flex justify-content-around">
<div class="p-2">Flex item 1</div>
<div class="p-2">Flex item 2</div>
<div class="p-2">Flex item 3</div>
</div>
<button id="test-btn" class="btn btn-success">Button</button>
<!-- SCRIPTS-->
<script src="../public/javascripts/jquery.min.js"></script>
<script src="../public/javascripts/bootstrap.min.js"></script>
<script src="../public/javascripts/index.js"></script>
</body>
</html>
Here is a screenshot of the output:
As you can see justify-content-around is not behaving as expected. I have tried several Flexbox classes with the same results.
A:
Can you check which version of bootstrap you use.
When I try your code with version 3.xx it gives output like this in your question, but when I include bootstrap 4 css it gives this ( picture bellow)
link for image
If you want something like this, just include this script for bootstrap css
https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css
|
[
"stackoverflow",
"0045248193.txt"
] | Q:
What is a concrete class in C++?
I am in the process of reading "The C++ Programming Language 4th Edition" and I've gotten to the point where Bjarne is trying to explain concrete classes. His explanation is confusing me, and I cannot find any explanation online that satisfies me. I understand that abstract classes are classes that have at least one virtual function and that concrete classes are the opposite, but I can not wrap my head around concrete classes. The book "Programming Principles and Practice using C++" is saying that a concrete class is essentially a derived class, and an abstract class is a base class. Is this the correct interpretation? I have been trying to figure out this concept all day. Also, "a class that can be used to create objects is a concrete class". Does this mean that a class is concrete if I can do something like "myclass classobject1;", and I am not able to make objects with abstract classes?
A:
Essentially, a concrete class is a class that implements an interface. An interface, such as an abstract class, defines how you can interact with an instance that implements that interface. You interact with an instance through member functions, so an interface typically declares virtual member functions that are meant to be overridden (implemented) by an implementing class (concrete class). If I have an abstract class Animal, it might have a virtual member function named speak. Animals all make different sounds, so the Animal interface does not know how to define that function. It will be up to the concrete classes, such as Dog, or Tiger, to define what actually happens when the speak function is invoked.
|
[
"stackoverflow",
"0053768596.txt"
] | Q:
Streaming data to .csv not showing results C#
I am attempting to stream data from a SQLServer DB to a .CSV file; However, after execution, the .csv is still blank. The first while loop is/was for testing purposes which executed correctly. I know I am doing something wrong in my Streaming portion.
Any help is greatly appreciated!
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
SqlConnection conn = new SqlConnection("Server=*******;Database=*********;Integrated Security=true");
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT p.cFName, p.cLName, s.cSugTitle, s.cEcrno, g.cName, h.mNotes, u.UserID, u.NetworkID FROM people p INNER JOIN suggest s ON p.cidPeople = s.cidPeople_WhoEntered INNER JOIN Grp g on s.cidGrp = g.cidGrp INNER JOIN history h ON h.cidSuggest = s.cidSuggest INNER JOIN users u ON u.cidPeople = p.cidPeople", conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}", reader.GetString(0), reader.GetString(1), reader.GetString(2), reader.GetString(3), reader.GetString(4), reader.IsDBNull(5) ? null : reader.GetString(5), reader.GetString(6), reader.IsDBNull(7) ? null : reader.GetString(7));
}
String path = @"C:\Users\AEEVANS\Desktop\example.csv";
using (StreamWriter sr = File.AppendText(path))
{
while (reader.Read())
{
sr.WriteLine("{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}", reader.GetString(0), reader.GetString(1), reader.GetString(2), reader.GetString(3), reader.GetString(4), reader.IsDBNull(5) ? null : reader.GetString(5), reader.GetString(6), reader.IsDBNull(7) ? null : reader.GetString(7));
sr.Close();
}
}
Console.ReadKey();
reader.Close();
conn.Close();
if (Debugger.IsAttached)
{
Console.ReadLine();
}
}
}
}
EDIT
I have edited my original code to not include the first while loop per recommendation. I am now running into the following error:
System.ObjectDisposedException: 'Cannot write to a closed TextWriter.'
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
SqlConnection conn = new SqlConnection("Server=********;Database=*********;Integrated Security=true");
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT p.cFName, p.cLName, s.cSugTitle, s.cEcrno, g.cName, h.mNotes, u.UserID, u.NetworkID FROM people p INNER JOIN suggest s ON p.cidPeople = s.cidPeople_WhoEntered INNER JOIN Grp g on s.cidGrp = g.cidGrp INNER JOIN history h ON h.cidSuggest = s.cidSuggest INNER JOIN users u ON u.cidPeople = p.cidPeople", conn);
SqlDataReader reader = cmd.ExecuteReader();
String path = @"C:\Users\AEEVANS\Desktop\example.csv";
using (StreamWriter sr = File.AppendText(path))
{
while (reader.Read())
{
sr.WriteLine("{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}", reader.GetString(0), reader.GetString(1), reader.GetString(2), reader.GetString(3), reader.GetString(4), reader.IsDBNull(5) ? null : reader.GetString(5), reader.GetString(6), reader.IsDBNull(7) ? null : reader.GetString(7));
sr.Close();
}
}
reader.Close();
conn.Close();
if (Debugger.IsAttached)
{
Console.ReadLine();
}
}
}
}
A:
while (reader.Read()) is a one-way trip through a data reader. If you do another while (reader.Read()), you'll get nothing because the pointer is already at the end of the reader's contents.
Looks like you should be able to combine your two while (reader.Read()) blocks into one.
|
[
"stackoverflow",
"0011099930.txt"
] | Q:
100% width background image with an 'auto' height
I'm currently working on a mobile landing page for a company. It's a really basic layout but below the header there's an image of a product which will always be 100% width (the design shows it always going from edge to edge). Depending on the width of the screen the height of the image will obviously adjust accordingly. I originally did this with an img (with a CSS width of 100%) and it worked great but I've realised that I'd like to use media queries to serve different images based on different resolutions - let's say a small, medium and a large version of the same image, for example. I know you can't change the img src with CSS so I figured I should be using a CSS background for the image as opposed to an img tag in the HTML.
I can't seem to get this working properly as the div with the background image needs both a width and a height to show the background. I can obviously use 'width: 100%' but what do I use for the height? I can put a random fixed height like 150px and then I can see the top 150px of the image but this isn't the solution as there isn't a fixed height. I had a play and found that once there is a height (tested with 150px) I can use 'background-size: 100%' to fit the image in the div correctly. I can use the more recent CSS3 for this project as it's aimed solely at mobile.
I've added a rough example below. Please excuse the inline styles but I wanted to give a basic example to try and make my question a little clearer.
<div id="image-container">
<div id="image" style="background: url(image.jpg) no-repeat; width: 100%; height: 150px; background-size: 100%;"></div>
</div>
Do I maybe have to give the container div a percentage height based on the whole page or am I looking at this completely wrong?
Also, do you think CSS backgrounds are the best way to do this? Maybe there's a technique which serves different img tags based on device/screen width. The general idea is that the landing page template will be used numerous times with different product images so I need to make sure I develop this the best way possible.
I apologise is this is a little long-winded but I'm back and forth from this project to the next so I'd like to get this little thing done. Thanks in advance for your time, it's much appreciated.
Regards
A:
Tim S. was much closer to a "correct" answer then the currently accepted one. If you want to have a 100% width, variable height background image done with CSS, instead of using cover (which will allow the image to extend out from the sides) or contain (which does not allow the image to extend out at all), just set the CSS like so:
body {
background-image: url(img.jpg);
background-position: center top;
background-size: 100% auto;
}
This will set your background image to 100% width and allow the height to overflow. Now you can use media queries to swap out that image instead of relying on JavaScript.
EDIT: I just realized (3 months later) that you probably don't want the image to overflow; you seem to want the container element to resize based on it's background-image (to preserve it's aspect ratio), which is not possible with CSS as far as I know.
Hopefully soon you'll be able to use the new srcset attribute on the img element. If you want to use img elements now, the currently accepted answer is probably best.
However, you can create a responsive background-image element with a constant aspect ratio using purely CSS. To do this, you set the height to 0 and set the padding-bottom to a percentage of the element's own width, like so:
.foo {
height: 0;
padding: 0; /* remove any pre-existing padding, just in case */
padding-bottom: 75%; /* for a 4:3 aspect ratio */
background-image: url(foo.png);
background-position: center center;
background-size: 100%;
background-repeat: no-repeat;
}
In order to use different aspect ratios, divide the height of the original image by it's own width, and multiply by 100 to get the percentage value. This works because padding percentage is always calculated based on width, even if it's vertical padding.
A:
Try this
html {
background: url(image.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
Simplified version
html {
background: url(image.jpg) center center / cover no-repeat fixed;
}
A:
You can use the CSS property background-size and set it to cover or contain, depending your preference. Cover will cover the window entirely, while contain will make one side fit the window thus not covering the entire page (unless the aspect ratio of the screen is equal to the image).
Please note that this is a CSS3 property. In older browsers, this property is ignored. Alternatively, you can use javascript to change the CSS settings depending on the window size, but this isn't preferred.
body {
background-image: url(image.jpg); /* image */
background-position: center; /* center the image */
background-size: cover; /* cover the entire window */
}
|
[
"stackoverflow",
"0037084907.txt"
] | Q:
assert_select is flagged as deprecated in RubyMine 2016.1
I recently upgraded to RubyMine 2016.1, and have noticed that the assert_select method in minitest is marked as deprecated.
Here is the warning I get,
'Rails::Dom::Testing::Assertions::SelectorAssertions.assert_select' call is deprecated less... (⌘F1)
This inspection warns about features that were deprecated in Rails 3.0 and will be removed in future versions.
Is this true? I can't find any clear information to corroborate this. Can anyone clarify if this is just a bug in RubyMine, or if it is actually being deprecated?
A:
The assert_select is actually not deprecated. This seems to be a bug in Rubymine 2016.1, similar to the Model.find deprecation warning bug. Someone even referenced this problem it in the same issue in the bug tracker.
So, although I could not find any more relevant links to prove, I guess it is the same bug which is supposed to be fixed in the Rubymine 2016.1.2 release later this year.
Update: the bug seems to be fixed now in the Rubymine 2016.1.1 security release. The IDE no longer annotates this statement as deprecated.
|
[
"stackoverflow",
"0010027574.txt"
] | Q:
Express JS reverse URL route (Django style)
I'm using Express JS and I want a functionality similar to Django's reverse function. So if I have a route, for example
app.get('/users/:id/:name', function(req, res) { /* some code */ } )
I'd like to use a function for example
reverse('/users/:id/:name', 15, 'John');
or even better
reverse('/users/:id/:name', { id : 15, name : 'John' });
which will give me the url /users/15/John. Does such function exist? And if not then do you have any ideas how to write such function (considering Express' routing algorithm)?
A:
Here is your code:
function reverse(url, obj) {
return url.replace(/(\/:\w+\??)/g, function (m, c) {
c=c.replace(/[/:?]/g, '');
return obj[c] ? '/' + obj[c] : "";
});
}
reverse('/users/:id/:name', { id: 15, name: 'John' });
reverse('/users/:id?', { id: 15});
reverse('/users/:id?', {});
A:
I've just created the package reversable-router that solves this along other problems for the routing.
Example from the readme:
app.get('/admin/user/:id', 'admin.user.edit', function(req, res, next){
//...
});
//.. and a helper in the view files:
url('admin.user.edit', {id: 2})
|
[
"stackoverflow",
"0004404787.txt"
] | Q:
What's the best way to parse a tab-delimited file in Ruby?
What's the best (most efficient) way to parse a tab-delimited file in Ruby?
A:
The Ruby CSV library lets you specify the field delimiter. Ruby 1.9 uses FasterCSV. Something like this would work:
require "csv"
parsed_file = CSV.read("path-to-file.csv", { :col_sep => "\t" })
A:
The rules for TSV are actually a bit different from CSV. The main difference is that CSV has provisions for sticking a comma inside a field and then using quotation characters and escaping quotes inside a field. I wrote a quick example to show how the simple response fails:
require 'csv'
line = 'boogie\ttime\tis "now"'
begin
line = CSV.parse_line(line, col_sep: "\t")
puts "parsed correctly"
rescue CSV::MalformedCSVError
puts "failed to parse line"
end
begin
line = CSV.parse_line(line, col_sep: "\t", quote_char: "Ƃ")
puts "parsed correctly with random quote char"
rescue CSV::MalformedCSVError
puts "failed to parse line with random quote char"
end
#Output:
# failed to parse line
# parsed correctly with random quote char
If you want to use the CSV library you could used a random quote character that you don't expect to see if your file (the example shows this), but you could also use a simpler methodology like the StrictTsv class shown below to get the same effect without having to worry about field quotations.
# The main parse method is mostly borrowed from a tweet by @JEG2
class StrictTsv
attr_reader :filepath
def initialize(filepath)
@filepath = filepath
end
def parse
open(filepath) do |f|
headers = f.gets.strip.split("\t")
f.each do |line|
fields = Hash[headers.zip(line.split("\t"))]
yield fields
end
end
end
end
# Example Usage
tsv = Vendor::StrictTsv.new("your_file.tsv")
tsv.parse do |row|
puts row['named field']
end
The choice of using the CSV library or something more strict just depends on who is sending you the file and whether they are expecting to adhere to the strict TSV standard.
Details about the TSV standard can be found at http://en.wikipedia.org/wiki/Tab-separated_values
|
[
"stackoverflow",
"0015129584.txt"
] | Q:
How to change only width of path(rect, circle) while mouse drag using paper.js
I have stucked at resizing only width of an item in the canvas using paper.js
I have done in following ways to resize , but it results in resizing both left and right sides from the center of rectangle/circle.
function onMouseDrag(event){
(selectedItem.bounds.contains(event.point)) ?
selectedItem.scale(0.9871668311944719,1) : selectedItem.scale(1.013, 1);
}
above code resizes in both x-directions.
Help me to resize width only in one direction.
thanks,
suribabu.
A:
You can center the scale operation at any point by using the form:
scale(hor, ver, point)
So in your case, if you want to scale from the left-center of your selected item, you could use:
function onMouseDrag(event){
(selectedItem.bounds.contains(event.point)) ?
selectedItem.scale(0.9871668311944719, 1, selectedItem.bounds.left) : selectedItem.scale(1.013, 1, selectedItem.bounds.left);
}
|
[
"stackoverflow",
"0057798069.txt"
] | Q:
How to wait for multiple observable streams to resolve and return them together
In the observable pipeline below colWithIds$ gives me an observable of a firestore collection (a single array of objects) which I'll refer to as the parent documents. For each of those documents I use flatMap to make a single call for an associated document, which I'll call the child documents. I then store the parent and child docs on local variables:
this.db.colWithIds$('parentCollection')
.pipe(
tap(parentDocs => this.parentDocs = _.keyBy(parentDocs, '_id')),
flatMap(parentDocs => combineLatest(parentDocs.map(doc => this.db.doc(`childCollection/${doc.childId}`).get()))),
map(snaps => convertSnaps(snaps)),
tap(childDocs => this.childDocs = _.keyBy(childDocs, '_id'))
).subscribe()
The problems with this approach:
There is a moment when the parent docs are available, but the child docs are not
I would like to put this in a service for reuse, so assigning local variables in this way is problematic.
I'm looking for a way that I can wait until all values have been resolved and return a single object in the following form:
{
parentDocs: [{}, {}, ...], // the documents
childDocs: [{}, {}, ...], // the documents
}
I'm open to other solutions to the problems listed above. Thanks in advance.
A:
Is this what you are looking for? This way you don't query the database twice for parents.
this.db.colWithIds$(`parentCollection`).pipe(
map(parentDocs => _.keyBy(parentDocs, '_id')),
flatMap(parentDocs => combineLatest(_.map(parentDocs, parent => this.db.docWithId$(`childDocs/${parent.childId}`))).pipe(
map(childDocs => _.keyBy(childDocs, '_id')),
map(childDocs => ({parentDocs, childDocs}))
))
);
|
[
"stackoverflow",
"0032782109.txt"
] | Q:
How to read * from command line in C
I'll go straight to the point. This is my code, and I want to read the '*' char from command line parameter, but it's not working properly. I hope you can explain me what I'm doing wrong.
#include <stdio.h>
#include <stdlib.h>
int sum(int, int);
int rest(int, int);
int division(int, int);
int mult(int, int);
int module(int, int);
int main(int argc, char **argv){
char operator;
int number1;
int number2;
int result;
if(argc != 4){
printf("Wrong parameter quantity (%d of 3 needed)\n", argc-1);
return -1;
}
number1 = atoi(argv[1]);
operator = *argv[2];
number2 = atoi(argv[3]);
switch(operator){
case '+':
result = sum(number1, number2);
printf("%d %c %d = %d\n", number1, operator, number2, result);
break;
case '-':
result = rest(number1, number2);
printf("%d %c %d = %d\n", number1, operator, number2, result);
break;
case '/':
result = division(number1, number2);
printf("%d %c %d = %d\n", number1, operator, number2, result);
break;
case '*':
result = mult(number1, number2);
printf("%d %c %d = %d\n", number1, operator, number2, result);
break;
case '%':
result = module(number1, number2);
printf("%d %c %d = %d\n", number1, operator, number2, result);
break;
default:
printf("Error. Wrong operator inserted (%d, %c)\n", operator, operator);
return -2;
}
return 0;
}
int sum(number1, number2){
return number1 + number2;
}
int rest(number1, number2){
return number1 - number2;
}
int division(number1, number2){
return number1 / number2;
}
int mult(number1, number2){
return number1 * number2;
}
int module(number1, number2){
return number1 % number2;
}
I know my mistake is en this line operator = *argv[2]; but I don't know what happens when the '*' char is passed through command line parameter. For all other symbols (+, -, /, %) everything works fine. I'm coding this in Ubuntu and compiling in command line with gcc.
A:
The problem isn't in your program. It's how you're calling it.
The UNIX/Linux shell automatically expands * on the command line to all files in the current directory. To prevent that, you need to quote it.
So instead of doing this
./prog 3 * 4
Do this:
./prod 3 "*" 4
Or this:
./prod 3 \* 4
|
[
"tex.stackexchange",
"0000147077.txt"
] | Q:
Compilation Error "! Missing \endcsname inserted" The control sequence marked should not appear between \csname and \endcsname
here's my thesis Latex files: http://www.mediafire.com/download/c7q8z4v6gv864rk/triet_thesis_clean.rar
Please help me to fix the error, I've tried all the things I can find with Google :( :
! Missing \endcsname inserted.
<to be read again>
\begingroup
l.52 ...}intopreamble]Deobfuscation}{{4.1.1}{xii}}
The control sequence marked <to be read again> should
not appear between \csname and \endcsname.
(D:\DH\Luan_Van_Tot_Nghiep\Latex\triet_thesis_test\LVTN.aux
A:
You have a wrong character in one of your labels:
\subsection{LLVM}
\label{subsec:LLVMDeobfuscation}
where, between LLVM and Deobfuscation, you have the Unicode character U+200E (LEFT-TO-RIGHT MARK) that somehow sneaked in.
Retype the label and you should be OK.
A:
For others if you have not tried to delete all the generated files from pdflatex and bibtex, then do that before any other changes, because it could be a compilation error.
A:
I never wrote Vietnamese and don't know if it can be done with pdflatex. However, if I use xelatex instead and
\documentclass[a4paper,oneside]{report}
%\usepackage[utf8x]{vietnam}%% xelatex is by default utf8
\usepackage{fontspec}%% load unicode fonts
\usepackage{graphicx}
\usepackage{pdfpages}
\usepackage{suthesis-2e}
\begin{document}
...
I'll get a proper output with out any errors.
|
[
"stackoverflow",
"0045271397.txt"
] | Q:
Python Tkinter: Paned Window not sticking to top
Thanks for taking time to look at this. I've been struggling with this for almost a week and its driving me crazy.
I have a horizontal Paned Window which is supposed to stretch from the bottom of my toolbar to the bottom of my window, but it's sticking only to the bottom of the root window. Eventually I want to have a Treeview widget in the left pane and thumbnails in the right pane.
Can anyone help me to get the Paned Window to stick NSEW? Do I need to put it inside another frame?
I'm using Python 2.7 on Windows 7. (This isn't my whole program, just a sample to demonstrate the problem.)
#!/usr/bin/env python
# coding=utf-8
from Tkinter import *
from ttk import *
class MainWindow:
def null(self):
pass
def __init__(self):
self.root = Tk()
self.root.geometry("700x300")
self.root.resizable(width=TRUE, height=TRUE)
self.root.rowconfigure(0, weight=1)
self.root.columnconfigure(0, weight=1)
self.menubar = Menu(self.root)
File_menu = Menu(self.menubar, tearoff=0)
self.menubar.add_cascade(label="Pandoras Box", menu=File_menu)
File_menu.add_command(label="Black Hole", command=self.null)
self.root.config(menu=self.menubar)
self.toolbar = Frame(self.root, relief=RAISED)
self.toolbar.grid(row=0, column=0, sticky='NEW')
self.toolbar.grid_columnconfigure(0, weight=1)
self.toolbar.rowconfigure(0, weight=1)
dummy = Button(self.toolbar, text="Tool Button")
dummy.grid(row=0, column=0, sticky='EW')
Find = Label(self.toolbar, text="Search")
Search = Entry(self.toolbar)
Find.grid(row=0, column=5, sticky='E', padx=6)
Search.grid(row=0, column=6, sticky='E', padx=8)
self.info_column = Frame(self.root, relief=RAISED, width=100)
self.info_column.grid(row=0, column=5, rowspan=3, sticky='NSW')
self.info_column.grid_rowconfigure(0, weight=1)
self.info_column.grid_columnconfigure(0, weight=1)
self.rootpane = PanedWindow(self.root, orient=HORIZONTAL)
self.rootpane.grid(row=1, column=0, sticky='NS')
self.rootpane.grid_rowconfigure(0, weight=1)
self.rootpane.grid_columnconfigure(0, weight=1)
self.leftpane = Frame(self.rootpane, relief=RAISED)
self.leftpane.grid(row=0, column=0, sticky='NSEW')
self.rightpane = Frame(self.rootpane, relief=RAISED)
self.rightpane.grid(row=0, column=0, sticky='NSEW')
''' THESE BUTTONS ARE SUPPOSED TO BE INSIDE PANED WINDOW STUCK TO THE TOP!'''
but_left = Button(self.leftpane, text="SHOULD BE IN LEFT PANE UNDER TOOLBAR FRAME")
but_left.grid(row=0, column=0, sticky='NEW')
but_right = Button(self.rightpane, text="SHOULD BE IN RIGHT PANE UNDER TOOLBAR FRAME")
but_right.grid(row=0, column=0, sticky='NEW')
self.rootpane.add(self.leftpane)
self.rootpane.add(self.rightpane)
self.SbarMesg = StringVar()
self.label = Label(self.root, textvariable=self.SbarMesg, font=('arial', 8, 'normal'))
self.SbarMesg.set('Status Bar:')
self.label.grid(row=3, column=0, columnspan=6, sticky='SEW')
self.label.grid_rowconfigure(0, weight=1)
self.label.grid_columnconfigure(0, weight=1)
self.root.mainloop()
a = MainWindow()
A:
Short answer: the space you see between the buttons and the toolbar frame is because you allow the row containing the toolbar to resize, instead of the row containing the PanedWindow... To get what you want, replace:
self.root.rowconfigure(0, weight=1)
with
self.root.rowconfigure(1, weight=1)
Other comments:
Try to avoid wildcard imports. In this case, it makes it difficult to differentiate between tk and ttk widgets
To allow resizing of widgets aligned using grid(), .rowconfigure(..., weight=x) must be called on the widget's parent not the widget itself.
background colors are very useful to debug alignment issues in tkinter.
Code:
import Tkinter as tk
import ttk
class MainWindow:
def __init__(self):
self.root = tk.Tk()
self.root.geometry("700x300")
self.root.resizable(width=tk.TRUE, height=tk.TRUE)
self.root.rowconfigure(1, weight=1)
self.root.columnconfigure(0, weight=1)
self.toolbar = tk.Frame(self.root, relief=tk.RAISED, bg="yellow")
self.toolbar.grid(row=0, column=0, sticky='NEW')
self.toolbar.columnconfigure(0, weight=1)
dummy = ttk.Button(self.toolbar, text="Tool Button")
dummy.grid(row=0, column=0, sticky='EW')
Find = tk.Label(self.toolbar, text="Search")
Search = ttk.Entry(self.toolbar)
Find.grid(row=0, column=5, sticky='E', padx=6)
Search.grid(row=0, column=6, sticky='E', padx=8)
self.info_column = tk.Frame(self.root, relief=tk.RAISED, width=100, bg="orange")
self.info_column.grid(row=0, column=5, rowspan=2, sticky='NSW')
self.rootpane = tk.PanedWindow(self.root, orient=tk.HORIZONTAL, bg="blue")
self.rootpane.grid(row=1, column=0, sticky='NSEW')
self.leftpane = tk.Frame(self.rootpane, bg="pink")
self.rootpane.add(self.leftpane)
self.rightpane = tk.Frame(self.rootpane, bg="red")
self.rootpane.add(self.rightpane)
''' THESE BUTTONS ARE SUPPOSED TO BE INSIDE PANED WINDOW STUCK TO THE TOP!'''
but_left = ttk.Button(self.leftpane, text="SHOULD BE IN LEFT PANE UNDER TOOLBAR FRAME")
but_left.grid(row=0, column=0, sticky='NEW')
but_right = ttk.Button(self.rightpane, text="SHOULD BE IN RIGHT PANE UNDER TOOLBAR FRAME")
but_right.grid(row=0, column=0, sticky='NEW')
self.label = tk.Label(self.root, text="Status:", anchor="w")
self.label.grid(row=3, column=0, columnspan=6, sticky='SEW')
self.root.mainloop()
a = MainWindow()
|
[
"stackoverflow",
"0020486322.txt"
] | Q:
Why does it keep outputing "0"?
import java.util.Scanner;
class DataInput {
String name[];
int korean[], math[], english[];
int sum[];
double average[];
static int rank[];
int students;
public void save() {
Scanner sc = new Scanner(System.in);
System.out.println("Please input number of students");
students = sc.nextInt();
name = new String[students];
korean = new int[students];
math = new int[students];
english = new int[students];
sum = new int[students];
average = new double[students];
rank = new int[students];
for (int i = 0; i < students; i++) {
System.out.println("Name?");
name[i] = sc.next();
System.out.println("Korean Score :");
korean[i] = sc.nextInt();
System.out.println("Math Score :");
math[i] = sc.nextInt();
System.out.println("English Score :");
english[i] = sc.nextInt();
sum[i] = korean[i] + math[i] + english[i];
average[i] = sum[i] / 3;
}
}
}
class DataOutput extends DataInput {
public void ranker() {
for (int i = 0; i < students; i++){
rank[i] = 1;
}
for (int i = 0; i < students; i++) {
for (int j = i + 1; j < students; j++) {
if (sum[i] < sum[j]) {
rank[i] += 1;
} else if(sum[i]>sum[j]){
rank[j] += 1;
}
}
}
}
}
public class Score {
public static void main(String[] args) {
DataInput data = new DataInput();
DataOutput out = new DataOutput();
data.save();
out.ranker();
System.out.println();
System.out.println("Name\t\tKorean Math English\tSum Average Rank");
System.out
.println("-------------------------------------------------------");
for (int i = 0; i < data.students; i++) {
System.out
.println(data.name[i] + "\t\t" + data.korean[i] + " "
+ data.math[i] + " " + data.english[i] + "\t"
+ data.sum[i] + " " + data.average[i] + " "
+ out.rank[i]);
}
}
}
So, this is a little program I built. I think the logic is quite right, but when I run the program and type in all the variables, the ranks of students are all 0.
I can't figure out what's the problem. It would be really thankful if someone helps me.
A:
Instead of average[i] = sum[i] / 3; - which does integer math; I think you really need average[i] = sum[i] / 3.0; which should give you a non-zero result.
|
[
"apple.stackexchange",
"0000287491.txt"
] | Q:
Function keys default
I have a MacBook Pro with Touch Bar. Touch Bar shows default buttons for brightness, volume, play/pause, etc.
I know there is the option to add applications to the shortcut bar in system settings to have the function keys F1…F12 on the Touch Bar, but I want them ALWAYS.
I need them for programming (and I'm lazy and don't want to change my behaviour — imho it is part of the job of my computer to adapt to me, not the other way around) and so I have added PHPStorm to the apps, showing F1…
The problem is, when I'm in my browser, calendar etc. Play, etc. is showing. So I never know whether I have to push Fn or not to pause the music.
Is there any way to make the display of the Touch Bar consistent?
And consistently showing F1…F12?
A:
You can only do that: How to use function keys on MacBook Pro with Touch Bar
For some apps, you can make the function keys display permanently in
Touch Bar:
In System Preferences, choose Keyboard.
Click Shortcuts.
From the left sidebar, select Function Keys.
Click the “+” symbol, then navigate to the app and select it.
Now when you open or switch to this app, Touch Bar always displays the
function keys.
|
[
"stackoverflow",
"0010873634.txt"
] | Q:
correlated query to update a table based on a select
I have these tables Genre and Songs. There is obviously many to many relationship btw them, as one genre can have (obviously) have many songs and one song may belong to many genre (say there is a song xyz, it belong to rap, it can also belong to hip-hop). I have this table GenreSongs which acts as a many to many relationship map btw these two, as it contains GenreID and SongID column. So, what I am supposed to do this, add a column to this Genre table named SongsCount which will contain the number of songs in this genre. I can alter table to add a column, also create a query that will give the count of song,
SELECT GenreID, Count(SongID) FROM GenreSongs GROUP BY GenreID
Now, this gives us what we require, the number of songs per genre, but how can I use this query to update the column I made (SongsCount). One way is that run this query and see the results, and then manually update that column, but I am sure everyone will agree that's not a programmtic way to do it.
I came to think I would require to create a query with a subquery, that would get the value of GenreID from outer query and then count of its value from inner query (correlated query) but I can't make any. Can any one please help me make this?
A:
The question of how to approach this depends on the size of your data and how frequently it is updated. Here are some scenarios.
If your songs are updated quite frequently and your tables are quite large, then you might want to have a column in Genre with the count, and update the column using a trigger on the Songs table.
Alternatively, you could build an index on the GenreSong table on Genre. Then the following query:
select count(*)
from GenreSong gs
where genre = <whatever>
should run quite fast.
If your songs are updated infrequently or in a batch (say nightly or weekly), then you can update the song count as part of the batch. Your query might look like:
update Genre
set SongCnt = cnt
from (select Genre, count(*) as cnt from GenreCount gc group by Genre) gc
where Genre.genre = gc.Genre
And yet another possibility is that you don't need to store the value at all. You can make it part of a view/query that does the calculation on the fly.
Relational databases are quite flexible, and there is often more than one way to do things. The right approach depends very much on what you are trying to accomplish.
|
[
"stackoverflow",
"0035605285.txt"
] | Q:
Make http request from within a function - Node.js
i'm writing a Web Service in node and i'm new with callbacks concept.
I have in my routing file a route that receives url param - a Facebook access token, and should call the getMP function. This function creates http request to Facebook and retrieve some info I want to process later.
so the route looks like this:
//route that recives parameter using defined parameters - enter FB access token to get music info about it
app.get('/MP/:FBat',
function (req, res, next){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
},
function (req, res) {
res.status(200).json(FB.getMP(req.params.FBat));
});
and the function getMP :
exports.getMP = function(access_token) {
request("https://graph.facebook.com/v2.5/me/music?access_token=" + access_token, function(error, response, body) {
if (!error && response.statusCode == 200) {
FB_MP = JSON.parse(body);
// console.log(FB_MP); this returns ok
}else{
console.log(response.statusCode);
}
});
//return value - I wand to use it after the request has returned
return FB_MP;
}
What is the correct way of doing this? It works if the res is fast but of course its not good.
any advice ?
thanks
A:
You can use a library for promises like q and make the response after you get the necessary value inside the method then, try something like this:
//route that receives parameter using defined parameters - enter FB access token to get music info about it
app.get('/MP/:FBat',
function (req, res, next){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
},
function (req, res) {
FB.getMP(req.params.FBat)
.then(function(result){
if(result){
res.status(200).json(result);
}
else{
console.log('do something about it');
}
});
});
the code of getMP will be something like this:
var Q = requirie('q');
exports.getMP = function(access_token) {
var deferred = Q.defer();
request("https://graph.facebook.com/v2.5/me/music?access_token=" + access_token, function(error, response, body) {
if (!error && response.statusCode == 200) {
FB_MP = JSON.parse(body);
deferred.resolve(FB_MP);
}else{
deferred.resolve(false);
}
});
//return value - I wand to use it after the request has returned
return deferred.promise;
}
Also you can pass the req and res params to a kind of controller where you put the logic and then send the result to the view. Something like this:
//route that receives parameter using defined parameters - enter FB access token to get music info about it
var controller = require('path/to/controller');
app.get('/MP/:FBat',
function (req, res, next){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
},
function (req, res) {
controller.getFacebookAccess(req, res, req.params.FBat);
});
The controller:
module.exports = function getFacebookAccess(req, res, access_token){
request("https://graph.facebook.com/v2.5/me/music?access_token=" + access_token, function(error, response, body) {
if (!error && response.statusCode == 200) {
FB_MP = JSON.parse(body);
res.status(200).json(FB_MP);
}else{
res.send('do something about it');
}
});
}
};
|
[
"stackoverflow",
"0051744760.txt"
] | Q:
Find files with maxdepth 2 in Linux and move to respective folder
I have the following command to move files from one directory to another, which works fine.
find /volume1/backup/ -type f -mtime +365 -exec mv -v "{}" /usb1/backup/ \;
However, I've changed the directory structure in /backup to have subdirectories (one depth). Now I want to copy the files in those subdirs to their respective dirs on the /usb1 volume. I've already included -maxdepth 2 and -mindepth 2, but I'm clueless as what to do next...
find /volume1/backup/ -maxdepth 2 -mindepth 2 -type f -mtime +365 -exec mv -v "{}" /usb1/backup/ \;
A:
So, I haven't been able to find a short answer, but the following did the trick for me :
for d in $(find /volume1/backup/ -maxdepth 1 -mindepth 1 -type d)
do
for f in $(find $d -maxdepth 1 -type f -mtime +365 -print0 | sort -z | xargs -r0)
do
mv -v $f /usb1/backup/$(basename $d)/;
done
done
|
[
"stackoverflow",
"0060977858.txt"
] | Q:
Converting DateTime to Datetime? (null-coalescing?)
I've got a tiny problem. In my database my DateTime(?) has an auto property of null. I'm using the class RentalDTO() which has the property of DateTime? returnDate. Something like this:
public class RentalDTO
{
public DateTime? ReturnDate { get; set; }
public RentalDTO()
{
}
public RentalDTO(DateTime? returnDate)
{
ReturnDate = returnDate;
}
The question. How do I use my sql reader to convert my database DateTime to my RentalDTO DateTime?
public RentalDTO RentalDTOFromMySqlDataReader(MySqlDataReader reader)
{
RentalDTO rental = new RentalDTO(
Convert.ToDateTime(reader["returndate"]) // How to convert this? Convert.ToDateTime Does not work
);
return rental;
}
Convert.ToDateTime does not work. It gives an error.
A:
You should check the reader["returndate"] is null or not. then cast the value to a Nullable Datetime
public RentalDTO RentalDTOFromMySqlDataReader(MySqlDataReader reader)
{
DateTime? dateTime = string.IsNullOrEmpty(reader["returndate"]) ? (DateTime?)null : DateTime.Parse(reader["returndate"]);
RentalDTO rental = new RentalDTO(dateTime);
return rental;
}
|
[
"earthscience.stackexchange",
"0000007147.txt"
] | Q:
How is a UV Index calculated?
I have three parameters for a particular location, namely:
Ozone:- A numerical value representing the columnar density of total atmospheric ozone at the given time in Dobson units
Elevation: The elevation of the location in meters.
Cloud Cover: A numerical value between 0 and 1 (inclusive) representing the percentage of sky occluded by clouds.
Is it possible to calculate the UV index of that location using this information?
A:
The calculation of UV indices requires some effort.
Because different wavelengths of UV radiation have different effects on skin, to calculate the UV index you need to apply "McKinlay-Diffey" weighting factors to various wavelength components of UV radiation and then integrate (sum) those results and then divide by 25.
The procedure does not use ozone readings but it does use elevation and cloud cover.
The following two references list the procedure required:
Smithsonian Environmental Research Center
US EPA
NOAA-EPA Brewer Network
|
[
"stackoverflow",
"0055855487.txt"
] | Q:
AWS download file to s3 on a schedule
Right now I have a cron job that runs once a day. It pipes a curl command into a file, gzips that file, then uploads it to an s3 bucket. I'd like to move this off of my server and into aws tooling. What's the recommended way to do this currently? Make a lambda function and schedule it to run daily?
A:
The most cost effective option would be the one you describe :
create a lambda function that download your content, zip it and upload to S3.
Lambda functions have access to the host's file system (500 Mb in /tmp) and do not forget to delete the file afterwards. The container will be reused (in your account)
schedule a CloudWatch event to trigger the lambda function at regular time interval.
configure the lambda function to authorise CloudWatch Event to invoke your function
aws lambda add-permission --function-name my-function\
--action 'lambda:InvokeFunction' --principal events.amazonaws.com
--statement-id events-access \
--source-arn arn:aws:events:*:123456789012:rule/*
[UPDATE] : what if the file to download is 4Gb ?
In that case, you'll have two options. One with more work but more cost effective. One easier to implement but that might cost a bit more.
Option 1 : full serverless
You can design your AWS Lambda function to download the 4GB content and stream it to S3 by 5 Mb chuncks and compress chunck by chunck. I am not a compression expert, but I am sure it must be possible to find a library handling that for you.
The downside is that you need to write specific code, it will not be as easy as combining the AWS CLI and GZIP command line tool.
Option 2 : start an EC2 instance for the duration of the job
The scheduled Lambda function can use EC2's API to start an instance. The job script can be passed to the instance using userdata (a script the instance will execute at boot time). That script can call TerminateInstance when the job is done to kill itself and stop being charged for it.
The downside is that you will have to pay for the time this instance is running (you can have 750h/month for free of t2.micro instances)
The positive is that you can use standard command line tools such as AWS CLI and GZIP and you will have plenty of local storage for your task.
Here is how to start an instance from Python : https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.start_instances
|
[
"stackoverflow",
"0044002484.txt"
] | Q:
Electron pass BrowserWindow to external main function (not IPC)
I understand and can implement both IPC and .remote() from main <--> renderers.
This question is about an external function still in the main thread and sharing the instantiated BowerserWindow.
For example, main.js:
...
let mainWindow = null;
...
mainWindow = new BrowserWindow({
show: false,
width: 1024,
height: 728
});
...
I'm trying to access mainWindow from foo.js and can't seem to get there.
Psuedocode:
export default () => {
let win = mainWindow // from main.js;
win.webContents.send('toast', 'woohoo'); // Arbitrary Render side listener
}
A:
This works, although it seems like additional overhead as a lookup:
On main.js
foo(mainWindow.id)
On foo.js(id: number)
const win = BrowserWindow.fromId(id);
win.webContents.send('toast', 'woohoo');
I welcome any more efficient method.
|
[
"stackoverflow",
"0018045195.txt"
] | Q:
jQuery submit hidden form to database
In jQuery I get a variable from an api named "bank_account_uri" and I need to save this into my rails app User table. in the column customer_uri. However, I don't know how to get this information into my database in the correct way.
The API gave this as an example.
var bank_account_uri = response.data['uri'];
$('<input>').attr({
type: 'hidden',
value: bank_account_uri,
name: 'balancedBankAccountURI'
}).appendTo($form);
$form.attr({action: requestBinURL});
$form.get(0).submit(); }}
Any ideas?
A:
The example code they've provided seems pretty sound. To take through you through what it does:
var bank_account_uri = response.data['uri']; // Store the response in a variable
$('<input>').attr({ // Create an input
type: 'hidden', // make it hidden
value: bank_account_uri, // set its value to your bank_account_uri
name: 'balancedBankAccountURI' // give it a name, to pick up the server-side
}).appendTo($form); // Add it to a form, this doesn't exist
$form.attr({action: requestBinURL}); // Set url of where the post to
$form.get(0).submit(); }} // Submit the form
From this you'll need to add 2 extra variables:
1) A form variable/HTML element:
var $form = $("<form></form>").appendTo("body"); // Create & append to body
2) A URL of where to post the data to:
var requestBinURL = "/mypage";
I'd also remove the .get(0) part of the final line of code
|
[
"stackoverflow",
"0041799560.txt"
] | Q:
ngClipboard : expression value not getting replaced on copy
I have a copy to clipboard button on an error information tab which copies the error info. The error information is dynamically generated depending on which information is required. I have the error information generated in the form of an expression.
When I try to link the expression to data-clipboard-target the value is only stored statically, that is when close the first tab and open another one and click on copy it still reflects the previously copied information.
<div style="white-space:pre-wrap;" id="toCopy">
{{data[$index].text_mex}}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" ngclipboard ngclipboard-succes ="onSuccess(e);" ng-clipboard-error="onError(e);" data-clipboard-target="#toCopy">Copy to Clipboard</button>
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
{{data[$index].text_mex}} is the expression that is dynamically evaluated.
References: ngClipboard, ngClipboard Source
PS: I have added ngclipboard as a dependency.
A:
So, $index variable in Angular provides an offset for the ids and thus the elements are linked dynamically. Hope this is helpful for someone else :)
<div style="white-space:pre-wrap;" id="toCopy{{$index}}">
{{data[$index].text_mex}}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" ngclipboard ngclipboard-succes ="onSuccess(e);" ng-clipboard-error="onError(e);" data-clipboard-target="#toCopy{{$index}}">Copy to Clipboard</button>
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
|
[
"stackoverflow",
"0047911973.txt"
] | Q:
Acumatica - get the last displayed record
Is there an eloquent way, more or less, to get the last displayed record in a grid in Acumatica? Let's say even if they do all the sorting and rearranging, is there a way for example when pressing a button on a grid to get the last record? Basically, I would like to copy that record as a new one.
A:
Create a PXAction for your button.
Inside the PXAction iterate in your data view until the last record.
For example, if the name of your Data view Bound to your grid is YzLines, and object type in the grid line (DAC) is Yz, then it can be:
Yz lastLine;
foreach (Yz line in YzLines.Select())
lastLine = line;
To get to the last record you can also use .Last() or .LastOrDefault().
If you need the last record according to client sorting, you should implement a data view delegate, it looks like this:
protected virtual IEnumerable yzLines()
{
PXSelectBase<Yz> cmd =
new PXSelectJoinGroupBy<Yz, ...>(this);
int startRow = PXView.StartRow; //Get starting row of the current page
int totalRows = 0;
foreach (PXResult<Yz> res in
cmd.View.Select(null, null,
PXView.Searches,
ARDocumentList.View.GetExternalSorts(),//Get sorting fields
ARDocumentList.View.GetExternalDescendings(),//Get sorting direction
ARDocumentList.View.GetExternalFilters(),//Get filters
ref startRow,
PXView.MaximumRows, //Get count of records in the page
ref totalRows))
{
//processing of records
}
PXView.StartRow = 0;//Reset starting row
}
|
[
"stackoverflow",
"0007878444.txt"
] | Q:
Create new *package* in a Scala Compiler Plugin
In my quest to generate new code in a Scala compiler plugin, I have now created working classes. The next logical step is to put those classes in a new, non-existing package. In Java, a package is basically a directory name, but in Scala a package seems much more complicated. So far I haven't found/recognized an example where a compiler plugin creates a new package.
At my current level of understanding, I would think that I would need to create first a package symbol with:
parentPackage.newPackage(...)
// ...
and than later create a Tree for the package with PackageDef. But PackageDef doesn't take the symbol as parameter, as one would expect, and searching for:
Scala newPackage PackageDef
returned nothing useful. So it seems that I don't need to do those two steps together. Possibly one is done for my by the compiler, but I don't know which one. So far, what I have looks like this:
val newPkg = parentPackage.newPackage(NoPosition, newTermName(name))
newPkg.moduleClass.setInfo(new PackageClassInfoType(new Scope,
newPkg.moduleClass))
newPkg.setInfo(newPkg.moduleClass.tpe)
parentPackage.info.decls.enter(newPkg)
// ...
val newPkgTree = PackageDef(Ident(newPkg.name), List(ClassDef(...)))
A:
I think my answer to your other question should answer this one as well:
How to add a new Class in a Scala Compiler Plugin?
|
[
"serverfault",
"0000000710.txt"
] | Q:
How do I turn my DD-WRT router in to an access point?
I have a n-based router from Linksys with DD-WRT installed. I would like to turn this in to an access point because I already have a router/firewall installed on my network.
A:
The trick is to make sure DHCP is turned OFF in the router/access point so that your wireless clients get IPs from your existing router/firewall.
There are more details on the DD-WRT wiki but the main idea is that you set the WAN to "Disabled", Disable DHCP, and plug the AP into your network using one of the LAN ports instead of the WAN port (or use the "Assign WAN Port to Switch" feature).
You can actually do this with basically any Wireless router without DD-WRT using the same basic steps (disable DHCP, plug into LAN instead of WAN).
A:
You have a few options:
1) two networks, wired and wireless, routing between them:
You need to:
set up the wireless interface
start serving DHCP out over the wireless interface
and then you're mostly done. Note that while step 2 is fairly straightforward using dnsmasq, the difficult of step 1 can vary from 'trivial' to 'you need to reverse engineer the wireless drivers'. Giving you more instructions at the moment requires more info (model number & rev) of the Linksys router in question. There's a DD-WRT table of supported hardware that can probably help you.
Oh, and all this is presuming that your definition of 'access point' is something like 'a way to connect a machine with a wireless ethernet card to the network' as opposed to some kind of walled garden setup.
2) one network, using a LAN port to bridge from wired to wireless:
Turn off DHCP on the DD-WRT router
plug the AP into your network using one of the LAN ports instead of the WAN port
3) one network, using software to bridge from wired to wireless
Turn off DHCP
Read the DD-WRT page under 'LAN Uplink through WAN port'
|
[
"stackoverflow",
"0035356908.txt"
] | Q:
Linq items in a list exist in another list
I have 2 lists
List 1
var hashTags = new List<HashTag>();
hashTags.Add(new HashTag
{
Name = "#HashTag1",
Index = 1
});
hashTags.Add(new HashTag
{
Name = "#HashTag2",
Index = 2
});
hashTags.Add(new HashTag
{
Name = "#HashTag3",
Index = 3
});
hashTags.Add(new HashTag
{
Name = "#HashTag4",
Index = 4
});
List 2
var hashTags2 = new List<HashTag>();
hashTags2.Add(new HashTag
{
Name = "#HashTag1",
Index = 1
});
hashTags2.Add(new HashTag
{
Name = "#HashTag3",
Index = 3
});
hashTags2.Add(new HashTag
{
Name = "#HashTag4",
Index = 4
});
How do I check if all the elements in hashTags2 exist in hashTags? The index can be ignored and only the name matching is crucial. I can write a for loop to check element but I am looking for a LINQ solution.
A:
As only equality of the names is to be taken into account, the problem can be solved by first mapping to the names and then checking containment as follows.
var hashTags2Names = hashTags2.Select( iItem => iItem.Name );
var hashTagsNames = hashTags.Select( iItem => iItem.Name );
var Result = hashTags2Names.Except( hashTagsNames ).Any();
A:
Simple linq approach.
hashTags2.All(h=> hashTags.Any(h1 => h1.Name == h.Name))
Working Demo
|
[
"homebrew.stackexchange",
"0000000041.txt"
] | Q:
Why do red wines tend to be stored in green bottles and white wines not?
It seems that all red wines are stored in green or occasionally other dark coloured bottles and white wines in clear or light coloured bottles.
Why is this?
A:
The commonly repeated belief is that green bottles are better at keeping sunlight out and whites don't need this because they are often refrigerated. I never put much stock into this since worldwide refrigeration was not always common and a most wine is stored out of sunlight anyway.
A few winemakers in Sonoma told me that it was tradition based on the reasoning that reds were stored in darker bottles to hide the natural sediment that came along with those styles.
I don't know which, or if either, is true, but I'll tend to believe the tradition story over the UV-blocking reason.
A:
It's a combination of marketing and tradition. For better or worse you're average consumer expects white wine to come in a clear bottle.
This is not exclusive however, one example being Riesling which is traditionally bottled in brown glass.
Both white and red wine will change when exposed to light (Google "light struck wine" for plenty of interesting reading) but generally this is not as big an issue for white wine as it is usually drunk fairly young and stored cold.
|
[
"stackoverflow",
"0015199605.txt"
] | Q:
How should I handle the html output generated in my Play 2 app by default helper or twitterBootstrap helper
This is my template:
@(smsReviewForm: Form[SmsReview], grades: Seq[Grade])
@styles = {
}
@scripts = {
}
@import mobile.mobileMain
@import helper._
@mobileMain(Messages("reco.index.title"), styles, scripts) {
<div id="header">
<p class="floatleft"><img src="@routes.Assets.at("images/mobile/general/reco.png")" alt="Reco" /></p>
<div class="clear"></div>
</div>
@helper.form(routes.Sms.submit) {
@helper.inputText(
smsReviewForm("lastname"),
'_label -> "Label",
'_id -> "lastname"
)
<div class="actions">
<input type="submit" class="btn primary" value="Submit">
</div>
}
}
When using the regular @import helper._ the html generated in my app looks like the example in the play 2.1 documentation:
<dl class=" " id="lastname_field">
<dt><label for="lastname">Label</label></dt>
<dd>
<input type="text" id="lastname" name="lastname" value="">
</dd>
<dd class="info">Required</dd>
</dl>
If I use @import helper.twitterBootstrap._ it looks like:
<div class="clearfix " id="lastname_field">
<label for="lastname">Label</label>
<div class="input">
<input type="text" id="lastname" name="lastname" value="">
<span class="help-inline"></span>
<span class="help-block">Required</span>
</div>
I'm not used the dd hml type of implementation and the twitter bootstrap stuff looks more like the structure I'm used to work withm but I'm not interested in implementing the bootstrap js and css. So my question is what is your thoughts on this.
What have you used? Maybe you use your own implementation for the html rendering?
A:
You should create your own field constructor in order to specify your rendering style.
Look at the official documentation here for the "Writing your own constructor" part:
http://www.playframework.com/documentation/2.1.0/ScalaFormHelpers
Therefore, instead of importing the basic helpers._ or the default bootstrap field constructor helper.twitterBootstrap._, you would import MyOwnHelpers._ refering to your template.
The whole is well explains in the doc :)
For more information, here an example of one field constructor I've created:
Of course, you are free to not use boostrap, I precise. In my case, I did.
twitterBootstrapInput.scala.html
<div class="control-group @if(elements.hasErrors) {error}">
<label class="control-label" for="@elements.id">@elements.label</label>
<div class="controls">
@if(elements.args.contains(Symbol("data-schedule"))){
<div class="schedulepicker input-append">
@elements.input
<span class="add-on">
<i data-time-icon="icon-time" data-date-icon="icon-calendar"></i>
</span>
</div>
} else {
@elements.input
}
<span class="help-inline">@elements.errors.mkString(", ")</span>
</div>
</div>
and its import within my concerned xx.scala.html file:
@implicitFieldConstructor = @{ FieldConstructor(twitterBoostrapInput.f) }
|
[
"stackoverflow",
"0006231209.txt"
] | Q:
Rails: whenever + delayed_job to optimize rake tasks?
I use whenever to call rake tasks throughout the day, but each task launches a new Rails environment. How can I run tasks throughout the day without relaunching Rails for each job?
Here's what I came up with, would love to get some feedback on this...?
Refactor each rake task to instead be a method within the appropriate Model.
Use the delayed_job gem to assign low priority and ensure these methods run asynchronously.
Instruct whenever to call each Model.method instead of calling the rake task
Does this solution make sense? Will it help avoid launching a new Rails environment for each job? .. or is there a better way to do this?
--
Running Rails 3
A:
You could certainly look into enqueuing delayed_jobs via cron, then having one long running delayed_job worker.
Then you could use whenever to help you create the delayed_job enqueuing methods. It's probably easiest to have whenever's cron output call a small wrapper script which loads active_record and delayed_job directly rather than your whole rails stack. http://snippets.aktagon.com/snippets/257-How-to-use-ActiveRecord-without-Rails
You might also like to look into clockwork.rb, which is a long-running process that would do the same thing you're using cron for (enqueuing delayed_jobs): http://rubydoc.info/gems/clockwork/0.2.3/frames
You could also just try using a requeuing strategy in your delayed_jobs: https://gist.github.com/704047
A:
Lots of good solutions to this problem, the one I eventually ended up integrating is as such:
Moved my rake code to the appropriate models
Added controller/routing code for calling models methods from the browser
Configured cronjobs using the whenever gem to run command 'curl mywebsite.com/model#method'
I tried giving delayed_job a go but didn't like the idea of running another Rails instance. My methods are not too server intensive, and the above solution allows me to utilize the already-running Rails environment.
|
[
"unix.stackexchange",
"0000567869.txt"
] | Q:
Why am I getting different outputs from parted and fdisk?
note: I am a Linux beginner, and trying to learn from the following book: How Linux Works
Running parted -l I get:
Model: KBG30ZMV256G TOSHIBA (nvme)
Disk /dev/nvme0n1: 256GB
Sector size (logical/physical): 512B/512B
Partition Table: gpt
Disk Flags:
Number Start End Size File system Name Flags
1 1049kB 538MB 537MB fat32 EFI System Partition boot, esp
2 538MB 256GB 256GB ext4
While running fdisk-l I get:
Disk /dev/loop0: 137,9 MiB, 144527360 bytes, 282280 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk /dev/loop1: 612,3 MiB, 642023424 bytes, 1253952 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk /dev/loop2: 120,4 MiB, 126201856 bytes, 246488 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk /dev/loop4: 89,1 MiB, 93417472 bytes, 182456 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk /dev/loop5: 91,3 MiB, 95748096 bytes, 187008 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk /dev/loop6: 612,1 MiB, 641851392 bytes, 1253616 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk /dev/loop7: 171,6 MiB, 179875840 bytes, 351320 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk /dev/nvme0n1: 238,5 GiB, 256060514304 bytes, 500118192 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: BCB099F2-0FCD-4A90-83C2-A76C3E49682D
Device Start End Sectors Size Type
/dev/nvme0n1p1 2048 1050623 1048576 512M EFI System
/dev/nvme0n1p2 1050624 500117503 499066880 238G Linux filesystem
Disk /dev/loop8: 134,1 MiB, 140652544 bytes, 274712 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Another thing I noticed when running lsblk -a:
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
loop0 7:0 0 137,9M 1 loop /snap/code/24
loop1 7:1 0 612,3M 1 loop /snap/intellij-idea-community/202
loop2 7:2 0 120,4M 1 loop /snap/docker/423
loop3 7:3 0 1 loop
loop4 7:4 0 89,1M 1 loop /snap/core/8268
loop5 7:5 0 91,3M 1 loop /snap/core/8592
loop6 7:6 0 612,1M 1 loop /snap/intellij-idea-community/208
loop7 7:7 0 171,6M 1 loop /snap/microk8s/1173
loop8 7:8 0 134,1M 1 loop /snap/code/25
nvme0n1 259:0 0 238,5G 0 disk
├─nvme0n1p1 259:1 0 512M 0 part /boot/efi
└─nvme0n1p2 259:2 0 238G 0 part /
I have a basic understanding of the difference between creating partitions with fdisk vs. parted; however, I am curious about: Why do I get a different output (and partition sizes) between fdisk and parted?
my system information running uname -a:
Linux 5.3.0-28-generic #30~18.04.1-Ubuntu SMP Fri Jan 17 06:14:09 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
A:
Outputs from parted and fdisk are somewhat different but not contradictory.
parted shows values expressed in units you see in its output (kB, MB, GB).
fdisk shows values expressed in physical sectors which in your case are of the size 512 bytes.
The latter values are strict. Their granularity is one sector. You do not need better granularity (e.g. in bytes) because partitions cannot start in the middle of a sector or contain fractional number of sectors. You can recalculate the values to bytes is you want.
Values expressed in units like kB or MB not only are rounded, but there is an ambiguity: see Is it true that 1 MB can mean either 1000000 bytes, 1024000 bytes, or 1048576 bytes? Because of this ambiguity the size of 256GB (from parted) and 238G (from fdisk) are both "right", only they use different units.
Take the strict size of /dev/nvme0n1p2, it's 499066880 sectors. Multiply by the sector size (512 bytes). The result is 255522242560. Divide by 109 and round the result. You get 256.
Now take 255522242560, divide by 10243 and round the result. You get 238.
|
[
"stackoverflow",
"0035499477.txt"
] | Q:
Is it possible to have options on select change from when other select changes without javascript
There are a bunch of question on this but no answers on how to do it without javascript.
If you have one form that has 2 select boxes. The second select box has different options based on what you choose for the first select box. Here is a js example. Not all users have js enabled so for these users this option would be unavailable.
Can this be achieved solely using CSS3, HTML5 and Ruby? I would show what I've got so far in trying this but I got nothing.
A:
What you are asking is how to manipulate the DOM after it has loaded without a client-side scripting language. This is not possible as far as I am aware; unfortunately that is not what you want to hear.
The proper solution in this case would be to have the user submit the page and generate the second selection box at that time. You will have to rely entirely on server-side logic to handle the problem. So basically something like:
Serve a page with just a single selection box
When the page is posted generate a similar page where the first selection is locked and display a second selection box with the possible options.
Continue the iteration until you have all of the required selections filled out by the user.
Serve the result that the user requested.
|
[
"japanese.stackexchange",
"0000062172.txt"
] | Q:
Problem with 大きくなって
I'm translating a letter and came across this sentence:
今{いま}よりもっと[大きく]{おおきく}なって...
I'm having problems understanding the grammar used here. I know this means "When I get bigger" or "When I grow up" after reading English translations.
Why is より being used?
When I look for おおきく on the dictionary it translates to "on a grand scale" and I'm not sure this is correct.
A:
より is a comparative term. So 今+より = compared to now/~than now, inferring "further along in time", or in this case "when I/you get older/bigger" as modified by "大きくなって"
As for "大きくなって", this is the い-adj. 大きい (meaning "big, large") that when used to modify a verb, the final い is changed to く (becoming the adverbial form) and added to the verb.
The confusion may lie in that we're taught that 大き is a な-adjective, so you would never see 大きく. But the reality is that 大きい also exists and is used that way. The only thing that keeps me sane is the ”すずめの兄弟” song that has a repeating phrase of "...大きくなったら何になる?” It was very popular in Japan when I was a beginning 日本語 student in Tokyo. It was hard to escape as it flooded the airwaves for nearly a year. So I suppose that I was just beaten into submission... Once you hear the song you'll never be able to unhear it. Try it. It will fix your dilemma.
|
[
"rpg.stackexchange",
"0000068323.txt"
] | Q:
Can "normal" Hermetic Magi take virtues from Realms of Power: Magic?
Page 43 of Realms of Power: Magic starts a list of new Virtues & Flaws for "when designing magic characters or characters that are somehow associated with the realm of Magic". Hermetic magi are usually taken to be associated with the realm of Magic, so are they permitted to take these virtues and flaws?
Some of the virtues and flaws are clearly only appropriate for Magical Companions; but others, particularly the Hermetic ones, seem to be appropriate for any magi.
A:
The beginning of the chapter that you are referring to, RoPM page 29, says that those rules, including the Virtues and Flaws, are for magical characters who have a Magical Might Score.
Since most magi are "merely aligned with the realm of Magic" they would not be permitted to take those virtues and flaws. However, it does state that characters with the Transformed (Being) Virtue would have a Magical Might Score and would be able to take other virtues and flaws from the chapter.
|
[
"physics.stackexchange",
"0000156364.txt"
] | Q:
Proof of the relation $d^4 \xi = \sqrt{|g|} \,\, d^4x$ switching between local and non-inertial coordinates
Denoting with $d\xi^m$ and $dx^\mu$ respectively flat and non-inertial coordinates, we have the following relation between the volume elements in the two coordinate systems:
$$ d^4 \xi = \sqrt{|\det g_{\mu\nu}|} \,\, d^4 x \equiv \sqrt{|g|}\,\, d^4 x. $$
How is this relation proven?
A:
You learned in calculus that for a variable change $x\longrightarrow \bar x$ we have
$$d^nx=J\,d^n\bar{x}$$
where
$$J=\left|\frac{\partial x}{\partial \bar{x}}\right|$$
Look at the transformation law for the metric under the same coordinate transformation:
$$\bar{g}(\bar{x})=\left(\frac{\partial x}{\partial \bar{x}}\right)^Tg(x)\left(\frac{\partial x}{\partial \bar{x}}\right)$$
Taking the determinant, we get
$$\bar{g}=gJ^2$$
Then
$$\sqrt{g}d^nx=J\sqrt{g}d^n\bar x=J\sqrt{\frac{\bar{g}}{J^2}}d^n\bar x=\sqrt{\bar{g}}d^n\bar x$$
For a flat system we have $g=-1$. Insert a negative to make the root(s) well-defined. Thus
$$d^n\xi=\sqrt{-g}d^nx$$
EDIT: Let the components of the metric be $g_{ij}$.The usual transformation rule for a (0,2) tensor is
$$\bar{g}_{ij}(\bar x)=g_{mn}(x)\frac{\partial x^m}{\partial\bar x^i}\frac{\partial x^n}{\partial\bar x^j}$$
Denote the matrix with components $\partial x^m/\partial\bar x^i$ by $K$.Then $\bar{g}=K^T gK$. We have to use a transpose because $\partial x^m/\partial\bar x^i=K_{mi}$. Thus
$$(K^TgK)_{ij}=(K^T)_{im}g_{mn}K_{nj}=g_{mn}K_{mi}N_{ni}=g_{mn}\frac{\partial x^m}{\partial\bar x^i}\frac{\partial x^n}{\partial\bar x^j}=\bar{g}_{ij}$$
I didn't pay much attention to index placement.
|
[
"stackoverflow",
"0005031843.txt"
] | Q:
Visual Studio 2008: Keeping vertical space between tags when code formatting HTML
Quite new to Visual Studio, more of a PHP/Eclipse person.
I prefer to have lots of white space in my markup - it makes it easier to edit, I find.
However, when I format the markup with CTRL K CTRL D, VS2008 strips out all vertical whitespace (ie, newlines) between my tags.
Is there a setting to prevent this and only indent my markup?
I have not been able to find anything online that seems to address this, neither is there a previous question that I could find.
Thanks in advance,
G
A:
Found the answer: the settings for empty lines before and after HTML tags are, infuriatingly, tag-specific. So I've had to set it in several places.
You don't quite have to do it for each particular tag, though, there are four kinds you have to set it for.
For your information, Tools -> Options -> Text Editor -> HTML -> Format -> Tag Specific Options -> Default Settings and then the four types are listed under there. Select your value from the 'Line breaks' dropdown and click OK when done. The CTRL K, CTRL D will add lots of vertical whitespace as desired.
Thanks if you've been looking at this, and I hope this helps others.
G
|
[
"stackoverflow",
"0018153344.txt"
] | Q:
EditText getText() returns different value then what is displayed
I have been developing android for a while now and have never come across this before so im hoping some one here can help. I have multiple EditText's and autocompleTextViews that populate themselves from sharedprefs. The problem is that the views are not displaying the text they should be. They display the old value that was there until i leave the activity and come back. The strange part is that if i call the getText function on the editText when it has the wrong value displayed getText() returns the correct value. Can someone please explain why this might be.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
view = inflater.inflate(R.layout.extra_info, container, false);
myPrefs = PreferenceManager
.getDefaultSharedPreferences(getActivity());
initPrefs();
findTextViews();
findViews();
initDataSource();
runQueries();
getAllFields();
return view;
}
private void findViews() {
EditPayID = (AutoCompleteTextView)view.findViewById( R.id.EditpayID );
EditPayID.setText(PayIDPref);
Log.e("findviews",EditPayID.getText().toString());
//^^ correct value but screen still displays wrong value
}
private void initPrefs(){
editor = myPrefs.edit();
PayIDPref = myPrefs.getString("PayID", "");
Log.e("payidPref", PayIDPref);
}
The following code I think is unrelated to the problem but maybe I am missing something
this is all of the code associated with payID
EditPayID.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
EditPayID.showDropDown();
EditPayID.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
String selected = EditPayID.getAdapter().getItem(arg2).toString();
EditPayID.setText(selected);
editor.putString("PayID" ,selected);
editor.apply();
}
});
return false;
}
});
EditPayID.setValidator(new android.widget.AutoCompleteTextView.Validator() {
@Override
public boolean isValid(CharSequence text) {
Log.e("in pay isValid" , "validating");
Collections.sort(validPays);
if (Collections.binarySearch(validPays, text.toString()) >= 0){
return true;
}
return false;
}
@Override
public CharSequence fixText(CharSequence invalidText) {
EditPayID.setError("You have Entered invalid PayID");
editor.putString("PayID" ,"Invalid PayID");
editor.apply();
return "Invalid PayID";
}
});
A:
I solved it by calling finsViews() and initPrefs() in my onResume() Method. Although I am not sure why this solved the issues seeing that these two methods were being called from the oncreate whenever I cam to the Fragment. If someone could explain this further It'd be greatly appreciated
|
[
"softwareengineering.stackexchange",
"0000379565.txt"
] | Q:
Preexisting culture issues during Scrum transition
My team has been trying to transition to Scrum for some time now, but it seems like the preexisting culture is preventing the team from switching to a new mindset or even causing it to move in the opposite direction.
For reference, the team has two line managers, a project manager, a product owner, and five developers.
Developers never have direct contact with the product owner. Although it could be argued the line managers fill that role since they define the work for the team, that is denied by PM.
The project manager insists she is the 'Scrum leader'.
PM also insists line managers are part of the Dev Team since all Agile teams have a "Team Lead" role, and direct supervision of the work by LMs is fine since they are the technical leads after all, which is a valid Scrum role.
PM also insists daily standups serve as a reporting tool.
Daily stand-ups are run by LMs who use it to track daily progress, supervise each individual developer, comment on their approach, and assign new tasks.
1-3 days per user story is taken as a hard limit per user story by LMs instead of a breakdown guideline. If a developer exceeds 2 days on a user story he receives an email about how a developer is responsible for delivering on a deadline.
LMs insist collective ownership means there should be an individual per feature responsible for its development.
Bonus:
When I brought up these points in an impromptu way at a meeting, I was pretty much told I was silly for suggesting to remove the LMs from the development process since they were the ones with the business knowledge, or making suggestions since I was new.
A few hours after I sent out an email to the LMs with the devs CCed summarizing the points I made citing relevant articles, I received an email CCing all people in that email about an issue with a feature I have been working on and how it was taking too long.
Is there anything I can do in this situation to help the team as a developer transition to a Scrum mindset and avoid breaking the morale of the team due daily monitoring and supervision resulting from this that takes as much as 10-15% of the work week?
A:
Focus on individual problems rather than methodologies, and get everyone involved.
Rather than jumping straight in and proposing changes, start by suggesting that the team holds regular retrospective meetings every few weeks where the objective is to discuss what's going well, what isn't going well, and what could be improved. This should be the starting point for identifying specific problems to be solved, as well as deciding whether the problems are worth solving and putting forward suggestions for possible remedial action.
Retrospectives are a chance for everybody in the team (including stakeholders and people responsible for delivery) to have an honest, open-air discussion about what the team is currently doing well, and the things which are causing pain or problems. This doesn't just include process/human problems, it may be that there are persistent technical problems or technical solutions too. It's a matter for the team as a whole to discuss whether the problem identified really need solving or whether it's something the team can live with, or it may be that the problem exists entirely outside of the team's control and it may need to be escalated upwards.
For example, if you're saying that developers are not given the opportunity to provide estimates for the work to be completed, it might be a case that technical risks may not be getting identified as quickly as they otherwise might be, or that the estimates being provided may not be realistic.
It's a matter for the team as a whole to discuss these and to decide whether these are real problems which have a real impact on the delivery of the software; if the team agree that these are problems which need solving, then everybody in the team also has an opportunity to suggest improvements, and for the person/people responsible for delivery of the software to listen and raise their concerns too - ultimately they are the ones who bear responsibility if anything goes wrong so their involvement is critical.
Remember that a methodology shouldn't be the goal, the goal should be to have a development process which allows the team to manage risk effectively, to respond to the demands of the business in the best way possible given whatever constraints exist around the team, and just to get working software delivered which meets everybody's expectations.
|
[
"wordpress.stackexchange",
"0000126208.txt"
] | Q:
Where do I go to change the position of the style.css?
My CSS style.css file is in my theme folder. I would like to put it in a CDN. How do I change the link element that loads the css?
I am using as a base the 2013 wordpress theme.
A:
Add the following code to themes functions.php file. Replace 'http://cdn.something.com/something.css' to your stylesheet file uri on CDN.
add_filter('stylesheet_uri', 'my_custom_stylesheet_location');
function my_custom_stylesheet_location( $stylesheet_uri ){
return 'http://cdn.something.com/something.css';
}
|
[
"stackoverflow",
"0041086116.txt"
] | Q:
Custom Radio Button Gallery
Hello there I have next code and is only one problem
when input is checked its not image left in li where is checked the input
I try few ways to fix this like setup same img on each li same like a
label but got other problems than :) is anyone can give some ideas?
.test2{
width: 110px;
height: 110px;
display: block;
position: fixed;
top: 10px;
background: url(images/animal-small.jpg) no-repeat;
}
.test3{
width: 110px;
height: 110px;
display: block;
position: fixed;
top: 10px;
background: url(images/animal-small3.jpg) no-repeat;
}
.test{
width: 110px;
height: 110px;
display: block;
position: fixed;
top: 10px;
background: url(images/animal-small2.jpg) no-repeat;
}
input{
visibility: hidden
}
input:checked + label{
padding: 10%;
position: fixed;
top:150px;
left: 150px;
display: block;
background-size: 400px , 400px;
border: 1px solid black
}
li{
display: inline-block;
list-style: none;
width: 110px;
height: 110px;
}
li :hover{
cursor: pointer;
background-size: 110px 110px
}
<body>
<ul>
<li>
<input type="radio" name="test" value="" id="test">
<label for="test" class="test"></label>
</li>
<li>
<input type="radio" name="test" value="" id="test2">
<label for="test2" class="test2"></label>
</li>
<li>
<input type="radio" name="test" value="" id="test3">
<label for="test3" class="test3"></label>
</li>
</ul>
</body>
A:
UPDATE
OP request is to have a thumbnail image and the enlarged image for a more intuitive navigation of the gallery. Changed the layout a little and adjusted the CSS to accommodate the extra element (<figure>.)
Avoid repeating code, condense styles together.
when input is checked its not image left in li
I suspect the urls are not pointing to the image files. A slightly adapted version in the following Snippet is successful displaying pictures.
SNIPPET
.test1,
.test2,
.test3 {
width: 110px;
height: 110px;
display: block;
position: fixed;
top: 10px;
cursor: pointer;
}
.test1 {
background: url(http://placehold.it/50x50/000/fff?text=1) no-repeat;
}
.test2 {
background: url(http://placehold.it/50x50/00f/eee?text=2) no-repeat;
}
.test3 {
background: url(http://placehold.it/50x50/0e0/111?text=3) no-repeat;
}
input,
input + figure.img {
display: none;
}
input:checked + figure.img {
padding: 10%;
position: fixed;
top: 150px;
left: 150px;
display: block;
background-size: 400px, 400px;
border: 1px solid black
}
li {
display: inline-block;
list-style: none;
width: 110px;
height: 110px;
}
li:hover {
background-size: 110px 110px
}
<body>
<fieldset>
<ul>
<li>
<label for="test1" class="test1">
<input type="radio" name="test" value="" id="test1">
<figure class='img test1'></figure>
</label>
</li>
<li>
<label for="test2" class="test2">
<input type="radio" name="test" value="" id="test2">
<figure class='img test2'></figure>
</label>
</li>
<li>
<label for="test3" class="test3">
<input type="radio" name="test" value="" id="test3">
<figure class='img test3'></figure>
</label>
</ul>
</fieldset>
</body>
|
[
"stackoverflow",
"0016737250.txt"
] | Q:
How can I put a video into a canvas?
Since yesterday, I tried to find out a solution to put a video into canvas, but it's a canvas which has a specific shape like this one : http://letsdunkit.com/so/rectangle.html
I saw a lot of tutorials who talked about "drawImage" but that's not what I want or perhaps I'm wrong and I didn't use it correctly.
Any ideas ?
Thank you
A:
You can use drawImage with a <video> element argument to draw the currently displayed frame of the video:
<video id="myvideo" src="..."></video>
<canvas id="mycanvas"></canvas>
...
// in a <script>...
var myvideo = document.getElementById("myvideo");
var mycanvas = document.getElementById("mycanvas");
myvideo.play();
// assuming video is loaded (otherwise it won't have any frames to be drawn yet)
mycanvas.getContet("2d").drawImage(myvideo);
If you play the video and make drawImage calls repeatedly, you can show a series of images from the video as it plays.
O'Reilly has a complete tutorial on how to accomplish this.
|
[
"money.stackexchange",
"0000030095.txt"
] | Q:
What is the added advantage of a broker being a member of NFA in addition to IIROC
If my broker is a member of the national futures association, what extra protection does it give me over the fact that it is also a member of IIROC? I am particularly referring to this:
http://www.oanda.com/corp/story/regulatory
A:
This shows that in each market (US and Canada) the company is registered with the appropriate regulatory organization.
OANDA is registered in the US with the National Futures Association which is a "self-regulatory organization for the U.S. derivatives industry".
OANDA Canada is registered in Canada with IIROC which is the "Investment Industry Regulatory Organization of Canada".
The company does business in both the US and in Canada so the US arm is registered with the US regulatory organization and the Canadian arm is registered with the Canadian regulatory organization.
|
[
"stackoverflow",
"0002409217.txt"
] | Q:
Windows service Null ReferenceException
I built a windows service on my local machine. when I install and run it locally it works perfectly fine. When I try to move it to my production machine I get a null reference exception error.
I've created an installation package that also works perfectly fine on my machine, but when i run it on the production machine the service still fails.
The service references a .dll that in turn has references to 3 other dlls. when i build the project it pulls all of the dlls into the debug folder for the project... I've even installed the service from that folder and it works localy on my machine.
I know this has to have something to do with the references, but this is beyond me. Any tips/hints would be appreciated.
A:
if you take a look at the comments you'll see what the issue was.
|
[
"stackoverflow",
"0028857082.txt"
] | Q:
Hawtio Camel 2.8.0-fuse-07-16 no trace messages
HawtIO shows the trace tab for my camel context, and when I run trace it shows messages counting up on the diagram. However, I never see any messages in the message table at the bottom. I'm using Camel 2.8.0-fuse-07-16. Thanks for any help.
A:
You need a newer version of Camel to support tracing from hawtio. I think you would need the Camel version from JBoss Fuse 6.0 or better.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.