text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
How to collapse a categorical variable into less elements in R
Suppose I have a categorical variable such like:
set.seed(123)
x<-sample(c("I", "IA", "IB", "II", "IIB", "IIC", "III", "IIID", "IIIF", "XA", "XB", "XC"),
100, TRUE)
table(x, exclude=NULL)
# x
# I IA IB II IIB IIC III IIID IIIF XA XB XC <NA>
# 5 12 9 7 9 11 6 8 6 12 9 6 0
My question is how to easily collapse x into four elements, e.g. I, II, III and X? E.g. combining I, IA, IB into I etc.
A:
Here's one option:
table(gsub("[^I]", "", x))
# I II III
# 33 34 33
This replaces all characters that are not I from your vector and then computes its frequencies.
Or, to change x:
x <- gsub("[^I]", "", x)
A:
More generally, if your categorical variables aren't grouped by such patterns, you can specify a mapping using case_when from dplyr:
y <- case_when(x %in% c("I", "IA", "IB") ~ "I", #or whatever conditions you want
x %in% c("II", "IIA", "IIB") ~ "II", #as above
TRUE ~ "III")
table(y)
I II III
33 24 43
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Error while creating own linked list
I'm trying to create a program that reads from a text file and stores the words into a singly linked list. I'm supposed to create my own linked list as opposed to using the STL. I've tried looking up a fair number of tutorials, but I keep getting an error on the variable "head." It says "a value type of Node cannot be used to initialize an entity of type Node"
This is List.cpp:
#include "List.h"
#include "Node.h"
#include <iostream>
using namespace std;
void List::add(string s){
Node* newNode = new Node();
newNode->addString(s);
newNode->setNext(NULL);
Node *temp = head;
if(temp != NULL)
{
while(temp->Next() != NULL)
{
temp = temp->Next();
}
temp->setNext(newNode);
}
else
{
head = newNode;
}
}
void List::print(){
Node *temp = head;
if(temp == NULL)
{
cout<<"EMPTY"<< endl;
return;
}
if(temp->Next() == NULL)
{
cout<<temp->Word();
cout<< "-->";
cout<< "NULL" << endl;
}
else
{ do{
cout<<temp->Word();
cout<<"-->";
temp = temp->Next();
}
while( temp != NULL);
cout << "NULL" << endl;
}
}
void List::read(ifstream& fin){
while(!fin.eof())
{
fin>>sTemp;
add(sTemp);
}
}
This is Node.h
using namespace std;
#include <string>
class Node
{ string val;
Node* next;
public:
Node(void){}
Node(string s)
{
val = s;
next = nullptr;
}
void addString(string aString){ val = aString;};
void setNext(Node* aNext){next = aNext;};
string Word(){return val;};
Node* Next(){return next;};
string sTemp;
};
This is List.h
#include <string>
#include <fstream>
#include "Node.h"
using namespace std;
class List{
Node* head;
public:
List()
{
head = NULL;
}
void print();
void add(string s);
void find(string key);
void read(ifstream& fin);
string sTemp;
}
Under the actual List.cpp, it gives me an error when I say Node *temp = head; with the aforementioned error. Any reason why and how can I fix this?
A:
Part of the problem here is that in List.cpp you've included Node.h twice.
directly includes List.h which itself includes Node.h
directly includes Node.h
I'm surprised that the compiler didn't warn you about this. It seems instead that it chose to redefine Node hence you end up with two Node values which aren't compatible. You need to add include guards to your header files to prevent double includes
List.h
#if !LIST_H
#define LIST_H
...
#endif
Node.h
#if !NODE_H
#define NODE_H
...
#endif
Also note that it's generally speaking considered bad practice to have using statements in header files. Instead use namespace qualified names in headers and put the using statements into the .cpp files.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Tripping with a Natural attack that has Grab
The Grab special says:
If a creature with this special attack hits with the indicated attack (usually a claw or bite attack), it deals normal damage and attempts to start a grapple as a free action without provoking an attack of opportunity.
If you use that attack to make a Trip instead, does this trigger the free grapple check?
A:
A creature with the special ability grab cannot use that ability if it makes a trip attempt
The special ability grab says, in part, that
If a creature with this special attack hits with the indicated attack (usually a claw or bite attack), it deals normal damage and attempts to start a grapple as a free action without provoking an attack of opportunity.
Pathfinder says that natural attacks
fall into one of two categories, primary and secondary attacks. Primary attacks are made using the creature's full base attack bonus and add the creature's full Strength bonus on damage rolls. Secondary attacks are made using the creature's base attack bonus −5 and add only 1/2 the creature's Strength bonus on damage rolls.
A creature making a trip attempt—even if making that trip attempt with a natural weapon—is not making an attack with the "indicated attack" in the creature's statistics block as required by the special ability grab. The creature's instead making a trip attempt.
Because of the vast amount of material available for Pathfinder, I'm certain there are creatures with attacks that are exceptions to this, but in general this holds true for the grab special ability. The grab special ability usually won't activate on a trip, much like it also wouldn't activate on a successful disarm, reposition, sunder, or initial grapple attempt.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Scala implicit conversion blocked somehow
I wrote a small service with Scalatra that does two things:
serve JSON data
serve same data as an Excel sheet
JSON is done with spray-json, Excel - with apache POI
Basically, I wrote two methods in my ScalatraServlet implementation:
def serveJson[T: JsonWriter](data: T) = {
contentType = "text/json"
data.toJson.prettyPrint
}
def serveExcel[T: ExcelWriter](data: T) = {
contentType = "application/excel"
data.toExcel.getBytes
}
Here, toJson is implemented with spray-json, so I just provide a JsonWriter implicit conversion. So I decided to write a similar toExcel conversion.
// ExcelWriter.scala
package com.example.app.excel
import org.apache.poi.hssf.usermodel.HSSFWorkbook
import annotation.implicitNotFound
@implicitNotFound(msg = "Cannot find ExcelWriter type class for ${T}")
trait ExcelWriter[T] {
def write(obj: T): HSSFWorkbook
}
object ExcelWriter {
implicit def func2Writer[T](f: T => HSSFWorkbook): ExcelWriter[T] = new ExcelWriter[T] {
def write(obj: T) = f(obj)
}
}
// Imports.scala
package com.example.app.excel
import org.apache.poi.hssf.usermodel.HSSFWorkbook
object Imports {
type ExcelWriter[T] = com.example.app.excel.ExcelWriter[T]
implicit def pimpAny[T](any: T) = new AnyExcelPimp(any)
private[excel] class AnyExcelPimp[T](any: T) {
def toExcel(implicit writer: ExcelWriter[T]): HSSFWorkbook = writer.write(any)
}
}
Now, the problem is:
If I import import cc.spray.json._, then import excel.Imports._, scalac throws error in serveJson (value toJson is not a member of type parameter T)
If I import import excel.Imports._, then import cc.spray.json._, scalac throws analogous error in serveExcel (value toExcel is not a member of type parameter T)
Surprisingly, if I use only one of the imports, everything compiles and works just fine (well, half of it, since I comment out the half, that uses removed import).
What is wrong with my implementation?
Link to spray-json source, which I used as a reference: https://github.com/spray/spray-json/tree/master/src/main/scala/cc/spray/json
Scala version - 2.9.2
A:
The problem seems to be that I used the same name for implicit conversion as the one used in spray-json: pimpAny.
// my implicit
implicit def pimpAny[T: ExcelWriter](any: T) = new AnyExcelPimp(any)
// spray-json implicit
implicit def pimpAny[T](any: T) = new PimpedAny(any)
So a simple rename solved the problem.
Still, kinda strange to not see the root problem but its result at compile time. Guess I'm to sleepy...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Images are rendering in a different ratio than it should - Phonegap in Android
I'm developing an Android App using PhoneGap, but I found a problem very soon.
Whenever I insert a image (background or image tag), it shows bigger than it should be.
I initially thought this was my emulator issue, presenting my app in a different ratio, but it wasn't! I took a screenshot, and the width of my viewport is 540, just like I defined in the AVD.
As you can see in the screenshot below, in my HTML I did set a image tag, forcing width to 69, and height to 70 (the real dimensions of my source image).
But it always renders bigger!
The label "original source image" points to the real image I dragged from it's directory to the screenshot, just to prove they're very different.
A:
In an android project there are different folders where you put drawables (images). These are called xdpi hdpi mdpi ldpi. I dont know how PhoneGap works but you should be able to tell phonegap in which folder to put the image. Here is someone who specified device dpi in a meta tag, maybe you can try this: http://wiki.phonegap.com/w/page/32771298/Android%20High%20Pixel%20Density%20App
Metatag
<meta name="viewport" content="width=device-width; target-densityDpi=device-dpi; initial-scale=1; maximum-scale=1; minimum-scale=1; user-scalable=0" />
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Imports failing in VScode for pylint when importing pygame
When importing pygame pylint is going crazy:
E1101:Module 'pygame' has no 'init' member
E1101:Module 'pygame' has no 'QUIT' member
I have searched the net and I have found this:
"python.linting.pylintArgs": ["--ignored-modules=pygame"]
It solves the problem with pygame, but now pylint is going crazy in other way: crazy_pylint.png.
Then I have found "python.linting.pylintArgs": ["--ignored-files=pygame"], but what it does is completely disabling pylint for the whole directory I am working in.
So how do I say pylint that everything is OK with pygame?
A:
For E1101:
The problem is that most of Pygame is implemented in C directly. Now, this is all well and dandy in terms of performance, however, pylint (the linter used by VSCode) is unable to scan these C files.
Unfortunately, these same files define a bunch of useful things, namely QUIT and other constants, such as MOUSEBUTTONDOWN, K_SPACE, etc, as well as functions like init or quit.
To fix this, first things first, stop ignoring the pygame module by removing all your arguments in "python.linting.pylintArgs". Trust me, the linter can come in handy.
Now to fix the problems. For your constants (anything in caps), manually import them like so:
from pygame.constants import (
MOUSEBUTTONDOWN, QUIT, MOUSEMOTION, KEYDOWN
)
You can now use these without prepending them with pygame.:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
if event.type == KEYDOWN:
# Code
Next, for your init and other functions errors, you can manually help the linter in resolving these, by way of 2 methods:
Either add this somewhere in your code: # pylint: disable=no-member. This will deactivate member validation for the entire file, preventing such errors from being shown.
Or you can encase the line with the error:
# pylint: disable=no-member
pygame.quit()
# pylint: enable=no-member
This is similar to what the first method does, however it limits the effect to only that line.
Finally, for all your other warnings, the solution is to fix them. Pylint is there to show you places in which your code is either pointless, or nonconforming to the Python specs. A quick glance at your screenshot shows for example that your module doesn't have a docstring, that you have declared unused variables...
Pylint is here to aid you in writing concise, clear, and beautiful code. You can ignore these warnings or hide them (with # pylint: disable= and these codes) or spend a little time cleaning up everything.
In the long run, this is the best solution, as it'll make your code more readable and therefore maintainable, and just more pleasing to look at.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Query To Send To Method
I am working on an requirement to assign users to chatter groups when they are new or edited to meet a criteria. One part is looking for existing CollaborationGroupMembers to see if there is an existing group member as you cannot insert members that already exist.
The problem is I cannot figure out how to return records and then send only the ids for the ones that do not exist to the method to create the member record.
I have this bit that works for one group at a time but with my expected 3 groups it errors in the future method if the user is already in one of the group.
First error: Insert failed. First exception on row 1; first error: DUPLICATE_VALUE, User is already a Member of this group.: [MemberId]
public static void matchExisting(Set<Id> userIds)
{
// Find the Chatter group Ids from the names of the custom setting "Chatter Auto Follow"
List<CollaborationGroup> chatterGroups = [SELECT Id
FROM CollaborationGroup
WHERE Name in :Chatter_Auto_Follow__c.getall().keySet()];
// Query for existing chatter group records
List<CollaborationGroupMember> cGMember = [SELECT Id,
MemberId,
CollaborationGroupId
FROM CollaborationGroupMember
WHERE MemberId IN :userIds AND
CollaborationGroupId IN :chatterGroups];
System.debug('member size is:: ' + cGMember.size());
if(cGMember.size() == 0)
{
addToGroups(userIds);
}
}
EDIT:
Once I have a list of users to add to the group then I have this method to do the work of adding the group:
@future
public static void addToGroups(Set<Id> userIds)
{
// The users that will be added to the group
List<User> users = [SELECT id, Username FROM User WHERE id in :userIds];
// Find the Chatter group Ids from the names of the custom setting "Chatter Auto Follow"
List<CollaborationGroup> chatterGroups = [SELECT Id, Name
FROM CollaborationGroup
WHERE Name in :Chatter_Auto_Follow__c.getall().keySet()];
// Get Chatter values
List<Chatter_Auto_Follow__c> settings = [SELECT Name, Frequency__c FROM Chatter_Auto_Follow__c];
// Create blank lists for inserting new records
List<CollaborationGroupMember> chatterGroupMembers = new List<CollaborationGroupMember>();
List<FeedItem> feedPosts = new List<FeedItem>();
// loop the users that have been created
for (User u : users)
{
// loop the custom setting records
for(Chatter_Auto_Follow__c s : settings)
{
// loop the groups
for (CollaborationGroup c : chatterGroups)
{
// add the user to the group
CollaborationGroupMember cMember = new CollaborationGroupMember(
CollaborationGroupId = c.id,
MemberId = u.Id,
CollaborationRole = 'Standard',
NotificationFrequency = s.Frequency__c
);
chatterGroupMembers.add(cMember);
}
}
}
System.debug('chatter members to insert is:: ' + chatterGroupMembers);
insert chatterGroupMembers;
}
A:
This is my logic. I have put the comments in the code. You can refactor the code based on your need.
First, create a map mapCollabrUser which will store collaborationGroupId and List of Members retrieved from the query.
Then, loop through userIds to find out for each Collaboration Group, user does not exist as a member in the group and if that satisfies then add the new user for that Collaboration Group.
public static void matchExisting(Set<Id> userIds)
{
// Find the Chatter group Ids from the names of the custom setting "Chatter Auto Follow"
List<CollaborationGroup> chatterGroups = [SELECT Id
FROM CollaborationGroup
WHERE Name in :Chatter_Auto_Follow__c.getall().keySet()];
Set<Id> settingsChatterGroupId = new Set<Id>();
for(CollaborationGroup cgroup:chatterGroups)
{
settingsChatterGroupId.add(cgroup.Id);
}
// Query for existing chatter group records
List<CollaborationGroupMember> cGMember = [SELECT Id,
MemberId,
CollaborationGroupId
FROM CollaborationGroupMember
WHERE MemberId IN :userIds AND
CollaborationGroupId IN :chatterGroups];
System.debug('member size is:: ' + cGMember.size());
//this will store existing members belong to each group.
Map<Id, Set<Id>> mapCollabrUser = new Map<Id, Set<Id>>();
if(cGMember.size()>0)
{
//loop through the group members
for(CollaborationGroupMember gm:cGMember)
{
if(mapCollabrUser.containsKey(gm.CollaborationGroupId))
{
Set<Id> lst = mapCollabrUser.get(gm.CollaborationGroupId);
lst.add(gm.MemberId);
mapCollabrUser.put(gm.CollaborationGroupId,lst);
}
else
{
Set<Id> lst = new Set<Id>();
lst.add(gm.MemberId);
mapCollabrUser.put(gm.CollaborationGroupId,lst);
}
}
}
List<CollaborationGroupMember> chatterGroupMembers = new List<CollaborationGroupMember>();
for(Id userId:userIds)
{
//loop through the custom settings value
for(Id cgroupSettingId: settingsChatterGroupId)
{
//check if this is existing CollaborationGroup
if(mapCollabrUser.containsKey(cgroupSettingId))
{
//loop through the user list and find out user does not exist.
for(CollaborationGroupId grpId:mapCollabrUser.keySet())
{
//retrieve existing user list
Set<Id> setExistingUser = mapCollabrUser.get(grpId);
//if user does not belong to userlist of the group then add him.
if(!setExistingUser.contains(userId))
{
CollaborationGroupMember cMember = new CollaborationGroupMember(
CollaborationGroupId = grpId,
MemberId = userId,
CollaborationRole = 'Standard',
NotificationFrequency = s.Frequency__c
);
chatterGroupMembers.add(cMember);
}
}
}
else
{
//this is of new entries which doesn't exist in database and add the new user
CollaborationGroupMember cMember = new CollaborationGroupMember(
CollaborationGroupId = cgroupSettingId,
MemberId = userId,
CollaborationRole = 'Standard',
NotificationFrequency = s.Frequency__c
);
chatterGroupMembers.add(cMember);
}
}
}
insert chatterGroupMembers;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there any other kingdom than Hyrule?
In the same vein as my other question Is there any other kingdom than the Mushroom Kingdom?, we all know that Zelda is the Princess of Hyrule, but is there any other kingdoms visited during Link's adventures? What territories seen in the games are not in the Hyrule 'Kingdom' (thinking about it, I've never heard it mentionned as a kingdom)
What are the limits of Hyrule, and what is over them?
A:
Yes, there are places other than Hyrule kingdom.
Koholint Island
An island which Link visits during the events of Link's Awakening and is quite separate from Hyrule. While there is a castle on Koholint Island, it belongs to a nobleman, and not to a king.
The Sacred Realm / Dark World
First introduced in A Link to the Past, the Dark World exists in a dimension parallel to Hyrule and is a corrupted version of the Sacred Realm (where the Triforce rests). Despite being called a "realm", it does not seem to have a ruler, and therefore cannot really be called a kingdom.
Termina
Termina is where Majora's Mask takes place. It is considered a parallel world to Hyrule due to its stark resemblance to the Kingdom. Termina is split in 5 areas: the swamps, home to the Deku Scrubs and their king; the mountains, home to the Gorons and their elder; the ocean, where the Zoras live; the Ikana Canyon, where the Ikana kingdom once stood; and Clock Town, which is ruled by a mayor.
Labrynna
The setting for Oracle of Ages, it is one of few places that aren't a parallel version of Hyrule one way or another. While Labrynna is no longer a kingdom, it used to be 400 years before the events of the game. Link can actually visit Labrynna kingdom by travelling to the past using the Harp of Ages.
Holodrum
Where Oracle of Seasons takes place. Similar to Labrynna, it is another place that is no parallel version of Hyrule. Holodrum is mostly uninhabited. Below Holodrum is Subrosia, whose Subrosian population does not seem to have a ruler.
The Twilight Realm
Twilight Princess' parallel version of Hyrule is home to the descendants of a people that have been banned from Hyrule a long time ago. Ruled by a Twili royal family, it can be considered a kingdom.
Skyloft
While floating above what will eventually be known as Hyrule, it is difficult to say if Skyward Sword's starting town does belong to Hyrule kingdom or not. Skyloft isn't ruled by a king, however.
Lorule
Often confused with the Dark World, Lorule is not A Link Between Worlds' version of the Dark World. It is instead yet another parallel version of Hyrule. Ruled by its own version of Hyrule's royal family with its own "Princess Hilda", it is as much a kingdom as Hyrule is.
Hytopia
Since I haven't played Tri Force Heroes, I do not know the relationship between Hyrule and Hytopia. All I know, is that they aren't the same place. Hytopia is currently ruled by King Tuft, whose daughter is called Princess Styla.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Are there constraint problem calculators?
So I just remembered Lincoln Logs exist, so I found ten giant sets of them on ebay for Buy It Now, and I'm trying to decide what combination of purchases gives me the most logs for the least money if I'm going to purchase $n$ sets.
Then I remembered this is exactly the sort of thing I learned in algorithms class, but I really don't want to set this up myself. Much, much too lazy on this rainy day. Are there any online or downloadable calculators which let me set it up easily?
A:
The search term you want is "Knapsack Problem".
http://en.wikipedia.org/wiki/Knapsack_problem
There are some interactive ones online,
https://www.google.com/#q=knapsack+problem+solver
As you remembered, this is in principle equivalent to CSP's, or any other NP-complete problem.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
AWS EC2 instance based on RHEL7.2 ami can not install Docker
I created one EC2 instance that's based on AMI: RHEL-7.2_HVM-20161025-x86_64-1-Hourly2-GP2 - ami-2265c543 , but when I wanna install docker via yum install docker -y it shows me error: No package docker available. Error: Nothing to do . So anyone know how to install docker on this ami OS?
thanks in advance.
A:
You can install Docker-CE by setting up Docker repo.
To do So, you can follow official Documentation (Use Docker EE for RHEL).
Install required packages
sudo yum install -y yum-utils \
device-mapper-persistent-data \
lvm2
Use the following command to set up the stable repository
sudo yum-config-manager \
--add-repo \
https://download.docker.com/linux/centos/docker-ce.repo
INSTALL DOCKER CE
sudo yum install docker-ce
Start Docker
sudo systemctl start docker
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Drawing a filled circle in a canvas on mouseclick
I want to draw a filled (or not filled) circle in a canvas on mouseclick, but I can't get my code to work properly, I've tried pretty much everything!
This is my HTML:
<div id="images"></div>
<canvas style="margin:0;padding:0;position:relative;left:50px;top:50px;" id="imgCanvas" width="250" height="250" onclick="draw(e)"></canvas>
and my current script:
var canvas = document.getElementById("imgCanvas");
var context = canvas.getContext("2d");
function createImageOnCanvas(imageId) {
canvas.style.display = "block";
document.getElementById("images").style.overflowY = "hidden";
var img = new Image(300, 300);
img.src = document.getElementById(imageId).src;
context.drawImage(img, (0), (0)); //onload....
}
function draw(e) {
var pos = getMousePos(canvas, e);
posx = pos.x;
posy = pos.y;
context.fillStyle = "#000000";
context.arc(posx, posy, 50, 0, 2 * Math.PI);
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
The code works just fine if and only if I remove the "use strict";, but in this assignment I have to make a code that works even with it, which is my problem.
Here is the jsFiddle
A:
Solved it myself.
function draw(e) {
var canvas = document.getElementById("imgCanvas");
var context = canvas.getContext("2d");
var rect = canvas.getBoundingClientRect();
var posx = e.clientX - rect.left;
var posy = e.clientY - rect.top;
context.fillStyle = "#000000";
context.beginPath();
context.arc(posx, posy, 50, 0, 2 * Math.PI);
context.fill();
}
This script works fine for me.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
str_extract expressions in R
I would like to convert this:
AIR-GEN-SUM-UD-ELA-NH-COMBINED-3-SEG1
to this:
ELA-3
I tried this function:
str_extract(.,pattern = ":?(ELA).*(\\d\\-)"))
it printed this:
"ELA-NH-COMBINED-3-"
I need to get rid of the text or anything between the two extracts. The number will be a number between 3 and 9. How should I modify my expression in pattern =?
Thanks!
A:
1) Match everything up to -ELA followed by anything (.*) up to - followed by captured digits (\\d+)followed by - followed by anything. Then replace that with ELA- followed by the captured digits. No packages are used.
x <- "AIR-GEN-SUM-UD-ELA-NH-COMBINED-3-SEG1"
sub(".*-ELA.*-(\\d+)-.*", "ELA-\\1", x)
## [1] "ELA-3"
2) Another approach if there is only one numeric field is that we can read in the fields, grep out the numeric one and preface it with ELA- . No packages are used.
s <- scan(text = x, what = "", quiet = TRUE, sep = "-")
paste("ELA", grep("^\\d+$", s, value = TRUE), sep = "-")
## [1] "ELA-3"
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Multiple videos with AVPlayer
I am developing an iOS app for iPad that needs to play videos in some part of the screen. I have several video files that needs to be played after each other in an order that is not given at compile time. It must looks as if it is just one video playing. It is fine that when going from one video to the next that is some delay where the last or first frame of the two videos are shown, but there should be no flickering or white screens with no content. The videos does not contain audio. It is important to take memory usage into account. The videos have a very high resolution and several different video sequences can be played next to each other at the same time.
In order to obtain this I have tried a few solutions for far. They are listed below:
1. AVPlayer with AVComposition with all the videos in it
In this solution I have an AVPlayer that will use only on AVPlayerItem made using a AVComposition containing all the videos put in next to each other. When going to specific videos I seek to the time in the composition where the next video start.The issue with this solution is that when seeking the player will quickly show some of the frames that it is seeking by, which is not acceptable. It seems that there is no way to jump directly to a specific time in the composition. I tried solving this by making an image of the last frame in the video that just finished, then show that in front of the AVPLayer while seeking, and finally remove it after seeking was done. I am making the image using AVAssetImageGenerator, but for some reason the quality of the image is not the same as the video, so there is notable changes when showing and hiding the image over the video.
Another issue is that the AVPlayer uses a lot of memory because a single AVPlayerItem holds all the videos.
2. AVPlayer with multiple AVPlayerItems
This solution uses a AVPlayerItem for each video and the replaces the item of the AVPlayer when switching to a new video. The issue with this is that when switching the item of a AVPlayer it will show a white screen for a short time while loading the new item. To fix this the solution with putting an image in front with the last frame while loading could be used, but still with the issue that the quality of image and video is different and notable.
3. Two AVPlayers on top of each other taking turns to play AVPlayerItem
The next solution I tried was having two AVPlayer on top of each other that would take turns playing AVPlayerItems. So When on of the players is done playing it will stay on the last frame of the video. The other AVPlayer will be brought to the front (with its item set to nil, so it is transparent), and the next AVPlayerItem will be inserted in that AVPlayer. As soon as it is loaded it will start playing and the illusion of smooth transaction between the two videos will be intact. The issue with this solution is the memory usage. In some cases I need to play two videos on the screen at the same time, which will result in 4 AVPlayers with a loaded AVPlayerItem at the same time. This is simply too much memory since the videos can be in a very high resolution.
Does anyone have some thoughts, suggestions, comments or something concerning the overall problem and the tried solutions posted above.
A:
So the project is now live in the App Store and it is time to come back to this thread and share my findings and reveal what I ended up doing.
What did not work
The first option where I used on big AVComposition with all the videos in it was not good enough since there was no way to jump to a specific time in the composition without having a small scrubbing glitch. Further I had a problem with pausing the video exactly between two videos in the composition since the API could not provide frame guarantee for pausing.
The third with having two AVPlayers and let them take turns worked great in practice. Exspecially on iPad 4 or iPhone 5. Devices with lower amount of RAM was a problem though since having several videos in memory at the same time consumed too much memory. Especially since I had to deal with videos of very high resolution.
What I ended up doing
Well, left was option number 2. Creating an AVPlayerItem for a video when needed and feeding it to the AVPlayer. The good thing about this solution was the memory consumption. By lazy creating the AVPlayerItems and throwing them away the moment they were not longer needed in could keep memory consumption to a minimum, which was very important in order to support older devices with limited RAM. The problem with this solution was that when going from one video to the next there a blank screen for at quick moment while the next video was loaded into memory. My idea of fixing this was to put an image behind the AVPlayer that would show when the player was buffering. I knew I needed images that we exactly pixel to pixel perfect with the video, so I captured images that were exact copies of the last and first frame of the videos. This solution worked great in practice.
The problem with this solution
I had the issue though that the position of the image inside the UIImageView was not the same as the position of the video inside the AVPlayer if the video/image was not its native size or a module 4 scaling of that. Said other words, I had a problem with how half pixels were handled with a UIImageView and a AVPlayer. It did not seem to be the same way.
How I fixed it
I tried a lot of stuff since I my application was using the videos in interactive way where shown in different sizes. I tried changed the magnificationfilter and minificationFilter of AVPlayerLayer and CALayer to use the same algorithm but did not really change anything. In the end I ended up creating an iPad app that automatically could take screenshots of the videos in all the sizes I needed and then use the right image when the video was scaled to a certain size. This gave images that were pixel perfect in all of the sizes I was showing a specific video. Not a perfect toolchain, but the result was perfect.
Final reflection
The main reason why this position problem was very visible for me (and therefore very important to solve), was because the video content my app is playing is drawn animations, where a lot the content is in a fixed position and only a part of the picture is moving. If all the content is moved just one pixel it gives a very visible and ugly glitch. At WWDC this year I discussed this problem with an Apple engineer that is an expert in AVFoundation. When I introduced the problem to him his suggestion basically was to go with option 3, but I explained to him that that was not possible because memory consumption and that I already tried that solution out. In that light he said that I choose the right solution and asked me to file a bug report for the UIImage/AVPlayer positioning when video is scaled.
A:
You may have looked at this already, but have you checked out AVQueuePlayer Documentation
It is designed for playing AVPlayerItems in a queue and is a direct subclass of AVPlayer so just use it in the same way. You set it up like follows:
AVPlayerItem *firstItem = [AVPlayerItem playerItemWithURL: firstItemURL];
AVPlayerItem *secondItem = [AVPlayerItem playerItemWithURL: secondItemURL];
AVQueuePlayer *player = [AVQueuePlayer queuePlayerWithItems:[NSArray arrayWithObjects:firstItem, secondItem, nil]];
[player play];
If you want to add new items to the queue at runtime just use this method:
[player insertItem:thirdPlayerItem afterItem:firstPlayerItem];
I haven't tested to see if this reduces the flickering issue you have mentioned but it seems like this would be the way to go.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Synchronizing access to Immutable Integer object
Code snippet - 1
class RequestObject implements Runnable
{
private static Integer nRequests = 0;
@Override
public void run()
{
synchronized (nRequests)
{
nRequests++;
}
}
}
Code snippet - 2
class RequestObject implements Runnable
{
private static Integer nRequests = 0;
private static Object lock = new Object();
@Override
public void run()
{
synchronized (lock)
{
nRequests++;
}
}
}
While the second code snippet is working fine without causing any race conditions, the first one isn't successful in synchronizing access to the static data member between different instances of the same class(RequestObject). Could somebody throw more light on this. I would like to understand why the first approach isn't working.
My original implementation is the first one. The later I saw in https://stackoverflow.com/a/2120409/134387.
A:
You are constantly creating new Integer objects, which you then synchronize on, which at least makes it extremely confusing to think about it. So you can get the following scenario:
Thread A gets hold of the current value of nRequests (lets say 0)
Thread B queues for the same value (0)
Thread A increases nRequests (to the value 1)
Thread C gets hold of the new value and synchronizes on it, increases it and lets go of the value.
Thread A lets go of the monitor on 0
Thread B synchronizes on 0 and increases it to 1, overwriting the changes of C
With the second approach you have a single object that everybody has to synchronize on. Which is exactly what you want.
A:
Instances of Integer are immutable, nRequests++ therefore creates a new Integer object to hold the result, and stores it in nRequests. The synchronized statement synchronizes on an object. Therefore, the threads will synchronize on different objects. Yes, there may be only one thread in a synchronized block on the same object at the same time, but different threads may be in synchronized blocks of different objects at the same time ...
The easiest way to synchronize access to static state is putting it in a static synchronized method:
static synchronized void increment() {
nRequests++;
}
This is equivalent to the following synchronized block:
synchronized (RequestObject.class) {
nRequests++;
}
where RequestObject is the class containing the static field.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is a self-propelling "working" piston mechanism called?
In anticipation of the Redstone Update, I've been experimenting with this type of "wormhead" piston configuration lately:
or:
PSXXXXSP
where P = normal piston, S = sticky piston, X = anything .
By alternating power to the two pistons at the extremes, one can move the entire chain in the given direction. A usage of example would be a cane farm like this one:
or an extendable fence.
This type of configuration will become more useful with the next update (hoppers allow continuous collection of items, redstone blocks allow easier movement in two dimensions).
I don't recall this type of mechanism described anywhere I read (including the Wiki), but as this is basically an extension of the self-propelling piston concept, I doubt that there isn't already a name for it. So, what is the popular name of this type of contraption?
A:
This is an inchworm drive. The name is typically used in connection with RedPower frame/motor contraptions, but it's not a actual block's name so it's not especially tied to the RedPower way of building one. It's not unlike what is called an inchworm motor in the real world, so it's a pretty reasonable name for it in the first place. RedPower's users have invented a precedent for calling machines like that in Minecraft "inchworm drives", so using it to describe the same thing implemented with different blocks seems reasonable too.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Easeljs snap to grid
I am building an app using HTML5 in which a grid is drawn. I have some shapes on it that you can move.
What I'm trying to do is to snap objects to some points defined when you hover them while moving a shape.
What I tried is to save anchors points inside an array and when the shape is dropped, I draw the shape on the closest anchor point.
Easeljs is my main js lib so I want to keep it but if needed I can use an other one with easeljs.
Thanks in advance for your help!
A:
This is pretty straightforward:
Loop over each point, and get the distance to the mouse
If the item is closer than the others, set the object to its position
Otherwise snap to the mouse instead
Here is a quick sample with the latest EaselJS: http://jsfiddle.net/lannymcnie/qk1gs3xt/
The distance check looks like this:
// Determine the distance from the mouse position to the point
var diffX = Math.abs(event.stageX - p.x);
var diffY = Math.abs(event.stageY - p.y);
var d = Math.sqrt(diffX*diffX + diffY*diffY);
// If the current point is closeEnough and the closest (so far)
// Then choose it to snap to.
var closest = (d<snapDistance && (dist == null || d < dist));
if (closest) {
neighbour = p;
}
And the snap is super simple:
// If there is a close neighbour, snap to it.
if (neighbour) {
s.x = neighbour.x;
s.y = neighbour.y;
// Otherwise snap to the mouse
} else {
s.x = event.stageX;
s.y = event.stageY;
}
Hope that helps!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Google compute engine external ip
I have a nodejs app in google compute engine which I can access with the given appspot adress.
In networking I set the ip adress as static.
I have added a firewall rule for allow any trafic , tcp:8080.
But when I try to go onto external ip adress on my browser it fails to load. So I cannot acces my site with external ip adress.
What should I do to be able to use external IP adress?
A:
So it seems like , when you use "gcloud preview app deploy" command it deploys to google cloud compute engine where the app is runing on port 8080.
To have a static IP to you project here are the steps to take:
1) In your code , create an app.yaml file. Forward port 80 to port 8080 (where your app is listening)
network:
forwarded_ports:
- 80:8080
2) go head and deploy you app
gcloud preview app deploy
3) In your google console go to NETWORKING > FIREWALL RULES and add new firewall rule for tcp:80
4) Go onto EXTERNAL IP ADDRESSES and change your apps IP address to static.
You will see your site runing on the external ip adress.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to disable one check box if other is checked?
I have the form with 4 rows and each row has 10 cells. Each cell has 2 check boxes. If one check box is checked i would like do disable the other check box and other way around. Here is example of what I have:
$(".myTbl input:checkbox").click(function() {
$(this).siblings("input:checkbox").prop("checked", false);
});
table.myTbl {
width: 100%;
}
table.myTbl td {
text-align: center;
padding: 1px;
margin: 0px;
background-color: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="myTbl">
<tr>
<td>
<input type="checkbox" name="frmra0m" id="frmra0m" /><b>M</b>
<input type="checkbox" name="frmra0nr" id="frmra0nr" /><b>NR</b><br>
<input type="number" name="frmra0" id="frmra0" min="0" max="120" step="5" style="width:50px" />
</td>
<td>
<input type="checkbox" name="frmra1m" id="frmra1m" /><b>M</b>
<input type="checkbox" name="frmra1nr" id="frmra1nr" /><b>NR</b><br>
<input type="number" name="frmra1" id="frmra1" min="0" max="120" step="5" style="width:50px" />
</td>
<td>
<input type="checkbox" name="frmra2m" id="frmra2m" /><b>M</b>
<input type="checkbox" name="frmra2nr" id="frmra2nr" /><b>NR</b><br>
<input type="number" name="frmra2" id="frmra2" min="0" max="120" step="5" style="width:50px" />
</td>
<td>
<input type="checkbox" name="frmra3m" id="frmra3m" /><b>M</b>
<input type="checkbox" name="frmra3nr" id="frmra3nr" /><b>NR</b><br>
<input type="number" name="frmra3" id="frmra3" min="0" max="120" step="5" style="width:50px" />
</td>
<td>
<input type="checkbox" name="frmra4m" id="frmra4m" /><b>M</b>
<input type="checkbox" name="frmra4nr" id="frmra4nr" /><b>NR</b><br>
<input type="number" name="frmra4" id="frmra4" min="0" max="120" step="5" style="width:50px" />
</td>
<td>
<input type="checkbox" name="frmra5m" id="frmra5m" /><b>M</b>
<input type="checkbox" name="frmra5nr" id="frmra5nr" /><b>NR</b><br>
<input type="number" name="frmra5" id="frmra5" min="0" max="120" step="5" style="width:50px" />
</td>
<td>
<input type="checkbox" name="frmra6m" id="frmra6m" /><b>M</b>
<input type="checkbox" name="frmra6nr" id="frmra6nr" /><b>NR</b><br>
<input type="number" name="frmra6" id="frmra6" min="0" max="120" step="5" style="width:50px" />
</td>
<td>
<input type="checkbox" name="frmra7m" id="frmra7m" /><b>M</b>
<input type="checkbox" name="frmra7nr" id="frmra7nr" /><b>NR</b><br>
<input type="number" name="frmra7" id="frmra7" min="0" max="120" step="5" style="width:50px" />
</td>
<td>
<input type="checkbox" name="frmra8m" id="frmra8m" /><b>M</b>
<input type="checkbox" name="frmra8nr" id="frmra8nr" /><b>NR</b><br>
<input type="number" name="frmra8" id="frmra8" min="0" max="120" step="5" style="width:50px" />
</td>
<td>
<input type="checkbox" name="frmra9m" id="frmra9m" /><b>M</b>
<input type="checkbox" name="frmra9nr" id="frmra9nr" /><b>NR</b><br>
<input type="number" name="frmra9" id="frmra9" min="0" max="120" step="5" style="width:50px" />
</td>
<td>
<input type="checkbox" name="frmra10m" id="frmra10m" /><b>M</b>
<input type="checkbox" name="frmra10nr" id="frmra10nr" /><b>NR</b><br>
<input type="number" name="frmra10" id="frmra10" min="0" max="120" step="5" style="width:50px" />
</td>
</tr>
</table>
I was thinking about radio buttons but there is a problem. Radio button can't be unchecked. If anyone can provide any advise or solution for this problem please let me know. Thanks in advance.
A:
You can get the siblings using the jQuery siblings function and uncheck them. Btw I assume you mean uncheck and not disable?
e.g.
$(".mtTbl input:checkbox").click(function() {
$(this).siblings("input:checkbox").prop("checked", false);
});
table.myTbl {
width: 100%;
}
table.myTbl td {
text-align: center;
padding: 1px;
margin: 0px;
background-color: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="mtTbl">
<tr>
<td>
<input type="checkbox" name="frmra0m" id="frmra0m" /><b>M</b>
<input type="checkbox" name="frmra0nr" id="frmra0nr" /><b>NR</b><br>
<input type="number" name="frmra0" id="frmra0" min="0" max="120" step="5" style="width:50px" />
</td>
<td>
<input type="checkbox" name="frmra1m" id="frmra1m" /><b>M</b>
<input type="checkbox" name="frmra1nr" id="frmra1nr" /><b>NR</b><br>
<input type="number" name="frmra1" id="frmra1" min="0" max="120" step="5" style="width:50px" />
</td>
<td>
<input type="checkbox" name="frmra2m" id="frmra2m" /><b>M</b>
<input type="checkbox" name="frmra2nr" id="frmra2nr" /><b>NR</b><br>
<input type="number" name="frmra2" id="frmra2" min="0" max="120" step="5" style="width:50px" />
</td>
<td>
<input type="checkbox" name="frmra3m" id="frmra3m" /><b>M</b>
<input type="checkbox" name="frmra3nr" id="frmra3nr" /><b>NR</b><br>
<input type="number" name="frmra3" id="frmra3" min="0" max="120" step="5" style="width:50px" />
</td>
<td>
<input type="checkbox" name="frmra4m" id="frmra4m" /><b>M</b>
<input type="checkbox" name="frmra4nr" id="frmra4nr" /><b>NR</b><br>
<input type="number" name="frmra4" id="frmra4" min="0" max="120" step="5" style="width:50px" />
</td>
<td>
<input type="checkbox" name="frmra5m" id="frmra5m" /><b>M</b>
<input type="checkbox" name="frmra5nr" id="frmra5nr" /><b>NR</b><br>
<input type="number" name="frmra5" id="frmra5" min="0" max="120" step="5" style="width:50px" />
</td>
<td>
<input type="checkbox" name="frmra6m" id="frmra6m" /><b>M</b>
<input type="checkbox" name="frmra6nr" id="frmra6nr" /><b>NR</b><br>
<input type="number" name="frmra6" id="frmra6" min="0" max="120" step="5" style="width:50px" />
</td>
<td>
<input type="checkbox" name="frmra7m" id="frmra7m" /><b>M</b>
<input type="checkbox" name="frmra7nr" id="frmra7nr" /><b>NR</b><br>
<input type="number" name="frmra7" id="frmra7" min="0" max="120" step="5" style="width:50px" />
</td>
<td>
<input type="checkbox" name="frmra8m" id="frmra8m" /><b>M</b>
<input type="checkbox" name="frmra8nr" id="frmra8nr" /><b>NR</b><br>
<input type="number" name="frmra8" id="frmra8" min="0" max="120" step="5" style="width:50px" />
</td>
<td>
<input type="checkbox" name="frmra9m" id="frmra9m" /><b>M</b>
<input type="checkbox" name="frmra9nr" id="frmra9nr" /><b>NR</b><br>
<input type="number" name="frmra9" id="frmra9" min="0" max="120" step="5" style="width:50px" />
</td>
<td>
<input type="checkbox" name="frmra10m" id="frmra10m" /><b>M</b>
<input type="checkbox" name="frmra10nr" id="frmra10nr" /><b>NR</b><br>
<input type="number" name="frmra10" id="frmra10" min="0" max="120" step="5" style="width:50px" />
</td>
</tr>
</table>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Syntax highlighting for custom LaTeX commands
I have a few custom LaTeX commands like this one, for instance:
\newcommand{\oeuvre}[1]{\textit{#1}}
I use this for titles of books and other works. Sometimes I want them to be italicized, sometimes I want them to be in quotes, so I just use this command and I can change it all at once when necessary.
Now I want Vim to highlight that command and its contents as it does with \emph or \textit, and I want to disable spelling inside it.
(So in \oeuvre{whatver} "oeuvre" should be highlighted the same way as "emph" or "textit", and "whatver" should be in italics and it shouldn't count as a spelling mistake.)
Based on Vim's default TeX highlighting file, I tried this in my after/syntax/tex.vim:
syn match texTypeStyle "\\oeuvre\>"
syn region texOeuvreStyle matchgroup=texTypeStyle start="\\oeuvre\s*{" matchgroup=texTypeStyle end="}" concealends contains=@texItalGroup,@NoSpell
hi texOeuvreStyle gui=italic cterm=italic
But it doesn't work. The command itself is highlighted properly, but not its contents, and spelling is still enabled.
So how can I get that to work?
(I know there are similar questions here, but I couldn't adapt them to my needs, I find this syntax highlighting stuff really confusing, sorry.)
Edit: Ok, I figured out that if I use syn region texItalStyle it'll work like I want it to… I'm still curious as to why I can't define my own texOeuvreStyle in what seems to me is the same way it's done for texItalStyle in the default syntax file though.
A:
The problem is that the TeX syntax is hierarchical; the default texItalStyle is contained in two clusters, texFoldGroup and texItalGroup. The former cluster is contained in the top-level regions (texDocZone, texPartZone, and so on). Without that containment, your syntax rule never has a chance to match; the toplevel regions slice up your entire document, and they only allow contained members to match subsets of them.
By choosing the same syntax group for your extension, you automatically fit in. If you absolutely want to define a custom syntax group, you'd have to add them into the clusters (untested):
syntax cluster texFoldGroup add=texOeuvreStyle
syntax cluster texItalGroupGroup add=texOeuvreStyle
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Gradle batch task that invokes subproject and other tasks in order
I am writing gradle 1.4 build file for multimodule project. So there is root build.gradle that defines something like:
subprojects {
apply plugin: 'java'
...
which defines build task for all submodules. Submodules are included in settings.gradle and each module has its build file with defined dependencies.
Everything by-the-book, so far:) Now, in the main build file I've added some additional project-scope tasks, like: aggregateJavadoc (collects all javadocs into one) or bundleJar (creates bundle jar from all classes), etc. Each on works when invoked manually.
Now I need a task release that will
build all submodules (as invoked from command line - meaning, i dont want to manually write execute() for each submodule)
invoke additional tasks (using execute() I presume).
I tried dependsOn but the order of listed tasks is not followed. Also, dependent modules seems to be executed after release task execution. I tried several other ideas and failed.
Question: what would be the best way to create such batch task, that has to invoke something on all submodules and additionally to perform some more tasks? What would be the best gradle-friendly solution? Thanx!
A:
It happened that this can be solved with simple dependency management.
So, we have many modules. Now, lets create additional tasks that depends on modules being build:
task aggregateJavadoc(type: Javadoc) {
dependsOn subprojects.build
task bundleJar(type: Jar) {
dependsOn subprojects.build
Finally, our release task would simply look like this:
task release() {
dependsOn subprojects.build
dependsOn aggregateJavadoc
dependsOn bundleJar
...
}
This will build subprojects first; not because it is listed first, but because additional tasks depends on building. Order of additional task is not important. This make sense the most to me.
EDIT
if one of your subprojects (i.e. modules) is non-java module, then you will have a problem building this project. What I do is to group submodules, like this:
def javaModules() {
subprojects.findAll {it.name.contains('jodd-')}
}
and then instead to refer to subprojects, use javaModules everywhere! For example:
configure(javaModules()) {
apply plugin: 'java'
...
and
task prj {
dependsOn javaModules().build
}
btw, I am using this 'dummy' task prj for dependsOn on all those additional projects that depends on building, to prevent repeating.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
getting data from HTTP put
Note: This question is specific to Grails and jQuery
I'm making an ajax call to my server using PUT:
$.ajax({
url: "admin/services/instance",
type: "PUT",
data: {instance: dataAsJSON},
dataType: "json",
async: false,
success: function(){},
error: function(){}
});
So this call works fine, it calls my controller, but when print params.instance, it's null.
But when i do this as a "POST" it works fine.
Does anyone have any thoughts?
A:
According to the jQuery manual: "Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers."
Does your browser support PUT?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Group .txt data into dataframe
I have a .txt file with data like such:
[12.06.17, 13:18:36] Name1: Test test test
[12.06.17, 13:20:20] Name2 ❤️: blabla
[12.06.17, 13:20:44] Name2 ❤️: words words words
words
words
words
[12.06.17, 13:29:03] Name1: more words more words
[12.06.17, 13:38:52] Name3 Surname Nickname:
[12.06.17, 13:40:37] Name1: message?
Note, that there can be multiple names before the message and also multiline messages can occur. I tried many things for the last days already to split the data into the groups 'date', 'time', 'name', 'message'.
I was able to figure out, that the regex
(.)(\d+\.\d+\.\d+)(,)(\s)(\d+:\d+:\d+)(.)(\s)([^:]+)(:)
is able to capture everything up to the message (cf.: https://regex101.com/r/hQlgeM/3). But I cannot figure out how to add the message so that multiline messages are grouped into the previous message.
Lastly: If I am able to capture each group from the .txt with regex, how do I actually pass each group into a separate column. I've been looking at examples for the last three days, but I still cannot figure out how to finally construct this dataframe.
Code that I tried to work with:
df = pd.read_csv('chat.txt', names = ['raw'])
data = df.iloc[:,0]
re.match(r'\[([^]]+)\] ([^:]+):(.*)', data)
Another try that did not work:
input_file = open("chat.txt", "r", encoding='utf-8')
content = input_file.read()
df = pd.DataFrame(content, columns = ['raw'])
df['date'] = df['raw'].str.extract(r'^(.)(\d+\.\d+\.\d+)', expand=True)
df['time'] = df['raw'].str.extract(r'(\s)(\d+:\d+:\d+)', expand=True)
df['name'] = df['raw'].str.extract(r'(\s)([^:]+)(:)', expand=True)
df['message'] = df['raw'].str.extract(r'^(.)(?<=:).*$', expand=True)
df
A:
A complete solution will look like
import pandas as pd
import io, re
file_path = 'chat.txt'
rx = re.compile(r'\[(?P<date>\d+(?:\.\d+){2}),\s(?P<time>\d+(?::\d+){2})]\s(?P<name>[^:]+):(?P<message>.*)')
col_list = []
date = time = name = message = ''
with io.open(file_path, "r", encoding = "utf-8", newline="\n") as sr:
for line in sr:
m = rx.match(line)
if m:
col_list.append([date, time, name, message])
date = m.group("date")
time = m.group("time")
name = m.group("name")
message = m.group("message")
else:
if line:
message += line
df = pd.DataFrame(col_list, columns=['date', 'time', 'name', 'message'])
Pattern details
\[ - a [ char
(?P<date>\d+(?:\.\d+){2}) - Group "date": 1+ digits and then two repetitions of . and two digits
,\s - , and a whitespace
(?P<time>\d+(?::\d+){2}) - Group "time": 1+ digits and then two repetitions of : and two digits
]\s - ] and a whitespace
(?P<name>[^:]+) - Group "name": one or more chars other than :
: - a colon
(?P<message>.*) - Group "message": any 0+ chars, as many as possible, up to the end of line.
Then, the logic is as follows:
A line is read in and tested against the pattern
If there is a match, the four variables - date, time, name and message - details are initialized
If the next line does not match the pattern it is considered part of the message and is thus appended to message variable.
A:
Here is the solution that I figured works in my case. The problem was that I was using read_csv() when it is txt data. Also I needed to use regex to build my format before passing in into pandas:
import re
import pandas as pd
chat = open('chat.txt').read()
pattern = r'(?s)\[(?P<date>\d+(?:\.\d+){2}),\s(?P<time>\d+(?::\d+){2})]\s(?P<name>[^:]+):(?P<message>.*?)(?=\[\d+\.\d+\.\d+,\s\d+:\d+:\d+]|\Z)'
for row in re.findall(pattern, chat):
row
df = pd.DataFrame(re.findall(pattern, chat), columns=['date', 'time', 'name', 'message'])
print (df.tail)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to alphabetize a list of hashmaps
I have an ArrayList defined as so:
ArrayList<HashMap<String, String>> recallList = new ArrayList<HashMap<String, String>>();
Each map only has one element in it company which is the name of a company. My question is how do I alphabetize the ArrayList. I am using this because later down the line (in other views) there will be more elements to the HashMap.
A:
Use the following:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
public class MainClass {
public static void main(String[] args) {
ArrayList<HashMap<String, String>> recallList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> hashMap;
hashMap = new HashMap<String, String>();
hashMap.put("company", "a");
recallList.add(hashMap);
hashMap = new HashMap<String, String>();
hashMap.put("company", "c");
recallList.add(hashMap);
hashMap = new HashMap<String, String>();
hashMap.put("company", "b");
recallList.add(hashMap);
System.out.println(recallList);
Collections.sort(recallList, new Comparator<HashMap<String, String>>() {
@Override
public int compare(HashMap<String, String> hashMap1, HashMap<String, String> hashMap2) {
return hashMap1.get("company").compareTo(hashMap2.get("company"));
}
});
System.out.println(recallList);
}
}
The first and second output are:
[{company=a}, {company=c}, {company=b}]
[{company=a}, {company=b}, {company=c}]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Python 2 raw_input() : EOFError when reading a line in WINDOWS 7 command prompt
NOTE: Many of the same questions have been asked about python raw_input() in sublime text. This question is NOT about sublime. The python code is called in Windows command prompt which unlike the sublime terminal does support interactive inputs.
I have a python program that takes user input with the built-in function raw_input(). See below.
def password_score():
pwd = raw_input('Enter a password: ')
gname = raw_input('Enter your first name: ')
...
I call the program in cmd by
echo password_score()|python -i a06q1.py
where a06q1.py is the file name. The path of the python directory has been added to system variable %PATH% temporarily. I am in the directory of the file. My operating system is Windows 7. I am using python 2.6. The same command has worked until now.
Then cmd returns
File "<stdin>", line 1, in <module>
File "a06q1.py", line 27, in password_score
pwd = raw_input(p_prompt)
EOFError: EOF when reading a line
Is there a way to get around it within cmd?
EDIT: I just tried in on an iOS terminal too. With the same command as in cmd (with quotes), it returns the same error. Is there anything wrong about the command line I used? Thank you!
EDIT: Sebastian's answer solves the problem. The command should adapt to windows as follows.
printf "a06q1.password_score()\n'arg1\n'arg2"|python -i -c "import a06q1"
The single quotes succeeding \n can be replaced by spaces. They separate multiple inputs.
A:
EOF means that there is no more input. And it is true, the only line is consumed by -i option:
$ echo "f()" | python -i -c "def f(): print('x'); input('y\n')"
>>> x
y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in f
EOFError: EOF when reading a line
>>>
Provide more input:
$ printf "f()\n'z'" | python -i -c "def f(): print('x'); print(input('y\n')*3)"
>>> x
y
zzz
>>>
As you said: it is "canonically bad" to specify a function to run in such manner. If you don't know in advance, what function you want to run then as an alternative, you could run it as:
$ python -c "from a06q1 import password_score as f; f()" < input_file.txt
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to position a in a navbar?
I create a Bootstrap 4 navbar with a navbar-brand logo and Navbar-brand text.
But i don't know how to position the brand-logo and text :(
<!doctype html>
<html lang="en">
<head>
<title>Hello, world!</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
<a class="navbar-brand" href="#">
<img src="http://via.placeholder.com/117x52" class="d-inline-block align-top" alt="logo"> Tools
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link1</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link2</a>
</li>
</ul>
</div>
</nav>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</body>
</html>
My problem: I like to have that the border over and under the img is only 1px small and the "Tools" text is in the middle.
I try out some padding and margin in CSS but I did not solve the problem.
How I imagine the navbar:
A:
you can overwrite the bootstrap css adding this to yous css:
.navbar {padding:1px 1rem !important}
.navbar-brand { padding:0 !important; line-height: 52px !important}
<!doctype html>
<html lang="en">
<head>
<title>Hello, world!</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
<a class="navbar-brand" href="#">
<img src="http://via.placeholder.com/117x52" class="d-inline-block align-top" alt="logo"> Tools
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link1</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link2</a>
</li>
</ul>
</div>
</nav>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</body>
</html>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Firebase Collection into ReorderableListView
I have a Firebase collection in Flutter that I want to have in a reorderableListView. The documents in the collection have a 'position' field that should determine the order of the list and be updated onReorder of the list.
A:
I've worked it out myself finally.
onReorder: (oldIndex, newIndex) {
setState(() {
List<MyObjectClass> objectList =
myObjects
.data;
if (newIndex > oldIndex) {
newIndex -= 1;
}
final MyObjectClass
myObject = objectList.removeAt(oldIndex);
objectList.insert(newIndex, myObject);
for (MyObjectClass o in objectList) {
o.position = objectList.indexOf(o);
DatabaseService()
.updateMyObjects(
o);
}
});
}
This is assuming you've got a function in a DatabaseService() class that maps a Firestore Collection to objects, and then have the ReorderableListView in a StreamBuilder that passes it a snapshot of said objects 'myObjects'.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
From Linux shell, how to batch-remove dust from images using scan of dust?
I have a large number of scans made with the same scanner. After noticing that there are a few consistent specs of dust on the images, I made a scan of the dust hoping to somehow remove the dust from the images, but I couldn't figure it out. Is there a way I can use ImageMagick (or similar scriptable utility that works on Linux) to use the scan of dust to (script-magically) remove the dust from the rest of the images?
A:
Dust removal using a dust mask can be done with G'MIC with the "Inpaint [Multi-Scale]" filter. The easiest way to use G'MIC is as a plugin for GIMP, Krita, or Paint.NET. However, it is available as a command-line utility.
Convert the dust image into a bitmap with pure red and white (or transparent) pixels. (G'MIC uses pure Red as the default mask color.)
Use ImageMagick to overlay the dust map over the original image. (Make sure they are aligned first. This step may be unnecessary if G'MIC is able to take the mask as input directly.)
Call G'MIC with the "Inpaint [Multi-Scale]" filter. (Look up usage in the command reference.)
Repeat with each image.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Removing one data element (value) at a time from variable and performing function in R
I am attempting to write code in R that permits me to:
Remove the first data element (value) from a variable (column) within a larger data frame.
Run a function on the full data frame (with the data element from step 1 removed).
Repeat this process for the remaining data elements in the column.
I've tried the following code and have run it without receiving errors. However, it is clear from the results that the data elements are not being successively removed as desired.
For context, my data frame (df) is 50x18 and the function that I am attempting to run from step 2 is a multiple imputation function. Here is my code:
procedure <- function(x) {
x <- NA
mice(df, m = 5, maxit = 5, method = "norm", pred = pred_matrix, seed = 2019)
}
results <- lapply(df$variable, procedure)
As desired, this code produces a list with 50 sets of output. However, it appears to perform the procedure 50 times on the same exact data frame. Thus, my question: Why isn't my code looping through each element in the data variable and removing it before running the procedure? I am not trying to shrink the data frame (remove a row). Instead, for each value (x) in the variable, I want to make the value "NA" (go missing) and then execute the procedure.
Thanks in advance!
A:
Assuming that the elements of df$variable are unique the following should work:
procedure <- function(x) {
df1 <- df
df1[df1$variable == x,"variable"] <- NA
mice(df1, m = 5, maxit = 5, method = "norm", pred = pred_matrix, seed = 2019)
}
results <- lapply(df$variable, procedure)
If they are not unique you can loop over the indices as follows:
procedure <- function(x) {
df1 <- df
df1[x,"variable"] <- NA
mice(df1, m = 5, maxit = 5, method = "norm", pred = pred_matrix, seed = 2019)
}
results <- lapply(1:length(df$variable), procedure)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is an appropriate cut radius for a semi-circle bench for a 36" round table?
I'm designing a dining room space, a 36" round pedestal table is ideal for this space, but I'd like to add a semi-circular bench on one side (like a booth at a bistro). I'm wondering what the ideal cut radius would be for the bench so that people can sit comfortably at the table (without leaning in too much, etc)?
Here is a simplistic, overhead view of the scenario. The table is in green, and the bench is in red.
A:
Table over hang is anywhere from 0-5 inches judging from these pictures' measurements and eyeballing what I've seen online. Meaning the seat is the same radius or smaller. If you call it at a 4" over hang per side then you need a 28" radius semi-circle cut in the bench. I slouch, so 2-4" is good for me. People with good posture probably expect 4-6".
Experiment with a chair and table to find your preference. Go to a restaurant that has booths, take some measurements and scale them to your table. I wouldn't make it any smaller though, unless you only expect your kids to sit there. I've never seen a corner booth smaller then say 4'. I'd better really like the dude I'm sharing my 28" circle of knee space with.
Your question was asked here: gardenweb.com, specifically suggesting to pay attention to the seat back distance from the table, to accommodate normal(?) sized humans. The differential of the radii is open to interpretation, the space between the table and the back of the seat isn't, generally to be not less than 18". (example 1 has it at 21")
http://www.centralrestaurant.com/bg-spaceplanning.html
https://m1.behance.net/rendition/modules/6133285/hd/ad04c5d37a255529d55320cc9d96b257.jpg
http://www.pinterest.com/pin/161074124148336216/
It doesn't seam like you'll be having a fixed table, and if the booth is built wrong, guests will be continually deciding 'where it goes'.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to make circled image in gimp?
I want to get a circular image from a rectangle image. You can see the image below, please.
A:
First things first, there is actually nothing as a circular image. Images that appear circular are due to the fact that the corners are made transparent and shaped such that a circle is portrayed.
With that clarification, I believe you have a clue about what you will do.
So you can go about it as follows:
First, make sure that your layer has an “alpha channel”.
Layer → Transparency → Add alpha channel
If it’s greyed out it means you already have one
Create a circular selection with the “Ellipse select tool” (the 2nd one in the toolbox).
Use the “Tool options” dialog
Windows → Dockable dialogs → Tool options
a) If you want a true circle, use the Fixed option: select Aspect ratio and enter 1:1.
b) Depending on what kind of marks you have, you can use:
i) The diagonal framing (default): click on one corner, drag across a full diagonal and release at the opposite corner.
ii) The radial framing (check Expand from center in the Tool options): click on the center, drag across a half diagonal release on a corner.
If the selection isn’t perfect on the first try, you can move it (click around the middle) or extend it (click inside, near a border or a corner).
Once you have the required selection, invert the selection (Select → Invert, or Ctrl-I) so that everything is selected, except your circle.
Erase the selection (Edit → Clear or [Delete] key). You should have your central circle left, surrounded by a checkerboard pattern. (this checkerboard is not part of the image, it just indicates the transparent parts of the image).
You can reduce the checkerboard to the minimum by auto-cropping the image (Image → Autocrop image)
Last, save the image in a format that supports transparency, like PNG (JPEG doesn’t support transparent images…)
If you are going to work further on the picture, save it as XCF (Gimp native format).
You may equally visit this link for more clarification: https://www.gimp.org/tutorials/CircleImage/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Retrieving coordinate positions using ChemicalData for input to quanutm modelling software
I am trying to set up an input file for a quantum chemical modelling software. How do I obtain the (XYZ) coordinate positions in Angstroms using information obtained using ChemicalData. Have some initial input for fructose below:
ChemicalData["Fructose", "AtomPositions"]
What I expect in the output (just an example not the actual positions)
Coordinates (Angstroms)
ATOM X Y Z
1 C 2.5130891440 -0.0345557109 -0.2500995821
2 O 0.0459435630 3.3652982874 1.6477735205
3 H 0.0347565292 2.5110247340 0.2498797086
.......
A:
Let's first pre-process the data you need for the output file to be used in your quantum simulation software:
pos = ChemicalData["Fructose", "AtomPositions"][[1]]/100.;
atype = ChemicalData["Fructose", "VertexTypes"][[1]];
data = Transpose[{atype, pos}];
Here's a function to give you the output file the way you specified in your question:
writeXYZ[file_String, data_] :=
Module[{str = OpenWrite[file, FormatType -> OutputForm], len = Length @ data},
Scan[WriteLine[str, #] &, {ToString @ len, " Coordinates (Angstroms)"}];
Scan[Write[str, " ", data[[#, 1]], PaddedForm[data[[#, 2, 1]], {14, 6}],
PaddedForm[data[[#, 2, 2]], {10, 6}],
PaddedForm[data[[#, 2, 3]], {10, 6}]] &, Range @ len];
Close[str]
]
Now, let's use it:
writeXYZ["test.xyz", data]
We can view the file to see what it looks like:
FilePrint["test.xyz"]
And here is what it looks like when imported
Import["test.xyz", "XYZ"]
Plot with Mathematica
radii = QuantityMagnitude @ Map[ElementData[#, "VanDerWaalsRadius"] &, atype] / 100.;
color = Map[ColorData["Atoms", #] &, atype];
Then:
Graphics3D[{Specularity[White, 40], MapThread[{#1, Sphere[#2, #3 / 1.2]} &, {color, pos, radii}]},
Boxed -> False]
A:
pos = ChemicalData["DFructose", "AtomPositions"]/100;
elems = ChemicalData["DFructose", "VertexTypes"];
positions = Transpose[{elems, pos}];
Grid[positions, Frame -> All]
Graphics3D[{ColorData["Atoms", #[[1]]], Sphere[#[[2]], .2]} & /@
positions, Axes -> True, Lighting -> "Neutral"]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to include the commands of envsetup.sh in Android?
Hi
I have run the command ./build/envsetup.sh on my source code of android while compiling.
I want to use the following commands present in the same file.
-cgrep
-mmm
-mm
but I get the following errors!!
Command 'pgrep' from package 'procps' (main)
Command 'fgrep' from package 'grep' (main)
Command 'egrep' from package 'grep' (main)
Command 'sgrep' from package 'sgrep' (universe)
Command 'grep' from package 'grep' (main)
Command 'lgrep' from package 'lv' (universe)
Command 'rgrep' from package 'grep' (main)
Command 'zgrep' from package 'gzip' (main)
Command 'dgrep' from package 'debian-goodies' (main)
Command 'vgrep' from package 'atfs' (universe)
Command 'ngrep' from package 'ngrep' (universe)
Command 'wcgrep' from package 'kdesdk-scripts' (main)
Command 'agrep' from package 'agrep' (multiverse)
Command 'xgrep' from package 'xgrep' (universe)
cgrep: command not found
How should I resolve this?
Do I need to make any changes in the envsetup.sh file?
A:
The mm, mmm and cgrep are defined as shell functions. What does the following return for you:
set | egrep "^mmm \(\)|^mm \(\)|^cgrep \(\)"
On my environment I get:
cgrep ()
mm ()
mmm ()
If you are getting nothing back, you are probably sourcing the script wrong. Remember you can't just make the script executable and run it as it won't be exporting the functions back to your shell. You must use either:
. build/envsetup.sh
OR
source build/envsetup.sh
to ensure it runs in parent shell.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Converting ADODB Loop into DAO
Hi I've been developing a vba project with a lot of help from examples here. I'm trying to access a MS Access database from Excel VBA and import large data sets (500-100+ rows) per request.
Currently, the following loop works using ADODB however, the Range("").Copyfromrecordset line is taking very long roughly 7 seconds per request.
Public Sub BC_Data()
Dim cn As New ADODB.Connection, rs As New ADODB.Recordset
Dim strCon, SQL As String
Dim ID As Integer
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=...\Database.accdb;"
cn.Open strCon
For i = 0 To n
ID = Range("A2").Offset(i, 0).Value
SQL = "SELECT [Sales] WHERE [ID] = " & ID & _
" AND [Date] >= #" & [A1].Text & "# AND [Date] <= #" & _
[B1].Text & "#;"
rs.Open SQL, cn
Range("C2").Offset(0, i).CopyFromRecordset rs
rs.Close
Next
cn.Close
Set rs = Nothing
Set cn = Nothing
End Sub
The SQL works fine and is just selecting each transaction for a given product ID and time period.
The reason I'm using this sort of loop is that the we only want the data for ~20 of the products at a time and they aren't necessarily in a sequence so the IDs could be 1,2,4, 7, 200, 205, 654 etc.
The IDs are stored in Column A and then the request loops through and pastes each new column in Columns C onwards.
I have 2 questions:
Will using a DAO connection instead of ADODB speed up this process? If so, how would I go about replicating this in DAO?
Is the method I'm using to loop through the IDs and then request an efficient one? Is there a faster method, maybe using a "For each" loop instead?
Thank you!
A:
DAO might be a little faster, but not materially. Instead, use an IN clause in your SQL Statement so you only have to do it once.
Sub test()
Dim vaIds As Variant
Dim sSql As String
vaIds = Split("1 2 4 7 200 205 654", Space(1))
sSql = "SELECT [Sales] WHERE [ID] In(" & Join(vaIds, ",") & ")" & _
" AND [Date] >= #" & [A1].Text & "# AND [Date] <= #" & _
[B1].Text & "#;"
Debug.Print sSql
End Sub
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Increase by one for each change in group in R
I'm trying to change this
data.frame(id=c(1,1,1,1,1,2,2), val=c('a','a','b','a','a','a','b'))
id val
1 1 a
2 1 a
3 1 b
4 1 a
5 1 a
6 2 a
7 2 b
into
id val
1 1 1
2 1 1
3 1 2
4 1 3
5 1 3
6 2 1
7 2 2
For each id, the value of val begins with 1 and increases by 1 when val changes.
A:
One dplyr possibility could be:
df %>%
group_by(id) %>%
mutate(val = with(rle(as.numeric(val)), rep(seq_along(lengths), lengths)))
id val
<dbl> <int>
1 1 1
2 1 1
3 1 2
4 1 3
5 1 3
6 2 1
7 2 2
The same idea using rleid() from data.table:
df %>%
group_by(id) %>%
mutate(val = rleid(val))
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Do I have to disclose my dual citizenship when applying for a US visa?
If you apply for a working visa to the US, but will be travelling and applying with your South African passport, must you disclose that you have a British passport as well? It asks the question do you have nationality with another country. I just don't want to complicate things so not sure whether to say yes or no.
A:
Yes, you should absolutely answer questions truthfully on immigration forms.
Giving false answers on an immigration form is a criminal offense. The consequences if your omissions is discovered are much more severe than any problems you will get from admitting dual nationality, and can include revoking your visa and being banned from the US.
It's very unlikely that having British nationality will negatively impact your application. Relations between the US and Britain have improved considerably in the last 200 years, they don't see being British as a negative.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I tell if an object is an Angular $q promise?
I have a pre-existing non-Angular API library in my project. It has a .request method which returns jQuery.Deferred promises. I created a simple Angular service which wraps the .request method to transform its result into an Angular $q promise instead. It looks something like this:
var module = angular.module('example.api', []);
module.factory('api', function(
$q,
$window
) {
function wrappedRequest() {
var result = $window.API.request.apply($window.API, arguments);
return $q.when(result);
};
return {
request: wrappedRequest
};
});
I would like to write a test which ensures that this service is functioning correctly. It will provide a mock $window with an API whose request method returns jQuery.Deferred promises. I need to ensure that the resulting objects are Angular $q promises.
How can I determine whether an object is an Angular $q promise?
For the example given in this question it would be sufficient to distinguish between jQuery.Deferred promises and Angular $q promises, but ideally we could identify Angular $q promises in general.
A:
Generally the better approach is to cast whatever object you do have into an Angular promise.
The concept of assimilating thenables is part of the Promises/A+ specification. Most promise libraries have a way to do this. It's what allows for awesome interop between promise implementations and a uniform API.
For this, $q uses .when :
Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.
It uses the concept of thenables to convert a 'non trusted' promise into a $q promise.
So all you have to do is
var p = $q.when(value); // p is now always a $q promise
// if it already was one - no harm
A:
As a partial solution, adequate and appropriate for the given example, we can easily distinguish between jQuery.Deferred promises and Angular promises by checking for the presence of specific methods. For instance, Angular's $q promises have the method catch to handle errors, while jQuery.Deferred's promises have the method fail.
function promiseIsAngularOrJQuery(promise) {
if (typeof promise.fail === 'function') {
return 'jquery';
} else if (typeof promise.catch === 'function') {
return 'angular';
} else {
throw new Error("this can't be either type of promise!");
}
}
However, using this technique to distinguish between more different types of promises, or between promises and non-promises, could get very messy. Different implementations often use use many of the same method names. It could probably be made to work, but I'm not going down that road.
There is an alternative that should be able to reliably identify $q promises under reasonable conditions: operating on trusted objects in a non-hostile environment, with only a single version of Angular in use. However, some might see it as too "hacky" for serious use.
If you convert a function to a string using the String() function, the result is the source code for that function. We just need to use this to compare the .then method on a potential promise object to the .then method of a known $q promise object:
function isAngularPromise(value) {
if (typeof value.then !== 'function') {
return false;
}
var promiseThenSrc = String($q.defer().promise.then);
var valueThenSrc = String(value.then);
return promiseThenSrc === valueThenSrc;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there a way to track the Simplify process?
Is there any way to track how Mathematica actually performs Simplify, so that we can see what those "Automatic" transformation functions it applies are and how it works with assumptions?
For example,
ClearSystemCache[];
Simplify[Sin[x]^2 + Cos[x]^2, ComplexityFunction -> ((Print[#]; LeafCount[#]) &)]
will output
Cos[x]^2+Sin[x]^2
Cos[x]^2+Sin[x]^2
Cos[x]^2+Sin[x]^2
Cos[x]^2+Sin[x]^2
Cos[x]^2+Sin[x]^2
1
1
1
Is there a way to see what Mathematica does between these steps?
A:
As Nasser stated in his comment,
TableForm[Trace[Simplify[Sqrt[x^2], x ∈ Integers], TraceInternal -> True]]
will provide you the information you seek. Most of the very long output you encountered comes from Mathematica loading packages needed to carry out the simplification. If you evaluate
TableForm[Trace[Simplify[Sqrt[x^2], x ∈ Integers], TraceInternal -> True]]
a second time, the packages will be already loaded -- the output will still be messy but the Trace results will print in their entirety.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
hibernate insert to a collection causes a delete then all the items in the collection to be inserted again
I have a many to may relationship CohortGroup and Employee. Any time I insert an Employee into the CohortGroup hibernate deletes the group from the resolution table and inserts all the members again, plus the new one. Why not just add the new one?
The annotation in the Group:
@ManyToMany(cascade = { PERSIST, MERGE, REFRESH })
@JoinTable(name="MYSITE_RES_COHORT_GROUP_STAFF",
joinColumns={@JoinColumn(name="COHORT_GROUPID")},
inverseJoinColumns={@JoinColumn(name="USERID")})
public List<Employee> getMembers(){
return members;
}
The other side in the Employee
@ManyToMany(mappedBy="members",cascade = { PERSIST, MERGE, REFRESH } )
public List<CohortGroup> getMemberGroups(){
return memberGroups;
}
Code snipit
Employee emp = edao.findByID(cohortId);
CohortGroup group = cgdao.findByID(Long.decode(groupId));
group.getMembers().add(emp);
cgdao.persist(group);
below is the sql reported in the log
delete from swas.MYSITE_RES_COHORT_GROUP_STAFF where COHORT_GROUPID=?
insert into swas.MYSITE_RES_COHORT_GROUP_STAFF (COHORT_GROUPID, USERID) values (?, ?)
insert into swas.MYSITE_RES_COHORT_GROUP_STAFF (COHORT_GROUPID, USERID) values (?, ?)
insert into swas.MYSITE_RES_COHORT_GROUP_STAFF (COHORT_GROUPID, USERID) values (?, ?)
insert into swas.MYSITE_RES_COHORT_GROUP_STAFF (COHORT_GROUPID, USERID) values (?, ?)
insert into swas.MYSITE_RES_COHORT_GROUP_STAFF (COHORT_GROUPID, USERID) values (?, ?)
insert into swas.MYSITE_RES_COHORT_GROUP_STAFF (COHORT_GROUPID, USERID) values (?, ?)
This seams really inefficient and is causing some issues. If sevral requests are made to add an employee to the group then some get over written.
Seams like equals and hashCode might be a reason for this. Below are the implementation for these methods. Any red flags?
CohortGroup
@Override
public int hashCode() {
final int prime = 31;
int result = getName().hashCode();
result = prime * result + ((emp == null) ? 0 : emp.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {return true;}
if (!(obj instanceof CohortGroup)) {return false;}
CohortGroup other = (CohortGroup) obj;
if(!getName().equals(other.getName())){return false;}
if (emp == null && other.getOwner() != null) {
return false;
} else if (!emp.equals(other.getOwner())) {
return false;
}
return true;
}
Employee
@Override
public boolean equals(Object obj) {
if (this == obj) {return true;}
if (obj == null) {return false;}
if (!(obj instanceof Employee)) {return false;}
Employee other = (Employee) obj;
if (EMPLID == null && other.getEMPLID() != null) {
return false;
} else if (!EMPLID.equals(other.getEMPLID())) {
return false;
}
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((EMPLID == null) ? 0 : EMPLID.hashCode());
return result;
}
I have added an addMember method to the CohortGroup that adds to both sides of the relationship:
public void addMember(Employee emp){
this.getMembers().add(emp);
emp.getMemberGroups().add(this);
}
Continued thanks to all that are helping.
A:
I highly suspect that you're not overriding equals and hashCode properly. Wrongly overriding them can lead to the kind of behavior you're experiencing (as the hash key is used as keys in maps). Double check what you did with equals and hashCode.
Using your annotated entities with good equals and hashCode, this code (logically equivalent):
Session session = HibernateUtil.beginTransaction();
Employee emp = (Employee) session.load(Employee.class, 1L);
CohortGroup group = (CohortGroup) session.load(CohortGroup.class, 1L);
group.getMembers().add(emp);
emp.getMemberGroup().add(group); // set the other side too!!
session.saveOrUpdate(group);
HibernateUtil.commitTransaction();
produces the following output on my machine:
08:10:32.426 [main] DEBUG o.h.e.d.AbstractFlushingEventListener - processing flush-time cascades
08:10:32.431 [main] DEBUG o.h.e.d.AbstractFlushingEventListener - dirty checking collections
08:10:32.432 [main] DEBUG org.hibernate.engine.CollectionEntry - Collection dirty: [com.stackoverflow.q2649145.CohortGroup.members#1]
08:10:32.432 [main] DEBUG org.hibernate.engine.CollectionEntry - Collection dirty: [com.stackoverflow.q2649145.Employee.memberGroup#1]
08:10:32.443 [main] DEBUG org.hibernate.engine.Collections - Collection found: [com.stackoverflow.q2649145.CohortGroup.members#1], was: [com.stackoverflow.q2649145.CohortGroup.members#1] (initialized)
08:10:32.448 [main] DEBUG org.hibernate.engine.Collections - Collection found: [com.stackoverflow.q2649145.Employee.memberGroup#1], was: [com.stackoverflow.q2649145.Employee.memberGroup#1] (uninitialized)
08:10:32.460 [main] DEBUG o.h.e.d.AbstractFlushingEventListener - Flushed: 0 insertions, 0 updates, 0 deletions to 2 objects
08:10:32.461 [main] DEBUG o.h.e.d.AbstractFlushingEventListener - Flushed: 0 (re)creations, 2 updates, 0 removals to 2 collections
08:10:32.463 [main] DEBUG org.hibernate.pretty.Printer - listing entities:
08:10:32.473 [main] DEBUG org.hibernate.pretty.Printer - com.stackoverflow.q2649145.CohortGroup{id=1, members=[com.stackoverflow.q2649145.Employee#1]}
08:10:32.474 [main] DEBUG org.hibernate.pretty.Printer - com.stackoverflow.q2649145.Employee{id=1, memberGroup=}
08:10:32.474 [main] DEBUG o.h.p.c.AbstractCollectionPersister - Inserting collection: [com.stackoverflow.q2649145.CohortGroup.members#1]
08:10:32.480 [main] DEBUG org.hibernate.jdbc.AbstractBatcher - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
08:10:32.491 [main] DEBUG org.hibernate.SQL - insert into MYSITE_RES_COHORT_GROUP_STAFF (COHORT_GROUPID, USERID) values (?, ?)
Hibernate: insert into MYSITE_RES_COHORT_GROUP_STAFF (COHORT_GROUPID, USERID) values (?, ?)
08:10:32.496 [main] TRACE org.hibernate.type.LongType - binding '1' to parameter: 1
08:10:32.497 [main] TRACE org.hibernate.type.LongType - binding '1' to parameter: 2
08:10:32.499 [main] DEBUG o.h.p.c.AbstractCollectionPersister - done inserting collection: 1 rows inserted
No delete before the insert!
By the way, note that you should set the link on both sides when working with bi-directional associations, like I did on the group and on the employee.
Or add defensive link management methods on your classes, for example on CohortGroup:
public void addToMembers(Employee emp) {
this.getMembers().add(emp);
emp.getMemberGroup().add(this);
}
public void removeFromMembers(Employee emp) {
this.getMembers().remove(emp);
emp.getMemberGroup().remove(this);
}
A:
I had this same problem and with some trial and error found that the deletes did not occur if I used a Set instead of a List as my collection. Irritating, given that I'm using JSF and the UI components will only iterate over Lists. But there it is.
A:
I have inserts acting the way I expect them to now. Thanks to Pascal and z5h, I have learned a lot. I believe I have the hashCode and equals implemented correctly. This never solved the problem for me though. Instead I have implemented an Intermediate Entity.
For what it is worth below are the mapping in my Employee, CohortGroup, and now CohortGroupMemeber classes.
Employee:
@OneToMany(mappedBy="member")
public List<CohortGroupMember> getMemberGroups(){
return memberGroups;
}
public void setMemberGroups(List<CohortGroupMember> grps){
memberGroups = grps;
}
CohortGroupMember
@ManyToOne
@JoinColumn(name="USERID")
public Employee getMember(){
return emp;
}
public void setMember(Employee e){
emp = e;
}
@ManyToOne
@JoinColumn(name="COHORT_GROUPID")
public CohortGroup getGroup(){
return group;
}
public void setGroup(CohortGroup cg){
group = cg;
}
CohortGroup
@OneToMany(mappedBy="group")
public List<CohortGroupMember> getMembers(){
return members;
}
public void setMembers(List<CohortGroupMember> emps){
members = emps;
}
The book I followed for this is Java Persistence with Hibernate chapter 7.2.3
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is that any similar thing like cache for Mobile(cordova)
I am developing a mobile apps using cordova 3.10 ,HTML5 and jquery mobile , The Apps will be targeting Apple, android, blackberry and windows phone. Currently the apps every time will call back to server and grab data. even though i switch page and back it also will call the page.
I would like to implement a cache for the apps , so that i can reduce the call to my server, but i have no idea where should start from for the caching method.
Any advice will be appreciate .
A:
Either use HTML5 caching or (as Daniel says), use local storage - lawnchair makes this pretty easy with Phonegap.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Should always use uppercase "I"?
Should "I" (first person pronoun) always be used in uppercase, or does it depend on situation (uppercase in the first word of a sentence)?
And why are other pronouns not capitalized?
A:
Yes, in standard written English, we always capitalize I.
From a Wikipedia page,
I (and only this form of the pronoun) is the only pronoun that is always capitalized. The practice became established in the late 15th century, though lowercase 'i' was sometimes found as late as the 17th century.
Additional information (to the question "Why are other pronouns not capitalized?"):
One thing that makes I unique is that I is the only one-letter pronoun. All other pronouns (including me, my, and mine) have two or more letters.
Further reading:
Why Do We Capitalize I?
Me, Myself and I - The New York Times
http://www.etymonline.com/index.php?term=I
(Special thanks go to GoDucks for the link to the article Me, Myself and I.)
A:
Yes, I (the pronoun) should always be capitalised.
A lowercase i means the letter "i" or Roman numeral 1. The only time a lower case pronoun I is acceptable is if done for reasons of style, for instance deliberately avoiding the use of all capital letters, such as alice, bob and i (normally Alice, Bob and I). I have read a published book written entirely this way, however, in mainstream writing this is usually frowned upon.
As to why the other pronouns are not capitalised, language doesn't have to have logical rules. In Latin the first letter of a sentence is not capitalised unless it is a proper noun. In German all nouns (not just proper nouns) are capitalised. English is no more or less logical than any other natural language, it's just different. The rules are somewhat arbitrary and sometimes we have evidence as to why it is the way it is and sometimes we don't.
I try to avoid mentioning other people answers, but in this case you already have some excellent links which I won't attempt to duplicate. I will, however, recommend the following entries on Wiktionary:
https://en.wiktionary.org/wiki/I#English (Capital I)
https://en.wiktionary.org/wiki/i#English (Lowercase i)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Add an extra option "All" in my dropdownlist
I have a dropdown list in Asp.net where I am extracting data directly to the dropdown list from SQL server. So apart from all the data that has been extracted to the dropdown list I want to put one more option "All" in my dropdown list. How could I do that?
Below there is the code for the dropdown list:
if (!Page.IsPostBack)
{
con.Open();
string s = "IPAddress";
SqlDataAdapter da = new SqlDataAdapter(s, con);
DataSet ds = new DataSet();
da.Fill(ds);
DropDownList5.DataTextField = "IPAddress";
DropDownList5.DataValueField = "IPAddress";
DropDownList5.DataSource = ds;
DropDownList5.DataBind();
con.Close();
}
A:
This is a possible way:
if (!Page.IsPostBack){
con.Open();
string s = "IPAddress";
SqlDataAdapter da = new SqlDataAdapter(s, con);
DataSet ds = new DataSet();
da.Fill(ds);
DropDownList5.DataTextField = "IPAddress";
DropDownList5.DataValueField = "IPAddress";
DropDownList5.DataSource = ds;
DropDownList5.DataBind();
con.Close();
DropDownList5.Items.Insert(0, "<-- All-->"); //add this line
}
Insert zero will add it at top of your dropdown.
Cheers,
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to automatically search and filters all engineers from linkedin and store results in excel?
Does anyone know how i can parse LinkedIn accounts? Or Any tool( not paid ).
For example:
I will look for "Software Engineer" from Dallas,TX.
Tool will automatically pick all candidates from linkedin or for example first 100 candidates, and store their First Name, Last Name , LinkedinLink and Experience in excel document? ( Or from specific company)
Is it should be done threw API, or there specific account which allow to do this? Or does anyone knows tools which will help to do this? Or Script?
I need to parse a large amount of candidates , 100+ maybe 1000+ and store them.
I have multiple thoughts about implementation but i feel that it 100% already implemented.
A:
https://developer.linkedin.com/docs/rest-api
Use linked in APIs to fetch data and process it however you would like. I don't know how much of 'private' fields you can get access to but names seem to be there.
I use nodeJS to process excel data - xlsx is a very good option but it only allows synchronous execution so you would have to spawn another process. It also has filter function so you can do whatever you want with it.
The problem that I had faced with parsing large data into excel is that excel file is a compressed xml format so it takes a long time to parse both reading and writing. A faster option would be to create and read csv which excel can naturally do as well.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is it possible to embed an HTTP basic username/password in a Paypal IPN notification URL?
I am building a site and it is currently protected by an HTTP Basic Auth username and password.
I want to test integration with Paypal IPN.
In the Paypal Sandbox account for my test seller, I specified my IPN Notification URL in the form:
http://USERNAME:PASSWORD@IP_ADDRESS/?QUERY_PARAMS
I have confirmed that this URL works correctly when I load it in an incognito Chrome window.
When I do a test purchase, Paypal does not seem to send the HTTP Basic Auth headers and the IPN notification fails because it can not authorize. I have also tested this using the IPN tester in the Paypal developer tools.
Is there a way to tell Paypal to send the necessary auth headers or do I have to reconfigure on the server side?
A:
It is not possible according to PayPal documentation, but if you are asking about real-world scenarios usually you have proxy-server in front of/as your web-server which handles simple HTTP auth and you can set up exclusion rules for your PayPal IPN urls. For example if you use Nginx, yourdirectives will look like:
server {
listen 80;
server_name example.com;
location /paypal/ipn {
try_files $uri @proxy_to_app;
}
location / {
auth_basic "Restricted";
auth_basic_user_file /example/.htpasswd;
try_files $uri @proxy_to_app;
}
location @proxy_to_app {
if (!-f $request_filename) {
proxy_pass http://localhost;
break;
}
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is the difference between passing a function as a prop with or without parentheses in React?
This is probably something that I should know but I don't quite understand the behavior of my component when I pass a function without parentheses. Here's my component code.
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import AppBar from 'material-ui/AppBar';
import LoginButton from './LoginButton';
import LogoutButton from './LogoutButton';
class Header extends Component {
renderButton() {
switch (this.props.auth) {
case null:
return
case false:
return <LoginButton />
default:
return <LogoutButton />
}
}
handleTitleClick() {
return(
<Link to={this.props.auth ? '/classes' : '/'}>
QueueMe
</Link>
);
}
render() {
const styles = {
title: {
cursor: 'pointer',
},
};
return(
<AppBar
title={<span style={styles.title}>QueueMe</span>}
onTitleClick={this.handleTitleClick()}
iconElementRight={this.renderButton()}
showMenuIconButton={false}
/>
);
}
}
/*
* @input: redux state
* Allows the component to access certain piece of the state as props
* Reducers determine the key in the state
*/
function mapStateToProps(state) {
return { auth: state.auth };
}
export default connect(mapStateToProps)(Header);
For my onTitleClick property in <AppBar>, I get the expected behavior when I pass it handleTitleClick() but when I pass it handleTitleClick and click it, I get an error that says Cannot read property 'auth' of undefined. What exactly is the difference here that causes the handleTitleClick not to be aware of the state?
A:
Good question! There are a few things wrong going on here. Javascript this can be a real pain. The problem is that your functions are not bound.
When you write onTitleClick={this.handleTitleClick()} you are immediately invoking the function at compile time. When you pass it handleTitleClick when you are providing an unbound function, it has no this defined.
There are two potential solutions, you can either define
handleTitleClick = (event) =>
return(
<Link to={this.props.auth ? '/classes' : '/'}>
QueueMe
</Link>
);
}
This makes handleTitleClick an arrow function, arrow functions bind their this to the closure that they were created in.
If you don't like using the IIFE way, you can always use
constructor(props) {
super(props)
this.handleTitleClick = this.handleTitleClick.bind(this)
}
Check this out if you're still stuck.
https://medium.freecodecamp.org/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can I say, "Choose your true, new flavour"?
What the phrase is expressing is, "Choose what's truly your favourite flavour".
Can I say, "Choose your true, new flavour"?
A:
Gramatically that's correct, but always think if the opposite makes sense.
Choose your false, old flavour
The true is absolutely unclear as to what it means - what does it mean a flavor is true? It's nowhere near implying "truly favorite". It could be interpreted as "real flavor of X" instead of an artificial substitute maybe, but that's stretching it.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Ionic 2 changing card text color
I've been trying to use ion-cards using ion dark theme, and I can't actually see the text;
I tried to change the CSS with this:
h2,p {
color:white;
}
and it's still black.
I took the code right from ionic documentation:
<ion-card class="col-md-4" *ngFor="let new of news;let i=index">
<ion-item>
<ion-avatar item-left>
<img [src]="new.image_url" *ngIf="new.image_url">
</ion-avatar>
<h2>TEST</h2>
<p>AA TEST</p>
</ion-item>
<ion-card-content>
<p>
TSET SUMMARY
</p>
</ion-card-content>
<ion-row>
<ion-col>
<button ion-button icon-left clear small>
<ion-icon name="thumbs-up"></ion-icon>
<div>12 likes</div>
</button>
</ion-col>
</ion-row>
</ion-card>
Any ideas?
A:
You can overwrite the ionic variable itself. Navigate the ./theme/variables.scss and add
$card-ios-text-color(#fff);
$card-md-text-color(#fff);
$card-wp-text-color(#fff);
All the ionic variables can be found here for quick reference
|
{
"pile_set_name": "StackExchange"
}
|
Q:
If I finish the campaign mode, will I get some benefit when I play on-line?
I know that I'll have visited the map and I'll probably have tried every weapon...
Benefits I'm thinking about are like a new class, stronger weapons, emblems, badges...
A:
To me, the singleplayer is useful for multiplayer as it lets you gauge the feel of the game; what movement feels like, how guns behave, what control setup works best for you, how the game engine and graphics feel. It's good for stuff like recognising what bits of scenery are easy to mistake for players, what sort of height of wall must be mantled and what can just be jumped over and so on. If you like the fiction of the game world, it also lets you get some idea of who the teams/factions are.
A:
If you mean will you unlock badges, better weapons for multiplayer then no. They all have to be unlocked by playing multiplayer only.
The only benefit you'll get is from more experience with the game. Like you say, you'll be more familiar with the weapons and slightly more familiar with the maps (although overall layout will be different).
I'd definitely recommend playing through single player first just to get your bearings with the game, but be advised multiplayer is a whole different ball game to single player, good luck!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
A list of suitable foods for a long hike
In my opinion, the priorities when selecting trekking food are:
maximizing calories per kilogram
not easily spoilable, especially in hot weather
reasonably priced
variety throughout the trip
I'm posting to help build a wider variety of ideas. I would like to see as long a list as possible of food for long( * ) authonomous(**) treks. Also would appreciate some evaluation on the uplisted priorities.
(*) - between a week and a month
(**) - i.e. no resupply
A:
To remedy the lack of sources (and hard numbers), I've started to write down here (for easier references) what is given for caloric values here: USDA Food Composition Databases.
Feel free to contribute. ALL CALORIC VALUES LISTED BELOW ARE IN KCALS FOR 100 GRAMS OF THE PRODUCT.
Pâté
Fish in tin cans
(+) practically never spoils
(+) can be warmed on the fire very conveniently, no additional dishes needed
(-) tin can difficult to dispose of - smells of fish, cuts skin very nasty, does not degrade if thrown away in nature (this can be remedied somewhat - tin cans can be transfered to sealed plastic bag using a vaccum machine and wouldn't spoil the product if done soon before leaving and under clean conditions)
(-) quite heavy, considering the weight of the sauce and of the can
Caloric values: 198 for tuna in oil
Dried meat
(+) long-lasting - can last almost a month in the summer
(+) high calories to weight ratio
Caloric value: varies depending. For beef jerky, 288 kcal show up in a few different products.
Salami
(+) long lasting
(+) small quantities add taste to bland ingredients
(+) high calories to weight ratio
(+) can be used cold or cooked
(+) high quality artisan products are easily available in continental Europe
Caloric value: about 420 for artisan Italian Salami. Varies.
Dried bread
(+) high calories to weight ratio
(+) cheap
(+) good for your stomach (fibres)
DIY: Put oil and toss bread chunks for 15 min on 150 degrees centigrade in the oven.
Small packages of cheese, vacuum
(+) tasty
(+) healthy food
(-) not very long-lasting - at most a week in the sun
(-) Freezes in winter. Lasts longer but not as convenient.
Caloric value: about 400 for cheddar cheese. Varies.
Note: "Small" package means such that can be eaten up in one day. If the group eats together maybe even 1kg can be considered sufficiently small.
Chocolate
(+) high calories to weight ratio
(+) easy to eat on the go
(+) rapid energy - chocolate is both psychologically stimulating and quick to give off energy (however, it is not a substitute for solid food)
Dried fruits and nuts
(+) high calories to weight ratio
(+) healthy food - especially those, containing Mn (apricots)
(+) easy to eat on the go
(+) diverse - get as many different types of dried fruits and nuts as possible
Caloric value: Regular trail mix weights in at 462 kcal/100g.
Couscous
(+) high calories to weight ratio - it's much denser than most forms of pasta so takes up less space, and can be cooked using much less fuel
(+) easy to cook - Mixed with a packet of dried soup or even just chilli powder it's reasonably palatable, or you can chuck in anything else you can find (meat, veg, etc).
(+) Requires less water than many other cooked meals.
(-) needs to be cooked
Caloric value: 376 for regular, dry couscous.
Quinoa
(+) Excellent nutritional value and high in protein
(+) Easy to cook, goes with many types of food
(+) Lightweight
(+) Requires less water than many other cooked meals.
(-) Needs to be cooked
Tahini paste
(+) healthy food
(-) needs to be cooked - typically you'll want to eat it with something else, not on its own- and then you need bread, crackers, or something similar for it
Caloric value: 368
Military Rations
(+) long shelf life
(-) bulky
(-) More expensive than DIY
Survival Energy Bars
(+) compact
(-) not good day to day food - they turn to powder very easily
Marmalade, Jam
(+) tasty addition to the main food
(-) problems with storage - usually sold in massive glass jars, other than that this food has very high calorie to weight ratio
Potato paste
(+) high calories to weight ratio
(+) can be cooked or just dissolved in cold water
(-) not tasty unless mixed with something else and probably cooked
Potato Chips:
(+) high calories to weight ratio
(+) tasty: different flavours plus they use industrial taste enhancers to make the good more marketable
(-) low in vitamins and micro nutrients
(-) crumbles
Nido (dried whole milk)
(+) high calories to weight ratio
Cookies:
(+) high calories to weight ratio
(-) good desert, especially combined with nido or tea
Sunflower/Olive Oil
(+) can be eaten raw (with bread) or used for cooking virtually anything
Caloric value: 884
Lentils
(+) Do not spoil
(+) Good ratio of nutrition to weight - beside calories, they provide much protein and micronutrients
(+) Easily cooked, just like rice (unlike beans, don't need to be soaked)
(+) They pair well with the concentrated tastes of preserved food (e.g. salted meat) and with foraged stuff (thyme, sorrel, etc.). Less bland than typical carb food (rice, couscous) when eaten alone.
(-) need cooking (watch out for the type: some, usually orange/yellow ones, are quite fast, while others may need an hour)
(-) the tent will smell
Caloric value: 180
Whole wheat pasta
(+) Do not spoil
(+) Good caloric value for weight
(+) Easy to cook (preferably go for thinner & compact varieties, such as thin spaghetinni)
(-) Needs to be cooked. For winter camping, you can either make it a soup or else you have to waste the water.
Caloric value: 352
Oatcakes
(+) long lasting
(+) high calories to weight ratio
(+) go well with cheese, spreads, salami etc
Caloric value: about 430.
Peanut Butter
(+) long lasting (not the 100% kind, though)
(+) highly caloric
(+) small volume
(+) comes in many package sizes, usually light but strong plastic jars with screw lid
(-) Usually requires something to spread it on
(-) Hardens in cold weather
Caloric value: 588
Honey
(+) does not spoil. (apparently literally never)
(+) small volume
(+) comes in many package sizes, including light but strong plastic jars with screw lid
(+) also serves as sweetener for tea/coffee
(-) Usually requires something to spread it on
Caloric value: 304
Other ideas:
tea - not for eating, but a must nevertheless
Powdered juices
smoked cheese
butter
instant soups & powdered sauces: you can add a bit of flavor a little cost
dried soiled fish
rice: Very easy for digestion hence very light food, yet a great source of carbohydrates.
Some of those are not particularly unspoilable. I bring them, and even move spoilable food for the first couple of days for a hike. Eat fresh at the beginning, eat light at the end.
Regardless of what you bring, you should never keep them in original packaging. It is better to portion out everything while at home, rather than having to do it in the bush (easy to do when the sun shines, not as fun when it's raining cows). You also save the weight. The objective should be that every "package" is in its own ziploc bag or such. You just need to take it out & cook it or eat it.
A:
Couscous is one of the best sources of carbohydrate I've found. It's much denser than most forms of pasta so takes up less space, and can be cooked using much less fuel. Mixed with a packet of dried soup or even just chilli powder it's reasonably palatable, or you can chuck in anything else you can find (meat, veg, etc).
A:
For pure calorific content, you cant beat Kendall Mint Cake.
Its basically glucose, sugar and some mint essence, stores very well, is light, cheap and you can even make some yourself easily enough. There's a reason Edmund Hillary took it to Everest :-)
Id also take lots of beef jerky, which is great protein for the weight.
Various flavours and substitutes exist such as turkey jerky. I had fish and squid jerky in ukraine recently, and they were great alternatives too.
Many people are suggesting canned goods, but I dont think Id want to be lugging these about personally, they're very heavy for what is essentially 1 can = 1 meal.
You mentioned finding water in the woods is easy, compared to finding food. That would make me think one of the best things you can take is a fishing rod, or maybe even a net. You could set this up in a river overnight and build a basic funnel/box from sticks. Even if it only worked on 2 nights, it would still be worth packing compared to 2 days food.
You could also spend some time reading up on various berries, plants and nuts growing in the woods. There are quite a few that are easy to identify, but obviously there are also some which are poisonous or best left to the experts to identify.
Finally Id want to be taking a lot of grains. Quinoa would be my choice, along with a few bags of herbs and spices (salt and pepper essential, garlic powder etc). These can make even the most boring meal a lot more tolerable.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why is this Pointer to Constant Pointer assignment Illegal?
int x = 10;
int * const p = &x;
const int **p1 = &p;
Having some trouble understanding why this is illegal.
EDIT
Thank you for all the great answers.
Here is my interpretation of the answers, feel free to disagree.
So, the error is in the 3rd line. It implies that original integer is constant but does not imply that the pointer it points to is constant and therefore it is illegal because we could attempt to change the pointer 'p' through 'p1' which is not possible because that is a constant pointer. So to fix this the third line must be:
int * const *p1 = &p;
This works because it says that while the original integer is non-constant (mutable) the pointer it points to is constant and therefore it is a legal statement. So this is also legal:
const int * const *p1 = &p;
This says the same thing except it also says that you cant change the original integer because it is constant.
A:
Something you need to get used to with pointer declarations is that you need to try reading them right to left. What matters is what's on each side of the *
int * const p means p is a const pointer to a non-const int
const int **p1 means p1 is a non-const pointer to a non-const pointer to a const int
Your second declaration fails because it creates a non-const variable from a const one.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Material UI: Cannot read property 'button' of undefined
import { createMuiTheme, ThemeOptions } from '@material-ui/core/styles';
const theme = (options: ThemeOptions) => {
return createMuiTheme({
palette: {
primary: {
main: '#b5ddd1'
},
secondary: {
main: '#b2d9ea'
},
},
typography: {
fontFamily: 'Raleway, Arial',
button: {
fontStyle: 'italic',
},
},
...options,
})
}
provider
import { ThemeProvider } from '@material-ui/core/styles'
<Provider store={store}>
<ConnectedRouter>
<ThemeProvider theme={theme}>
<GlobalStyles/>
{/*<ErrorBoundary>*/}
{/*<Layout>*/}
<Component {...pageProps} />
{/*</Layout>*/}
{/*</ErrorBoundary>*/}
</ThemeProvider>
</ConnectedRouter>
</Provider>
import Button from '@material-ui/core/Button'
<div>
<div>Log into APP</div>
<Button>Test</Button>
</div>
But I am still getting error in Button.js
at styles (/Users/filipbrezina/Documents/Projekty/sportee-frontend/node_modules/
material-ui/core/Button/Button.js:33:78
Can someone help me please? I don't know what am I doing wrong
A:
There is an error in the way you are defining / providing the theme:
You need to provide it like this:
<ThemeProvider theme={theme({})}> {/* function call: theme({}) */}
Or if you define it like this:
const theme = createMuiTheme({
palette: {
primary: {
main: '#b5ddd1',
},
// you can add more options
}
})
you can provide it this way:
<ThemeProvider theme={theme}>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Error: Class 'App\Model\Entity\DefaultPasswordHasher' not found
<?php
namespace App\Model\Entity;
use Cake\ORM\Entity;
/**
* User Entity.
*/
class User extends Entity
{
/**
* Fields that can be mass assigned using newEntity() or patchEntity().
* Note that '*' is set to true, which allows all unspecified fields to be
* mass assigned. For security purposes, it is advised to set '*' to false
* (or remove), and explicitly make individual fields accessible as needed.
*
* @var array
*/
protected $_accessible = [
'*' => true,
'id' => false,
];
protected function _setPassword($value)
{
$hasher = new DefaultPasswordHasher();
return $hasher->hash($value);
}
}
Here is my code in user.php.
I am hashing the password and got this one error
Error: Class 'App\Model\Entity\DefaultPasswordHasher' not found File
C:\xamp\htdocs\bookmarker\src\Model\Entity\User.php Line: 27
A:
I was missing the following line:
use Cake\Auth\DefaultPasswordHasher;
This was the reason why I got the error.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Unordered map in c++
I am trying to implement this problem in C++ using unordered map:
Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
My solution:
class Solution {
public:
int singleNumber(vector<int>& nums) {
std::unordered_map<int, int> umap;
for (auto i = nums.begin(); i != nums.end(); i++) {
umap[*i] = umap[*i] + 1;
}
for (auto i = umap.begin(); i != umap.end(); i++) {
if (umap[*i] == 1) {
return *i;
}
}
}
};
But unfortunately, it does not work. I get this error while compiling
Line 16: Char 17: fatal error: no viable overloaded operator[] for type 'std::unordered_map'
if (umap[*i] == 1) {
~~~~^~~
/usr/bin/../lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/bits/unordered_map.h:973:7: note: candidate function not viable: no known conversion from 'std::pair' to 'const std::unordered_map, std::equal_to, std::allocator > >::key_type' (aka 'const int') for 1st argument
operator[](const key_type& __k)
^
/usr/bin/../lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/bits/unordered_map.h:977:7: note: candidate function not viable: no known conversion from 'std::pair' to 'std::unordered_map, std::equal_to, std::allocator > >::key_type' (aka 'int') for 1st argument
operator[](key_type&& __k)
^
1 error generated.
I cannot understand the error. Can anyone explain to me?
A:
You do not need std::unordered_map as std::unordered_set would be sufficient in this case:
std::unordered_set<int> set;
for( auto i : nums ) {
auto p = set.insert( i );
if( !p.second ) set.erase( p.first );
}
So logic is you try to insert a number, but if it was already there you remove it. Another benefit of this approach beside smaller memory footprint is that after loop you will have only one element in the set - one you need. So you do not need to iterate and search.
But proper solution is a trick that you should be aware about. It based of the properties of xor operation:
A xor A == 0 for any A
A xor 0 == A for any A
and because xor operation has commutative property as well:
A xor B xor A == A xor A xor B == 0 xor B == B
I think you now can get the idea of implementation without additional memory.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can jenkins slave connect to multiple servers?
We have several parallel development groups working on different things in separate environments. Each group has a jenkins server/2 windows slaves setup that is executing selenium nunit tests.
Is it possible to to have all the slave instances in a pool that each of the jenkins servers can pick from? We are using the JNLP b/c there are issues with some of the browser tests that require running in an interactive desktop. I thought perhaps I could start a JNLP for each server instance on each machine, but that seemed the wrong way as each server would have no knowledge of other servers use of it. Is there any way to make a slave available to multiple servers?
A:
I don't think you can do what you are looking for.
You can run multiple slaves on one computer, but as you said, there is no way to keep multiple servers from trying to access the same desktop.
A better solution is probably to combine your Jenkins servers. You can use the security settings and views to set it so that regular users are not even aware of the other projects being run in parallel- while allowing one Jenkins server to coordinate all of the builds (which is what you want).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to get the touching position of large image in android
I need to get the touching position of image in android. Let me explain in detail as i am having a image user can touch and do pinchzoom for image resizing. When user touch the certain position i need to show the details about the particular position of image in seperate position.
If the image is in the fixed size of screen size then no problem to find position it should fized for all device. How it possible? can any please help me..
A:
OnTouchListener{
@Override
public boolean onTouch(View v, MotionEvent mv) {
float x = mv.getRawX();
float y = mv.getRawY();
return true;
}
This will give you the screen position of the touch. If you need to calculate the X/Y within the image which isn't the full size of the screen you can get the start X/Y coordinates of the image with
v = (ImageView) findViewById(R.id.myImageView);
float v_x = v.getTop();
float v_y = v.getLeft();
float real_x = x - v_x;
float real_y = y - v_y;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
replace fragment in fragmentstatepageradapter
i need to disable a fragment based on the menu id array retrieved from the server. i already retrieved the menu id but i do not know how to replace the equivalent fragment for that id. do i need to use fragmentmanager and fragmenttransaction. i can't use getSupportFragmentManager or getFragmentManager in FragmentStatePagerAdapter. i used framelayout before but not viewpager. please help
this is my code
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
String tabName;
PreferencesHelper prefHelp;
final FragmentManager disablefm;
SharedPreferences disabledMenu;
SharedPreferences.Editor editor;
Context ctx;
public PagerAdapter(FragmentManager fm, int NumOfTabs, Context context) {
super(fm);
this.mNumOfTabs = NumOfTabs;
disablefm = fm;
ctx = context;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
CallFragment tab1 = new CallFragment();
return tab1;
case 1:
ChatFragment tab2 = new ChatFragment();
return tab2;
case 2:
RoomServiceMenu tab3 = new RoomServiceMenu();
return tab3;
case 3:
HouseKeepingFragment tab4 = new HouseKeepingFragment();
//MealFragment tab4 = new MealFragment();
return tab4;
case 4:
//dnd
DndFragment tab5 = new DndFragment();
return tab5;
case 5:
//open door
OpenDoorFragment tab6 = new OpenDoorFragment();
return tab6;
case 6:
ServiceFragment tab7 = new ServiceFragment();
return tab7;
case 7:
//chauffeur
ChauffeurFragment tab8 = new ChauffeurFragment();
return tab8;
case 8:
SpecialOfferFragment tab9 = new SpecialOfferFragment();
return tab9;
default:
return null;
}
}
private void loadPref(){
disabledMenu = PreferenceManager.getDefaultSharedPreferences(ctx);
int disabledmenuSize = Integer.parseInt(prefHelp.getPreferences("disable menu length"));
String disabledMenuarray[] = new String[disabledmenuSize];
Log.d("log1", "disabled menu len: "+disabledmenuSize);
for(int u = 0; u < disabledmenuSize; u++){
disabledMenuarray[u] = prefHelp.getPreferences("disabledMenuId"+u);
Log.d("log1", "disabled menu id# "+u+" id: "+Arrays.toString(disabledMenuarray));
if(Arrays.asList(disabledMenuarray).contains("20")){
Log.d("log1", "main | pref contain id 20");
//disable call fragment
}
}
}
@Override
public int getCount() {
return mNumOfTabs;
}
}
A:
hey i already figured out how to do what i want.
here's my code:
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
String tabName;
PreferencesHelper prefHelp;
FragmentManager disablefm;
SharedPreferences disabledMenu;
SharedPreferences.Editor editor;
Context ctx;
Boolean roomSrvOn, houseKeepOn, dndOn, doorOn, spaOn, chauffeurOn, offerOn, callOn;
public PagerAdapter(FragmentManager fm, int NumOfTabs, Context context) {
super(fm);
this.mNumOfTabs = NumOfTabs;
disablefm = fm;
ctx = context;
disabledMenu = PreferenceManager.getDefaultSharedPreferences(ctx);
Log.d("log1", "pager ctx: "+ctx);
}
@Override
public Fragment getItem(int position) {
roomSrvOn = true;
houseKeepOn = true;
dndOn = true;
doorOn = true;
spaOn = true;
chauffeurOn = true;
offerOn = true;
callOn = true;
//disable menu
prefHelp = new PreferencesHelper(ctx);
int disabledmenuSize = ((MainActivity)ctx).disabledmenuSize;
String disabledMenuarray[] = new String[disabledmenuSize];
Log.d("log1", "pager | disabled menu len: "+disabledmenuSize);
for(int u = 0; u < disabledmenuSize; u++){
disabledMenuarray[u] = prefHelp.getPreferences("disabledMenuId"+u);
Log.d("log1", "pager | disabled menu id# "+u+" id: "+Arrays.toString(disabledMenuarray));
if(Arrays.asList(disabledMenuarray).contains("20")){
Log.d("log1", "pager | call disabled");
callOn = false;
}else if(Arrays.asList(disabledMenuarray).contains("10")){
Log.d("log1", "pager | room service disabled");
roomSrvOn = false;
}else if(Arrays.asList(disabledMenuarray).contains("8")){
Log.d("log1", "pager | house keeping disabled");
houseKeepOn = false;
}else if(Arrays.asList(disabledMenuarray).contains("17")){
Log.d("log1", "pager | dnd disabled");
dndOn = false;
}else if(Arrays.asList(disabledMenuarray).contains("14")){
Log.d("log1", "pager | open door disabled");
doorOn = false;
}else if(Arrays.asList(disabledMenuarray).contains("11")){
Log.d("log1", "pager | spa disabled");
spaOn = false;
}else if(Arrays.asList(disabledMenuarray).contains("19")){
Log.d("log1", "pager | chauffuer disabled");
chauffeurOn = false;
}else if(Arrays.asList(disabledMenuarray).contains("18")){
Log.d("log1", "pager | offer disabled");
offerOn = false;
}
}
switch (position) {
case 0:
if(callOn == false){
DisabledFragment tab1 = new DisabledFragment();
return tab1;
}else {
CallFragment tab1 = new CallFragment();
return tab1;
}
case 1:
ChatFragment tab2 = new ChatFragment();
return tab2;
case 2:
if(roomSrvOn == false){
DisabledFragment tab3 = new DisabledFragment();
return tab3;
}else {
RoomServiceMenu tab3 = new RoomServiceMenu();
return tab3;
}
case 3:
if(houseKeepOn == false){
DisabledFragment tab4 = new DisabledFragment();
return tab4;
}else {
HouseKeepingFragment tab4 = new HouseKeepingFragment();
//MealFragment tab4 = new MealFragment();
return tab4;
}
case 4:
if(dndOn == false){
DisabledFragment tab5 = new DisabledFragment();
return tab5;
}else {
//dnd
DndFragment tab5 = new DndFragment();
return tab5;
}
case 5:
if(doorOn == false){
DisabledFragment tab6 = new DisabledFragment();
return tab6;
}else {
//open door
OpenDoorFragment tab6 = new OpenDoorFragment();
return tab6;
}
case 6:
if(spaOn == false){
DisabledFragment tab7 = new DisabledFragment();
return tab7;
}else {
ServiceFragment tab7 = new ServiceFragment();
return tab7;
}
case 7:
if(chauffeurOn == false){
DisabledFragment tab8 = new DisabledFragment();
return tab8;
}else {
//chauffeur
ChauffeurFragment tab8 = new ChauffeurFragment();
return tab8;
}
case 8:
if(offerOn == false){
DisabledFragment tab9 = new DisabledFragment();
return tab9;
}else {
SpecialOfferFragment tab9 = new SpecialOfferFragment();
return tab9;
}
default:
return null;
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Need Quartis II CPLD tutorial for learning VHDL from ZERO
I am learning VHDL from zero using Altera CPLD. Already got Quartis II 12.1 and a 15-lines example VHDL (like Hello World for C learner).
To avoid learning bad coding style or digging too deep too early, what should I look out for?
A:
This page has a (PDF) book that is quite good on the process of learning the tools and the stages between VHDL and a working design. It uses the Xilinx tools and an FPGA but the steps are similar for Altera.
Plus it costs nothing except disk and bandwidth to download the Xilinx tools and have them on hand for comparison.
In particular he says quite a lot that I skipped over, on the process of diagnosing and optimising performance problems.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
JavasScript alert() Angular 2 simple equivalent?
I need to display an alert box when clicking on a div. In pure JavaScript (vanilla.js) this would be
alert("message displayed");
How would I do that in Angular2 in the most simple way possible?
A:
It is the same in angular as well.Since window is a global object and is accessible directly in your class
alert("message displayed");
DEMO
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Redirect to detail page lightning page
Ik have found this example of a controller directing to the account detailpage lightning component of account which works. I am trying to reproduce this for a custom component but my links shows /s/test123 and keeps loading when I remove test123 and replace with detail/id it works
where does this link test123 come from? am I missing something?
Class Account
public class NavigateToAccountController {
@AuraEnabled
public static String getLoggedInUser(){
User currentUser = [SELECT Id, Contact.AccountId FROM User WHERE Id =: UserInfo.getUserId() LIMIT 1];
if(currentUser.contact.AccountId != null){
return currentUser.contact.AccountId;
}else{
return 'NULL';
}
}
}
Controller lightning account
({
redirectToAccount: function(component, event, helper) {
var AccountId;
var state;
var navEvt;
var action = component.get("c.getLoggedInUser");
action.setCallback(this, function(response) {
state = response.getState();
if (state === "SUCCESS") {
AccountId = response.getReturnValue();
//console.log(AccountId);
if (AccountId != 'NULL'){
navEvt = $A.get("e.force:navigateToSObject");
navEvt.setParams({
"recordId": AccountId,
"slideDevName": "detail"
});
navEvt.fire();
} else{
var toastEvent = $A.get("e.force:showToast");
toastEvent.setParams({
"title": "Error!",
"message": "Logged in user don't have Account Id associated"
});
toastEvent.fire();
}
}
});
$A.enqueueAction(action);
}
})
Class custom object
public class NavigateToProfielController {
@AuraEnabled
public static String getLoggedInUser(){
User currentUser = [SELECT Id, Contact.Profiel__r.name FROM User WHERE Id =: UserInfo.getUserId() LIMIT 1];
if(currentUser.Contact.Profiel__r.name!= null){
system.debug('currentUser.Contact.Profiel__r.name '+ currentUser.Contact.Profiel__r.name);
return currentUser.Contact.Profiel__r.name;
}else{
return 'NULL';
}
}
}
Controller lightning custom object
({
redirectToProfiel: function(component, event, helper) {
var Profielid;
var state;
var navEvt;
var action = component.get("c.getLoggedInUserContact");
action.setCallback(this, function(response) {
state = response.getState();
if (state === "SUCCESS") {
Profielid = response.getReturnValue();
//console.log(Profiel__c.id);
if (Profielid != 'NULL'){
navEvt = $A.get("e.force:navigateToSObject");
navEvt.setParams({
"recordId": Profielid,
"slideDevName": "detail"
});
navEvt.fire();
} else{
var toastEvent = $A.get("e.force:showToast");
toastEvent.setParams({
"title": "Error!",
"message": "Logged in user don't have Contact Id associated"
});
toastEvent.fire();
}
}
});
$A.enqueueAction(action);
}
})
Component code
<aura:component controller="NavigateToProfielController" implements="forceCommunity:availableForAllPageTypes" access="global">
<aura:handler name="init" value="{!this}" action="{!c.redirectToProfiel}"/>
A:
In your controller method (NavigateToProfielController.getLoggedInuser), you are returning the name of your user, and not the Id for that user (return currentUser.Contact.Profiel__r.name), which is then inserted to ProfielId in your lightning js controller, and finally placed in your e.force:navigateToSObject param for recordId. As a result, instead of force.com/s/*record_id_here, you will get force.com/s/*name_of_record_here.
Try updating your query to return the Contact.Profiel__c to get your Id, and return that.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
quantmod getFinancials() not pulling financials
I'm looking to download fundamental data for public companies. Utilizing the quantmod package, I was trying to use getFinancials() to pull data, for which it works for some companies but has varied results (I read and understand the disclaimer about free data) but want to confirm that I am pulling this correctly.
For JPM:
On the Yahoo finance website, I do see financials populated, but the below call seems to pull "google" as the src instead of "yahoo", for which there are sparse financials populated.
Google - https://www.google.com/finance?q=NYSE%3AJPM&fstype=ii&ei=9kh-WejLE5e_etbzmpgP
Yahoo - https://finance.yahoo.com/quote/JPM/financials?p=JPM
library(quantmod)
JPM <- getFinancials("JPM", src = "yahoo", auto.assign = FALSE)
viewFin(JPM, type = "IS", period = "A")
Is there a correct way to specify the src? Also is there a way to use getFinancials() but if there is a NA in an indicative column (Revenues for example) switch the source (google vs. yahoo)?
A:
The top of the help page for getFinancials says (emphasis added),
Download Income Statement, Balance Sheet, and Cash Flow Statements from Google Finance.
There is currently no way to specify Yahoo Finance as a source. Doing so would require someone to write a method to scrape and parse the HTML from Yahoo Finance, since there's no way to download it in a file like there is for price data.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Get inserted id if inserted happend by REPLACE INTO
I'm using REPLACE INTO to update the row where mod_id is the unique/primary key. I wanted to know the mysql_inserted_id() if it was inserted.
I tried this:
$query_2 = $DB->query('REPLACE INTO mods (mod_id, group_id, css) VALUES (0, 4585, "css string")');
$inserted_id = mysql_insert_id();
But I keep getting $inserted_id of 0 even if an insert happend.
A:
I think, its better to use INSERT... ON DUPLICATE KEY UPDATE. The reason being REPLACE always delete the old row optionally and then insert new row. While INSERT...ON DUPLICATE KEY UPDATE, tries to update the existing row as far as possible (based on primary or unique keys). And you can last_insert_id()
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Slideshow crashes FF
I have a slideshow working perfectly on every browser except FF. I know the slideshow is the problem because it is only on the homepage and every other page loads fine, but I can't figure out what's wrong. I made this fiddle and put the exact same code, and all I can see is that FF is a bit slower but that's it. The actual homepage crashes or, at the very best, the slides move at about 1 cm per second.
Can someone take a look at the code? I know I must be missing something.
Thanks in advance.
EDIT:
Here's the actual link
A:
Strange, I didn't change anything but it is working now, so problem solved.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Extracting soccer scores from website
I am trying to extract several data from http://www.rsssf.com/tablese/eng2014.html such as the league standings as well as the scores for each round into R.
I know that I am trying to use XML, RCurl package can be used but i am not totally sure of the way to do it.
Referring to this:
Scraping html tables into R data frames using the XML package
library(XML)
theurl <- "http://en.wikipedia.org/wiki/Brazil_national_football_team"
tables <- readHTMLTable(theurl)
n.rows <- unlist(lapply(tables, function(t) dim(t)[1]))
the picked table is the longest one on the page
tables[[which.max(n.rows)]]
I still cant get the table on the website. Really appreciate if anyone can help me with this. Thanks!
A:
The reason you are having trouble is that the given table is NOT an HTML Table. You can see that by using View Page Source in your browser. Here is some code to help you get started with extracting the data in the table and putting it into a data frame.
dat = readLines('http://www.rsssf.com/tablese/eng2014.html', warn = F)
start = grep('Table', dat)[1] + 2
end = grep('Round', dat)[1] - 2
dat2 <- dat[start:end]
dat3 = read.fwf(textConnection(dat2), widths = c(3, 24, 3, 3, 3, 3, 8, 3))
dat3[dat3$V1 != "---",]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Delphi XE8 TThread Frozen on Android, but works on Windows
I use one thread and a synchronized procedure for a simple game loop.
On my computer, Windows 7, it works as a charm but when I run it on my android device and after I click play and the thread starts the screen goes black or sometimes dim, and sometimes it stays normal but all objects visible on screen either stretch or fail to render properly; at this point the thread seems to be frozen (The music from the main form still continue to play).
Here is the thread itself:
procedure TTheThread.Loop;
begin
MainForm.GameLoop;
end;
procedure TTheThread.Execute;
begin
while NOT Terminated do
begin
Application.ProcessMessages;
TC:= TStopwatch.GetTimeStamp;
//The Following repeats itself every second:
if TC>(TCTime+10000000) then
begin
TCTime:= TStopwatch.GetTimeStamp;
TimeT:= TimeT+1; //Time in seconds
//Increasing game playing speed:
Gravity:= Gravity + 0.0075 * DEF;
PJump:= PJump+IncJump
end;
//...just to have it on screen:
With MainForm do
Label1.Text:= IntToStr(TC);
//This seems to make the loop run smooth and without lagging on my PC:
if TC>(TCLast) then
begin
Synchronize(Loop);
TCLast:= TC;
end;
end;
end;
This is how it starts:
TCTime:= TStopwatch.GetTimeStamp;
TCLast:= TCTime;
GameThread:= TTheThread.Create(True);
GameThread.FreeOnTerminate:= True;
GameThread.Start;
A:
Your thread has some unsafe code in it, which can easily cause deadlocks and dead UIs (amongst other issues). DO NOT access UI controls directly in a thread, you must synchronize with the main UI thread, such as with TThread.Synchronize() or TThread.Queue(), eg:
TThread.Synchronize(nil,
procedure
begin
MainForm.Label1.Text := IntToStr(TC);
end
);
Also, do not call Application.ProcessMessages() in a thread, either. It belongs in the main UI thread only. And even then, if you have to report to calling it at all, you are likely doing something wrong to begin with. Under normal conditions, you should never have to resort to calling it manually.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
XML Schema Children With the Same Element
I am trying to write an XML schema for a server that accepts images. The images should either all have a mask or none should.
I would like to produce an XML like this:
<?xml version="1.0" encoding="utf-8"?>
<FIVR>
<meal>
<media>
<image2D filename="filename1">
<mask filename="filename1" />
</image2D>
<image2D filename="filename2">
<mask filename="filename1" />
</image2D>
<image2D filename="filename3">
<mask filename="filename1" />
</image2D>
<image2D filename="filename4">
<mask filename="filename1" />
</image2D>
<image2D filename="filename5">
<mask filename="filename1" />
</image2D>
</media>
</meal>
</FIVR>
or
<?xml version="1.0" encoding="utf-8"?>
<FIVR>
<meal>
<media>
<image2D filename="filename1">
</image2D>
<image2D filename="filename2">
</image2D>
<image2D filename="filename3">
</image2D>
<image2D filename="filename4">
</image2D>
<image2D filename="filename5">
</image2D>
</media>
</meal>
</FIVR>
But if some image2D elements have a mask child element but others dont, validation should fail. E.g the following should be rejected:
<?xml version="1.0" encoding="utf-8"?>
<FIVR>
<meal>
<media>
<image2D filename="filename1">
</image2D>
<image2D filename="filename2">
<mask filename="filename1" />
</image2D>
<image2D filename="filename3">
<mask filename="filename1" />
</image2D>
<image2D filename="filename4">
</image2D>
<image2D filename="filename5">
</image2D>
</media>
</meal>
</FIVR>
Can I express this using an XSD schema?
The schema I have right now looks like this:
<xs:element name="FIVR">
<xs:complexType>
<xs:sequence>
<xs:element name="meal" minOccurs="1" maxOccurs="1">
<xs:complexType>
<xs:sequence>
<xs:element name="media" minOccurs="1" maxOccurs="1">
<xs:complexType>
<xs:choice>
<xs:element name="image2D" minOccurs="5" maxOccurs="5" >
<xs:complexType>
<xs:all minOccurs="0">
<xs:element name="mask">
<xs:complexType>
<xs:attribute name="filename" type="xs:string" use="required"/>
</xs:complexType>
</xs:element>
</xs:all>
<xs:attribute name="filename" type="xs:string" use="required"/>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
A:
A simple solution would be to declare media as taking either a sequence of maskless images, or a set of images with masks. Since these two flavors of image have different validation behavior, it's simplest if you give them different names. Then the content model becomes something like
<xs:choice>
<xs:element ref="image2D-mask" maxOccurs="unbounded"/>
<xs:element ref="image2D-nomask" maxOccurs="unbounded"/>
</xs:choice>
The root of your difficulty is the desire to use the same name for two different things.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Server a static pdf - Vue CLI - Webpack - issue
I build a little front thanks to VueCLI (+ Vuetify).
I wanted to render a button where onClick open a new tab with a pdf located in the folder's tree of the project.
I have an error and after hours looking why, it's seems to be a webpack conf to modify.
I finally read this answer on S/O ; Serving static pdf with react webpack file loader
But I got an error saying include: paths -> paths is not defined
I have to admit that I have no clue how webpack works behind the scene so any help would be find.
A:
You probably don't need Webpack for this: you can just put it in your static folder and link to it <a href="/static/mypdf.pdf">pdf</a>. If you want to go the Webpack route, put it in your src/assets directory and import it and add it to data object:
import pdf from '../assets/mypdf.pdf'
//...
data: () => ({ pdf })
//...
Then use the link in your component:
<a :href="pdf">pdf</a>
You probably added include: paths to the loader config but you didn't define it, instead of modifying your image loader, add a new one for PDFs:
{
test: /\.(pdf)(\?.*)?$/,
loader: 'url-loader',
options: {
name: utils.assetsPath('[name].[hash:7].[ext]')
}
}
You can change [name].[hash:7].[ext] if you want, say you want to add a pdfs directory in assets instead of using the base assets directory you would use: pdfs/[name].[hash:7].[ext]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Ruby. How to write a loop of 1% percentage profit for one year on a 1000$ investment
I'd like to create a ruby program to calculate the 1% on my investment every day for one year.
For example, if I invest 1000$ and get a profit of 1% at the end of the day will be 1010.0$ The second day I will invest 1010.0$ and I will get a 1% profit of 1020.1$ and so on.
I'd like to determine after 365 days what will be my initial investment.
I'm trying with a loop to print every single returning value but as you see I'm still a superrookie.
Thanks. Sam
I made it alone! Thanks for all of your answers!
money = 1000
days = 0
perc = 0.01
while days < 366
puts days
puts money
days += 1
money = money * perc + money
end
A:
You should use BigDecimal instead of Float when dealing with monetary values:
require 'bigdecimal'
money = BigDecimal('1000')
percentage = BigDecimal('0.01')
For the loop I'd use upto which works very intuitively:
1.upto(365) do |day|
money += (money * percentage).round(2)
printf("%3d: %8.2f$\n", day, money)
end
money * percentage calculates the day's profit, rounded to 2 digits via round. You can adjust the rounding mode by passing a second argument.
printf then outputs day and money using the given formatting:
%3d prints an integer with width 3
%8.2f prints a float with 2 fractional digits and a total width of 8
Output:
1: 1010.00$
2: 1020.10$
3: 1030.30$
...
363: 37039.07$
364: 37409.46$
365: 37783.55$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
404 error when changing language on category
I've got a shop with two store:
DE (Store name: DE), (Store view: de, code: de)
UK (Store name: UK), (Store view: en, code: en)
By default, the shop is DE (German)
I've got a 404 error when : I go to the shop, go on a category and try to change the language to en (English).
I figure out that :
sitename.com/en/modern-carpets.html?___store=en&___from_store=de -> work
sitename.com/en/modern-carpets.html -> doesn't work
And also that if I switch off my cookies in my browser, everything is working.
I am using magento community 1.9.1.0
Already thank you that you took time to read my issue.
A:
This issue can be come for cookie is not being saved on your store.
Please check your browser cookie after switching language. There must have one cookie with a name of 'store'.
If you can not found that Then please go the system->configuration->web section and please set up session cookie management on a right way
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Priming and bottling for a first timer
It's been about ten days since I started fermenting my beer, and it didn't create bubbles in the air lock until day two or three. The air lock is still bubbling, should I begin priming and bottling? Also, my kit only came with a fermenter, not a bucket to prime and bottle with. The fermenter has a spigot at the bottom of it, could I just add the priming solution and then pour out of the spigot to fill my bottles...or will that include too much of the unwanted proteins and such? Please let me know your thoughts, being my first time, it's a little confusing....and at times frusterating. Thanks in advance!
A:
I recommend getting a bottling bucket and wand. It will make the operation a little easier. You need to stir in your priming sugar to get it homogenous throughout the beer. Otherwise, some bottles will be more carbed than others. Mixing in the fermenter will stir up all that sediment in the bottom, so that's no good. Secondly, yes trying to just bottle out the base will take too much of that trub into the bottles.
If you don't have a hydrometer, you need to get one. If its still actively bubbling after only 7-8 days of fermentation its probably still going. The only way to tell is to take a gravity reading once a day for a couple days. I routinely let my beers go for 14 days minimum before I even think of what to do next. In the case of being such a novice brewer the process often takes longer because of yeast issues.
Sorry that it seems so frustrating. I'd recommend looking into a couple good books like How to Brew or The Complete Joy of Homebrewing. Are you getting some advice from your local homebrew shop? Some shops do hand out really poor advice sometimes. Just stick with it and keep asking questions on sites like this. You'll get it all figured out pretty quickly. Making beer shouldn't be that tough.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Android: How to Enable/Disable Wifi or Internet Connection Programmatically
Using the Connectivity Manager Class we can get access to either wifi or Internet Network:
ConnectivityManager connec = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
// ARE WE CONNECTED TO THE NET
if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED ||
connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED ) {
// ...
}
where 0 and 1 respectively refers to mobile and wifi connection
If my Android device is connected to both, can we switch between any of the network or can we disable any of the network? Like using a function:
connec.getNetworkInfo(0).setState(NetworkInfo.State.DISCONNECTED);
A:
I know of enabling or disabling wifi:
WifiManager wifiManager = (WifiManager)this.context.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(status);
where status may be true or false as per requirement.
Edit:
You also need the following permissions in your manifest file:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
A:
To Enable WiFi:
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);
To Disable WiFi:
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(false);
Note:
To access with WiFi state, we have to add following permissions inside the AndroidManifest.xml file:
android.permission.ACCESS_WIFI_STATE
android.permission.UPDATE_DEVICE_STATS
android.permission.CHANGE_WIFI_STATE
A:
A complete solution:
try {
WifiManager wifi = (WifiManager)
context.getSystemService(Context.WIFI_SERVICE);
WifiConfiguration wc = new WifiConfiguration();
wc.SSID = "\"SSIDName\"";
wc.preSharedKey = "\"password\"";
wc.hiddenSSID = true;
wc.status = WifiConfiguration.Status.ENABLED;
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wc.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.TKIP);
wc.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.CCMP);
wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
boolean b=wifi.isWifiEnabled();
if (b) {
wifi.setWifiEnabled(false);
Toast.makeText(context, "yes", Toast.LENGTH_SHORT).show();
} else {
wifi.setWifiEnabled(true);
Toast.makeText(context, "no", Toast.LENGTH_SHORT).show();
}
//Log.d("WifiPreference", "enableNetwork returned " + b );
} catch (Exception e) {
e.printStackTrace();
}
Reference: http://amitkumar-android.blogspot.com/p/installation-steps.html
|
{
"pile_set_name": "StackExchange"
}
|
Q:
MySql query to perform join between 2 tables
These are the tables:
professor
+-------+--------+--------+--------+------+
| empid | name | status | salary | age |
+-------+--------+--------+--------+------+
| 1 | Arun | 1 | 2000 | 23 |
| 2 | Benoy | 0 | 3000 | 25 |
| 3 | Chacko | 1 | 1000 | 36 |
| 4 | Divin | 0 | 5000 | 32 |
| 5 | Edwin | 1 | 2500 | 55 |
| 7 | George | 0 | 1500 | 46 |
+-------+--------+--------+--------+------+
works
+----------+-------+---------+
| courseid | empid | classid |
+----------+-------+---------+
| 1 | 1 | 10 |
| 2 | 2 | 9 |
| 3 | 3 | 8 |
| 4 | 4 | 10 |
| 5 | 5 | 9 |
| 6 | 1 | 9 |
+----------+-------+---------+
The above are the tables from which I need to retrieve the data from.
The question is to return list of Employees who take both Class 10 and
Class 9.
The query I have written is:
select professor.name
from inner join works
on professor.empid=works.empid
where works.classid=9 and works.classid=10;
I know that the result I want is Arun, but I don't know what should be the exact query to retrieve the required result.
A:
He wants the professeors that take class 9 AND 10. So there are 2 different records in works that need to match.
select professor.name from professor
join works A on A.empid=professor.empid and A.classid=9
join works B on B.empid=professor.empid and B.classid=10
See http://sqlfiddle.com/#!2/4be88a/1
|
{
"pile_set_name": "StackExchange"
}
|
Q:
In TFS 2018, how do I get linked work items to show up in a release?
I understand how to link work items to a build, but when viewing release results, I see a section listed for Work Items, and that you can compare work items linked from an artifact in different releases.
What I don't understand is how to get the work item linked from a build to show up in the release that was triggered to run from the build.
How can I do such a thing?
For example, in this post, they show their build results with work items linked, and then show their release with other work items linked. What steps do I have to take to make that happen for me?
A:
To get linked work items to show up in a release, you just need to set the builds (show up work items) or the specific sources which associate work items with the changesets as artifact sources.
In the release summary, it compares the current release with the previous release and then displays the newly added work items associated with changesets.
Try below steps to achieve your requirement:
Create a build definition A, map sources to include the
files/items will be changed in source control
Edit and modify the files/items, check in the changes with work
items associated. (e.g. Task1 here)
Trigger build definition A to queue a build1 (Task1 should
display in Build summary)
Create a release definition B, and add build definition A as
the artifact source, then create a release. (Task1 should display
in release summary)
Edit and modify the files/items second time, check in the changes
with work items associated. (e.g. Task2 here)
Trigger build definition A to queue a build2 (Task2 should
display in Build summary)
Do not create release here
Edit and modify the files/items third time, check in the changes
with work items associated. (e.g. Task3 here)
Trigger build definition A to queue a build3 (Task3 should
display in Build summary)
Create a release now, Task2 and Task3 will display in the
release summary.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
IE8 display overlap occurs using insertBefore
I'm attempting to move div elements from one section to another using node.insertBefore and order the insertion alphabetically. Upon clicking (in this case clicking A) to reorder I have a problem with elements overlapping as seen in the image below:
The code I'm using to produce this follows; I'm sorry it's a little long, but if you copy it into an html file in it's entirety you'll easily see my problem.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
var moveUp, moveDown;
var moveUp = function() {
var e = window.event.srcElement;
var firstBlock = document.getElementById('firstBlock');
var moved = false;
for (var i=0; i<firstBlock.childNodes.length; i++) {
if (firstBlock.childNodes[i].innerText > e.innerText) {
firstBlock.insertBefore(e, firstBlock.childNodes[i]);
moved = true;
break;
}
if (!moved) firstBlock.appendChild(e);
}
e.onclick = moveDown;
};
var moveDown = function() {
var e = window.event.srcElement;
var secondBlock = document.getElementById('secondBlock');
var moved = false;
for (var i=0; i<secondBlock.childNodes.length; i++) {
if (secondBlock.childNodes[i].innerText > e.innerText) {
secondBlock.insertBefore(e, secondBlock.childNodes[i]);
moved = true;
break;
}
if (!moved) secondBlock.appendChild(e);
}
e.onclick = moveUp;
};
</script>
<title>Test</title>
</head>
<body>
<div id="firstBlock" style="background-color:#dddddd;">
<div onclick="moveDown()">A</div>
<div onclick="moveDown()">B</div>
<div onclick="moveDown()">C</div>
<div onclick="moveDown()">D</div>
</div>
<div id="secondBlock">
<div onclick="moveUp()">E</div>
<div onclick="moveUp()">F</div>
<div onclick="moveUp()">G</div>
<div onclick="moveUp()">H</div>
</div>
</body>
</html>
Am I doing something wrong/odd? Can this be fixed/worked around? Thanks in advance for your help!
Edit:
I can't currently test in any other browsers.
I notice that once one section fills up, the highlighting no longer readjusts itself when items move between sections.
Edit 2: Result of jsfiddle posted by Jared
A:
Happened to come back to this question now. In case anyone else is having this problem, I ended up having to replace the div list with a table and rearrange table rows. Another option may be to use a list.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
zendframework 2 elfinder helper error
I'm using zend framework 2 with elfinder and it's working fine (inside elfinder view).I have module named options , the problem is when i'm using that elfinder helper inside options view it gave me error called "Unable to connect to backend. Backend not found."this is the code i'm using inside options view
echo $this->QuElFinder('elfinder', array('width' => "50%",
'height' => "300",
)
)
;Please someone help me,ThanksLanka
A:
"Unable to connect to backend. Backend not found" seems to be a Javascript Exception? Maybe your options aren't complete. Possibibly you forgot to configure 'url' option within your view-helper code.
'url' options seems to configure backend route the ElFinder Javascript tries to connect to. Default route seems to be '/quelfinder/connector' ? (QuElFinder Module route config)
echo $this->QuElFinder('elfinder', array(
'width' => "50%",
'height' => '300',
'url' => '/quelfinder/connector'
)
);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Regex that checks if string in format "yyyy/mm/dd" is a valid date, including month bounds
I am trying to validate a date in c# in the format "yyyy/mm/dd". Is it even possible (using regex) to validate that there aren't 30 days in February?
A:
It is possible to do this with a regex, but it would be incredibly complex. I am quite comfortable writing regular expressions, but I would not use that solution to validate dates.
It's much simpler to use another solution for validating dates. There are date-validation components available for every programming language. I'm not a user of .NET, but with a quick search I find the DateTime class, which seems to do this.
See .NET Framework Developer's Guide, "Parsing Date and Time Strings."
A:
As others have said, a regex isn't the best approach unless you're forced to (e.g. for client-side JavaScript reasons).
I suggest you use DateTime.TryParseExact with a pattern of "yyyy/MM/dd".
A:
Yes, it's possible, but it gets rather lengthy. The pattern just for checking months and days has quite some variations, and it all has to be repeated for leap years.
As an example, here's a pattern from Michael Ash's Regex Blog for mm/dd/yyyy format:
^(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using matching entries only, print file A line if column values is between two other columns values in file B
I have a tab delim file1
A 1
A 20
B 17
B 33
C 10
C 20
E 7
and another tab delim file2
A 1 5
A 6 20
B 1 10
B 30 60
C 10 20
E 1 6
I need to print the lines in file1 for which col1 file1 = col1 file2 and value in col2 file1 falls within the ranges in cols 2 and 3 of file2.
The output would look like
A 1
A 20
B 33
C 10
C 20
I'm trying
awk 'FNR==NR{a[$1]=$2;next}; ($1) in a{if($2=(a[$1] >= $2 && a[$1] <=$3) {print}}1' file1 file2
But it's not working.
A:
To store multiple ranges, you really want to use arrays of arrays or lists. awk doesn't support them directly but they can be emulated. In this case arrays of arrays seem likely to be more efficient.
awk '
# store each range from file2
FNR==NR {
n = ++q[$1]
min[$1 FS n] = $2
max[$1 FS n] = $3
next
}
# process file1
n = q[$1] { # if no q entry, line cannot be in range
for (i=1; i<=n; i++)
if ( min[$1 FS i]<=$2 && $2<=max[$1 FS i]) {
print
next
}
}
' file2 file1
Each min/max range needs to be stored separately. By maintaining a counter (q[$1]) of occurrences of each different value of col1 ($1), we ensure creation of a distinct new array element [$1 FS n].
Subsequently, when checking the ranges, we know that any particular value of col1 occurs precisely q[$1] times.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Set count of rows in haystack
I use django-haystack. And when i execute this code:
sqs = SearchQuerySet().auto_query(q)
q_spell = sqs.spelling_suggestion()
results = SearchQuerySet().filter(SQ(content=q_spell) | SQ(content=q)).load_all()
In console i see like this:
> 365645 [qtp1539768275-13] INFO org.apache.solr.core.SolrCore –
> [collection1] webapp=/solr path=/select/
> params={spellcheck=true&fl=*+score&start=**990**&q=*:*&spellcheck.count=1&spellcheck.collate=true&wt=json&fq=django_ct:(...)&**rows=10**}
> hits=2034 status=0 QTime=0
How i can count of rows for example 1000?
A:
The number of items Haystack retrieves per query is controlled through HAYSTACK_ITERATOR_LOAD_PER_QUERY, but as the documentation states:
This is not used in the case of a slice on a SearchQuerySet, which already overrides the number of results pulled at once.
So using [0:1000] after the query set should allow you to get all 1000 results at once.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
RandomRange in assembly with Irvine
I am working on x86 assembly language. I want to get two parameters that one is column and other one is row, using randomrange within the interval [0,5]. Here I tried to adjust the interval by dividing the random number by 6, and getting the number remains in DL which is remainder of the division.
I also implemented an array that holds the numbers that randomized before and jumps back to randomization if the element is already 1, which uses row*6+col to check the index, but this array is not effective yet.
I get a segmentation fault, what could be the problem?
TITLE Program Template (template.asm)
INCLUDE Irvine32.inc
INCLUDE macros.inc
.data
onezero BYTE 36 DUP(0)
row BYTE 0
col BYTE 0
.code
main PROC
_again:
call randomrange
mov bx, 6
div bx
mov row, dl
call randomrange
div bx
mov col, dl
movzx eax, row
mov ebx, 6
mul ebx
movzx ecx, col
add eax, ecx
mov edi, eax
mov al, 1
cmp al, onezero[edi]
je _again
movzx eax, row
call writeint
movzx eax, col
call writeint
main ENDP
END main
A:
The irvine RandomRange function already has this functionality:
; Returns an unsigned pseudo-random 32-bit integer
; in EAX, between 0 and n-1. Input parameter:
; EAX = n.
Also note that div bx is dividing the 32 bit number formed from dx:ax and not eax.
As for the segfault, use a debugger and see where the crash is.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Regex for identifying a string which determines users, values split by commas
Each "User" is entered into my database as such:
First Name, Last Name, MIddle Name, email, [languages], [likes]
So an example entry would be:
John, Doe, Foo, [email protected], [English, French], [Cars, Bikes]
I need a way to try and split this string so that I would get:
John
Doe
Foo
[email protected]
English, French
Cars, Bikes
My currently implementation uses string.split() and a regex for getting the contents in the square brackets, but I don't feel as if that is really a good way to go about things, because it's not really maintainable.
So I figure a regex to identify this would be great
EDIT:
I forgot to mention that each user will be separated by a semi-colon.
So for example:
John, Doe, Foo, [email protected], [English, French], [Cars, Bikes];
Bob, M, Joe, [email protected], [English], [Bikes];
This will be counted as 2 different users
A:
You can use .replace() with RegExp /([^,\s\[\]]+)/ig to surround string with quotes, JSON.parse() to create an array, concatenate newline character "\n" to string or .join(", ") call.
var str = "John, Doe, Foo, [email protected], [English, French], [Cars, Bikes]";
var arr = JSON.parse("[" + str.replace(/([^,\s\[\]]+)/ig, "\"$1\"") + "]");
let pre = document.querySelector("pre");
for (let prop of arr) {
if (typeof prop === "string") {
pre.textContent += prop + "\n";
} else {
pre.textContent += prop.join(", ") + "\n"
}
}
<pre></pre>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Duplicate Checks with Multiple Values
I am doing some manual duplicate checks on my database, and have a complicated case.
I need to check for duplicate rows based on a value in Column A, which I have done. However, in this specific case, there might be multiple records that have the same value for Column A but a different value for Column E.
Here is my original query:
SELECT ColumnA, COUNT(*) TotalCount
FROM TableA
INNER JOIN TableA_1 on fID = hID
WHERE dateCreated > '2013-05-08 00:00:00'
GROUP BY ColumnA
HAVING COUNT(*) > 1
ORDER BY COUNT(*) DESC
I now need to filter out duplicates for ColumnA where ColumnE is different, or unique. I have added psuedocode to my original query
SELECT ColumnA, COUNT(*) TotalCount
FROM TableA
INNER JOIN TableA_1 on fID = hID
WHERE dateCreated > '2013-05-08 00:00:00'
AND ColumnE is not unique
GROUP BY ColumnA
HAVING COUNT(*) > 1
ORDER BY COUNT(*) DESC
I hope this makes sense.
A:
You need a GROUP BY clause on a ColumnA column and HAVING clause on DISTINCT ColumnE
SELECT ColumnA, COUNT(*) TotalCount
FROM TableA INNER JOIN TableA_1 on fID = hID
WHERE dateCreated > '2013-05-08 00:00:00'
GROUP BY ColumnA
HAVING COUNT(DISTINCT ColumnE) > 1
ORDER BY COUNT(*) DESC
|
{
"pile_set_name": "StackExchange"
}
|
Q:
DPI and PPI | DPI OR PPI
Is there any differ between DPI and PPI ? Is it true : Dot = Pixel ? And at Last what is DpiX and DpiY in C#.net ? How can we change them ?
A:
DPI
Stands for Dot Per Inch and is used when pritning. It is also heavily misused with screen resolution. A colour ink printer don't mix the colors, instead each color has its own "slot". When a printer says 12000 dpi it is actually 12000 / 5 "pixels" for a 5 color based printer. Never the less, DPI only becomes interesting in the context of a printed result. Photoshop use the image's DPI information to be able to tell you the printed size of the image. Many people missinterpret DPI as a measurement of the pictures image quality or pixel density. For example, if you change the DPI for an image in Photoshop without resampling the image, you still have the exact same amount of pixels but now photoshop shows another "physical" dimension (inch or whatever you use).
Look at this Wiki article.
PPI
Stands for Pixels Per Inch (or pixel density) and should be used with screens and defined as one pixel equals the area of all the three base colors (Red, Green and Bue). Look at this Wiki article.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Laravel: Send Data to Controller via AJAX Without Form
I need to send data via JS to a Laravel controller on a button click. I'm not using any form because the data is being created dynamically.
Every time i try to send the data, i get an Internal Server Error (500), but unable to catch that exception in the controller or the laravel.log file.
Here's what i'm doing:
Route:
Route::post('section/saveContactItems', 'SectionController@saveContactItems');
Controller:
public function saveContactItems($id, $type, $items, $languageID = "PT"){ ... }
JS:
$('button').on("click", function (evt) {
evt.preventDefault();
var items = [];
var id = $("#id").val();
var languageID = $("#languageID").val();
var data = { id: id, type: type, items: JSON.stringify(items), languageID: languageID };
$.ajax({
url: "/section/saveContactItems",
type: "POST",
data: data,
cache: false,
contentType: 'application/json; charset=utf-8',
processData: false,
success: function (response)
{
console.log(response);
}
});
});
What am i doing wrong? How can i accomplish this?
UPDATE: Thanks to @ShaktiPhartiyal's answer (and @Sanchit's help) i was able to solve my issue. In case some else comes into a similar problem, after following @Shakti's answer i wasn't able to access the data in the controller. So, i had to stringify the data before sending it to the server:
data: JSON.stringify(data),
A:
You do not need to use
public function saveContactItems($id, $type, $items, $languageID = "PT"){ ... }
You have to do the following:
public function saveContactItems()
{
$id = Input::get('id');
$type = Input::get('type');
$items = Input::get('items');
$languageID = Input::get('languageID');
}
and yes as @Sanchit Gupta suggested you need to send the CSRF token with the request:
Methods to send CSRF token in AJAX:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
If you use this approach you need to set a meta tag like so:
<meta name="csrf-token" content="{{csrf_token()}}">
or
data: {
"_token": "{{ csrf_token() }}",
"id": id
}
UPDATE
as @Sanchit Gupta pointed out use the Input facade like so:
use Input;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Preprocess GET/POST Data From Apache/JBoss
Is there a way to access GET/POST data before it is passed to a JBoss application, perhaps in the web serving environment? I'd like to perform some simple data cleaning prior to passing it to the JBoss app I have inherited. Thanks.
A:
you can use filters (requires Servlet specification version 2.3).
The following links might help you and you can search more.
http://www.oracle.com/technetwork/java/filters-137243.html
http://docs.oracle.com/cd/B14099_19/web.1012/b14017/filters.htm
http://www.jboss.org/jdf/quickstarts/jboss-as-quickstart/servlet-filterlistener/
http://javabeanz.wordpress.com/2009/02/11/how-to-write-a-simple-servlet-filter/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Light bulb broke in oven, wire still attached
I have a gas oven. The electrical light bulb burned out, and when I went to unscrew to replace it, it broke off. The metal ring is still in the socket, the wire is attached, and the glass bulb is detached, but unbroken. How on earth am I gonna get this thing out?
I'd appreciate any ideas.
A:
You can use needle nose pliers to grip the metal of the broken off light bulb. Grip the edge and unscrew it. Turn off the power to the stove at the breaker before you do this or unplug it if the plug is accessible. You MUST make sure that the light socket is unpowered while you stick pliers into a broken off light bulb.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Testing interface at runtime without casting
I have code like this, where I need to handle objects with potentially different interfaces:
interface A {
a: any[];
}
interface B {
b: any[];
}
function doSomething(x: A | B) {
if (x.a && x.a.length) console.log(x.a)
if (x.b && x.b.length) console.log(x.b)
}
and each instance of x.a and x.a.length results in a compile time error stating
Property 'a' does not exist on type 'A | B'.
Property 'a' does not exist on type 'B'.
I know I could type cast every single instance where I test the interface of x (i.e. if( (<A>x).a && (<A>x).a.length) ) but with dozens of type / attribute combinations, this gets old in a hurry.
Is there a way of testing the interface of an object at runtime in typescript without casting every single test?
A:
You need to define type guards:
function isA(obj: A | B): obj is A {
return (obj as A).a != undefined;
}
function isB(obj: A | B): obj is B {
return (obj as B).b != undefined;
}
function doSomething(x: A | B) {
if (isA(x)) console.log(x.a);
if (isB(x)) console.log(x.b);
}
(code in playground)
The compiler knows that if isA(x) fails then x is B, so this works as well:
function doSomething(x: A | B) {
if (isA(x)) console.log(x.a);
else console.log(x.b);
}
(code in playground)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to download the jquery-ui file of Uncompressed source , i download the file always jquery-ui-1.8.5.custom.min.js
how to download a jquery-ui file without **.min.js
thanks
A:
You can grab the 1.8.5 uncompressed version here: http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.js
Or, on the jQuery UI Homepage look on the right under Developer Links for Latest dev bundle (1.8.5), you'll find jquery-ui.js under the ui folder.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Maximizing page usage for a table
I'm printing a table enclosing 4 other data tables, one per page, and would like to maximize the space available by reducing the margins as much as possible. I still need the page number, but wonder if it can be made to take minimal space. My table contains resizebox'ed cells, so I wonder what surrounding mechanics can be employed to get rid of most of the margins specifically for those pages with such tables?
A:
You can use the newgeometry macro from the geometry package to change the margins to suit.
\documentclass{article}
\usepackage[hmargin=3cm,showframe]{geometry}
\begin{document}
L1
\newgeometry{left=3cm,right=1cm,bottom=0.1cm}
\savegeometry{L2}
L2 (new, saved)
15
\restoregeometry
L1 (restored)
\newgeometry{margin=1cm,includefoot}
L3 (new)
\loadgeometry{L2}
L2 (loaded)
\end{document}
You can also adjust margins by writing your own macros. For example see my answer at How to switch between two different marginparwidth size?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SQL Syntax help
What would be the SQL syntax to select 4 different columns in a single row in a table, add those together and then insert that value into a 5th different column in the same row? The columns are all numeric(11,2).
For example- Table name is DataCheck
there is an ID that is primary key so how do I select col1, col2, col3, col4 where ID = 232...etc and add them up, and insert into col4 where id = 232...etc
A:
Unless I'm misunderstanding:
UPDATE MyTable SET col5 = col1 + col2 + col3 + col4 WHERE id = 232
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Repeat HMTimerTrigger On multiple days (Ex: Every Monday,Wednesday.... like in iOS 10 Home app)
I have checked the iOS 10 Home app. The screenshot is captured from Home app only.
Since last 2 days I have been trying to implement the HMTimerTrigger repeat functionality. My requirement is I have to repeat the Trigger on every monday,tuesday and friday. What I found is I can add only one day(Monday or Tuesday ... but not Monday AND Tuesday) like below.
unsigned flags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitWeekOfYear | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute;
NSDate *fireDate = [NSDate date];
NSDateComponents *recurrenceComponents = [[NSDateComponents alloc] init];
recurrenceComponents.weekday = 2; // For monday
NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:flags fromDate:fireDate];
fireDate = [[NSCalendar currentCalendar] dateFromComponents:dateComponents];
HMTimerTrigger *trigger = [[HMTimerTrigger alloc] initWithName:triggerName.text
fireDate:fireDate
timeZone:nil
recurrence:recurrenceComponents
recurrenceCalendar:[NSCalendar currentCalendar]];
Thank you for reading my post. Any ideas/suggestions would be very helpful.
A:
This functionality is not available to the public even though Apple has it in their HomeKit app. The best you could do is create multiple triggers for each day but then the user would gets confused.
Please open up a radar bug on it here
|
{
"pile_set_name": "StackExchange"
}
|
Q:
UITextView, Line Numbers Not Aligned
I have a UITextView which I am using to display text. Along the side I have a UITableView that I am using to display the line Numbers. The problem occurs when when trying to align the line numbers with the lines of text. Here is a screenshot of the problem: https://www.dropbox.com/s/7sjqm4nrsqm6srh/Screen%20Shot%202012-10-11%20at%209.16.58%20PM.png
For example, line 7 should be moved down since it is not at the start of a new line. I think the problem has to deal with the spacing when the lines of text wrap, but I am not sure.
So for the UITableView, I am creating the same amount of cells as there are lines of text. Then the cells are stretched so their height is the same as each line of text by using the method:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
int i = indexPath.row;
if (i == 0) {
return 10;
}
UIFont *font = _codeView.font;
NSArray *strings = [_codeView.text componentsSeparatedByString:@"\n"];
NSString *tempString = [strings objectAtIndex:i-1];
if (([strings objectAtIndex:i-1] == @"\n") | ([[strings objectAtIndex:i-1] length] == 0) ) {
tempString = @"hi";
}
CGSize stringSize = [tempString sizeWithFont:font constrainedToSize:CGSizeMake(_codeView.bounds.size.width, 9999) lineBreakMode:NSLineBreakByWordWrapping];
CGFloat height = stringSize.height;
return height;
}
The _codeView is the UITextView that I am using to display the code. The UITableView that displays the line numbers also has one blank cell at the top so I can align first cell with a line number with the first line of text.
I have tried multiple ways of playing with the spacing, but none of them seem to fix the problem. Any help would be greatly appreciated.
A:
I believe the problem is with the size you pass to sizeWithFont. You are setting the width to the textView's width. This will actually be a little too wide. The text view actually has a little bit of a margin. Try subtracting a few points from the width. Also, you are dealing with attributed text, not plain strings. You should look at the methods for calculating the height of an NSAttributedString.
One last thing in the code you posted. Your are splitting the _codeView.text on every call to heightForRowAtIndexPath:. That's bad. You should do this once and save off the strings. This method is called a lot. That is a lot of redundant string splits.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is [talmud-bavli] useful?
Is there anything about talmud-bavli that cannot be covered by talmud-gemara and/or the pertinent masechet tags?
There are under 60 questions, many of which are already tagged under other Gemara tags.
Note: I'm not asking about talmud-yerushalmi, as it is a different format than the Bavli, and as such can have different types of questions.
A:
Perhaps the one to get rid of is talmud-gemara. Questions that address Talmud generally mostly actually address Bavli generally. Any questions that address both Bavli and Yerushalmi can tag them both, which makes sense, as they're two distinct bodies of work.
A:
Rethinking this now... both are actually appropriate tags. talmud-bavli and talmud-yerushalmi refer to two separate works, and can be tagged as such.
There are actually several questions for which talmud-gemara is wholly appropriate, for example (to list a few):
High School Math in the Talmud
What does "the Talmud" mean in the Talmud?
Insults in the gemarah
The only thing now is to clean up the tag a bit and remove questions that only apply to a certain part of the talmud.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why did no one stop Joker from burning money?
In the movie The Dark Knight, after Joker captures Lao from the Jail and brings him back, he gets his share of money. Then he burns it? Why did he burn the money? If you say Joker is a Psychopath and "he just want to see it burn", that can be accepted. Joker is a Psychopath, but the people working for him are not right? Why would they allow Joker to burn so much money. They would just hit him and run with the money.
A:
From the Wiki (of course we all know Wiki's can be wrong, but we'll assume they're close to the truth):
The Joker's Thugs were a gang of criminals, in part a combination of
small-time robbers, bounty hunters, shanghaied gangsters, and
mentally-ill escapees of Arkham Asylum, who served under the Joker.
Because of the Joker's appearance, most of the thugs wore clown masks
and similar apparel.
Now, that same page also lays out the scene in question:
Ending the Chechen's Regime
The Chechen met the Joker on a Container
Ship with his thugs and rottweilers. The Joker burned his half of an
immense mound of US dollars, which happened to be holding the
mobsters' half on top of it, and betrayed the Chechen by having his
own men join him, and possibly execute their former boss; also
possibly involving cutting him up into tiny pieces and feeding them to
his beloved rottweilers. There are only four thugs.
IIRC, it's accurate to say there were only 4 thugs present. So, Joker most likely picked 4 mentally ill, least money-driven guys to accompany him on that job. They want Anarchy, not money. Maybe they were pyro's. Maybe they were mass murderers. Who knows. But Joker would have selected them because they'd be least likely to want what he was about to burn.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Glassfish Admin Console - 404 error
I have several WARs in my Glassfish installation. Someday I found that Glassfish Admin Console disappeared. When I try to access click here - I see 404 HTTP Error.
Why Glassfish Admin Console is missing and how to return it back ?
I can't simple reinstall, because it is production server.
A:
Try access the console in this url: http://myservername.com:4848/login.jsf
In http://myservername.com:4848 redirect to http://myservername.com:4848/common/index.jsf and not work because the url not exists.
I found this solution in this topic: https://www.java.net/node/699754
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How To? Namespace and multiple dev orgs
What is the best practices to use multiple dev orgs while developing app that will be distributed as Managed Package with Namespace prefix.
The problem: Once Namespace has been created, there is some problems to deploy code to another Dev Org and do all changes there. SF handles namespace in many places automatically, but in some places not.
For example in Formula Fields, in some dynamic SOQL, of course in custom Javascript and so on, I have to add/remove it when transfer code between orgs with/without namespace.
So far only storing namespace in settings or query it works for APEX and SOQL.
Q: What about Formulas
Q: Is there are any easy way of doing development in multiple dev orgs with namespace in mind?
I have read about Salesforce DX and looks like there we can create Scratch Orgs WITH our namespace. Unfortunately missed the Pilot.
Q: Is it possible to achieve something similar now?
Goal: Do all the development in Dev orgs (without namespace) and deploy changes to Packaging org (with namespace) via IDE. Ideally avoiding of query/check for namespace in every class, manual add/delete to Formulas and sending in to Frontend for Webservice calls.
A:
The answer to this is to use Salesforce DX, which will be released any day now. DX allows you to create new dev orgs that all share the same namespace as the packaging org. This makes it a lot easier to deal with the namespace, since all orgs you develop and test in will have the correct namespace.
If you don't want to move DX, your next best choice is to develop exclusively only in non-namespaced dev orgs, and use a code versioning system to deploy code from the developer orgs to the packaging org. In other words, never develop in the packaging org, and only dev orgs.
Q: What about Formulas
Write the formulas in your non-namespaced orgs, and do not use the namespace in any of your formulas. They should be properly fixed up when deploying to your packaging org when you deploy to it.
Q: Is there are any easy way of doing development in multiple dev orgs with namespace in mind?
Preferably, use DX. DX will be available any day now. If you can't or won't use DX, you can do this using normal dev orgs, but it requires some strict development practices.
For example, instead of new PageReference('/apex/mypage') in Apex Code, you must use Page.myPage instead. For @RemoteAction, use {!$RemoteAction.className.methodName} instead of className.methodName. And so on, and so forth. Use only namespace-aware functions instead of non-standard "hacks."
Q: Is it possible to achieve something similar now?
Yes, it is possible. However, you must strictly avoid using anything that will break. This means doing your research on what works and what's broken, and avoiding what's broken. For example, inline queries are generally safe without the namespace, as are most class, field, and object references, etc. It just requires more work and more diligence than it would take for a non-namespaced package.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Explanations for Various GIS Job Titles
I've been out of school and working in the GIS field (mostly the field of a desk) for over five years now. The one consistency I've found when working for various companies and applying for various jobs is that there is no consistency in the way our job titles correlate to the actual tasks we accomplish on a daily basis.
Does anyone have a good list of the general tasks / job description for some of the GIS job titles:
GIS Technican
GIS Analyst
GIS Administrator
GIS Developer
GIS Applications Specialist
GIS Professional
GIS Manager
GIS / IT Technican
GIS Technical Architect
I know each title varies by region and company, but a general list would be a great resource. If I have left any out, please feel free to add.
A:
There are some great answers here already, but here's my brief tuppence worth as a round-up (from my perspective - I don't pretend this is a canonical set of definitions!):
GIS Technican - a junior grade GIS specialist, but somebody with more experience in performing GIS analysis and managing data than a casual GIS user. For the GIS Technician, GIS is the job. For a GIS user, GIS is an adjunct to or tool for the job.
GIS Analyst - Probably more experienced than the GIS Technician and probably having some specialist knowledge of spatial analysis maybe in a particular field (e.g. oil sector, renewable energy, civil engineering etc).
GIS Administrator - A GIS Technician who looks after a data store and possibly also provides some support to a company's GIS users.
GIS Developer - A GIS specialist who concentrates on adding value to existing software by developing functions and UIs. A GIS Developer will have a good knowledge of programming at least with Python and probably another language such as Java or C# as well and will have an in-depth knowledge of one or more GIS APIs.
GIS Applications Specialist - This is a vague term and could mean a Developer or an Analyst, or even somebody who is a cross between the two - read the job description!
GIS Professional - Anybody for whom GIS is the primary way they earn their living, but I would take this to mean somebody above the GIS Technician grade (not because GIS Technicians aren't professional but because of the way the term is commonly used). I would also expect such a position to be more akin to the Analyst role than Developer but read the Job Description. A GIS Professional could be of any level of experience or seniority.
GIS Manager - A more senior role which will involve managing staff and taking overall charge of data stores etc as well as providing specialist advice to company Management on GIS, plus support for the GIS staff etc and, depending on the size of the team, some hands-on GIS analysis/development.
GIS / IT Technican - A role very much like the GIS Technician but with a little more emphasis on the IT tech side of things. Probably more akin to a junior GIS Developer (where a GIS Technican is probably more like a Junior GIS Analyst)
GIS Technical Architect - I would interpret this role to be somebody who's primary function is the setting up and maintenance of large corporate GIS systems, including an enterprise spatial database back-end, through to the specification, integration and implementation of the front-end UI solutions.
A:
Take a look here at the GIS Competency Model... It covers a whole spectrum of expected skills and growth patterns.
http://www.careeronestop.org/competencymodel/blockModel.aspx?tier_id=4&block_id=708&GEO=Y
A:
Doing some digging, apparently there was a book called "Model Job Descriptions for GIS Professionals" written by William Huxhold and published by URISA in 2000. I found a link to a PDF here that gives great 1-page job description summaries for various titles. I cannot seem to find a hard- or soft-copy of it, but it would be a great reference if this book is still available.
Additionally, you might find the article called "Building a GIS Career" from http://www.gislounge.com to be helpful. It lists the most common job titles and job description overviews, although I think the amount of experience they have listed for each position is probably shorter than it takes your average professional to move up the ladder.
GIS Intern
GIS Technician/Specialist
GIS Analyst
GIS Coordinator or Manager
For more detailed job descriptions, in 2012, Los Angeles County released GIS Classifications and Specifications (job descriptions), which are quite detailed descriptions of:
Geographic Information Systems Technician
Supervising Geographic Information Systems Technician
Geographic Information Systems Analyst
Senior Geographic Information Systems Analyst
Principal Geographic Information Systems
Geographic Information Systems Specialist
Geographic Information Systems Manager I
Geographic Information Systems Manager II
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why does sweetness of coke change after freezing completely
I freeze my coke in a freezer completely to solid and then keep it out to melt and as it melts portion by portion I starts to drink, initially It will be very sweet and later it wont be sweet at all. why does this happen?
We know that all sugar in coke will be dissolved (Solid solution) but how a major portion of this melts faster than water in the juice their by getting more sweet? How these sucrose can escape through the crystals formed by the ice and join in the water.
I measured the sweetness (Brix) and found it varies.
A:
Substances in solution have the effect of decreasing the temperature of the freezing point of the liquid they are dissolved in. This is called freezing-point depression. This is one of the reasons why adding salt to ice helps it melt.
Your coke is a complicated solution + colloid and sugar is one of the main substances dissolved in it.
During freezing:
What happens is that during the freezing process, as the coke cools a lot of sugar is pushed out of solution which allows the less-saturated water to freeze first. The last bit of liquid to freeze has much more sugar in it and takes a while to freeze because it is a concentrated solution and the freezing point has been lowered a lot.
During melting:
The last portion of the coke to freeze has the bulk of the sugar and the lowest freezing point and will melt first when warmed. When you allow the coke to start melting the most saturated portions melt the fastest and you consume most of the sugar in this stage. Later when the drink continues to warm the rest of the water starts melting with much less sugar in it, thereby making the remaining portion less sweet.
More information about sugar solubility:
One common way to grow sugar crystals is by slowly cooling the solution to push the sugar out of solution. There is some information about this here and they provide a nice sugar (sucrose) solubility versus temperature graph too:
As you can see the temperature dependence for solubility is dramatic. I haven't been able to find a curve for fructose (the primary sugar in coke in the United States) but I suspect the curve is very similar.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SearchResultCollection to CSV
Is there any easy way to export the contents of my results (SearchResultCollection) to a CSV file?
or do I have to Iterate each result and Append it to a text file?
A:
Is there any easy way to export the contents of my results
(SearchResultCollection) to a CSV file or do I have to Iterate each
result and Append it to a text file?
No, there is no better option than iterating the SearchResultCollection and writing it to a text-file.
using (StreamWriter w = File.AppendText(path))
{
foreach (SearchResult result in allSearchResults)
{
w.WriteLine(string.Format("Path={0} Properties={1}"
, result.Path
, string.Join(",", result.Properties.PropertyNames));
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Linear phase FIR notch filter and IIR notch filter
I want to isolate fundamental frequency with the help of a Linear phase FIR notch filter and a IIR notch filter in Matlab. Can anyone tell me how to do that? I know i have to set the notch frequency at fundamental frequency. But cant understand how to implement on MATLAB.
A:
Things you need to know.
The sampling rate.
The fundamental frequency which you wish to isolate.
FIR filter basic and what order do you want.
I would suggest making a band stop filter, with a thin stop band.
stop band frequencies fc1 and fc2.
Then use the code below.
fc1 = fundamental_freqeuncy1/sampling_rate;
fc2 = fundamental_freqeuncy2/sampling_rate;
N = 10; % number of taps you can change
n = -(N/2):(N/2); % 11 order filter
n = n+(n==0)*eps;
[h] = sin(n*2*pi*fc1)./(n*pi) - sin(n*2*pi*fc2)./(n*pi);
h(0) = 1 - (2*pi*(fc2-fc1))/pi;
%coefficient for band stop filter... which could be used % as notch filter
[w] = 0.54 + 0.46*cos(2*pi*n/N); % window for betterment
d = h.*w; % better coefficients
Now d are the filter coefficients.
and your filter is
freqz(d); % use this command to see frequency response
After this you need to filter your input using the filter designed by coefficients 'd'.
so
y = filter(d,1,X) % X is input, y is filtered output
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Trees/plants/rocks spam for my game terrain
I'm making a terrain for a video game. Is there a tool to spread a lot of trees/plants/rocks on a terrain? For example Unity has a built-in terrain tool for placing them, are there similar methods for Blender? Also, I don't want to decrease perfomance for every tree. Thanks!
A:
If you intend to export a whole terrain to unity (or any other RT 3D game engine), it would be wise to create your terrain, the trees, rocks and so on as independent objects, then import them into unity and let unity's distribution method do the work.
The reason for this is that unity works with instances of objects, while Blender would produce actual geometry or - if you do not intend to join your terrain into one object - many objects with possible redundancy of materials. That means more draw calls which lead to a heavy load on the engine.
Besides from that, you would still need to create collision meshes, which means even more redundant data or, if you chose to join all objects into one mesh with submeshes, it would be nearly impossible to generate the collision meshes automatically.
A:
You could use Particle System with Clouds texture (or any texture, even hand painted) to do this.
Steps:
Add Particle System to your terrain (and set it as screenshot below shows).
Add texture to this Particle System.
Go to Texture tab, select created texture (and set it as screenshot below shows).
Settings:
Blend file:
Update:
To add custom generation of trees you need to create New Texture, then in Texture Paint Mode create Material (Material Diffuse Color) and choose it in Texture tab. Now you can paint wherever you want.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is it correct that it takes approx. 30 minutes for an ICBM to reach Russia?
Imagine an ICBM with a nuclear warhead is launched from the US to reach Moscow.
How long does it take to reach its target? I've read numbers of about 30 minutes (if the missile is launched from America) or even 15 minutes (if the missile is launched from Europe). Is this realistic?
A:
Those numbers are realistic, yes. Peak speed for an ICBM is in the ballpark of 6-7km/s (any faster and the payload would go orbital), and it takes about 10 minutes to accelerate to that speed.
New York to Moscow is 7500km, at 6.5km/s is ~20 minutes. Add in the acceleration time and you're looking at about 30 minutes total.
London to Moscow is 2500km; most of the flight time there would be accelerating on ascent and decelerating in re-entry rather than coasting; as TildalWave indicates, 15 minutes is about right for that.
A:
This response addresses the practical warning time for ordinary citizens. It isn't quite the scenario asked in the original question and is a response to the various comments that clarify that citizen perspective is of interest and also that the flight path Russia -> Western Europe is of interest.
In the 70's and 80's in the UK there was an awareness of the "four minute warning". The wiki article is quite chilling. Some salient points:
"the four-minute warning was a public alert system conceived by the British Government during the Cold War and operated between 1953 and 1992"
"From the early 1960s, initial detection of attack would be provided primarily by the RAF BMEWS station at Fylingdales in North Yorkshire."
The British government was not the main beneficiary of BMEWS, given that it would only receive ... ... "no more than 5 minutes warning time" of an attack. The United States ... ..., however, and its Strategic Air Command would have thirty minutes warning from the Fylingdales station.
As a peripheral point there may also be some inspiration for the novel in the book and film "On the beach".
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can software able to wrap gzip/gunzip around to preserve file ownership?
gzip/gunzip are found to change inode number, thus ownership are not preserved if opened by another owner.
soluion posted by OP since thread is closed prematurely
Here is the solution to keep ownership, if anyone interested.
I modified the procedures, it passed the current basic tests.
# the original file information
ok 1 - /shared/shared/colourbar.nii.gz Found
ok 2 - /shared/shared/colourbar.nii.gz -- fileowner <504>
ok 3 - /shared/shared/colourbar.nii.gz -- inode <692254>
# copy file to /tmp, processed by uid 500
***cp -vf /shared/shared/colourbar.nii.gz /tmp
`/shared/shared/colourbar.nii.gz' -> `/tmp/colourbar.nii.gz'
***gunzip -f /tmp/colourbar.nii.gz
***gzip -f /tmp/colourbar.nii
ok 4 - /tmp/colourbar.nii.gz -- fileowner <500>
ok 5 - /tmp/colourbar.nii.gz -- inode <31>
# copy back to overwrite, and the ownership preserved
***cp -vf /tmp/colourbar.nii.gz /shared/shared
`/tmp/colourbar.nii.gz' -> `/shared/shared/colourbar.nii.gz'
ok 6 - /shared/shared/colourbar.nii.gz -- fileowner <504>
ok 7 - /shared/shared/colourbar.nii.gz -- inode <692254>
Unit Test failed due to a feature in gzip/gunzip utility.
The discussion about gzip/gunzip is all over, I want to push a little further
Real problem need a real solution.
Can we get around to have the same fileowner on test6?
The original owner has uid 500, pass all unit tests
ok 1 - /shared/shared/colourbar.nii.gz Found
ok 2 - original fileowner <500>
ok 3 - original inode<692254>
gunzip -f /shared/shared/colourbar.nii.gz
ok 4 - fileowner after gunzip <500>
ok 5 - inode after gunzip<692255>
gzip -f /shared/shared/colourbar.nii
ok 6 - fileowner after gzip <500>
ok 7 - inode after gzip<692254>
Joe has uid of 504, test 6 failed
ok 1 - /shared/shared/colourbar.nii.gz Found
ok 2 - original fileowner <500>
ok 3 - original inode<692254>
gunzip -f /shared/shared/colourbar.nii.gz
not ok 4 - fileowner after gunzip <504>
ok 5 - inode after gunzip<692255>
gzip -f /shared/shared/colourbar.nii
not ok 6 - fileowner after gzip <504>
ok 7 - inode after gzip<692254>
The original test script is here:
#!/usr/bin/perl
use strict;
use warnings;
use Test::More ;
return 1 unless $0 eq __FILE__;
main(@ARGV) if $0 eq __FILE__;
sub mock_gzip{
my $file = $_[0];
my $cmd = "gzip -f $file";
print "$cmd\n";
system($cmd);
}
sub mock_gunzip{
my $file = $_[0];
my $cmd = "gunzip -f $file";
print "$cmd\n";
system($cmd);
}
sub fileowner{
my $file = $_[0];
my $uid = `stat -c %u $file`;
chomp($uid);
return $uid;
}
sub get_inode{
my $file =$_[0];
my $inode = `stat -c %i $file`;
chomp($inode);
return $inode;
}
sub main{
#simulate real life situation - user A
my $file = "/shared/shared/colourbar.nii.gz";
my $fileu = $file;
$fileu =~ s/.gz$//g;
ok(-e $file,"$file Found\n");
my $fileowner = fileowner($file);
ok($fileowner>0,"original fileowner <$fileowner>\n");
my $inode = get_inode($file);
ok($inode>0,"original inode<$inode>\n");
# user B - gunzip/gzip owner changed
mock_gunzip($file);
my $fileowner_gunzip = fileowner($fileu);
ok($fileowner_gunzip==$fileowner,"fileowner after gunzip <$fileowner_gunzip>\n");
my $inode_gunzip = get_inode($fileu);
ok($inode_gunzip>0,"inode after gunzip<$inode_gunzip>\n");
mock_gzip($fileu);
my $fileowner_gzip = fileowner($file);
ok($fileowner_gzip==$fileowner,"fileowner after gzip <$fileowner_gzip>\n");
my $inode_gzip = get_inode($file);
ok($inode_gzip==$inode,"inode after gzip<$inode_gzip>\n");
# solution, or verified no solution to be decided
}
A:
When you zip the file, you create a new file, and that is owned by the current user. Use the -i option to show the file's inode.
robert:~> touch test
robert:~> ls -li test
93644038 -rw-r--r-- 1 robert staff 0 Dec 26 20:42 test
If you zip in place, the old file gets deleted, so it looks like it could replace the file, but it did in fact create a new one.
robert:~> gzip test
robert:~> ls -li test*
93644048 -rw-r--r-- 1 robert staff 25 Dec 26 20:42 test.gz
When you unzip, you also create new files, again, owned by the current user.
robert:~> gunzip test.gz
robert:~> ls -li test*
93644052 -rw-r--r-- 1 robert staff 0 Dec 26 20:42 test
So your error is to assume it's the same file, which it is not --- note the changing inode number in the beginning of the ls output. If it tried to use the same inode, what would it do for archives with multiple files?
If you just rename the file, it is the same file and ownership is preserved:
robert:~> sudo mv test renamed
robert:~> ls -li renamed
93644052 -rw-r--r-- 1 robert staff 0 Dec 26 20:42 renamed
Same for appending (changing contents):
robert:~> sudo echo ... >> renamed
robert:~> ls -li renamed
93644052 -rw-r--r-- 1 robert staff 4 Dec 26 20:51 renamed
See Wikipedia on inodes for more details on inodes.
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.