text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Lightweight Symmetric-key algorithm for bluetooth communications?
In my app I've used AES algorithm for WLAN communications, but now I'm transferring data through bluetooth I would like to get some security. The problem is that AES is too much "heavy" because it gives me blocks of more than 100 bytes - when I'm transferring less than 10 bytes - I would like to use something lighter, if it's possible.
Anyone knows a better solution?
A:
Use AES with 128-bit blocks. That's 16 bytes. Initializing for encryption goes like this:
//Generate a key
KeyGenerator KeyGen = KeyGenerator.getInstance("AES");
KeyGen.init(128);
SecretKey Key = KeyGen.generateKey();
//Generate init vector
SecureRandom rng = SecureRandom.getInstance("SHA1PRNG");
byte [] IV = new byte[16];
rng.nextBytes(IV);
//Initialize the encryptor
Cipher ci = Cipher.getInstance("AES/CBC/NoPadding"); //The spec might be different!
ci.init(Cipher.ENCRYPT_MODE, Key, new IvParameterSpec(IV));
RC4 has known weaknesses.
| {
"pile_set_name": "StackExchange"
} |
Q:
Twitter Bootstrap alert message closes without pressing close button
I have a problem with alert messages. I want to use the alert message as a warning to the user after a particular action has been performed. The issue I am facing is that the message shows and then closes on its own without user closing the message.
<div class="row-fluid">
<div class="alert span10 offset1" style="display: none" id="changeStatusMsg">
<a class="close" onclick="$('.alert').hide()" href="#">×</a>
<strong>Status has been changed.</strong>
</div>
I am using jquery to show the message -- $('#changeStatusMsg').show();
I used the solution mentioned here
But it does not help in my case.
function changeStatus(status, widgetExternalId){
$.ajax({
url : 'Controller',
data : { 'widget' : widgetExternalId,
'method' : (status == 'I' ? "activate" : "inactivate")
},
success : function(data) {
window.location = "myaccount.jsp";
$('#changeStatusMsg').show();
}
}
});
}
A:
It is probably do to the fact you are not calling the action that is opening it. So the page is refreshing.
If you are doing it inline:
onclick="$('#changeStatusMsg').show();return false;"
If with a click event
$(".foobar").on("click",function (event) {
event.preventDefault();
$("#changeStatusMsg').show();
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Python: while loop/ control statements not achieving desired result, how can i fix this?
cost = int(input("Enter the cost:\n"))
payment = int(input("Deposit a coin or note:\n"))
if payment >= cost:
change = payment - cost
print (change)
elif payment < cost:
while payment < cost:
payment = int(input("Deposit a coin or note:\n"))
change = cost - payment
print (change)
break
I basically want the value of "change".
The above was wrong because it wasn't 'storing' the value of the first payment if it was less than cost, realized my bad mistake.
cost = int(input("Enter the cost:\n"))
payment = 0
while payment < cost:
firstpayment = int(input("Deposit a coin or note:\n"))
payment = payment + firstpayment
if payment > cost:
change = payment - cost
print ("Your change is: $",change)
A:
The loop condition says:
while payment< cost:
So, the loop automatically exists when payment becomes more than cost. So an easier approach will be,
while payment<cost:
#do something
change = payment-cost
Coz, when the loop ends, we know that payment should be >= cost...
| {
"pile_set_name": "StackExchange"
} |
Q:
Getting "complex-functions.cpp:57:25: error: expected initializer before ‘add’" What does it mean?
I have a class declared like this in a header file :
class COMPLEX{
private:
typedef struct{
double real;
double imaginary;
}complex;
Now when I call this from the function driver I get that error "expected initalizer before add right here in this section of code, and as you can see I have it just like other parts that compile just fine.
//returns the phase of the complex number
double COMPLEX :: getPhase(complex n, int form)
{
if(form == 0)
{
float x = n.real;
float y = n.imaginary;
return(atan2(y,x));
}
if(form == 1)
{
return(n.imaginary);
}
}
//adds two complex numbers together
void COMPLEX :: complex add(complex n, complex m, int form)
{
complex temp, temp2, temp3;
if(form == 0)
{
temp.real = n.real + m.real;
temp.imaginary = n.imaginary + m.imaginary;
return(temp);
}
if(form == 1)
{
temp3.real = (n.real*cos(n.imaginary) + m.real*cos(m.imaginary));
temp3.imaginary = (n.real*sin(n.imaginary) + m.real*sin(m.imaginary));
temp2.real = getMagnitude(temp3, 0);
temp2.imaginary = getPhase(temp3, 0);
return(temp2);
}
}
There is just the error right before add, I've tried putting things before the complex function caller but it still said it was expecting something before add.... can anyone help?
A:
This function
void COMPLEX :: complex add(complex n, complex m, int form)
looks like it is returning both void and COMPLEX::complex.
You have to decide what you want it to return.
| {
"pile_set_name": "StackExchange"
} |
Q:
Atom Class quick delete
I have an example: (before)
.root.rfx-space-between
And after:
.root
Is there any way that I can use only 1 keystroke to delete the '.rfx-space-between' ? Normal Ctrl+Backspace takes at least 3 times to delete the string. Thank you :)
A:
If you look in Atom's preferences, under the "Editor" section, you can define word delimiting characters. These are characters that define the boundary between "word" and "non-word". Plus, of course, whitespace always delimits words.
The default setting is this:
/\()"':,.;<>~!@#$%^&*|+=[]{}`?-…
If you remove the - from this setting (near the end), then will be considered part of a "word", and Ctrl-Backspace would remove rfx-space-between in one operation. However, this would leave the trailing dot, and you would end up with
.root.
You could also remove . from that setting if you want. Just keep in mind that this may affect other things. Ctrl-Backspace is not the only operation that takes into account what "word" means to Atom.
| {
"pile_set_name": "StackExchange"
} |
Q:
rails scaffold not plural generate
I would like to generate a scaffolded controller, view and helper named with not pluraled one, but singular one. Howevery, I got pluraled named files like below. I know they are based on the rails convention, but I just would like to create a dictionary page.
$ rails generate scaffold_controller dictionary
create app/controllers/dictionaries_controller.rb
invoke erb
create app/views/dictionaries
create app/views/dictionaries/index.html.erb
create app/views/dictionaries/edit.html.erb
create app/views/dictionaries/show.html.erb
create app/views/dictionaries/new.html.erb
create app/views/dictionaries/_form.html.erb
invoke helper
create app/helpers/dictionaries_helper.rb
So, my question is "Are there any better ways or the shortest way to generate a singular named controller/view/helper files by command?"
What I want is just below. I'm wondering if I should make the files manually?
app/controllers/dictionary_controller.rb
app/views/dictionary/index.html.erb
app/helpers/dictionary_helper.rb
A:
There is a railsway of doing this, you can use inflections to document such exceptions:
config/initializers/inflections.rb
ActiveSupport::Inflector.inflections do |inflect|
inflect.uncountable "dictionary"
end
| {
"pile_set_name": "StackExchange"
} |
Q:
Showing Validation Errors using MVC
I have been trying to display validation errors using MVC's inherent validation framework. I am using following code for my Controller:
[HttpPost]
public ActionResult SaveApplication(ApplicationModel application)
{
if (!ModelState.IsValid)
{
return View("New",application);
}
ApplicationBLL.SaveApplication(application);
return Content(string.Empty);
}
While my view looks like:
<tr>
<td>Name</td>
@Html.ValidationSummary(true)
<td>@Html.TextBoxFor(m => m.Name)</td>
<td>@Html.ValidationMessageFor(m => m.Name, "Name is required")</td>
</tr>
following is how the model class looks like:
public class ApplicationModel
{
public int ApplicationId { get; set; }
public string ApplicationNumber { get; set; }
[Required]
public string Name { get; set; }
public DateTime EventDate { get; set; }
public string EventAddress { get; set; }
}
My Model has [Required] validation on the name property and when I put debugger on my controller, it recognizes that the ModelState is not valid and returns back to the view but I do not see any errors on my page. I may be missing something very trivial since this is my first time using MVC's validation framework.
One thing I would like to add is that I am calling Controller with an Ajax Post Can that be contributing to this anomaly?
A:
<td>@Html.ValidationMessageFor(m => m.Name, "Name is required")</td>
This helper method generates a span with attribute below:
data-valmsg-replace="false"
Means that you'll see a static error message below your field, but you'll not be able to change that field with your Error Message defined in Model. Again, you'll see some static error message under your field.
if @stephen muecke's solution works, means that your problem wasn't about adding ErrorMessage to wrong place. The only difference I see between your code and @stephen's answer is
return View("New",application);
changed to
return View(application);
This means that maybe you were returning the wrong view from your Action.
| {
"pile_set_name": "StackExchange"
} |
Q:
C# Why does passing of an class instance to a method which accepts object as parameter and boxing it back work
For example lets consider the following example.
class A
{
int i;
string j;
double t;
}
A a =new A();
MethodCalled(a);
void Method(object a)
{
A newA = a as A; // This will work even though Class A is down casted to System.Object
}
Can somebody please help me understand this. A link reference to explanation ?
Thanks
A:
I don't see any boxing going on. Boxing is when a value type (e.g. int) is converted to a reference type. In your example, the value passed to the method is a reference type (class A). Link for boxing:
http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx
So all that's happening when you call Method (or MethodCalled, I assume that's a typo) is that the method is accepting the argument of type class A because it is an object. All reference types derive from object.
I think your question really boils down to "what does the 'as' operator do?" This line of code:
A newA = a as A;
logically translates to this pseudo-code:
A newA = null;
if (a can be cast to type A)
newA = a;
So you can see that the 'as' operator will set newA correctly because the parameter's type is actually class A. If you passed another object of type class B, the as operator would return null (assuming class B didn't derive from class A). Here's a link with a sample on the as operator, which might help explain a bit better:
http://msdn.microsoft.com/en-us/library/cscsdfbt.aspx
| {
"pile_set_name": "StackExchange"
} |
Q:
Differences : @SessionScoped vs @Stateful and @ApplicationScoped vs @Singleton
I would like to know, what are the principal differences between :
javax.enterprise.context.SessionScoped and javax.ejb.Stateful
javax.enterprise.context.ApplicationScoped and javax.ejb.Singleton
I know that a @SessionScoped and a @Stateful allows to create a new instance for each client. I also know that for the @ApplicationScoped and @Singleton / @Stateless they are shared between the clients.
=> But when should I consider it's better to choose an EJB, or the other?
A:
@SessionScoped denotes a scope while @Stateful is in a way what we would now call a stereotype. @Stateful adds a number a services to a bean, among which transactional behavior and passivation.
Central to @Stateful is however its session behavior, which indeed overlaps with the session scope.
The difference is that the session scope is tied to the HTTP session, while @Stateful is an open-ended user managed session, with its lifetime managed by a client that has a reference to the bean proxy.
@Stateful remote beans where originally the binary (RMI) counter parts of Servlets. Where Servlets listened to remote HTTP requests from a browser, @Stateful remote beans listened to remote RMI requests from Applets (and later Swing clients).
There were unfortunately many inconsistencies between the two. A Servlet was just an HTTP listener, while @Stateful beans automatically brought in a lot of other features. A Servlet also shared the session with all other Servlets and also shared the Java EE component namespace with all other Servlets in a war, while with the @Stateful EJB every separate bean has its own session and component namespace.
With the introduction of local beans in EJB 2 and a sharp decline of Swing/Applet clients for remote EJB communication, the function of the session that's maintained for an @Stateful bean has become less clear.
I think it's fair to say that @Stateful simply isn't used that much these days. For a web application the HTTP session is almost always leading, which means using the session scope and local @Stateless beans and/or CDI beans for business logic.
In some cases @Stateful beans are needed for their natural support for the extended persistence context from JPA and for their passivation features (Servlet doesn't have a standardized passivation mechanism). Note that @Stateful and @SessionScoped (or many other scopes) can be combined. The advantage of combining them is that user code no longer needs to manage the lifetime, but the container manages this.
There's a somewhat similar story for @ApplicationScoped and @Singleton, although without the legacy (@Singleton is a fairly new thing). @ApplicationScoped is just a scope, while @Singleton is a bean type (stereotype if you wish), which doesn't only give you application scoped behavior, but also provides you with transactional behavior again, with automatic locking (which can be tuned via @Lock) and with eager construction behavior (via @Startup).
Although @Stateful and @Singleton are by themselves pretty handy, the current way forward in Java EE seems to be to decompose those build-in stereotypes into separately useable annotations and who knows, perhaps one day they will be actual CDI stereotypes consisting of those decomposed annotations.
| {
"pile_set_name": "StackExchange"
} |
Q:
Need to select average age of employees department wise
I have a table in Postgresql DB. It has 3 fields: Emp_Name, Dept & Age. I need to show Average age of employees department wise. I need to display all 3 fields in the result-set. Below is the input and expected output:
Here is the SQL Fiddle : http://sqlfiddle.com/#!15/7c4cf
How do I show the expected result in PostgreSQL?
A:
You can use the string_agg function to concatinate the employee names and avg to get the average age:
SELECT STRING_AGG(emp_name, ','), dept, AVG(age)
FROM test1
GROUP BY dept
SQLFiddle
| {
"pile_set_name": "StackExchange"
} |
Q:
how to Extract the data from http://www.pse.com.ph/servlet/TickerServletFile save into mysql database?
This should be a code igniter based class,
The table header should be
Price Percent_change Company Name Company Code Volume
Please help any one knows?
Many thanks!
A:
You just need to parse the file and insert it into a database. A quick look at the link shows that it seems to be all separated by semi-colons. Take a look at explode()
To get your results, simply do
$splitContents = explode($rawContents);
$counter=0
while($counter <= count($splitContents)) {
$Price=$splitContents[$counter++]
$Percent_change=$splitContents[$counter++]
$Company_Name=$splitContents[$counter++]
$Company_Code=$splitContents[$counter++]
$Volume=$splitContents[$counter++]
mysql_query("INSERT INTO ....");
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I SELECT data based on pairs of columns (themselves the result of a SELECT)?
Suppose I have the following table structure:
TABLE session
int entity_id
int user_id
int status
TABLE entity_user
int entity_id
int user_id
int target
The session table logs interactions by different users on different entities. The entity_user table specifies which users have access to each entity. Significantly, each user can have access to more than one entity.
I want to select (entity, user) pairs from the session table based on some criteria, eg. a particular status. Having retrieved those pairs, I want to look up the corresponding target in the entity_user table for each pair.
Is there a way to do this cleanly in SQL, ideally with a single query?
My solution so far was to select the pairs, do some offline text processing to concatenate them (with a separator) and then use that text. Thus:
SELECT entity_id, user_id FROM session WHERE status = 100;
-- Returns (101, 234), (204, 157), etc.
-- Post-process this result using # as a separator
SELECT entity_id, user_id, target FROM entity_user
WHERE CONCAT(user_id, '#', entity_id) IN ( '101#234', '204#157', ...)
This works, but I feel like there should be a pure way to do this in SQL. Any suggestions?
A:
Can be done with a combination of subquery and join.
SELECT * FROM (
SELECT entity_id, user_id FROM session WHERE status = 100 ) as s
LEFT JOIN entity_user ON s.entity_id = entity_user.entity_id and s.user_id = entity_user.user_id
| {
"pile_set_name": "StackExchange"
} |
Q:
Migrate from unencrypted realm to encrypted realm
I'm trying to migrate from unencrypted realm to encrypted but I don't know how and where to use Realm().writeCopy(toFile: url, encryptionKey: key).
or even if there is another way to do it.
Thank you.
A:
I found a way to do that, you can find it below:
private static var realm: Realm! {
// Get the encryptionKey
var realmKey = Keychain.realmKey
if realmKey == nil {
var key = Data(count: 64)
key.withUnsafeMutableBytes { (bytes) -> Void in
_ = SecRandomCopyBytes(kSecRandomDefault, 64, bytes)
}
realmKey = key
Keychain.realmKey = realmKey
}
// Check if the user has the unencrypted Realm
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let fileManager = FileManager.default
let unencryptedRealmPath = "\(documentDirectory)/default.realm"
let encryptedPath = "\(documentDirectory)/default_new.realm"
let isUnencryptedRealmExsist = fileManager.fileExists(atPath: unencryptedRealmPath)
let isEncryptedRealmExsist = fileManager.fileExists(atPath: encryptedPath)
if isUnencryptedRealmExsist && !isEncryptedRealmExsist {
let unencryptedRealm = try! Realm(configuration: Realm.Configuration(schemaVersion: 7))
// if the user has unencrypted Realm write a copy to new path
try? unencryptedRealm.writeCopy(toFile: URL(fileURLWithPath: encryptedPath), encryptionKey: realmKey)
}
// read from the new encrypted Realm path
let configuration = Realm.Configuration(fileURL: URL(fileURLWithPath: encryptedPath), encryptionKey: realmKey, schemaVersion: 7, migrationBlock: { migration, oldSchemaVersion in })
return try! Realm(configuration: configuration)
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Product searcher on backend
I'm developing a backend module, which displays a table with all the products. I'm trying to make a searcher in order to search an specific product from the table. It's like making an order from the backend, that you have to choose some products and you can make filters with the searcher.
I tried to make it in php and javascript, but by the moment it doesn't works as I would like. So now I'm trying to do it in Ajax, but I've never typed any code in ajax, so it will take me a few hours to learn the basics.
The fact is, if any of you know where's the .phtml code which let you make orders from the backend, because I want to know how magento does the searcher. Maybe If I copy the code, it will be easier. Or if anyone knows a better way to do it, please let me know it.
Thanks.
A:
This should help you to add a Product Chooser widget in your custom module.
http://andreitara.com/2012/02/using-magento-product-chooser-widget-in-youre-own-module/
The author have also uploaded this extension on Github! Just download it as an extension and I think you will be good to go.
https://github.com/andrei-tara/magento-product-selector
| {
"pile_set_name": "StackExchange"
} |
Q:
Mysql python - randomly (every other attempt) gets access denied
I can't figure this out and i am not sure how to code for it.
def get_connection():
cnx = MySQLdb.connect(**DB_CONFIG)
print("Connected")
cnx.close()
print("Closed")
12:08 $ python test_mysql.py && python test_mysql.py
Connected
Closed
Traceback (most recent call last):
File "test_mysql.py", line 4, in <module>
get_connection()
File "XX"/mysql/tbred_mysql.py", line 7, in get_connection
cnx = MySQLdb.connect(**DB_CONFIG)
File "XX/lib/python2.7/site-packages/MySQLdb/__init__.py", line 81, in Connect
return Connection(*args, **kwargs)
File "XX/lib/python2.7/site-packages/MySQLdb/connections.py", line 193, in __init__
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (1045, "Access denied for user 'XXXX'@'10.0.8.5' (using password: YES)")
I ran them right after each other because it was easier to demonstrate but you can wait 10 or 15 seconds and it will still happen. I works and then it doesn't.
When it fails like this nothing is written to the mysql error log. If i change the user to something that doesn't exist to force this error a record is written to the mysql error log.
EDIT:
I can reproduce problem without python. If i try and remote connect via the mysql command line client in linux i get the same results. Also i have discovered its not random its every other connection regardless of time between attempts. 1st works, 2nd error, 3rd works, 4th errors again it doesn't matter the time between them. Also with these failures they are not recorded to the mysql error log like a normal access denied message is.
Losing my mind!
A:
Repeating this from my comment above.
Setting option skip_name_resolve fixes your issue.
By default, MySQL Server tries to do a reverse DNS lookup of the client IP address to make sure your user is logging in from an authorized hostname. This is a problem if your local DNS server is slow or intermittently flaky. It can slow down or even cause errors for MySQL connections, and it's not clear why.
Using skip_name_resolve tells the server to skip this validation. This should eliminate errors and slow performance due to DNS.
One implication of this is that you cannot use hostnames in GRANT statements. You must identify users' authorized client hosts by IP addresses or wildcards like %.
https://dev.mysql.com/doc/refman/5.7/en/host-cache.html says:
To disable DNS host name lookups, start the server with the --skip-name-resolve option. In this case, the server uses only IP addresses and not host names to match connecting hosts to rows in the MySQL grant tables. Only accounts specified in those tables using IP addresses can be used. (Be sure that an account exists that specifies an IP address or you may not be able to connect.)
Wildcards work too. You can GRANT ALL PRIVILEGES ON *.* TO 'username'@'192.168.%' for example.
| {
"pile_set_name": "StackExchange"
} |
Q:
IDE Compilation question - I'm not sure why this is downvoted so much
Relevant Link: https://softwareengineering.stackexchange.com/questions/189582/how-is-an-ide-compiled
I thought I was asking a fair question that's fit for programmers.stackexchange. Apparently, many experts do not think so. What's more unfortunate is that I cannot delete the question now even though it's terrible.
I'm not here to argue, I'm genuinely curious as to why the question is considered bad. All I'm interested in hearing is the procedures used to build a modern IDE, and I simply gave an example of VS and Eclipse to illustrate my point.
Apparently, people think the example is way too farfetched so I tried to remove the example given regarding VS and Eclipse.
Some specific questions I want to ask:
Is the question itself bad? For example, is it something blatantly obvious that you can't figure out why anyone would ask such question?
Is the question simply not fit for Programmers.SE?
Is the question itself fine but very poorly written? I'm not sure how I can improve the question from as is. I'd really love to hear suggestions for this.
A:
To borrow a phrase from a book title: everything is obvious, once you know the answer. A lot of the down votes are from people who can't imagine not knowing the answer or being able to easily figure it out. They vote you down because they assume you're just being lazy. There's probably not much you can do about that group of voters. Others are more tolerant and assume you wouldn't ask unless the answer truly eluded you.
The other problem is the question was worded in such a way as to allow a lot of reading between the lines. This problem was exacerbated by the first problem. In other words, people were thinking the simplest answer to how an IDE is compiled was too obvious, so you must have really been asking about the general bootstrap problem of how the first version of a compiler is created. Then you specifically said that's not what you were asking, without clarifying what you intended to ask. As Charles Babbage said, that left people "not able rightly to apprehend the kind of confusion of ideas that could provoke such a question."
So, if you want to salvage the question, you need to be specific about the source of your confusion. What exactly do you think makes compiling an IDE different from compiling any other software? Do you understand the bootstrap problem and are just curious about if IDE developers have special hooks for working on their own IDE? Are you confused as to how a stable version and an in-development version could coexist on the same system? Have you done some basic research, like looking at how an open source IDE does it? After doing that research, what specifically is still unclear?
| {
"pile_set_name": "StackExchange"
} |
Q:
flutter doctor --android-licenses not working on macOS Catalina
Recently I upgraded my Mac to Catalina.
I installed Java, set JAVA_HOME to $(/usr/libexec/java_home) as per the documentation. I installed Android Studio and SDK tools and set the ANDROID_HOME variable to /Users/username/Library/Android/sdk.
I downloaded flutter, and added flutter/bin to my env variable $PATH, and when I run flutter doctor, it's running fine and giving me the results as expected, without all the features checked however as I am setting it up for the first time.
But when I run flutter doctor --android-licenses, it's giving me an error which says:
Android sdkmanager tool was not found, try re-installing or upgrading your Android SDK.
A:
Run the command flutter upgrade.
Then run the command flutter doctor --android-licenses.
Actually it was the then latest version of Flutter 1.12.13+hotfix.8 installed, which was not reading the cmdline-tools folder from the latest Android SDK home.
Also to be on the safer side, just create a folder tools inside <path-to-sdk-home>, and copy the contents of <path-to-sdk-home>/cmdline-tools/latest/ to the folder <path-to-sdk-home>/tools/.
| {
"pile_set_name": "StackExchange"
} |
Q:
Arrays in Java to store a graph
I am creating a program in java to perform Depth first search on a graph.
The problem is the input file has 5 million lines. Each row of the file contains two numbers to indicate an undirected edge.
What would be the best way to store this data?
A:
Assuming a modern computer with reasonable amounts of RAM you should have no problems creating 5 million objects to store your links. The data structure you use will most likely be dictated by how you intend to use it. In your case you want to perform a depth first search which means that it would be convenient to have the links referenced from both nodes they touch.
Assuming unweighted links a very simple example of a data structure might be:
class Node {
private final int id;
private final List<Node> linkedNodes = new ArrayList<>();
public Node(int id) {
this.id = id;
}
public void addLink(Node linkNode) {
linkedNodes.add(linkNode);
}
}
class Graph {
private final Map<Integer, Node> nodes = new HashMap<>();
public addLink(int id1, int id2) {
getNode(id1).addLink(getNode(id2));
getNode(id2).addLink(getNode(id1));
}
private getNode(int id) {
if (!nodes.containsKey(id)) {
nodes.add(new Node(id));
}
return nodes.get(id);
}
}
Your search becomes relatively simple with this data structure:
public Node {
public void search(List<Node> visitedList, Consumer<Node> action) {
visitedList.add(this);
linkedNodes.stream()
.filter(n -> !visitedList.contains(n))
.collect(Collectors.toList())
.forEach(n -> n.search(visitedList, action);
action.accept(this);
}
}
I've used Java 8 streams here but converting to traditional iteration should not be too hard. Note that I collect the linked nodes into a list before searching them to avoid changing the list mid stream.
If you are running on light weight hardware or are going to be processing billions of rows then you might need to look at a lighter weight data structure.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can one tell if God is in favor of a modern value or not?
The Bible seems to condone slavery and accept wives as their husband's property. But these are generally acknowledged to be immoral in modern civilization.
Yet, there are other modern societal perspectives which differ from their Biblical perspectives that many (if not most) Christians deem to still be ungraceful in God's eyes, like homosexuality.
I'm familiar with arguments that the Bible was written for its own time and pertained only to the era. But, if some values can be progressive and Christian despite what is in the Bible while others cannot, how can one know which ones God is okay with?
Also, is it possible he just doesn't care about stuff like slavery?
A:
Your question basically boils down to two things: hermeneutics and doctrine.
Hermeneuetics is the study of texts, and Biblical Hermeneutics is the application of textual study to the scripture and the process of determining what it means. This field is relevant to your question because your question itself contains clear trances of not being backed by any kind of hermeneutics at all. For example you mention that a "woman as property" view is condoned by Scripture. This is commonly made assertion made by commentators with an anti-Christian bias, but it is not based on a good reading of the text. In order to come away with an idea like that one must ignore the difference in literary genres between passages. The difference between narrative and prescriptive passages is very important and how that is determined is part of what the field of hermeneutics addresses.
Doctrines are beliefs about any given topic. Good doctrine is the result of careful application of hereneutics and a good overall understanding of Scripture and general revelation. Bad doctrine looks a lot like humanism and is the result of man using his own internal moral compass to delineate what he wants to believe. One must always choose between doctrines.
There are of course conflicting doctrines out there. Some will say that practicing homosexuality is fine for a Christian, others will say it's a result of man's fallen sinful nature and an abomination in God's eyes. In order to determine which bit of doctrine you are going to subscribe to you need to do some research. If, as in the title of your question, you plan on subscribing to whatever you can determine to be God's judgement on the matter then your first order of business is to figure out what he said on the matter in the past and what it means to you today.
This means approaching Scripture using the lens of hermeneutics, examining the Canon to determine which books and teachings you are going to consider and authoritative witness on which to base your doctrinal conclusions, what methods of interpreting the text you will use and then applying that to the whole of Scripture to deduce a cohesive theology (or understanding of God's nature and the nature of his dealings with men). Once you have that you can use it to help guide your discernment on individual decisions. Is X a sin? What do the scriptures I hold true say about the matter, how do I read and apply those scriptures and what conclusions must I draw?
All Christian traditions have some corpus of accepted doctrines. Part of your process in choosing what tradition to align yourself with should be examining their doctrines and the basis for those doctrines to see if their reasoning and sources are sound and comparing them to any other conclusions based on the same sources. When conflicts arise between conflicting doctrines, you should have some clear idea WHY you reject one interpretation over another that has taken into consideration how the various conclusions got drawn.
Lastly, any true search for God's opinion -- his will in any given matter -- is going to include communicating with him on the matter. Although they vary in how they see this implemented practically, all Christians pretty much agree that God has made some provision for guiding people into a proper understanding of his word through his Holy Spirit left as a counselor to men after Jesus left earth. Not asking Him to guide you in your discernment process would be like trying to map out the objects in a dark room without turning on the light.
A:
I love this question. I have wondered this myself and found answers. Here you go, from personal experience and study.
The short of it? Prophets, and prayer.
Prophets
Yes, you are right, the Bible is old, but as Amos 3:7 says, "Surely the Lord God will nothing but he revealeth his secret unto his servants the prophets." God calls prophets so that people can know what He is speaking at the time. That is mainly how we have the Bible, a collection of words of God's prophets, chosen and set apart to lead the people in specific, contemporary issues at the time, and also eternal truths, mainly that of the Atonement of Jesus Christ.
Often, people will being to disobey (apostasy) and not follow God's prophets, so He withdraws them from the earth. When the people are ready again, God calls another prophet to speak His word and clarify truth. This happens all throughout the Old Testament, and a period of apostasy begins again near the end of the New Testament.
So, God just leaves us alone forever? For hundreds of years there were no prophets on the earth, no new revelation. Hence a period of reformation/enlightenment when people sought greater spiritual truths for their day, and to restore teachings of the original Christ-organized Church.
As several denominations (and non-denominational sects too) believe (albeit differently depending on where you go/who you ask), God has prophets in the Church today. But we must be careful not to blindly follow a so-called prophet, ancient or modern. How can you know?
Prayer
God's values, or true eternal principles, will never change. God's truth then is God's truth now.
To know if something is right, or, as we might say, to know God's "opinion" on the subject, we can pray and ask. No promise is more repeated in canonized scripture than "Ask, and ye shall receive." Knock, and it will be opened unto you.
From my own experience I know that God answers prayers and will give you an answer to sincere prayer through the Holy Ghost. One must only have a sincere heart and faith in Christ, with real intent to act on the answer. If you have a question about any moral, doctrinal, or other issue, I know God is there, and that He is interested in you and it. He wants to answer you and He will.
| {
"pile_set_name": "StackExchange"
} |
Q:
UICollectionView UseLayoutToLayoutNavigationTransitions with different datasources
I have two UICollectionView objects, that both have different source and delegate. I would like to achieve a "Photos app'esque" look with the transition, using UseLayoutToLayoutNavigationTransitions.
It doesn't work though. When I call the UseLayoutToLayoutNavigationTransitions it changes the layout, but not the content.
First picture is first collection view. A series of categories and the people contained in them.
Second picture is what I'd like the animation to end up in. A series of people within a certain category.
Last picture is what happens right now. Categories just get rearranged.
A:
Have a look at http://www.objc.io/issue-12/collectionview-animations.html in the
Transitions Between UICollectionViewController Instances
section.
it basically shows you that you'll have to change the datasource and delegate manually by implementation of the navigation controller delegate methods:
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
if ([viewController isKindOfClass:[FJDetailViewController class]]) {
FJDetailViewController *dvc = (FJDetailViewController*)viewController;
dvc.collectionView.dataSource = dvc;
dvc.collectionView.delegate = dvc;
[dvc.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_selectedItem inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:NO];
}
else if (viewController == self){
self.collectionView.dataSource = self;
self.collectionView.delegate = self;
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Show child custom post types on single-{parent}.php?
I'm very new to WordPress, and from the get-go I need to implement custom post types. Not sure I have all my WordPress marbles in one tin, so I'm asking for a bit of constructive criticism and above all patience.
I want something similar to this: http://wp-types.com/documentation/user-guides/creating-post-type-relationships/. More specifically, the car rental website part, but only customized for events and artists.
BUT, artists will be pre-specified and not added with an event, so I just want to maybe link them via checkbox, is this even possible?
To be specific, this is the scenario:
I have a site, which displays a load of events, each with a line up of artists. Now, I have created two (2) custom post types, Events & Artists. Events is a child of Posts, and Artists a child of Events.
I have already added 'Artist' posts in the post type. Artists should be able to be linked to multiple Events and Events should be able to have multiple Artists.
A:
One post type can be the child of another post type: attachments for example are children of posts or pages. The association is described in the posts table in a field post_parent that holds a post ID.
But … what you want can be solved in many different ways. You don't have to use the post_parent field. I don't think that a simple hierarchy can reflect the relations between your objects. You need probably many-to-many relations, and these are not native to WordPress.
One blog post or page can cover multiple events, multiple artists or both.
One event can be associated with multiple artists and vice versa.
Possible solutions
Create a custom taxonomy for artists and build a shadow custom post type for it to hold longer text information and attachments. Not easy to manage, the code gets messy very fast.
Save the relationships in post meta data. Then have to decide which data are stored on which post, your queries will get very long and complicated.
Use separate tables (one for relationships, one for meta data about these relationships). Requires good knowledge of the WordPress data base API, and you have to take special care to catch these tables in backups and export files.
Maybe the plugin Posts 2 Posts will help you. It uses two extra tables – which is (from my experience with similar situations) the fastest option.
See also this related post about a similar question.
| {
"pile_set_name": "StackExchange"
} |
Q:
jQuery plugin that takes user method
I am working on a jQuery plugin and I would like for the user to pass in a method name to be executed after a flag (in the code) is set to true. I already have the flags working as needed, I just need a way to execute the method that is passed.
For example:
(function(jQuery){
$.fn.extend({
pluginName: function(options) {
var defaults = {
parameter1: 0,
method: function(){}
}
var options = $.extend(defaults, options);
return this.each(function() {
var opt = options;
var flag = false;
if(opt.parameter1 > 0){
flag = true;
}
if(flag){
//call users method
}
jQuery(this).hide();
});//END return
}//END counter method
});//END extend
})//END function
//Return jQuery object
(jQuery);
The user would call it like this:
$("#divName").pluginName({
parameter1: 1,
method: function(){alert("test");}
});
I haven't tested the code above, it's just an illustration so you can see what I'm trying to accomplish.
Thanks in advance!
A:
Since functions are first class objects in JavaScript, you can just use
options.method();
in your plugin to execute the function
A:
There is no difference between a user-supplied method like your example and any other method. Therefore, you can call it the same way you call any other method.
For example:
if (flag)
opt.method();
If the method takes arguments, you can pass them the same way you pass arguments to ordinary methods.
| {
"pile_set_name": "StackExchange"
} |
Q:
inheritance, policy mixed with templates
I want to do something as the following.
I have a class as follows with some elements which are not our concern right now.
template<class A>
class Domain
{
};
My issue is, I want some new objects to be members of this class. But I cannot specify them in this definition. I have to specify it in some other file. My first thought was using inheritance as follows:
template<class G,class ctype>
class Data
{
public:
Data(G& g_);
protected:
std::vector<ctype> data1;
};
and then
template<class A>
class Domain : public Data<A,A::ctype>
{
public:
Domain(A& a);
void writeData(data1);
};
template<class A>
Domain<A>::Domain(A& a)
{
}
however, I've not been able to get it to compile.
Any suggestions how to go about this?
Any method on how to do this in a cleaner way?
the full program is the following. Its only in the header file. I haven't created an instance yet. The program is
28 template<class GV, class Data>
29 class System : public Data<GV,GV::ctype>
30 {
31 private:
32 typedef Dune::VTKWriter<GV> VTKWriter;
33 GV& gv_;
34 VTKWriter vtkwriter_;
35
36 public:
37 System(GV& gv);
38 void writeSystemInfo(std::string outfile);
39 };
40
41 template<class GV, class Data>
42 System<GV,Data>::System(GV& gv) : gv_(gv) , vtkwriter_(gv)
43 {
44 }
45
46 template<class GV,class Data>
47 void System<GV,Data>::writeSystemInfo(std::string outfile)
48 {
49 Data::addDatatoVTK();
50 vtkwriter_.write(outfile, Dune::VTKOptions::binaryappended);
51 }
and the errors are
../dune/simulationlab/system/system.hh:29:29: error: expected template-name before ‘<’ token
../dune/simulationlab/system/system.hh:29:29: error: expected ‘{’ before ‘<’ token
../dune/simulationlab/system/system.hh:29:29: error: expected unqualified-id before ‘<’ token
../dune/simulationlab/system/system.hh:46:33: error: invalid use of incomplete type ‘class Dune::System<GV, Data>’
../dune/simulationlab/system/system.hh:29:9: error: declaration of ‘class Dune::System<GV, Data>’
../dune/simulationlab/system/system.hh:52:60: error: invalid use of incomplete type ‘class Dune::System<GV, Data>’
../dune/simulationlab/system/system.hh:29:9: error: declaration of ‘class Dune::System<GV, Data>’
A:
A::ctype is seen as a member call, not a type. You should use the typename keyword:
template<class A>
class Domain : public Data<A,typename A::ctype>
{
public:
Domain(A& a);
};
| {
"pile_set_name": "StackExchange"
} |
Q:
Input not being submitted from a Web2Py / Python form
I am trying to create a comments section using Web2Py/Python, I have created the form with no errors, but when the form submits the comments are not completely added. Can anyone spot something I am missing?
db1.py modal:
db.define_table('products',
Field('Product_Name',requires=IS_NOT_EMPTY()),
Field('Product_Description',requires=IS_NOT_EMPTY()),
Field('Product_Review',requires=IS_NOT_EMPTY()),
auth.signature)
db.define_table('product_comments',
Field('products', 'reference products'),
Field('body', 'text', requires=IS_NOT_EMPTY()),
auth.signature)
default.py controller:
def show():
post = db.products(request.args(0, cast=int))
productDescription = T("Product Description")
productReview = T("Product Review")
back = T("Back")
#commentHeading = T("Comments")
db.product_comments.products.default = post.id
db.product_comments.products.readable = False
db.product_comments.products.writable = False
comments = db(db.product_comments.products==post.id).select()
form = SQLFORM(db.product_comments).process()
return locals()
default/show.html view:
{{extend 'layout.html'}}
<h1>{{=XML(post.Product_Name, sanitize=True)}}</h1>
<h2>{{=XML(productDescription, sanitize=True)}}</h2>
{{=XML(post.Product_Description, sanitize=True)}}
<h2>{{=XML(productReview, sanitize=True)}}</h2>
{{=XML(post.Product_Review, sanitize=True)}}
<h2>Comments</h2>
{{for comment in comments:}}
<div class="well">
{{=comment.created_by.first_name}} {{=comment.created_by.last_name}}
on {{=comment.created_on}} says
{{comment.body}}
</div>
{{pass}}
{{=XML(form, sanitize=True)}}
<a href="/ReviewMyProduct/default/index">{{=XML(back, sanitize=True)}}</a>
A:
I needed an = inside {{comment.body}} to make it look like {{=comment.body}}. However Anthony's answer is customary if you want the comments section to show the body based on index.
Without it, submitting a comment would post the previous submitted comment (always one behind).
| {
"pile_set_name": "StackExchange"
} |
Q:
htaccess redirect issue: Want all ajax request from root folder
RewriteRule ^cat/([^/]*)\.html$ /cat.php?p1=$1 [L]
RewriteRule ^cat/([^/]*)/([^/]*)\.html$ /cat.php?p1=$1&p2=$2 [L]
RewriteRule ^cat/([^/]*)/([^/]*)/([^/]*)\.html$ /cat.php?p1=$1&p2=$2&p3=$3 [L]
I have created this htaccess and it works fine.
But the next problem is in jquery ajax url parameters url:"ajax/la.php" in cat.php. it should redirect from root folder not subfolder
go like this public_html/ajax/la.php...
Thanks!
A:
Maybe you can try with
url:"/ajax/la.php"
if I've understood correct.
| {
"pile_set_name": "StackExchange"
} |
Q:
Get hwnd by process id c++
How can I get the HWND of application, if I know the process ID? Anyone could post a sample please? I'm using MSV C++ 2010.
I found Process::MainWindowHandle but I don't know how to use it.
A:
HWND g_HWND=NULL;
BOOL CALLBACK EnumWindowsProcMy(HWND hwnd,LPARAM lParam)
{
DWORD lpdwProcessId;
GetWindowThreadProcessId(hwnd,&lpdwProcessId);
if(lpdwProcessId==lParam)
{
g_HWND=hwnd;
return FALSE;
}
return TRUE;
}
EnumWindows(EnumWindowsProcMy,m_ProcessId);
A:
You can use EnumWindows and GetWindowThreadProcessId() functions as mentioned in this MSDN article.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can an employee represent themselves as another company as long as a contractual obligation needs to be met
I am wondering if an employee of a company can represent themselves on the telephones as long as another company legally allows that employee to do so.
For example, Company A – a small delivery company – writes a contract which requests the services of Company B – a sales company – to do sales and dispatching for the delivery company.
Now Bob, who gets paid by and is employed by Company B, would need to call the delivery drivers or new potential clients and say "Hi this is Bob from Company A...". Under normal circumstances, this is fraud, but since there is a contract in place asking for the sales company to provide a service, if it would allow their employees to provide a service, in theory, there would be an alternate solution.
Can this representation on the telephones, and with clients or any other entity lead to legal problems as long as there are contracts in place allowing such an action?
A:
If Bob is employed by B and B is contracted by A, it doesn't mean that there is a valid agency agreement between Bob and A, not even an implied agency agreement.
If Bob nevertheless decides to continue to claim that he is calling on behalf of A (only to the point of executing the contractual obligations of B which B has delegated to him), as long as he doesn't induce the clients to act in a way that would result in a (financial) injury/damage, his false claim wouldn't be considered as fraud. However, it would be viewed as misrepresentation. If the clients end up with monetary damages then it would be a fraudulent misrepresentation.
The only solution would be to create an addendum to the contract between A and B which can be easily done in 5 minutes to specify what Bob can and cannot do.
When unsure, always steer on the safe side and do it in writing.
I'm not a lawyer though, I just relied on a basic Google search.
| {
"pile_set_name": "StackExchange"
} |
Q:
Field Editor with Python: select by attribute & open table (QGIS)
I want to search on number values (>, = etc.) within a column and open table for the selected ones. It's an easy task within field calculator, but I want to see how it's build up with the python syntax and then run it. It would help me understand. Or should I run it with the consols editor?
While this is an expression by the attribute (population) i won't need the feature-class, right?
What I want is something like this:
def "population" < 2000
def showAttributeTable() (but only for the selected ones)
A:
There's various way how to do it and depends on what you want.
Solution 1 : with selection assuming you've already select your features :
# My layer test
Layer=QgsVectorLayer("path/to/shapefile.shp","Display name", "ogr")
# list of selected features
selected_features = [ feature for feature in layer.selectedFeatures()]
Solution 2 : with the querie builder :
# My layer test
Layer=QgsVectorLayer("path/to/shapefile.shp","Display name", "ogr")
# set a querie like querie builder in properties
Layer.setSubsetString(u'"population" < 2000')
list_of_features = [feature for feature in layer.getFeatures()]
# reset the querie
layer.setSubsetString("")
I would use the first one for spatial selection and the other one for queries on attributs field
A:
Great answer by @SIGIS! You could also use the following to set your current layer, set the expression and load the Attributes Table with the selected features:
layer = qgis.utils.iface.activeLayer()
exp = QgsExpression( "\"population\"< 2000" )
ids = [i.id() for i in layer.getFeatures(QgsFeatureRequest(exp))]
layer.setSelectedFeatures(ids)
qgis.utils.iface.showAttributeTable(layer)
| {
"pile_set_name": "StackExchange"
} |
Q:
CodeIgniter select dropdown box with for loop
I try to create loop for select box
for select time start 8.00 and increasing it continusly
for this matter i found solution from
creating a loop for time incremented by 15 minutes
but i put it into my code under array it shows only one time
but i use
var_dump($timeinoption)
it shows correctly
as
array (size=1)
'8 . 0' => string '8 . 0' (length=5)
array (size=1)
'8 . 15' => string '8 . 15' (length=6)
array (size=1)
'8 . 30' => string '8 . 30' (length=6)
array (size=1)
'8 . 45' => string '8 . 45' (length=6)
array (size=1)
'9 . 0' => string '9 . 0' (length=5
but codeignaiter select box not work;
form_dropdown('timein',$timeinoption,'8.30');
it shows only one time on select box
echo form_label('Time Start','timestart');
for ($i = 8; $i <= 17; $i++)
{
for ($j = 0; $j <= 45; $j+=15)
{
//inside the inner loop
$opti= $i.' . '. $j;
$timeinoption=array($opti=>$opti) ;
}
//inside the outer loop
}
echo form_dropdown('timein',$timeinoption,'8.30');
?>
A:
You are overwriting your array on each loop
$timeinoption=array($opti=>$opti);
So there will only be 1 value in your array.
Try changing to
$timeinoption[$opti]= $opti;
| {
"pile_set_name": "StackExchange"
} |
Q:
Invalid use of group function in mysql
I've a table like this:
+----+------+--------+
| id | name | salary |
+----+------+--------+
| 1 | Ajay | 20000 |
| 2 | Aja | 2000 |
| 3 | Aj | 200 |
| 4 | A | 3000 |
| 5 | q | 30000 |
+----+------+--------+
I want to write a query that can print highest salary, medium salary and lowest salary. So I wrote this query:
select salary
from parent
where max(sal)
&& salary < ( SELECT MAX( salary )
FROM parent )
&& min(salary);
And mysql returned an error:
ERROR 1111 (HY000): Invalid use of group function
what is the correct query?
A:
MySQL doesn't offer an aggregate function to grab a median value, sorry to say. Hopefully you can go with the average (the arithmetic mean) value.
Stuff like MAX(), MIN(), and AVG() (called aggregate functions in the jargon of SQL) can't appear in WHERE clauses. They can show up in SELECT and HAVING clauses. That's why you got an error.
You'll be wanting
SELECT MAX(salary) max_salary,
AVG(salary) avg_salary,
MIN(salary) min_salary
FROM parent
If you control your own MySQL server and you have a few MySQL dba chops, you can install a user-defined function to compute the median value. (If you're using a hosting service with a multitenant MySQL server, forget about this.) Read this.
http://mysql-udf.sourceforge.net/
| {
"pile_set_name": "StackExchange"
} |
Q:
Combinatorics. How many ways can you split 8 people into pairs for the game of bridge.
The title explain the problem. First I would choose two random people out of 8, there is 4 ways to choose two people, then there's still 6 people left. Then again two people should be chosen, so there are 3 ways to do it. Then only 4 people are left. Again we choose two random people from those who have been left: 2 ways to arrange them into pair. Lastly there are only two people left, so there is only $1$ way to choose a pair. So together it will make $4\cdot 3 \cdot 2=24.$ I would like to know whether my answer is correct and also I notice that the result is $\left(\frac {N}{2} \right)!$ so what's the reasoning behind this?
A:
Assuming you do not "name the teams" or order the teams, etc...
Without loss of generality, assume that everyone's age is different.
Choose the partner for the youngest person: $7$ options
From those remaining people (not the previously selected pair), choose the partner for the youngest remaining: $5$ options
Continue in this fashion, giving a final total of $7!! = 7\times 5\times 3\times 1$
| {
"pile_set_name": "StackExchange"
} |
Q:
AutoQuery is not getting the name db connection when run through gateway
I have an implementation, where I am calling an autoquery operation via the service gateway. The service gateway will successfully call both internal and external operations. However, any autoquery operation fails because it is not getting the connection string set. These same autoquery operations work just fine when called directly and not through the gateway.
Here is the stack trace.
at ServiceStack.OrmLite.OrmLiteConnectionFactory.CreateDbConnection() in C:\\BuildAgent\\work\\27e4cc16641be8c0\\src\\ServiceStack.OrmLite\\OrmLiteConnectionFactory.cs:line 70\r\n at ServiceStack.OrmLite.OrmLiteConnectionFactory.OpenDbConnection() in C:\\BuildAgent\\work\\27e4cc16641be8c0\\src\\ServiceStack.OrmLite\\OrmLiteConnectionFactory.cs:line 95\r\n at ServiceStack.ServiceStackHost.GetDbConnection(IRequest req) in C:\\BuildAgent\\work\\3481147c480f4a2f\\src\\ServiceStack\\ServiceStackHost.Runtime.cs:line 691\r\n at ServiceStack.AutoQuery.GetDb(Type type, IRequest req) in C:\\BuildAgent\\work\\3481147c480f4a2f\\src\\ServiceStack.Server\\AutoQueryFeature.cs:line 598\r\n at ServiceStack.AutoQuery.CreateQuery[From](IQueryDb`1 dto, Dictionary`2 dynamicParams, IRequest req) in C:\\BuildAgent\\work\\3481147c480f4a2f\\src\\ServiceStack.Server\\AutoQueryFeature.cs:line 608\r\n at IDOE.SecurityPortal.Api.ServiceInterface.OrganizationUserStaffTypeService.Get(QueryOrganizationUserStaffTypes query) in E:\\source\\repos\\Azure - Security Portal\\src\\IDOE.SecurityPortal\\IDOE.SecurityPortal.Api.ServiceInterface\\OrganizationUserStaffTypeService.cs:line 47\r\n at ServiceStack.Host.ServiceRunner`1.<ExecuteAsync>d__15.MoveNext() in C:\\BuildAgent\\work\\3481147c480f4a2f\\src\\ServiceStack\\Host\\ServiceRunner.cs:line 133
Database Connection Registration in startup.cs
var dbFacotry = container.Resolve<IDbConnectionFactory>();
dbFacotry.RegisterConnection("SecPortal", AppSettings.Get<string>("SQLSERVER-SECPORTAL-CONNECTIONSTRING"), SqlServer2017Dialect.Provider);
dbFacotry.RegisterConnection("EdfiMdm", AppSettings.Get<string>("SQLSERVER-EDFIMDM-CONNECTIONSTRING"), SqlServer2017Dialect.Provider);
Plugins.Add(new AutoQueryFeature { IncludeTotal = true });
AutoQuery Definition
[Authenticate]
[RequiredClaim("scope", "secprtl-read")]
[Route("/files", Verbs = "GET")]
[ConnectionInfo(NamedConnection = "SecPortal")]
public class QueryFiles : QueryDb<Types.File>
{
[QueryDbField(Field = "Id", Template = "({Value} IS NULL OR {Field} = {Value})")]
public int? Id { get; set; }
[QueryDbField(Field = "FileName", Template = "({Value} IS NULL OR UPPER({Field}) LIKE UPPER({Value}))", ValueFormat = "%{0}%")]
public string FileName { get; set; }
[QueryDbField(Field = "UserId", Template = "({Value} IS NULL OR UPPER({Field}) LIKE UPPER({Value}))", ValueFormat = "%{0}%")]
public string UserId { get; set; }
[QueryDbField(Field = "StateOrganizationId", Template = "({Value} IS NULL OR UPPER({Field}) LIKE UPPER({Value}))", ValueFormat = "%{0}%")]
public string StateOrganizationId { get; set; }
[QueryDbField(Field = "Notes", Template = "({Value} IS NULL OR UPPER({Field}) LIKE UPPER({Value}))", ValueFormat = "%{0}%")]
public string Notes { get; set; }
}
Code calling the service
public class ContactService : Service
{
public ContactService()
{
}
public async Task<object> Post(PostContact request)
{
try
{
var files = base.Gateway.Send(new QueryFiles() { });
return new Contact() { Name = request.Name };
}
catch (Exception ex)
{
throw ex;
}
}
}
Custom Service Gateway
public class CustomServiceGatewayFactory : ServiceGatewayFactoryBase
{
private IRequest request;
public override IServiceGateway GetServiceGateway(IRequest request)
{
this.request = request;
return base.GetServiceGateway(request);
}
public override IServiceGateway GetGateway(Type requestType)
{
var isLocal = HostContext.Metadata.RequestTypes.Contains(requestType);
if (isLocal)
{
return base.localGateway;
}
else
{
return new JsonServiceClient("https://localhost:6001")
{
BearerToken = request.GetBearerToken()
};
}
}
}
Custom service gateway registration in startup.cs
container.Register<IServiceGatewayFactory>(x => new CustomServiceGatewayFactory()).ReusedWithin(ReuseScope.None);
The call being made in the service class is a local call. Calling an external service that uses autoquery works just fine. I can also call the local service directly with no problem.
I created a custom autoquery method in the service interface, I noticed that the db connection info was not populated on the request.items array. So I manually added that information to the request, and it worked as expected. So somehow, in my setup, the autoquery operations that are called locally, the db connection info is not getting added to the request object.
A:
Request Filter Attributes like [ConnectionInfo] is only applied on HTTP Requests, not internal Service Gateway requests.
The Connection info isn't configured because it's not annotated on your PostContact Service Request DTO that calls the in-procces Service Gateway.
You can have the [ConnectionInfo] on the QueryFiles AutoQuery Request DTO attached to the current Request with:
public async Task<object> Post(PostContact request)
{
try
{
typeof(QueryFiles).FirstAttribute<ConnectionInfoAttribute>()
.Execute(Request,Response,request);
var files = base.Gateway.Send(new QueryFiles() { });
return new Contact() { Name = request.Name };
}
catch (Exception ex)
{
throw ex;
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to make my app lives longer in background android?
The main activity of my app takes the current location and send it to server via httppost using asynk. My problem is that when the user push home button and app goes to background after a long time period the system kill my app as it should. onDestroy is called and my app unregistering the locationlistener and also closes the Activity.I tried saveinstancestate method but it doesn't help me.So is any trick to make my activity lives longer in background?
A:
There's no way to keep your "Activity" alive but you can (and have to) implement an Android Service: http://developer.android.com/reference/android/app/Service.html. Just move your background functionality there.
| {
"pile_set_name": "StackExchange"
} |
Q:
Lower bound of mixing time time of two glued complete graphs
I am reading the "Markov Chains and mixing time 1st edition" by Levin and Peres, I got stuck on exercise $6.7$ and have a hard time to understand its solution.
Here is the description direct from the page. $80$ of this book.
Consider the graph $G$ obtained by taking two complete graphs on n vertices and “gluing” them together at a single vertex. We analyze here simple random walk on a slightly modified graph, $G'$.
Let $v^{\ast}$ be the vertex where the two complete graphs meet. After gluing, $v^{\ast}$ has degree $2n − 2$, while every other vertex has degree $n − 1$. To make the graph regular and to ensure non-zero holding probability at each vertex, in $G'$ we add one loop at $v^{\ast}$ and $n $ loops at all other vertices. (See Figure 6.2 for an illustration when $n = 4$.) The uniform distribution is stationary for simple random walk on $G'$, since it is regular of degree $2n − 1$.Figure 6.2
\
the exercise $6.7$ in page. $84$ is asked to prove a lower bound of of mixing time of this random walk by considering the set $A \subset \mathcal{X} $ of all the vertices in one of the two complete graph. Where $\mathcal{X}$ is the set of vertices.
Solution in page. $333$ the authors claims that the transition distribution of $A$ after $t$ steps from initial vertex $x \not \in A$ is
$$P^{t}(x, A) = 1-(1-\alpha_n)^t$$
where
$$\alpha_n =\frac{1}{2}\left[ 1- \frac{1}{2n-1}\right] \frac{1}{n-1}$$
how does this comes out?
A:
The solution in the book seems to me to be incorrect (at least, I can't see how to make sense of the expression for $P^{t}(x,A)$ they give). I'll give an alternate solution here. I'm assuming the vertex $v^{*}$ is in $A.$
Since the stationary distribution is uniform, we have $\pi(A)=\frac{n}{2n-1}>\frac{1}{2}.$ From the definition of total variation distance, for any vertex $x$ we have
$$|| P^{t}(x, \cdot)-\pi ||_{TV} \geq |P^{t}(x,A)-\pi(A)| \geq \pi(A)-P^{t}(x,A)>\frac{1}{2}-P^{t}(x,A)$$
If $x \not\in A$, then for the walk started at $x$ to be in $A$ at $t$ steps, it must first travel through $v^{*}$. Let $\tau_{v^{*}}$ be the hitting time of $v^{*}$, i.e., the first time the walk visits $v^{*}.$ From the preceding observation, we must have $P^{t}(x, A) \leq \mathbf{P}_{x}(\tau_{v^{*}} \leq t).$ Since $P(v,v^{*})=\frac{1}{2n-1}$ for any vertex $v$, we have
$$\mathbf{P}_{x}(\tau_{v^{*}}>t)=\left(1-\frac{1}{2n-1}\right)^{t}=\left(1-\frac{1}{2n}(1+o(1))\right)^{t}.$$
Therefore,
$$P^{t}(x,A) \leq \mathbf{P}_{x}(\tau_{v^{*}})=1-\mathbf{P}_{x}(\tau_{v^{*}}>t)=1-\left(1-\frac{1}{2n}(1+o(1))\right)^{t}$$
which, combined with the first inequality, yields
$$|| P^{t}(x, \cdot)-\pi ||_{TV} \geq \left(1-\frac{1}{2n}(1+o(1))\right)^{t}-\frac{1}{2}.$$
From here, the proof in the book proceeds correctly.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to set dilation rate for atrous convolution dynamically in TensorFlow?
I'm writing a custom recurrent neural network. The network state is defined in the body of a while loop and the recursion stops when a certain condition occurs. I'd like to use the number of iterations as a parameter for some functions inside the loop. For example when I use atrous convolutions I'd want the rate of dilation to depend on the current iteration.
def body(self,..., iteration):
dilation_rate = 2**iteration
state = tf.nn.atrous_conv2d(..., rate = dilation_rate)
iteration += 1
def RNN_loop(...)
iter = tf.constant(np.array(0), dtype = tf.int32)
... = tf.while_loop(self.condition, self.body, [...,iter])
Because iteration is defined as a tensor I don't know how to pass it to the atrous_conv2d which expect a number. If I try to evaluate the value of the tensor inside the loop with iteration.eval I get:
ValueError: Operation u'layer/while/Identity_4' has been marked as not fetchable.
If I pass the tensor to the function I get:
ValueError: setting an array element with a sequence.
A:
TL;DR: use tf.nn.convolution() instead of tf.nn.atrous_conv2d() and short-circuit tf.nn._nn_ops._get_strides_and_dilation_rate(). (See code sample at the bottom of the answer.)
TS;WM:
The implementation of tf.nn.atrous_conv2d() basically just calls tf.nn.convolution() with the dilation_rate set to [rate, rate]. This is the current position in the source, but I'm copying it here (without 130 lines of comments) because it might change so the link might get outdated:
def atrous_conv2d(value, filters, rate, padding, name=None):
return convolution(
input=value,
filter=filters,
padding=padding,
dilation_rate=np.broadcast_to(rate, (2,)),
name=name)
Here it's clear that the np.broadcast_to() makes it impossible to use a tensor for the dilation_rate. Maybe in tf.nn.convolution() then?
Well, theoretically, yes, up until the call to _get_strides_and_dilation_rate() which most unhelpfully has things like
dilation_rate = np.array(dilation_rate, dtype=np.int32)
After that, the Convolution class doesn't care much and the _WithSpaceToBatch.__init__() ends up explicitly converting it to tensor right away:
dilation_rate = ops.convert_to_tensor(
dilation_rate, dtypes.int32, name="dilation_rate")
So if you're super confident that your parameters are all right, you can then short-circuit tf.nn._get_strides_and_dilation_rate() and then call tf.nn.convolution() directly with a two-dim dilation rate, like this code (tested):
import tensorflow as tf
square_size = 5
dr = tf.placeholder( shape = ( 2, ), dtype = tf.int32 )
inp = tf.reshape( tf.constant( range( square_size * square_size ), dtype = tf.float32 ), ( 1, square_size, square_size, 1 ) )
fltr = tf.reshape( tf.ones( ( 3, 3 ) ), ( 3, 3, 1, 1 ))
_original = tf.nn._nn_ops._get_strides_and_dilation_rate
tf.nn._nn_ops._get_strides_and_dilation_rate = lambda a, b, c : ( b, c )
state = tf.nn.convolution( inp, fltr, "SAME", strides = [ 1, 1 ], dilation_rate = dr )
tf.nn._nn_ops._get_strides_and_dilation_rate = _original
with tf.Session() as sess:
print( sess.run( tf.squeeze( inp ) ) )
print
print( sess.run( tf.squeeze( state ), feed_dict = { dr : [ 2, 2 ] } ) )
print
print( sess.run( tf.squeeze( state ), feed_dict = { dr : [ 3, 3 ] } ) )
will output the results with dynamically changed dilation rate (the tf.squeezes are for legibility only):
[[ 0. 1. 2. 3. 4.]
[ 5. 6. 7. 8. 9.]
[10. 11. 12. 13. 14.]
[15. 16. 17. 18. 19.]
[20. 21. 22. 23. 24.]]
[[ 24. 28. 42. 28. 32.]
[ 44. 48. 72. 48. 52.]
[ 66. 72. 108. 72. 78.]
[ 44. 48. 72. 48. 52.]
[ 64. 68. 102. 68. 72.]]
[[36. 40. 19. 36. 40.]
[56. 60. 29. 56. 60.]
[23. 25. 12. 23. 25.]
[36. 40. 19. 36. 40.]
[56. 60. 29. 56. 60.]]
| {
"pile_set_name": "StackExchange"
} |
Q:
Straight-pull spokes - worth it?
Straight-pull spokes have been around for awhile on MTB wheels, but mainly just on very expensive wheelsets (Mavic Deemax for example). Recently the better wheel component manufacturers have been getting in on this by selling straight-pull spokes and compatible hubs individually, and they are generally considerably more expensive than the 'normal' variety.
However in my many years of snapping spokes they have never snapped at the elbow (the 'weak' point straight-pulls are supposed to address), they always break in the centre - presumably because the double-butting process has moved the weak point there.
So my question is this: Are straight-pull spokes worth it, or are they another expensive marketing gimick to solve a problem that doesn't exist?
A:
Yes, straight pull spokes are technically superior to traditional J-bend spokes. The only reason that J-bend spokes are relatively more popular is because it's cheaper to machine a hub with simple flanges on a lathe. Well-designed straightpull hubs typically cost more.
Note that a straight-pull spoke in generally can and should be tensioned higher than the equivalent J-bend spoke. As always, build quality is key, and the average bike shop won't necessarily have the experience to do it well. Nevertheless, in comparison to a J-bend, a straight pull spoke properly assembled onto a properly designed hub will:
Not fatigue as fast -- especially if a J-bend is not kept adequately tensioned. in other words, a straightpull spoke will not relax as quickly.
Eliminate spoke rubbing typical in most traditionally laced wheels.
be stiffer radially AND laterally than most traditional lacing for the same spoke gauge (though it is hard to do a direct comparison because hub and rim geometry varies widely)
Be lighter for the equivalent capability -- or, more importantly, will have less inertia due to the ability to use fewer spokes and/or narrower gauge butted spokes with no loss in stiffness & strength
Will last longer -- the J-bend spoke beds in, then frets and ovalizes the spoke hole, losing tension as the wheel wears in, as well as wearing out the hub. In a straightpull spoke, there is much less motion & wear at the hub and nipple.
Bottom line: straight pull spokes, properly designed and built, will be lighter, stiffer, and require less truing than a conventional wheelset with the same number of spokes.
What are the advantages of J-bend spokes? Price and parts availability.
A:
This is debatable, but since you asked, here go my cents:
A wheel has three "parts": rim, hub and spokes.
Spokes have two functions:
Sustain the vertical forces on the wheel (weight of the rider, landing, etc.);
Transmit torque while accelerating (rear wheel only) and braking;
Any properly laced wheel will do it, but there are many ways to design the connection of the spokes to the hub, or to the rim. These manufacturers have chosen to make the spokes "elbowless", which could result in less chance of failure, and could result in other side-benefits, like flangeless hubs, or fancier-looking wheels.
I'd much rather use standard components only, since they are easily replacable and swappable. I sometimes damage some rim, then I can change the rim only, because the nipple-hole connection is standard. I also can change the hub if needed, because the flange-elbow connection is standard. In the other hand these fancy wheels are proprietary, and you have only a single source of spare parts, which tend to be VERY expensive and sometimes are not available on the shelf.
As a bottomline, my spokes tend to break at the elbow, rarely at the thread end. I don't use butted spokes, so that could make some difference. Recently, I had some breakages at the mid-length, but I suppose this is due to excessive weight per wheel (tandem) and sub-optimal quality spokes.
Final thought: I would only spend big in such a wheel if I have a very well-defined reason. These are made for racing, and for anyone who doesn't race (and isn't sponsored), I'm pretty sure the cost is too much for the benefit.
| {
"pile_set_name": "StackExchange"
} |
Q:
Oracle Error in oci_parse()
I have the following error
Warning: oci_parse() expects parameter 1 to be resource, boolean given in C:\wamp\www\JQueryMobileTest\submit.php on line 28
this is my code :
<?php
$sql="UPDATE table1 SET updated_date =SYSDATE ,trx_status ='Submitted' where TO_CHAR(trx_date, 'mm/dd/yyyy') LIKE '%$search%' AND trx_status = 'Saved'";
$res= oci_parse($link, $sql);
oci_execute($res);
?>
i don't konw whats the problem ,, please any one can help me ?
A:
If $link is boolean, then most likely its value is false. This happens when connection to database failed. oci_connect returns false if an error happened. See documentation for more details.
You can find the error by calling oci_error(). Example from the documentation:
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Object of size dependent on runtime information
I want to test if different subgroups of objects stored in an array will satisfy a certain condition if grouped together, and I know that some objects cannot satisfy it if grouped with other objects.
An example to make it clear. The second row indicates which other objects are compatible with that given object (i.e. 1 is compatible with 2, 4 and 5; 2 with 1, 3 and 5...).
+----------+----------+----------+----------+----------+
| Object 1 | Object 2 | Object 3 | Object 4 | Object 5 |
+----------+----------+----------+----------+----------+
| 2 4 5 | 1 3 5 | 1 2 | 1 5 | 1 2 4 |
+----------+----------+----------+----------+----------+
I want to remove unnecessary comparisons, since they would speed up the code a lot. That is, when checking if 1 and 2 together could satisfy the condition when grouped with something else, I can avoid checking against 3 (since 1 cannot satisfy it when grouped with 3) and 4 (since 2 cannot satisfy it when grouped with 4).
Since this happens millions of time in the code, I need a quick way of getting the list of objects with which a subset of objects is compatible. I thought of using a series of bits, each of them representing an entry of the array, and having the nth bit set if the object associated with it is compatible with the object in the nth entry of the array.
So if we imagine using 5 bits, we would get:
+----------+----------+----------+----------+----------+
| Object 1 | Object 2 | Object 3 | Object 4 | Object 5 |
+----------+----------+----------+----------+----------+
| 01011 | 10101 | 11000 | 10001 | 11010 |
+----------+----------+----------+----------+----------+
To see the objects against which it is worth testing 1-2, one would do the AND to both sets of bits:
01011 & 10101 = 00001
That is, only should test against the 5th entry.
I do this because I assume bit operations are faster and take less memory than storing more complex objects such as vectors and doing their intersection.
The problem is that I do not know in compile time how many objects I'll have (I can have up to hundreds). What type could I use to represent the set of bits then?
I can think of hacks such as:
Using a huge type (a struct of a few dozens uint64): this would be a waste of memory and potentially slow if I only have a few objects (having to compare thousands of bits when I only have 8 objects, for example).
Using dynamic arrays: I think dynamic allocation could prove expensive, although I have not given it too much thought. Also, I do not know if iterating through two arrays AND-ing each entrance would be as fast as AND-ing an object of the same size, but I suspect not.
Is there an efficient solution to this problem? I'd be happy with another alternative to this way of checking 'compatibility' if it proves faster.
A:
As suggested by CoryKramer in a comment, I went for boost::dynamic_bitset, which did the trick.
| {
"pile_set_name": "StackExchange"
} |
Q:
An irreducible polynomial of degree coprime to the degree of an extension is irreducible over this extension
I'm having a hard time showing this:
If $K$ is an extension of $\mathbb{Q}$ with degree $m$ and $f(x)$ an irreducible polynomial over the rationals with degree $n$, such that $\gcd(m, n)=1$, then $f(x)$ is irreducible over $K$.
I have tried it by writing $f(x)=a(x)b(x)$ and then looking at the coefficients of those polynomials (some of them must belong to $K-\mathbb{Q}$ which could possibly result in a contradiction) to no success. I have no idea where to use the hypothesis of m and n being relatively prime.
Any help would be appreciated.
A:
Let $u$ be a root of $f(x)$. Then $[\mathbb{Q}(u):\mathbb{Q}] = n$. Now consider $K(u)$. We know that $[K(u):K]\leq n$, since the monic irreducible of $u$ over $K$ divides $f$. Since
$$[K(u):\mathbb{Q}] = [K(u):K][K:\mathbb{Q}] = m[K(u):K]\leq mn$$
and
$$[K(u):\mathbb{Q}] = [K(u):\mathbb{Q}(u)][\mathbb{Q}(u):\mathbb{Q}] = n[K(u):\mathbb{Q}(u)]$$
then $[K(u):\mathbb{Q}]$ is at most $nm$, is a multiple of $n$, and is a multiple of $m$. Since $\gcd(n,m)=1$, it follows that $[K(u):\mathbb{Q}]=nm$, so the degree $[K(u):K]$ is equal to $n$.
What does that imply about the monic irreducible of $u$ over $K$ and about $f$?
| {
"pile_set_name": "StackExchange"
} |
Q:
Sort column names by number
I have 3 differents dataframes. After a colname(df) , i have this form of name column for a dataframe :
Name Length 20 21 22 23 24 25 26
Name Length factor 18 19 20 21 22 23 24
Name Length deep 18 19 20 21 22 23 24 25 26
But I would like to get the largest and smallest element (the numbers are always in the right order but not necessarily in the same position.)
in this example, it would be for the first: 20 , 26
for the second: 18 , 24
and for the third: 18 , 26
I use: range(colname(df), finite = TRUE)
but the results is "18" "length"
Any idea?
A:
We can convert the column names to numeric for the selected columns and then take the range
nm1 <- grep("^\\d+$", names(df1))
range(as.numeric(names(df1)[nm1]))
It can be converted to a function
f1 <- function(data) {
nm1 <- grep("^\\d+$", names(data))
range(as.numeric(names(data)[nm1]))
}
f1(df1)
f1(df2)
It can also be directly converted without subsetting the column, but there will be a warning message
range(as.numeric(names(df1)), na.rm = TRUE)
| {
"pile_set_name": "StackExchange"
} |
Q:
Python magicmock causes 'NoneType' object has no attribute 'unregister'
I'm trying to patch a function call with a custom mock I wrote
subscriberMock = MagicMock(side_effect=subscriber)
subscriberMock.return_value.unregister.return_value = True
with patch('rospy.Subscriber', subscriberMock):
data['op'] = "unsubscribe"
data['topic'] = "/helo"
self.rosbridge.incoming(data)
The inner method has this piece of code
self.subscribers[topic] = rospy.Subscriber(topic, 'msg', outgoing_function)
self.subscribers[topic].unregister() # <-- AttributeError
However when I run this it returns an attribute error
'NoneType' object has no attribute 'unregister'
I'm guessing the return_value is set to a NoneType but I thought this subscriberMock.return_value.unregister.return_value would override it
More Information:
if I print self.subscribers[topic] it returns None. It then runs the side effect. Why should self.subscribers[topic] = None given that I have a return value for a parameter in it.
A:
Instead of the above mock, you have to write a Mock calling the instantiation within the side effect
def subscriber (topic, topic_type, outgoing_function):
# convert to a ROS object
output = ROSBridgeObject()
output.foo = topic
# pretend we got a message from what we subscribed to
outgoing_function(output)
mock = MagicMock()
subscriberMock.unregister.return_value = True
return mock
subscriberMock = MagicMock(side_effect=subscriber)
This is because MagicMock's either have return values or side effects
| {
"pile_set_name": "StackExchange"
} |
Q:
Initializing int4 using Swift; bug or expected behaviour?
Playground code:
import simd
let test = int4(1,2,3,4) // this works
let x = 1
let test2 = int4(x,2,3,4) // doesn't work (nor does let x: Int = 1)
let y: Int32 = 1
let test3 = int4(y,2,3,4) // works
It's clear that int4 expects Int32 values, but in the first case it seems able to figure it out without explicitly specifying the type of Int, but in the second case (when the integer is first stored as a separate variable) it doesn't.
Is this expected behaviour in Swift?
A:
At a first glance, this looks like expected behavior.
When you specify
let test = int4(1,2,3,4)
the integer literals there are implicitly initialized as Int32 types. When you just do a
let x = 1
x by default has a type of Int. As a safety measure, Swift doesn't do implicit type conversion on integers and floating point types. You would need to explicitly cast it to an Int32 to get this to work:
let test2 = int4(Int32(x),2,3,4)
which is why your third example works. Rather than relying on type inference to set what y is, you give it the Int32 type and the types now align.
| {
"pile_set_name": "StackExchange"
} |
Q:
Wipe all WiFi settings from MacBook
My old MacBook has come out of retirement after about two years turned off. It connected to my WiFi but the browsers complain it's insecure and might be connected to servers pretending to be the ones I'm entering. And my ISP's security features are warning me I'm not using their DNS (which explains the browser warnings too I guess).
I've tried forgetting the network and logging back in, and deleting any DNS settings I can see in system settings, and re-setting DHCP->manual and back, and nothing works.
Do I need to wipe all WiFi settings or is there something else? On ethernet it works fine (it's one of those antique MacBooks before Apple improved them by removing such things).
A:
IIRC, there is a pretty simple way to do this! The first set of instructions in this link explains it pretty well, but in case the link breaks, here is the text from the site. The idea is to delete the network configuration related plist files.
Turn off Wi-Fi from the menu bar.
Navigate to /Library/Preferences/SystemConfiguration/ in Finder by pressing ⌘ + Shift + G.
Select the following files:
com.apple.airport.preferences.plist
com.apple.network.identification.plist
com.apple.wifi.message-tracer.plist
NetworkInterfaces.plist
preferences.plist
Copy these files in a safe location so that if anything gets messed up, you can easily restore them.
Delete the files (from the original location).
Reboot your Mac and enable Wi-Fi again.
Let me know how this goes!
Via the command line:
cd /Library/Preferences/SystemConfiguration/
sudo zip backup.zip \
com.apple.airport.preferences.plist \
com.apple.network.identification.plist \
com.apple.wifi.message-tracer.plist \
NetworkInterfaces.plist preferences.plist
sudo rm com.apple.airport.preferences.plist \
com.apple.network.identification.plist \
com.apple.wifi.message-tracer.plist \
NetworkInterfaces.plist preferences.plist
Note: In macOS Mojave 10.14.4, the file com.apple.network.identification.plist didn't exist on atleast 1 machine where this was tested. The file not found errors can be ignored.
| {
"pile_set_name": "StackExchange"
} |
Q:
Add one element to the DOM at every iteration not all at the end of the loop
I'm not a pure front end developer and I wonder why, in a loop where at every iteration an element is added to the DOM, the resulting DOM is only visible at the end of the loop and not progressively.
<html>
<body>
<div id="body"></div>
</body>
<script>
for(var i = 0; i < 1000000; i++){
document.getElementById('body').appendChild(document.createElement('br'));
document.getElementById('body').appendChild(document.createTextNode(i));
}
</script>
</html>
A:
Javascript runs code to completion before the repaint events get processed. So in order to get the display updated at regular times, you need to end the script execution at regular times and put something in the event queue that will call back your function for proceeding further.
For instance, you can do this with setTimeout:
(function loop(i) {
if (i > 10000) return; // end condition
document.body.appendChild(document.createElement('br'));
document.body.appendChild(document.createTextNode(i));
void document.body.offsetWidth;
setTimeout(loop.bind(null, i+1), 0);
})(0);
| {
"pile_set_name": "StackExchange"
} |
Q:
getting values in column from inside the function outer
I am attempting to get the values of the row being passed into outer. What am I missing?
#create dataframe as example that will work for this function
exampledf<- matrix(ceiling(runif(16,0,50)), ncol=4)
colnames(exampledf)<-c("col1","col2","col3","col4")
x<-as.data.frame(exampledf)
cols<-cbind(colnames(x))
#end creating variables
matr<-outer(cols,cols,function(a,b){
return(eval(parse(text = "x$a")))#Doesnt work
})
My end goal is to get a partial correlation matrix. The function spcor.test() takes in two vectors (not the dataframe I am trying to give it). I am trying to write a version that takes a dataframe.
All my code so far:
library(matrixcalc)
library(ppcor)
exampledf<- matrix(ceiling(runif(16,0,50)), ncol=4)
while(is.singular.matrix(exampledf)!=TRUE){
exampledf<- matrix(ceiling(runif(16,0,50)), ncol=4)
}
colnames(exampledf)<-c("col1","col2","col3","col4")
#single example
#spcor.test(exampledf[,1],exampledf[,2],exampledf[,3])
x<-as.data.frame(exampledf)
cont<-"col3"
#semiCorr<-function(x,cont){ #x=dataframe to correlate, z=names of variables to control for
library(ppcor)
cols<-cbind(colnames(x))
cols<-cols[-c(grep(cont,cols))]
matr<-outer(cols,cols,function(a,b){
get(x$a)
#spcor.test(eval(parse(text = "x$a")),eval(parse(text = "x$b")),x[,c(cont)])
})
return((matr)) #return a matrix of the semipartial correlations
#}
#semiCorr(exampledf,"col3")
cols<-cols[-c(grep(cont,cols))]
matr<-outer(cols,cols,function(a,b){
return(a)
#return(eval(parse(text = "x$a")))#Doesnt work
})
A:
We can use expand.grid with apply
apply(expand.grid(cols, cols), 1, FUN= function(cols) x[cols])
| {
"pile_set_name": "StackExchange"
} |
Q:
How to add timestamp certificate to a signed PE file on Linux?
I need to digitally sign×tamp a PE file (EFI, actually) on Linux. I found 3 tools for signing PE files: pesign, osslsigncode and signcode (mono), but it seems none quite fits my needs. The problem is, the key is on a hardware token and cannot be exported. Therefore I have to create a certificate database, add token driver entry there and work via this DB. Only pesign allows this, but it does not support timestamping. osslsigncode and signcode support timestamping, but they cannot use the database.
The Windows signttool.exe can perform signing and timestamping as separate steps. So I thought, I might use pesign to sign the file and then only timestamp it with another tool. But as I discovered, osslsigncode and signcode do not support separate timestamping (in osslsigncode project it's listed in the TODO file, but no signs of it in repository yet).
Are there some tools I missed? Are there not-too-lowlevel libraries which would allow me to write such program myself? (Preferrably, C/C++/Perl/Python.) I tried to get the timestamping code from osslsigncode, but failed to detach it easily from the prior steps (removing existing signature and adding a new one).
P.S. I also tried to run signtool.exe under wine, but 1) failed to get it working, and 2) I'm not sure it's legally permitted (I'm not good at analyzing EULAs).
A:
Since march 2015, there is a patch in osslsigncode which allows you sign the code via a key on a PKCS#11 token. It is not part of an official release yet. So you have to build it yourself, but it works like charm for me.
An example invocation looks like this:
osslsigncode sign -pkcs11engine /usr/lib/engines/engine_pkcs11.so -pkcs11module /usr/lib/libeTPkcs11.so -certs ~/mysigningcert.pem -key 0:42ff -in ~/filetosign.exe -out ~/signedfile.exe
The -pkcs11module switch takes the PKCS#11 library as a parameter, the parameter for -key is in the format slotID:keyID.
| {
"pile_set_name": "StackExchange"
} |
Q:
Setting up Rails project on TeamCity hosted on a Windows server
I'm setting up my first Ruby project on Team City, which is hosted on a Windows Server, but I'm having a problem. Now, because the server may not have the required gems installed, I've added a command line build step:
bundle install
Now I thought this would be enough, but apparently bundle is not recognized as an internal or external command. Except, if I RDP into the server, if I run bundle install from anywhere, it is fine, and just notifies me that no gemfile was found.
Any ideas on if I've missed a step, or I'm going about this the wrong way?
A:
Most likely this is a problem with TeamCity not finding the path to ruby executables.
You can address this by overriding the value to the PATH environment variable in your build configuration in the Build Parameters section.
env.PATH=/path/to/ruby;%env.PATH%
See this answer for the proper links to documentation, etc.
EDIT #1
I noticed when updating one of my configurations that TeamCity is supposed to take care of appending values so you DO NOT need to set path equal to itself. The post mentioned above is a workaround for a bug where TeamCity was overwriting the values, but that has been corrected. See the help at the mouse-over for more information:
EDIT #2
I tested edit #1 and found that is not the case. You do need to
create an environment variable env.Path
and set it's value to itself plus your new path; in my example, C:\Program Files\MySQL\MySQL Server 5.6\bin\;%env.Path%
you do NOT need to say env.Path=... as listed above; that is what the configuration file will look like.
I tested this out by doing the following:
Created a new project with no repository
Added a command line build step to `echo %env.Path%
Added a command step to call MySql mysql --help This will fail if it cannot find MySql
I then ran it for each of the following settings for the env.Path variable:
Not added / changed; TeamCity reports out the environment variable for the build agent as is.
Added as just C:\Program Files\MySQL\MySQL Server 5.6\bin\. TeamCity reports out only that entry.
Added as C:\Program Files\MySQL\MySQL Server 5.6\bin\;%env.Path%. TeamCity prepends C:\Program Files\MySQL\MySQL Server 5.6\bin\ to the build agent's values shown in #1. The result is what we want, #1 + #2
| {
"pile_set_name": "StackExchange"
} |
Q:
Cross join causes value to be repeated
I am using CROSS JOIN in my SQL query below
SELECT
store.ACTIVITY_MTH,
Cmps_Util,
SUM(store.Renew) AS GR
FROM
store
CROSS JOIN
(SELECT
SUM(revenue.rev_attained) * 100 AS Cmps_Util
FROM
revenue
WHERE revenue.start_date BETWEEN '2014-05-01' AND '2014-10-31'
AND revenue.metric_id = 182
AND revenue.id = 'PH') AS Cmps_Util
WHERE
AND store.ACTIVITY_MTH BETWEEN '2014-05-01' AND '2014-10-31'
GROUP BY store.ACTIVITY_MTH
This results in the following response
ACTIVITY_MTH Cmps_Util GR
2014-05-01 1.2362 356
2014-06-01 1.2362 789
2014-07-01 1.2362 45
2014-08-01 1.2362 1567
2014-09-01 1.2362 45
2014-10-01 1.2362 786
Notice that the Column Cmps_Util all the values are the same . This is the Cross Joined column. How can i stop it form repeating? Notice the GR column the data is not repeated. Basically i want the data in Cmps_Util for a particular month line up with the Activity_MTH column. (the Revenue table also has revenue.start_date which is being used for Cmps_Util). If revenue table does not have a entry for that month then NULL like below.
ACTIVITY_MTH Cmps_Util GR
2014-05-01 null 356
2014-06-01 2.523 789
2014-07-01 null 45
2014-08-01 1.2362 1567
2014-09-01 1.6 45
2014-10-01 1.86 786
A:
Don't use CROSS JOIN. I believe you just want a boring old LEFT JOIN here, but your subquery needs to include the start of the month for each Revenue.start_date in your subquery so it can join to the Activity_Mth
SELECT store.ACTIVITY_MTH,
SUM(Cmps_Util.Cmps_Util),
SUM(store.Renew) AS GR
FROM store
LEFT JOIN
(
SELECT FIRST_DAY(revenue.start_date) AS start_date_month,
SUM(revenue.rev_attained) * 100 AS Cmps_Util
FROM revenue
WHERE revenue.start_date BETWEEN '2014-05-01'
AND '2014-10-31'
AND revenue.metric_id = 182
AND revenue.id = 'PH'
GROUP BY 1
) AS Cmps_Util
ON store.ACTIVITY_MTH = Cmps_Util.start_date_month
GROUP BY store.ACTIVITY_MTH
The problem is that CROSS JOIN is going to give you every value from Cmps_Util AND every value from store joined together in every possible combination. You, instead, were wanting to join on the month/date of the revenue table for each Activit_mth in the store table (I assumed).
| {
"pile_set_name": "StackExchange"
} |
Q:
Creating a new file blocks Textmate
When I want to create a new file through the button (left-bottom one) in the project drawer or in the file menu it takes a long time and blocks TextMate and even blocks TextMate totally in some cases.
I've installed the latest version of TextMate and installed all updates available for Mac OS X.
Anyone any idea what the problem is?
A:
I just tested it with a couple of different massive projects on my MBP and it created a new file right away.
First guess would be perhaps a bundle or other plugin you've added is interfering with the program operation somehow. You could also try trashing your Textmate preferences file and restart the program to see if that helps (~/Library/Preferences/com.macromates.textmate.plist).
| {
"pile_set_name": "StackExchange"
} |
Q:
How to generate XML on MonoTouch?
I need to generate XML on MonoTouch application ? How i can create like this,
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root>
...
</root>
I need to post the XML to web service as string format. And again I want to parse the response data. Response data also XML format string. I done it in j2me applications. But I don't know how to do this on MonoTouch? Anyone tell me How to do this?
A:
My favorite API these days is the System.Xml.Linq API, look at the documentation and samples here:
http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.aspx
For what you want, this is very easy:
var s = new XDocument () {
new XElement ("root")
};
Console.WriteLine ("The XML is: {0}", s.ToString ());
| {
"pile_set_name": "StackExchange"
} |
Q:
Who administers soul exchanges?
Mythology is replete with examples of people selling their soul to the devil. Except... how does that actually work, mechanically?
Let's say you sign a contract agreeing that the devil may take your soul. How does it get transferred to him? If he has the power to take it himself, he wouldn't need a contract. So maybe it's something you do, like how when you sell someone your car you have to physically hand them they keys. I don't know about you, but I wouldn't have the first clue how to go about handing someone my soul.
If it's not the devil that removes it, and it's not the contractor, that means there must be some third party. An external agency, that manages and administers the soul contracts, ensuring that the deal is fulfilled, and transferring the soul to the recipient. A neutral party, that can be trusted not to cheat, and is not interested in taking the soul for themselves. Possibly an individual, possibly an agency, but there's got to be someone.
So, who does this? And what do they get out of it?
Edit: Apparently I need to be more specific with what I am asking
Premise:
Assume that it is possible for a human to sell their soul to a supernatural being.
Supernatural beings interested in acquiring souls are not able to take them by force, and humans cannot transfer souls without assistance.
Therefore some other supernatural being (or organization of such) mediates soul-transfers, and enforces such contracts (i.e. rules whether the terms are met and the soul transfer goes ahead).
Question:
What is the identity of this being(s)?
Why do they do this? How do they benefit from assisting in the transfer of souls?
So, although additional details are certainly welcome, a basic answer might look like "soul exchanges are mediated by [NAME], who do it because [REASON]".
The best answer is the one that requires the least changes from standard mythology. That is, as much as possible using existing mythological beings, with an explanation that is similar to their myths/domain, rather than postulating an entire new cast or ascribing out of character motivations.
Apologies to whoever this was not clear to.
A:
God, of course.
Since we speak of soul and devil, we think it is safe to assume one of the Abrahamic religions in any of its variants.
So:
God is all-powerful, and
God has given men free will.
Which means that if a man decides to relinquish his soul to the devil, then God just obliges and performs the exchange himself out of respect to the man's will and the rules He established.
Yes, God is not preventing the man from getting eternal punishment for this, but God is not preventing other men from getting eternal punishment for other sins that they commit and that God could stop as easily as this transaction.
A:
Consider that the devil does indeed have the power to take a soul, but humans have the ability to keep their soul. All it would take for the devil to take the human soul is for the human to not resist. Most humans, however, innately hold onto their souls by some instinct. Presumably, humans don't have the innate knowledge of how to release their hold, so the devil, in his malign wisdom, has them sign a contract as a sort of aid to teach them how to release their grip. By succumbing to his will through the ritual of signing the contract, they release their hold, and the devil can take the soul.
Or, if you want a more magical approach, the ritual of signing the contract brings the human's will/spirit into contact with the devil's will/spirit, creating a link of contagion between them. This link is what the devil uses to magically seize the human's soul. Since the contract is also the contagious link between then, the devil is required to fulfill the contract's terms, or risk the link being severed and the soul returning to its human host.
A:
The agreement itself handles the transfer
Literature is replete with authors proposing rules that the devil must be subject to --even if we mere mortals don't understand those rules-- to get around the fundamental question most children figure out around age seven ("why hasn't the devil already conquered the world?").
The mechanics of soul transfer are governed by the same mortals-don't-need-to-understand rules. The agreement itself is the binding supernatural action, no further arbitration or action is needed.
There are several forms of appeal to the transfer (most notably contests, trials, and occasionally marriages). In trials, the ruling itself is typically sufficient to instantly negate the transfer, indicating that the same rules-we-don't-understand still apply, and that the words themselves have the supernatural power.
Best example of both immediate transfer and immediate nullification: The Simpsons Treehouse of Horror IV, in which Homer sells his soul for a donut, but the transaction is appealed and successfully reversed at trial upon presentation of a prior claim upon the soul.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to clean sms data messsages extracted from mobile phone. I want to do this with Python-Pandas
How to clean sms data messages extracted from mobile phone. I want to do this with Python-Pandas.
I need to clean data from sms messages,and I want to extract body of the message and exclude square brackets.
Example of sms message is:
' <sms protocol="0" address="+14242380303" date="1407256816998" type="1" subject="null" body="ChatON : 3630 Message is sent from the ChatON service." toa="null" sc_toa="null" service_center="null" read="1" status="-1" locked="0" date_sent="0" readable_date="5. kol 2014. 06:40:16 PM" contact_name="(Unknown)" />'
I use this code to extract body of the message.
func = lambda x: re.findall('(?<=\[)[^]]+(?=\])', x)
df=df.applymap(func)
This is the DataFrame with 'body column' which I want to clean.
Text
2 [Ok]
3 [Ok]
4 [Ok]
5 [U sedam u Dramaru kafa]
6 [Ok]
And I get this error
TypeError Traceback (most recent call last)
<ipython-input-10-f8a330ca2fe3> in <module>
1 func = lambda x: re.findall('(?<=\[)[^]]+(?=\])', x)
----> 2 df=df.applymap(func)
3
4
~/.local/lib/python3.6/site-packages/pandas/core/frame.py in applymap(self, func)
6070 return lib.map_infer(x.astype(object).values, func)
6071
-> 6072 return self.apply(infer)
6073
6074 # ----------------------------------------------------------------------
~/.local/lib/python3.6/site-packages/pandas/core/frame.py in apply(self, func, axis, broadcast, raw, reduce, result_type, args, **kwds)
6012 args=args,
6013 kwds=kwds)
-> 6014 return op.get_result()
6015
6016 def applymap(self, func):
~/.local/lib/python3.6/site-packages/pandas/core/apply.py in get_result(self)
316 *self.args, **self.kwds)
317
--> 318 return super(FrameRowApply, self).get_result()
319
320 def apply_broadcast(self):
~/.local/lib/python3.6/site-packages/pandas/core/apply.py in get_result(self)
140 return self.apply_raw()
141
--> 142 return self.apply_standard()
143
144 def apply_empty_result(self):
~/.local/lib/python3.6/site-packages/pandas/core/apply.py in apply_standard(self)
246
247 # compute the result using the series generator
--> 248 self.apply_series_generator()
249
250 # wrap results
~/.local/lib/python3.6/site-packages/pandas/core/apply.py in apply_series_generator(self)
275 try:
276 for i, v in enumerate(series_gen):
--> 277 results[i] = self.f(v)
278 keys.append(v.name)
279 except Exception as e:
~/.local/lib/python3.6/site-packages/pandas/core/frame.py in infer(x)
6068 if x.empty:
6069 return lib.map_infer(x, func)
-> 6070 return lib.map_infer(x.astype(object).values, func)
6071
6072 return self.apply(infer)
pandas/_libs/src/inference.pyx in pandas._libs.lib.map_infer()
<ipython-input-10-f8a330ca2fe3> in <lambda>(x)
----> 1 func = lambda x: re.findall('(?<=\[)[^]]+(?=\])', x)
2 df=df.applymap(func)
3
4
/usr/lib/python3.6/re.py in findall(pattern, string, flags)
220
221 Empty matches are included in the result."""
--> 222 return _compile(pattern, flags).findall(string)
223
224 def finditer(pattern, string, flags=0):
TypeError: ('expected string or bytes-like object', 'occurred at index Text')
A:
Your Text values are lists of strings, not strings. Best to first extract them. If all lists have only one message you can call
df['Text'] = df['Text'].apply(lambda x: x[0] if len(x) > 0 else x)
| {
"pile_set_name": "StackExchange"
} |
Q:
Tableau calculated field summing up the values
I have a table like this
----------------------------------------------
ID Name Value |
---------------------------------------------|
1 Bob 4 |
2 Mary 3 |
3 Bob 5 |
4 Jane 3 |
5 Jane 1 |
----------------------------------------------
Is there any ways to do out a calculated field where if the name is "Bob" , it'll sum up all the values that have the name "Bob"?
Thanks in advance!
A:
If Name = “Bob” then Value end
| {
"pile_set_name": "StackExchange"
} |
Q:
how to show JBG (yes, it is JBG) on web page
Here we store image bytes in JBG (not JPG) format, how can I show the image in web page like use img tag.
I prefer to convert the bytes into jpg image stream in java backend, but I don't know how to convert.
A:
Some googling around (I am not a JBG or Java image processing expert) shows that there is a JBIG Java image library. It plugs into the Java ImageIO framework which looks like has a JPEG plugin by default. You could use that.
| {
"pile_set_name": "StackExchange"
} |
Q:
C++ OpenMP program
I am trying to get a parallel effect in C++ program using the following code:
#include<iostream>
using namespace std;
int main()
{
#pragma omp parallel sections
{
#pragma omp section
{
cout<<"Hello";
cout<<" ";
cout<<"World";
cout<<endl;
}
#pragma omp section
{
cout<<"H";
cout<<"ello";
cout<<" W";
cout<<"orld";
cout<<endl;
}
#pragma omp section
cout<<"Hello"<<" "<<"World"<<endl;
#pragma omp section
{ cout<<"Hello ";
cout<<"World"<<endl;
}
}
return 0;
}
I had run this program many times.. I was expecting interleaved output due to parallelism..
However, every time I run this program the output is:
Hello World
Hello World
Hello World
Hello World
Am I doing something wrong?
Thanks
A:
How have you compiled the program? Is OpenMP activated?
Apart from that, a much simpler Hello World looks like this, if you want to get interleaving characters:
int main() {
char const* str = "Hello world";
unsigned const len = std::strlen(str);
#pragma omp parallel for num_threads(4)
for (unsigned thread = 0; thread < 4; ++thread)
for (unsigned i = 0; i < len; ++i)
std::cout << str[i] << std::endl;
}
A:
The code is correct, but interleaved output can be hard to get from such small programs. Try putting some calls to sleep or similar between output statements and do some flushing.
(Did you compile and link with -openmp, -fopenmp, or whatever your compiler want to hear?)
| {
"pile_set_name": "StackExchange"
} |
Q:
returning the string associated with the year and rank
So basically I have a map that looks like this
HashMap<Integer, HashMap<String, Integer>> girls =
new HashMap<Integer, HashMap<**String**, Integer>>();'
and I want to return the bolded string and this is my method so far
public String getGirlName(int year, int rank) { //year refers to Key
//rank refers to other integer in value map
if (girls.containsKey(year) && girls.get(year).containsKey(rank)){
//shouldn't this return the name
return girls.get(year).get(rank); //error here where it says I can't return an integer I have to return a string
else return null;
}
}
I'm not sure how to do the above title
A:
Let's try to see the structure of HashMap<Integer, HashMap<String, Integer>> visually, since it is quite a complex data structure
// A B
// |--------|--------|
// C D
// |------|---------------------------------------------------------------------|
{
Integer: {String: Integer, String: Integer, String: Integer, String: Integer},
Integer: {String: Integer, String: Integer, String: Integer, String: Integer},
Integer: {String: Integer, String: Integer, String: Integer, String: Integer},
Integer: {String: Integer, String: Integer, String: Integer, String: Integer}
}
Sections A and C are the keys, B and D are the values.
Now let's see what does .get(year).get(rank);. First, get(year) is called. year is a value in section C, so get(year) returns a value in section D. Next, get(rank) is called. Since it is called on the return value of get(year), rank here is a value in section A. get(rank) will return a value in section D, which are all Integers. Therefore, the compiler error occurs.
To fix this, simply swap the two types in the inner map. You change from HashMap<Integer, HashMap<String, Integer>> to HashMap<Integer, HashMap<Integer, String>>.
| {
"pile_set_name": "StackExchange"
} |
Q:
Nodejs handle button/ajax requests
I'm building a single page app and I was wondering if I'm actually doing it right. At the moment for each button that waits for a callback from the server I send an ajax request and on the server I handle it router.post/get like this:
index.html
<button id='baz' class'.foo'>Foo</button>
script.js
$(document).on('click', '.foo', function() {
var cursor = $(this);
$.ajax({
url: 'modalRoutes/bar',
type: 'POST',
dataType: 'json',
timeout: 5000,
data: {
baz: cursor.attr('id')
},
beforeSend: function() {
cursor.addClass('disabled');
},
complete: function() {
cursor.removeClass('disabled');
},
success: function(data) {
// do somehting here
},
error: function(err) {
console.log(err);
}
});
});
modalRoutes.js
var express = require('express');
var router = express.Router();
router.post('/bar', function(req,res){
// do some stuff here
res.send('done')
});
module.exports = router;
My modalRoutes.js file is growing, I barely started and it already has over 500 lines of code, is this the best way to handle buttons with node?
A:
You could have multiple modules, each exporting a default function, and just import them to have them apply onto the router, eg:
module code:
module.exports = function(router) {
router.post('/buylicense', function() {
// do some stuff here
res.send('done');
});
}
in modalRoutes, do:
var express = require('express');
var router = express.Router();
require('./someRoute')(router);
// add other imports here
module.exports = router;
| {
"pile_set_name": "StackExchange"
} |
Q:
Download file from URL without showing the full path in laravel
Download link:-
<a href='"+ downloadlink + '/attachment-download/' + $('#employee_ID').val()+'/'+ res[i].file_name +"'>
Route:-
Route::get('/attachment-download/{id}/{filename}', array(
'uses' => 'AttachmentsController@getDownloadAttachments'
));
Attachment Controller:-
public function getDownloadAttachments($id,$filename){
$file="./img/user-icon.png";
$resource = \Employee::WhereCompany()->findOrfail($id);
$path = $this->attachmentsList($resource);
foreach($path as $index => $attachment){
if ($filename == $attachment['file_name']) {
$filePath = $attachment['url'];
}
}
//return \Response::download($file);
return \Response::download($filePath);
}
File URL Output:-
https://zetpayroll.s3.ap-south-1.amazonaws.com/employees/81/Screenshot%20from%202017-04-26%2015%3A07%3A45.png?X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAI57OFN3HPCBPQZIQ%2F20170612%2Fap-south-1%2Fs3%2Faws4_request&X-Amz-Date=20170612T144818Z&X-Amz-SignedHeaders=host&X-Amz-Expires=3600&X-Amz-Signature=59ecc4d11b7ed71bd336531bd7f4ab7c84da6b7424878d6487679c97a8c52ca7
In this if try to download file by using static path like
$file="./img/user-icon.png";
return \Response::download($file);
it is downloaded fine. But not possible to downloading file from AWS URL, Please help me how to down file automatically using URL. Or How to get Path from URL in laravel or PHP.
Thank you.
A:
Using this above function All files are downloaded.
But while try to open those files are opened (.text, .csv, .pdf..).
But not open images.
$fileContent = file_get_contents($filePath);
$response = response($fileContent, 200, [
'Content-Type' => 'application/json',
'Content-Disposition' => 'attachment; filename="'.$filename.'"',
]);
return $response;
| {
"pile_set_name": "StackExchange"
} |
Q:
How to resize the block in wordpress?
I want to add some details in new line but I cannot do that .It is just moving on to next block
A:
Shiva, like VibrantVivek said more information would make it easier to get you the exact answer you are looking for. However, if you are trying to add text in a new line, but the same paragraph in a text block, try shift + enter
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I clean the shell of my tortoise?
The top and bottom of my tortoise's shell tend to get messy from wet substrate, waste, etc. How can I safely clean the shell, without damaging it in any way?
A:
I was afraid of damaging the shell (particularly in the growth regions) by scrubbing at it, so the tortoise's vet recommended using something like baby shampoo.
Baby shampoo has had some unfavorable press in the last few years due to additives. However, most of these additives have been removed from the formulations, and it also uses mild surfactants instead of soap. Surfactants are safer than soap to use in the growth regions in between the scutes (plates) of the shell, because these regions can dry out with regular soap, causing cracking and disturbing the natural "growth rings".
Using a soft cloth or chamois to gently wipe the surface and rinsing the tortoise well to get rid of any residue will remove most of the surface dirt.
A:
There is a good guide for bathing tortoises here.
All you really need to clean a tortoise's shell is water and a gentle scrubbing device of some kind, like a toothbrush or washcloth. Scrubbing (provided it's gentle) will not damage the shell and on the contrary can promote healthy shell growth.
Fill a container with lukewarm water so that it covers the entire plastron, and a few centimetres of the carapace. Let him soak for 15-20 minutes. This allows him to rehydrate and also softens any hardened dirt.
Replace with fresh water and gently scrub him all over, paying special attention to any problem areas, and rinse well at the end. Be extra gentle when dealing with any non-scaled areas, as they will be more sensitive. Coarse salt can be used as an "exfoliator" on any problem patches (shell only, not skin) but should not be used liberally and should be thoroughly rinsed off. If you find your tortoise has a lot of dirty patches that are hard to clean, it could be a sign that you need to clean his habitat more often.
A monthly bathing ritual can be a nice bonding opportunity, keeps the tortoise happy and healthy and also gives you a chance to thoroughly examine your tortoise's skin and shell, noticing problems as soon as they occur. Even when your tortoise appears clean, a regular scrub can remove dead cells and encourage healthy shell growth.
Never clean your tortoise with oil - a build up of oil is harmful to a tortoise's shell, because it can clog the pores. Tortoises "breathe" through their shells as we do through our skin and a buildup of dirt or oil can block oxygen transfer and create other problems. Detergents, shampoos, or other "products" should not be used unless recommended by your veterinary surgeon.
A:
We use a biosoap with a soft nail brush. Skatter absolutely loves having his shell scrubbed. We put a couple drops of soap in the sink, then dip the brush. Sure to always rinse him off after. It is part of our tank cleaning process. Everything is clean and fresh when he goes back!
| {
"pile_set_name": "StackExchange"
} |
Q:
Should Latitude, Longitude and Elevation have their own type in Haskell?
For people interested in this topic: the accepted answer involves some concepts that I think are well described here. Namely, differences between data, newtype and instance keywords, and ways to use them.
I started to learn Haskell like a week ago (coming from Python and C#), and I want to implement a class GeographicPosition, that stores Latitude, Longitude and Elevation.
Specifically, I'd like to do it in the most elegant, functional, "unit-of-measurement" aware way.
If we take, for example, X, Y and Z in cartesian ("rectangular") space, they all mean the same thing, have the same range (from -inf to +inf), being orthogonal and uniform.
Now with Latitude, Longitude and Elevation this is not like that. Longitude, for example, is periodic, Latitude has some maximum rangess at the poles (which are themselves singularities), and the elevation has a minimum absolute value at the center of the earth (another singularity).
Singularities apart, it is obvious (to me at least) that they are not "the same thing", in the sense that X, Y and Z are "the same thing" in a cartesian system. I cannot simply flip the origin and pretend that Latitude is now Longitude in the way that I can pretend that X now is Y, and such.
So the question is:
Should Latitude, Longitude and Elevation have their own numerical type in a type representing geographical position in Haskell? What would be a good type signature for that (a minimal sample code would be great)
I would imagine something along like
data Position = Position { latitude :: Latitude,
longitude :: Longitude,
elevation :: Elevation }
instead of the more obvious, position-based
data Position = Position RealFloat RealFloat RealFloat
but I don't know which style is more advised. It seems like Bounded is an interesting construct too, but I didn't quite understood how to use it in this case.
A:
I personally would make a type for them, and if you really want to make sure to keep things within their periodic bounds then this is a great opportunity to ensure that.
Start by making simple newtype constructors:
newtype Latitude = Latitude Double deriving (Eq, Show, Ord)
newtype Longitude = Longitude Double deriving (Eq, Show, Ord)
Note that I didn't use RealFloat, because RealFloat is a typeclass, not a concrete type so it can't be used as a field to a constructor. Next, write a function to normalize these values:
normalize :: Double -> Double -> Double
normalize upperBound x
| x > upperBound = normalize upperBound $ x - upperBound
| x < -upperBound = normalize upperBound $ x + upperBound
| otherwise = x
normLat :: Latitude -> Latitude
normLat (Latitude x) = Latitude $ normalize 90 x
normLong :: Longitude -> Longitude
normLong (Longitude x) = Longitude $ normalize 180 x
(Note: This is not the most efficient solution, but I wanted to keep it simple for illustrative purposes)
And now you can use these to create "smart constructors". This is essentially what the Data.Ratio.Ratio type does with the % function to ensure that you provide Integral arguments and reduce that fraction, and it doesn't export the actual data constructor :%.
mkLat :: Double -> Latitude
mkLat = normLat . Latitude
mkLong :: Double -> Longitude
mkLong = normLong . Longitude
These are the functions that you'd export from your module to ensure that no one misuses the Latitude and Longitude types. Next, you can write instances like Num that call normLat and normLong internally:
instance Num Latitude where
(Latitude x) + (Latitude y) = mkLat $ x + y
(Latitude x) - (Latitude y) = mkLat $ x - y
(Latitude x) * (Latitude y) = mkLat $ x * y
negate (Latitude x) = Latitude $ negate x
abs (Latitude x) = Latitude $ abs x
signum (Latitude x) = Latitude $ signum x
fromInteger = mkLat . fromInteger
And similarly for Longitude.
You can then safely perform arithmetic on Latitude and Longitude values without worrying about them ever going outside valid bounds, even if you're feeding them into functions from other libraries. If this seems like boilerplate, it is. Arguably, there are better ways to do this, but after a little bit of set up you have a consistent API that is harder to break.
One really nice feature implementing the Num typeclass gives you is the ability to convert integer literals to your custom types. If you implement the Fractional class with its fromRational function, you'll get full numeric literals for your types. Assuming you have both implemented properly, you can do things like
> 1 :: Latitude
Latitude 1.0
> 91 :: Latitude
Latitude 1.0
> 1234.5 :: Latitude
Latitude 64.5
Granted, you'll need to make sure that the normalize function is actually the one you want to use, there are different implementations that you could plug in there to get usable values. You might decide that you want Latitude 1 + Latitude 90 == Latitude 89 instance of Latitude 1 (where the values "bounce" back after the reach the upper bound), or you can have them wrap around to the lower bound so that Latitude 1 + Latitude 90 == Latitude -89, or you can keep it how I have it here where it just adds or subtracts the bound until it's within range. It's up to you which implementation is right for your use case.
A:
An alternative to using separate types for every field is to use encapsulation: create an abstract data type for your Positions, make all the fields private and only let users interact with positions using the public interface you provide.
module Position (
Position, --export position type but not its constructor and field accessor.
mkPosition, -- smart constructor for creating Positions
foo -- your other public functions
) where
-- Named fields and named conventions should be enough to
-- keep my code sane inside the module
data Position = Position {
latitude :: Double,
longitude :: Double,
elevation :: Double
} deriving (Eq, Show)
mkPosition :: Double -> Double -> Double -> Position
mkPosition lat long elev =
-- You can use this function to check invariants
-- and guarantee only valid Positions are created.
The main advantage of doing this is that there is less type system boilerplate and the types you work with are simpler. As long as your library is small enough, you can keep all the functions in your head the naming conventions + testing should be enough to make your functions bug free and respecting the Position invariants.
See more on http://www.haskell.org/haskellwiki/Smart_constructors
| {
"pile_set_name": "StackExchange"
} |
Q:
Django - NOT NULL constraint failed on stockinfo_note.stock_id - ForeignKey error
Purpose and Problem:
I want to put two forms in the same template and process them in the one view. I can get the template to display the two forms but not submit them (i.e process the submission). When I submit I get the following error:
Exception Value: NOT NULL constraint failed: stockinfo_note.stock_id
'stock' is the ForeignKey. I can't figure out how to get the function stock_new in Views.py to populate the foreign key ID which is what i think i need to do to overcome the above error.
Models.py:
class Stock(models.Model):
'''
Model representing the stock info.
'''
user = models.ForeignKey(User)
ticker_code = models.CharField(max_length=10, null=True, blank=True)
def __str__(self):
return self.ticker_code
class Note(models.Model):
'''
Model representing the note.
'''
user = models.ForeignKey(User)
text_note = models.TextField()
stock = models.ForeignKey(Stock)
def __str__(self):
return self.text_note
Forms.py
class StockForm(forms.ModelForm):
class Meta:
model = Stock
fields = ('ticker_code',)
class NoteForm(forms.ModelForm):
class Meta:
model = Note
fields = ('text_note',)
Views.py
def stocknoter(request):
stock = Stock.objects.filter(user=request.user)
note = Note.objects.filter(user=request.user)
context_dict = {'stock':stock, 'note':note}
return render(request, "stocknoter/stock.html", context_dict)
def stock_new(request):
if request.method == "POST":
form1 = StockForm(request.POST)
form2 = NoteForm(request.POST)
if form1.is_valid() and form2.is_valid():
stock = form1.save(commit=False)
stock.user = request.user
stock.save()
note = form2.save(commit=False)
note.user = request.user
'''
**THE PROBLEM IS AROUND HERE i think, how do i pass stock_id created
by form1 so form2 saves it as the foreignkey?**
'''
note.save()
return redirect('stock')
else:
form1 = StockForm()
form2 = NoteForm()
return render(request, 'stocknoter/stock_edit.html', {'form1':form1, 'form2':form2})
As mentioned above, i think the problem lies with this latter section (sorry should add i am new to Django). What do i need to do to save the foreign key id?
A:
Okay solved the problem. In stock_new i added: note.stock = stock
So views.py now look likes this:
def stocknoter(request):
stock = Stock.objects.filter(user=request.user)
note = Note.objects.filter(user=request.user)
context_dict = {'stock':stock, 'note':note}
return render(request, "stocknoter/stock.html", context_dict)
def stock_new(request):
if request.method == "POST":
form1 = StockForm(request.POST)
form2 = NoteForm(request.POST)
if form1.is_valid() and form2.is_valid():
stock = form1.save(commit=False)
stock.user = request.user
stock.save()
note = form2.save(commit=False)
note.user = request.user
note.stock = stock
note.save()
return redirect('stock')
else:
form1 = StockForm()
form2 = NoteForm()
return render(request, 'stocknoter/stock_edit.html', {'form1':form1, 'form2':form2})
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use $routeParams without template (website)
Is it possible use $stateParams without setting $stateProvider, $urlRouterProvider?
I would use $stateParams only in few page of my website!
A:
You can use $location.search() which will give you parameter from URL
If you want to get specific parameter you can do below code
$location.search().param
param will be parameter name which you want to search.
| {
"pile_set_name": "StackExchange"
} |
Q:
Knapsack: how to add item type to existing solution
I've been working with this variation of dynamic programming to solve a knapsack problem:
KnapsackItem = Struct.new(:name, :cost, :value)
KnapsackProblem = Struct.new(:items, :max_cost)
def dynamic_programming_knapsack(problem)
num_items = problem.items.size
items = problem.items
max_cost = problem.max_cost
cost_matrix = zeros(num_items, max_cost+1)
num_items.times do |i|
(max_cost + 1).times do |j|
if(items[i].cost > j)
cost_matrix[i][j] = cost_matrix[i-1][j]
else
cost_matrix[i][j] = [cost_matrix[i-1][j], items[i].value + cost_matrix[i-1][j-items[i].cost]].max
end
end
end
cost_matrix
end
def get_used_items(problem, cost_matrix)
i = cost_matrix.size - 1
currentCost = cost_matrix[0].size - 1
marked = Array.new(cost_matrix.size, 0)
while(i >= 0 && currentCost >= 0)
if(i == 0 && cost_matrix[i][currentCost] > 0 ) || (cost_matrix[i][currentCost] != cost_matrix[i-1][currentCost])
marked[i] = 1
currentCost -= problem.items[i].cost
end
i -= 1
end
marked
end
This has worked great for the structure above where you simply provide a name, cost and value. Items can be created like the following:
items = [
KnapsackItem.new('david lee', 8000, 30) ,
KnapsackItem.new('kevin love', 12000, 50),
KnapsackItem.new('kemba walker', 7300, 10),
KnapsackItem.new('jrue holiday', 12300, 30),
KnapsackItem.new('stephen curry', 10300, 80),
KnapsackItem.new('lebron james', 5300, 90),
KnapsackItem.new('kevin durant', 2300, 30),
KnapsackItem.new('russell westbrook', 9300, 30),
KnapsackItem.new('kevin martin', 8300, 15),
KnapsackItem.new('steve nash', 4300, 15),
KnapsackItem.new('kyle lowry', 6300, 20),
KnapsackItem.new('monta ellis', 8300, 30),
KnapsackItem.new('dirk nowitzki', 7300, 25),
KnapsackItem.new('david lee', 9500, 35),
KnapsackItem.new('klay thompson', 6800, 28)
]
problem = KnapsackProblem.new(items, 65000)
Now, the problem I'm having is that I need to add a position for each of these players and I have to let the knapsack algorithm know that it still needs to maximize value across all players, except there is a new restriction and that restriction is each player has a position and each position can only be selected a certain amount of times. Some positions can be selected twice, others once. Items would ideally become this:
KnapsackItem = Struct.new(:name, :cost, :position, :value)
Positions would have a restriction such as the following:
PositionLimits = Struct.new(:position, :max)
Limits would be instantiated perhaps like the following:
limits = [Struct.new('PG', 2), Struct.new('C', 1), Struct.new('SF', 2), Struct.new('PF', 2), Struct.new('Util', 2)]
What makes this a little more tricky is every player can be in the Util position. If we want to disable the Util position, we will just set the 2 to 0.
Our original items array would look something like the following:
items = [
KnapsackItem.new('david lee', 'PF', 8000, 30) ,
KnapsackItem.new('kevin love', 'C', 12000, 50),
KnapsackItem.new('kemba walker', 'PG', 7300, 10),
... etc ...
]
How can position restrictions be added to the knapsack algorithm in order to still retain max value for the provided player pool provided?
A:
There are some efficient libraries available in ruby which could suit your task , Its clear that you are looking for some constrain based optimization , there are some libraries in ruby which are a opensource so, free to use , Just include them in you project. All you need to do is generate Linear programming model objective function out of your constrains and library's optimizer would generate Solution which satisfy all your constrains , or says no solution exists if nothing can be concluded out of the given constrains .
Some such libraries available in ruby are
RGLPK
OPL
LP Solve
OPL follows the LP syntax similar to IBM CPLEX , which is widely used Optimization software, So you could get good references on how to model the LP using this , Moreover this is build on top of the RGLPK.
| {
"pile_set_name": "StackExchange"
} |
Q:
WPF Recreation window in different STA thread
I need to create window with loading gif when my main window is rendering. I have read some articles and make a decision that for this purposes i need to create new thread. I did it like in this article
As a result I have something like that:
LoadingDialog _loadingDlg;
Thread loadingThread;
public void ShowLoading()
{
loadingThread = new Thread(new ThreadStart(loadingThreadWork));
loadingThread.SetApartmentState(ApartmentState.STA);
loadingThread.Start();
}
private void loadingThreadWork()
{
_loadingDlg = new LoadingDialog();
_loadingDlg.Show();
System.Windows.Threading.Dispatcher.Run();
}
public void HideLoading()
{
_loadingDlg.Dispatcher.InvokeShutdown();
}
First time when I call ShowLoading() and then HideLoading() everything works like I want. But when I call ShowLoading() at the second time I get an exception at
_loadingDlg.Show();
with message The calling thread cannot access this object because a different thread owns it.
How can this be? _loadingDlg is created in the previous line, and in the same thread.
A:
In the loadingThreadWork you're creating the control, before the first run it's a null, so in first time you succeed. However, you're creating the dialog in a different thread, which is marked as an owner for the control.
At the next time you're calling the loadingThreadWork, control isn't null, and ant change for it from a different thread (and it is a different thread, because you're creating it again) leads to the exception you've got.
As you're using WPF, you probably should switch from threads to async operations, which are much more readable, supportable and predictable than your current solution.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why cannot we read the CIL inside .EXE files with a text editor?
I know that a C# compiler transforms the C# code into CIL, of which parts are then compiled by the installed .NET's JIT to machine code as needed during runtime.
What exactly does the compiler do, and what is the form of the .exe file that we cannot simply open it with a text editor and read the CIL inside?
A:
The native form of CIL is respresented by binary sequences and not a textual, human-readable code.
The readable representation we see is commonly achieved by decompilers, and it is not the original form that resides in executable files.
| {
"pile_set_name": "StackExchange"
} |
Q:
solve $h = 36\sin(1.5t) - 15\cos(1.5t) + 65$ using $k\sin(1.5t - \alpha)$
The blades of a turbine are turning at a steady rate.
The height $h$ metres, of the tip of one of the blades above the
ground at time, $t$ seconds is given by the formula:
$h = 36\sin(1.5t) - 15\cos(1.5t) + 65$
Express $36\sin(1.5t) - 15\cos(1.5t)$ in the form $k\sin(1.5t -
> \alpha)$ where $k>0$ and $0<\alpha < \frac{\pi}2$
and hence find the two values of t for which the tip of this blade is
at a height of 100 metres above the ground during the first turn.
$36\sin(1.5t) - 15\cos(1.5t) = k\sin(1.5t -\alpha)$
$36\sin(1.5t) - 15\cos(1.5t) = k\cos\alpha\sin 1.5 t - k\sin\alpha\cos 1.5t$
$k\cos \alpha = 36$
$k\sin \alpha = -15$
$\alpha = \arctan\frac{-15}{36} = -22.6$
$\alpha$ is in the 4th quadrant because $\sin$ is negative and $\cos$ is positive.
$k = \sqrt{15^2 + 36^2} = 39$
$\therefore 39\sin(1.5t - 337.4) = -65$
$39\sin(1.5t - 337.4) = -65$
$\sin(1.5t - 337.4) = \frac{-65}{39}$
Which is where I am stuck because $\arcsin\frac{-65}{39}$ is undefined.
A:
$36\sin(1.5t) - 15\cos(1.5t) = k\cos\alpha\sin 1.5 t - k\sin\alpha\cos 1.5t$
$k\cos \alpha = 36$
$k\sin \alpha = -15$
This is incorrect. We have $$-k\sin\alpha=-15\quad\Rightarrow\quad k\sin\alpha=\color{red}{+}15$$
and so we have $\alpha=\arctan(15/36)\approx 0.395$ satisfying $0\lt \alpha\lt \pi/2$.
$\therefore 39\sin(1.5t - 337.4) = -65$
We have $$h=39\sin(1.5t-0.395)+65.$$
However, we cannot write this as
$$39\sin(1.5t-0.395)=-65\tag1$$
because $(1)$ is equivalent to $39\sin(1.5t-0.395)+65=0$, i.e. $h=0$ which we don't have.
Now, $h=100$ comes from the question itself saying "find the two values of t for which the tip of this blade is at a height of 100 metres above the ground during the first turn".
It follows from these that
$$100=h=39\sin(1.5t-0.395)+65,$$
i.e.
$$39\sin(1.5t-0.395)=100-65=35$$
Dividing the both sides by $39$ gives
$$\sin(1.5t-0.395)=\frac{35}{39}$$
This is how we have $35/39$ as almagest has shown in comments.
$\qquad\qquad\qquad$
Finally, since $t\gt 0\Rightarrow 1.5t-0.395\gt -0.395=-\alpha$, we solve
$$1.5t-0.395=\arcsin\frac{35}{39}\quad\text{or}\quad \pi-\arcsin\frac{35}{39}$$
and the answer is $\color{red}{t\approx 1.006\quad\text{or}\quad 1.615}$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Vim: Quickly select rectangular blocks of text in visual-block mode
I'm looking for a fast way to select a block of text in visual-block mode. I deal with files of this nature:
aaaa bbbb cccc
aaaa bbbb cccc
aaaa bbbb cccc
dddd Xeee ffff
dddd eeee ffff
dddd eeee ffff
gggg hhhh iiii
gggg hhhh iiii
gggg hhhh iiii
My goal is to select the middle block in visual-block mode. I would do:
Navigate to the corner (where the X is)
Ctrl-V
'e' to extend selection to the end of block
'jj' or '2j' to extend the selection downward to the bottom of the block.
I'm looking for an alternative to (4) that, similar to 'e', would move to the last row of the block. In this simple example 'jj' is not too inconvenient, but sometimes these are large blocks.
There's a similar question here , but that involves jumping a pre-determined number of lines. Is there a way to do this, again an analog to 'e', but moving row-wise instead of column-wise? Thanks!
A:
Starting on the X, you could do this with <C-v>}kee:
<C-v> – start blockwise visual mode
} – go to the end of the paragraph (that motion supposedly provides the benefit of this rather involved combo)
k – one above to exclude the empty line
ee – move the cursor from the first column to the end of the inner block.
A:
I had some fun trying to make a function "select Visual block around cursor".
function! ContiguousVBlock()
let [lnum, vcol] = [line('.'), virtcol('.')]
let [top, bottom] = [lnum, lnum]
while matchstr(getline(top-1), '\%'.vcol.'v.') =~# '\S'
let top -= 1
endwhile
while matchstr(getline(bottom+1), '\%'.vcol.'v.') =~# '\S'
let bottom += 1
endwhile
let lines = getline(top, bottom)
let [left, right] = [vcol, vcol]
while len(filter(map(copy(lines), 'matchstr(v:val,"\\%".(left-1)."v.")'),'v:val=~#"\\S"')) == len(lines)
let left -= 1
endwhile
while len(filter(map(copy(lines), 'matchstr(v:val,"\\%".(right+1)."v.")'),'v:val=~#"\\S"')) == len(lines)
let right += 1
endwhile
call setpos('.', [0, top, strlen(matchstr(lines[0], '^.*\%'.left.'v.')), 0])
execute "normal! \<C-V>"
call setpos('.', [0, bottom, strlen(matchstr(lines[-1], '^.*\%'.right.'v.')), 0])
endfunction
nnoremap <Leader>vb :<C-U>call ContiguousVBlock()<CR>
You can try it with <Leader>vb: It should select any contiguous non-whitespace rectangular block around the cursor. The vertical axis is preferred.
Maybe I'll improve it later, but for now you can try if it solves your problem, if you like.
As an alternative to my homegrown attempt, you could try the popular plugin textobj-word-column. It gives you text objects ac ic aC iC to select a column of words or WORDs.
| {
"pile_set_name": "StackExchange"
} |
Q:
what is boiler-plate code? why should it be avoided?
What is boiler-plate code, and why it is called like that?
Example for android:
onCreate(Bundle saveInstance){
setcontentView(R.layout.m);
findViewById(R.id.f1);
findViewById(R.id.f2);
findViewById(R.id.f3);
findViewById(R.id.f4);
}
What other examples are there? Why should we avoid boiler-plate code?
A:
Boilerplate code is repetitious code that needs to be included in many places. The origins are well explained by the wikipedia article on the subject:
Interestingly, the term arose from the newspaper business. Columns and other pieces that were syndicated were sent out to subscribing newspapers in the form of a mat (i.e. a matrix). Once received, boiling lead was poured into this mat to create the plate used to print the piece, hence the name boilerplate. As the article printed on a boilerplate could not be altered, the term came to be used by attorneys to refer to the portions of a contract which did not change through repeated uses in different applications, and finally to language in general which did not change in any document that was used repeatedly for different occasions.
There are several problems with boilerplate code:
It's error prone. Your example may be straight-forward, but not all boilerplate instances are. In cases where the code includes a bit more logic to it there's more room to make mistakes (=bugs). Especially if these blocks just get copy-pasted from place to place, but require some alterations to work.
Moreover - if you ever have to change this logic, it's much harder to do, as you need to go over several places to do it.
It takes up screen realestate and attention. More code to read means there's more things you need to process when trying to understand a piece of code you're reading. Boilerplate code just adds another distraction.
It takes up actual space in the final (usually compiled) product. What would you rather deliver? A 1MB JAR file or a 10MB one?
| {
"pile_set_name": "StackExchange"
} |
Q:
Composer install missing curl-ext
I am developing some PHP on Ubuntu 14.04.4 LS. Running composer install is failing and I can't figure it out. This was working earlier when I was using PHP 5.5.9, but I had to update to at least 5.6 in order to install phpunit.
Running php -v outputs:
PHP 5.6.23-1+deb.sury.org~trusty+2 (cli)
Copyright (c) 1997-2016 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2016 Zend Technologies
with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2016, by Zend Technologies
Running which php outputs:
/usr/bin/php
which is kind of suspicious as it doesn't match php -v (/usr/bin has: "php", "php5", and "php5.6")
Here is my composer.json:
{
"require-dev": {
"phpunit/phpunit": "5.4.*"
},
"require": {
"silex/silex": "~1.3",
"stripe/stripe-php": "3.*"
}
}
Running composer install creates this output:
$ composer install
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.
Problem 1
- stripe/stripe-php v3.9.2 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- stripe/stripe-php v3.9.1 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- stripe/stripe-php v3.9.0 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- stripe/stripe-php v3.8.0 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- stripe/stripe-php v3.7.1 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- stripe/stripe-php v3.7.0 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- stripe/stripe-php v3.6.0 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- stripe/stripe-php v3.5.0 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- stripe/stripe-php v3.4.0 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- stripe/stripe-php v3.3.0 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- stripe/stripe-php v3.2.0 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- stripe/stripe-php v3.14.3 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- stripe/stripe-php v3.14.2 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- stripe/stripe-php v3.14.1 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- stripe/stripe-php v3.14.0 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- stripe/stripe-php v3.13.0 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- stripe/stripe-php v3.12.1 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- stripe/stripe-php v3.12.0 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- stripe/stripe-php v3.11.0 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- stripe/stripe-php v3.10.1 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- stripe/stripe-php v3.10.0 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- stripe/stripe-php v3.1.0 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- stripe/stripe-php v3.0.0 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- stripe/stripe-php v3.14.2 requires ext-curl * -> the requested PHP extension curl is missing from your system.
- Installation request for stripe/stripe-php 3.* -> satisfiable by stripe/stripe-php[v3.0.0, v3.1.0, v3.10.0, v3.10.1, v3.11.0, v3.12.0, v3.12.1, v3.13.0, v3.14.0, v3.14.1, v3.14.2, v3.14.3, v3.2.0, v3.3.0, v3.4.0, v3.5.0, v3.6.0, v3.7.0, v3.7.1, v3.8.0, v3.9.0, v3.9.1, v3.9.2].
To enable extensions, verify that they are enabled in those .ini files:
- /etc/php/5.6/cli/php.ini
- /etc/php/5.6/cli/conf.d/10-opcache.ini
- /etc/php/5.6/cli/conf.d/10-pdo.ini
- /etc/php/5.6/cli/conf.d/20-calendar.ini
- /etc/php/5.6/cli/conf.d/20-ctype.ini
- /etc/php/5.6/cli/conf.d/20-exif.ini
- /etc/php/5.6/cli/conf.d/20-fileinfo.ini
- /etc/php/5.6/cli/conf.d/20-ftp.ini
- /etc/php/5.6/cli/conf.d/20-gettext.ini
- /etc/php/5.6/cli/conf.d/20-iconv.ini
- /etc/php/5.6/cli/conf.d/20-json.ini
- /etc/php/5.6/cli/conf.d/20-phar.ini
- /etc/php/5.6/cli/conf.d/20-posix.ini
- /etc/php/5.6/cli/conf.d/20-readline.ini
- /etc/php/5.6/cli/conf.d/20-shmop.ini
- /etc/php/5.6/cli/conf.d/20-sockets.ini
- /etc/php/5.6/cli/conf.d/20-sysvmsg.ini
- /etc/php/5.6/cli/conf.d/20-sysvsem.ini
- /etc/php/5.6/cli/conf.d/20-sysvshm.ini
- /etc/php/5.6/cli/conf.d/20-tokenizer.ini
You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.
I followed these instructions but it doesnt work: Composer install error - requires ext_curl when it's actually enabled
Running php -i | grep php.ini outputs:
Configuration File (php.ini) Path => /etc/php/5.6/cli
Loaded Configuration File => /etc/php/5.6/cli/php.ini
Running: sudo apt-get install php5-curl outputs:
php5-curl is already the newest version.
Running curl -V outputs:
curl 7.35.0 (x86_64-pc-linux-gnu) libcurl/7.35.0 OpenSSL/1.0.1f zlib/1.2.8 libidn/1.28 librtmp/2.3
Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtmp rtsp smtp smtps telnet tftp
Features: AsynchDNS GSS-Negotiate IDN IPv6 Largefile NTLM NTLM_WB SSL libz TLS-SRP
Any help is appreciated.
A:
Execute this:
sudo apt-get install php-curl
A:
Some notes:
Running php -i is good. It shows you the php.ini used, so that you know which file to edit.
Running curl -v is not needed, because that's the standalone curl for usage on the CLI and unrelated to the PHP Extension curl.
You checked for php5-curl, that's the needed package. Ok.
What's missing? You need to make sure the extension is also loaded by PHP!
Edit your /etc/php/5.6/cli/php.ini, search for extension, look for php_curl and enable it: extension=php_curl.so.
Then run php -m on the CLI to see the list of loaded modules and ensure that curl is loaded.
Finally, re-run your composer install.
| {
"pile_set_name": "StackExchange"
} |
Q:
Regular expression to find URLs within a string
Possible Duplicate:
C# code to linkify urls in a string
I'm sure this is a stupid question but I can't find a decent answer anywhere. I need a good URL regular expression for C#. It needs to find all URLs in a string so that I can wrap each one in html to make it clickable.
What is the best expression to use for this?
Once I have the expression, what is the best way to replace these URLs with their properly formatted counterparts?
Thanks in advance!
A:
I am using this right now:
text = Regex.Replace(text,
@"((http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)",
"<a target='_blank' href='$1'>$1</a>");
A:
Use this code
protected string MakeLink(string txt)
{
Regex regx = new Regex("http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", RegexOptions.IgnoreCase);
MatchCollection mactches = regx.Matches(txt);
foreach (Match match in mactches)
{
txt = txt.Replace(match.Value, "<a href='" + match.Value + "'>" + match.Value + "</a>");
}
return txt;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Was Castrodinium named after Fidel Castro?
In Star Trek TOS episode Balance of Terror, Mr. Spock says that Castrodinium is "the hardest substance known to our science." Could it be that it was named after Fidel Castro?
A:
The actual quote is shown below. As you can see, it's not one word ('castrodinium'), it's actually two words ('cast rodinium'), referring to the fictional transuranic element rodinium.
The 'casting' process presumably refers to the method used to make the element into a usable shape.
SPOCK: From the outpost's protective shield. Cast rodinium.
This is
the hardest substance known to our science.
(He crushes it with his
hand)
The Starfleet Medical Reference Manual offers the following information about the substance but no particular indication of why the name was chosen:
If I had to make a complete guess, I'd say that Roddenberry had decided to name an element after himself.
| {
"pile_set_name": "StackExchange"
} |
Q:
Changing colors of Navigation Drawer menu items
This is how my current navigation drawer looks like:
I've divided it into 4 groups. All I'm trying is to give every group a different text-color. I'm trying the options SETTINGS, FEEDBACK and TERMS AND CONDITIONS to have a smaller font and a little off-black color. I searched, but couldn't find a way to customize the navigation drawer groups individually. Here's the code I wrote for the menu:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group
android:id="@+id/menu"
android:checkableBehavior="single">
<item
android:id="@+id/nav_targets"
android:icon="@drawable/icon_target"
android:title="Targets" />
<item
android:id="@+id/nav_testing"
android:icon="@drawable/icon_testing"
android:title="Testing" />
<item
android:id="@+id/nav_course_work"
android:icon="@drawable/icon_course_work"
android:title="Course Work" />
<item
android:id="@+id/nav_schedule"
android:icon="@drawable/icon_schedule"
android:title="Schedule" />
<item
android:id="@+id/nav_profile"
android:icon="@drawable/icon_profile"
android:title="Profile" />
</group>
<group
android:id="@+id/settings">
<item
android:title="SETTINGS"
android:id="@+id/settings_item"></item>
</group>
<group
android:id="@+id/feedback">
<item
android:title="FEEDBACK"
android:id="@+id/feedback_item"></item>
</group>
<group
android:id="@+id/TnC">
<item
android:title="TERMS & CONDITIONS"
android:id="@+id/t_n_c_item"></item>
</group>
Is there a way to achieve it?
A:
There are 2 ways to customize the navigation drawer menu items individually.
First way:
MenuItem menuItem = navigationView.getMenu().findItem(R.id.menu_item);
SpannableString s = new SpannableString(menuItem.getTitle());
s.setSpan(new ForegroundColorSpan(TEXT_COLOR), 0, s.length(), 0);
s.setSpan(new AbsoluteSizeSpan(TEXT_SIZE_in_dip, true), 0, s.length(), 0);
menuItem.setTitle(s);
Second way:
MenuItem menuItem = navigationView.getMenu().findItem(R.id.menu_item);
SpannableString s = new SpannableString(menuItem.getTitle());
s.setSpan(new TextAppearanceSpan(this, R.style.TextAppearance), 0, s.length(), 0);
menuItem.setTitle(s);
res / values / styles.xml
<style name="TextAppearance">
<item name="android:textColor">TEXT_COLOR</item>
<item name="android:textSize">TEXT_SIZE_in_sp</item>
</style>
| {
"pile_set_name": "StackExchange"
} |
Q:
Force ServicePointManager.SecurityProtocol to TLS 1.2 on all connections
I have a WCF service which sends an outgoing request. Currently it is using SSL 3.0 or TLS 1.0.
The service I am sending the request to now only accepts TLS 1.2.
I can set the SecurityProtocolType just before the request (and for each request), but I would like it to use TLS 1.2 for all outgoing requests without having to specify it for each request.
This code sets it correctly for the request:
<OperationContract(), WebGet(UriTemplate:="...")>
Public Function SomeService()
System.Net.ServicePointManager.SecurityProtocol = (System.Net.SecurityProtocolType) 3072; // 3072 is TLS 1.2
// Do request
End Function
But I cannot see how to set WCF to use TLS 1.2 for all requests. I have tried placing the above statement into Application_Start and Application_BeginRequest in Global.asax, but by the time it comes to doing the request, SecurityProtocol is back to SSL3/TLS1.0
A:
If you have access to the registry you can apply the following key:
registry key
This enforces TLS 1.2 at the Windows level of the Transport Layer so you don't need to change any code.
These are the keys changed in the above file:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001
| {
"pile_set_name": "StackExchange"
} |
Q:
Scala: Is object in every scope the identical singleton?
I have a flink application. I use an object inside the map function. Like this:
.map(value => {
import spray.json._
import com.webtrekk.sObjects._
import com.webtrekk.jsonProtocol._
import com.webtrekk.salesforce._
implicit val effortProcessing = streamProcessor.Effort
implicit val effortConsulting = effortConsultingFormat
var effort = value.toString.parseJson.convertTo[effortConsulting]
streamProcessor.Effort.mapping(
value.toString.parseJson.convertTo[effortConsulting]
)
effort
})
The streamProcessor is a object. Inside this object is another service object for the database. Flink executes this map function every time when an event comes to the application. What i want to know: Is the object every time the identical singleton object?
An example:
-> event comes to the application -> map function will execute and a singleton object will created
-> next event comes to the application -> map function will execute again ->
object will called again
Is the second object the identical instance?
A:
Yes and no. An object is a singleton within its scope:
scala> List(1, 2).map(i => { object foo { def bar: Int = i }; foo }).map(_.bar)
res2: List[Int] = List(1, 2)
This means that the following are loosely equivalent:
object foo extends Thing { ... }
lazy val foo = new Thing { ... }
In your case because the object is declared outside of the map function, it is the same instance every time.
| {
"pile_set_name": "StackExchange"
} |
Q:
Show up modal in navbar
I have navbar where I want to show up modal if I clic in one item.Title
So now I show my navbar in js menupopulator like these:
function completeMenu(data, target) {
var prefix = "<ul class='nav navbar-nav navbar-right'>";
var sufix = "</ul>";
var items = data.d.results;
var menu = "";
for (var item in items) {
if(items[item].Funcion != null && items[item].Funcion != ""){
menu += "<li><a href=" + items[item].Enlace + " id='"+items[item].Funcion+"'>" + items[item].Title + "</a></li><li class='divider-vertical'></li>";
}
else
menu += "<li><a href=" + items[item].Enlace + ">" + items[item].Title + "</a></li><li class='divider-vertical'></li>";
So that I want is where items[item].Title is == SignIn show modal instead open another link... can I do that?
I try something like these:
for (var item in items) {
if(items[item].Funcion != null && items[item].Funcion != ""){
menu += "<li><a href=" + items[item].Enlace + " id='"+items[item].Funcion+"'>" + items[item].Title + "</a></li><li class='divider-vertical'></li>";
}
else
menu += "<li><a href=" + items[item].Enlace + ">" + items[item].Title + "</a></li><li class='divider-vertical'></li>";
if(items[item].Title == "SignIn"){
menu += "<li><a href="#mymodal" data-toggle="modal" data-target="#mymodal"></a></li>"
}
}
}
But I don´t want to show up button, I want to show a href like my menupopulator
And then in view:
<div id="mymodal" class="fade modal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true" >
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">
<asp:Label runat="server" ID="lblHeader"></asp:Label></h4>
</div>
<div class="modal-body">
<p>Test modal</p>
</div>
</div>
</div>
----------------------------Update-----------------------------
There is my change but when I change it, I get only a label saying "true"
function completeMenu(data, target) {
var prefix = "<ul class='nav navbar-nav navbar-right'>";
var sufix = "</ul>";
var items = data.d.results;
var menu = "";
for (item in items) {
menu += "<li><a href=" + items[item].Enlace + ">" + items[item].Title + "</a></li><li class='divider-vertical'></li>";
if(items[item].Title == "SignUp"){
menu += "<button type= button class=btn btn-link data-toggle= modal data-target=#mymodal">""
}
}
$(target).html(prefix + menu + sufix);
}
A:
As I understand you need also change this line:
"<button type= button class=btn btn-default data-toggle= modal data-target=#mymodal">
To this one:
"<button type= button class=btn btn-link data-toggle= modal data-target=#mymodal">
| {
"pile_set_name": "StackExchange"
} |
Q:
Puppet reboot in stages
I need to do a two step installation of a CentOS6 host with puppet (currently using puppet apply) and got stuck. Not even sure it's currently possible today.
Step 1, setup of base system e.g. setup hosts, ntp, mail and some driver stuff.
reboot required
Step 2, setup of a custom service.
Can this bee done a smooth way? I'm not very familiar with the puppet environment yet.
A:
First off, I very much doubt that any setup steps on a CentOS machine strictly require a reboot. It is usually sufficient to restart the right set of services to make all settings take effect.
Anyway, basic approach to this type of problem could be to
Define a custom fact that determines whether a machine is ready to receive the final configuration steps (Step 2 in your question)
Protect the pertinent parts of your manifest with an if condition that uses that fact value.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the purpose of having a one-way function also be a permutation on it's on domain?
From a cryptographic sense, what value is added from setting the domain to be the image in the mapping?
A:
A one-way permutation (OWP) is more structured than a one-way function, and hence a stronger object. This makes the task of constructing higher cryptographic objects from OWPs easier and also, at times, leads to more efficient constructions. For example, consider pseudo-random generators (PRGs): it is quite straightforward to construct a PRG from a OWP; but constructing a PRG from a OWF took a lot more effort -- you can read more here.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to plot a heatmap under a curve?
If I were to have a data for a one-dimensional system evolving in time, essentially a two-dimensional array, and the array at each point in time is of the same size, how would I produce something like this:
(Taken from Turing’s model for biological pattern formation and the robustness problem by Maini et al., 2012)
I have tried to replicate this with matplotlib by resizing (or rather synthesising) each instance in time to an array of specific length, according to the growth of the domain, and filling the rest of the array with NaNs.
import numpy as np
import matplotlib.pyplot as plt
N = 750
x = []
t = np.linspace(0, N, N)
def asize(i, N): # Computes the necessary size of the array
return int(N*np.exp(2*(i-N)/N))
for i in range(N): # Concatenating data with whitespace
x.append(np.concatenate((np.sin(np.linspace(0,3*np.pi,asize(i,N)))**2,
np.NaN*np.zeros(N-asize(i,N)))))
x = np.transpose(np.array(x))
plt.imshow(x, cmap = 'Spectral_r', origin = 'lower')
plt.plot(t, N*np.exp(2*(t-N)/N), c='white', lw = 2) # Making the boundary smoother
plt.axis([0,N,0,N])
plt.xlabel('$t$')
plt.ylabel('$x$')
plt.xticks([0,250,500,750])
plt.yticks([0,250,500,750])
plt.show()
Naturally, with actual data this method would be even more tedious, requiring to somehow squish the arrays. Is there a more reasonable way of doing this with matplotlib, Mathematica or any other tool?
A:
I answered a similar question in StackOverflow.
The main "trick" is to transform your grid before plotting. For example, using the following transformation
\begin{align}
&t' = t\, ,\\
&x' = x e^t\, ,
\end{align}
and then use $(t', x')$ for your plot with contourf() or pcolormesh().
Following is a snippet showing the main idea.
import numpy as np
import matplotlib.pyplot as plt
t, x = np.pi*np.mgrid[0:1:100j, 0:1:100j]
val = x
new_x = x*np.exp(t)
# plt.contourf(t, new_x, val)
plt.pcolormesh(t, new_x, val)
plt.xlabel("t")
plt.ylabel("x")
plt.show()
And this is the result.
| {
"pile_set_name": "StackExchange"
} |
Q:
Auto center div within div.
Given the following
<style>
.container {
overflow: hidden;
height: 100%;
width: 90%;
margin: 15px auto 0px auto;
}
.square
{
float: left;
width: 80px;
height: 80px;
display: block;
background-image: url('commonimgs/empty_icon.png');
background-repeat: no-repeat;
margin: 2px;
padding-top: 3%;
margin-left: 5px;
}
</style>
<div>
<div class="container">
<div class="square">1R</div>
<div class="square">2R</div>
<div class="square">3R</div>
<div class="square">4R</div>
<div class="square">5R</div>
<div class="square">6</div>
<div class="square">7</div>
<div class="square">8</div>
<div class="square">9</div>
<div class="square">10</div>
</div>
</div>
I am trying to make a tiled layout that auto centers and adapts to screen size. What I can't figure out is how to get the squares to spread evenly across the container.
getting...
+------------------------------------+
| |
| +------------------------------+ |
| | | |
| | +----+ +----+ +----+ | |
| | | | | | | | | |
| | | | | | | | | |
| | +----+ +----+ +----+ | |
| | | |
| | +----+ +----+ +----+ | |
| | | | | | | | | |
| | | | | | | | | |
| | +----+ +----+ +----+ | |
| | | |
| | +----+ +----+ +----+ | |
| | | | | | | | | |
| | | | | | | | | |
| | +----+ +----+ +----+ | |
| | | |
| +------------------------------+ |
| |
+------------------------------------+
wanting
+------------------------------------+
| |
| +------------------------------+ |
| | | |
| | +----+ +----+ +----+ | |
| | | | | | | | | |
| | | | | | | | | |
| | +----+ +----+ +----+ | |
| | | |
| | +----+ +----+ +----+ | |
| | | | | | | | | |
| | | | | | | | | |
| | +----+ +----+ +----+ | |
| | | |
| | +----+ +----+ +----+ | |
| | | | | | | | | |
| | | | | | | | | |
| | +----+ +----+ +----+ | |
| | | |
| +------------------------------+ |
| |
+------------------------------------+
A:
Add padding: 3%; to .container
.container {
overflow: hidden;
height: 100%;
width: 90%;
margin: 15px auto 0px auto;
background:#dbdbdb;
padding: 3%;
}
DEMO
Or text-align:center to .container
.container {
overflow: hidden;
height: 100%;
width: 90%;
margin: 15px auto 0px auto;
background:#dbdbdb;
padding: 3%; text-align:center
}
DEMO 2
Also change display:block to display:inline-block in .square
| {
"pile_set_name": "StackExchange"
} |
Q:
Ant java task NoClassDefFoundError
I want to make a simple ant build hibernate test project.
There is no error during the compilation and the build (jar).
But when I run it I get this:
java.lang.NoClassDefFoundError: org/hibernate/cfg/Configuration ...
I have found an advise, what said : jars should be added to classpath in the command line, (classpath is ignored when the jar run from ant ... ehh), ok I tried the following:
java -jar dist/student.jar -cp /home/myname/workspace/basic_ant1/lib/hibernate/hibernate-core-4.2.8.Final.jar
But still have the some error :NoClassDefFoundError ...
What did I wrong ?
Thanks for the replies in advance.
(org.hibernate.cfg is in hibernate-core-4.2.8.Final.jar)
Cs.
A:
-jar and -cp are mutually exclusive.
If you want to use java -jar then your main JAR file needs a Class-Path entry in its manifest that points to all the other jars its Main-Class requires (the manifestclasspath task is a handy way to generate this value).
If you use java -cp then you have to give the main class name on the command line, the Main-Class from the manifest is ignored.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to figure out why the garbage collector is using 90% of my CPU?
I have a java program that starts getting laggy and using too much CPU after about 20-30 minutes of running, and continues to get worse as time goes on.
I'm on Ubuntu Linux 17.10 using the Open JRE 8_151. I confirmed that this bug also occurs on windows using Oracle JRE 8_131 (and i'm assuming 8_151).
I waited about 45 minutes until the program was using a lot of CPU (about 90%) and took the following actions to try to ID which thread in my program is being a hog:
ps aux
#Visually confirm the process is using 90% and note ID -- 20316
top -p20316
#confirm usage, in top it says 366.3%; 4-core processor so this makes sense
[while in top] press shift + H
# See four threads each using about 85%
20318
20319
20320
20321
# Convert those to hex
20318 -> 0x4f5e
20319 -> 0x4f5f
20320 -> 0x4f60
20321 -> 0x4f61
[Exit top]
jstack -l 20316 | less
[press / and search for those hex thread ids]
# Get the following results:
"GC task thread#0 (ParallelGC)" os_prio=0 tid=0x00007ff9f8020000 nid=0x4f5e runnable
"GC task thread#1 (ParallelGC)" os_prio=0 tid=0x00007ff9f8021800 nid=0x4f5f runnable
"GC task thread#2 (ParallelGC)" os_prio=0 tid=0x00007ff9f8023800 nid=0x4f60 runnable
"GC task thread#3 (ParallelGC)" os_prio=0 tid=0x00007ff9f8025000 nid=0x4f61 runnable
So it's the garbage collector that's using up my CPU. That's not very helpful to me, because I don't know which thread is generating the objects that are being collected, or why it's consuming 85% of my processor power to garbage collect.
Where do I go from here to try to debug this issue? I can start disabling active running threads to see if the problem goes away, but given that it
Doesn't manifest every launch; and
Takes 20-30 minutes to start appearing
This may take a while, so I'm hoping for something a bit more clever, like what I tried above.
Any suggestions?
P.S. I never call System.gc() in my code.
A:
Check if you have a very large amount of long-lived objects. This is a deadly case for a garbage collector with generations. In this case try to use G1 GC.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the point of paper alchemical cartridges?
Using a paper cartridge cost 1 gold more than just a bullet and a dose of black powder, so what exactly is the point of having them when you can just have a bullet and some loose black powder?
A:
Paper alchemical cartridges reload faster than a standard bullet. They reload one step faster than a regular bullet.
| {
"pile_set_name": "StackExchange"
} |
Q:
Catching exceptions when calling role::create and permission::create
I am using laravel permissions and i am creating and destroying permissions a lot and sometimes i cant tell if a user has a certain permission or don't and having to check if a user has a role and permission shall require additional code before i call role::create() for instance.
If i try creating a role that already exists i get a database error and i want for this to fail gracefully like ignore role create or permission create if a user has a specific permission or role i am trying to add.
Does laravel-permissions come with a method to catch such exceptions instead of presenting a user with database errors?.
A:
The simplest way to catch any sql syntax or query errors
Illuminate\Database\QueryException
try this
try {
role::create()
} catch(\Illuminate\Database\QueryException $ex){
dd($ex->getMessage());
// Note any method of class PDOException can be called on $ex.
} catch(Exception $e){
// order error handeling
}
see [https://laravel.com/api/6.x/Illuminate/Database/QueryException.html]1
| {
"pile_set_name": "StackExchange"
} |
Q:
Validation Drop down on a condition
its a bit confusing to write my idea but ill give it a try.
Here is what i was able to do. I have a drop down on my vertical cells, so i have a list of names to pick from which is linked by [name]-> [define] and [data] -> [validation].
what i would like is another vertical cell to populate another drop down depending on the condition of the first.
for instance i have a list of fruits and vegetables. My first drop down menu asks the type so i select fruit. Because of such selection my second drop down will give me a list of fruits only (no vegetables) and vice versa.+
your help is greatly appreciated.
thanks gang!
if i want to name the cell instead of vegetable but 2009 and fruit 2010 i get an error. is there a way arround?
thanks
A:
Let's work with some named ranges.
Name E7 "option"
Put "vegetables" into E4 and "fruits" into E5;
in E7, Data > Validation > List, source $E$4:$E$5;
put some vegetables into H4:H7; name that range "vegetables";
put some fruits into J4:J7; name that range "fruits";
Now, in E8: Data > Validation > List, source "=INDIRECT(option)".
When you make a choice in E7, the options for E8 are set accordingly.
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL distinct on one column with two tables
I am having trouble getting this query correct. I am using Postgres and trying to query the last 15 clients viewed by a user.
Table client
Columns id, name...
Table impressions
Columns imressionable_id, user_id, created_at ...
The impressionable_id is equal to the client_id and the tables can be joined on this field.
I need to get a list of the last 15 DISTINCT client names viewed by the user and ordered DESC by the created_at date. The problem is currently a query of the impressions table will produce many duplicate entries but with unique created_at timestamp as each time you view a client it creates a new impressions record.
So, a query of
select impressions.impressionable_id, created_at from impressions where user_id = 1 order by created_at DESC
will produce:
impressionable_id created_at
1 2014-11-14 21:44:47.705167
1 2014-11-14 21:32:15.411488
3 2014-11-14 18:43:26.020719
1 2014-11-14 18:42:15.974442
5 2014-11-14 18:41:10.609617
3 2014-10-29 20:53:01.383896
I need a query that will give me:
1 John Doe 2014-11-14 21:44:47.705167
3 Jay Smith 2014-11-14 18:43:26.020719
5 Tim Jones 2014-11-14 18:41:10.609617
and so on. Any help is greatly appreciated!
A:
Use MAX() and GROUP BY:
select I.impressionable_id,c.name, MAX(I.created_at) as created_at
from impressions JOIN
client c ON c.id = I.user_id
group by impressionable_id,c.name
order by created_at DESC
limit 15;
| {
"pile_set_name": "StackExchange"
} |
Q:
Unable to decode a NSObject in Swift
I am having a problem decoding an object after I encode it in Swift.
Here is my class:
class Player: NSObject, NSCoding {
var score:Int = 0
init(difficulty: Int!) {
super.init()
}
required init(coder aDecoder: NSCoder) {
score = aDecoder.decodeObjectForKey("score") as Int
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(score, forKey: "score")
}
Here is when I am encoding and decoding:
let data = NSKeyedArchiver.archivedDataWithRootObject(player)
let newPlayer = NSKeyedUnarchiver.unarchiveObjectWithData(data) as Player
It crashes everytime when I try to unarchive it. Anybody have any reasons why?
P.S. I have no idea why my code isn't formatted. I have it indented 4 spaces over! Sorry about that!
A:
Here is what I did to get it working:
Created an instance of player in my App Delegate
You can call this anywhere if your application UIApplication.sharedApplication().player
| {
"pile_set_name": "StackExchange"
} |
Q:
No users with ALL PRIVILEGES
I've encountered an issue after upgrade of MySQL server.
Probably, upgrade procedure went south.
The result was that none of the users had ALL PRIVILEGES grant.
All the administrators had GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, RELOAD, SHUTDOWN, PROCESS, FILE, REFERENCES, INDEX, ALTER, SHOW DATABASES, SUPER, CREATE TEMPORARY TABLES, LOCK TABLES, EXECUTE, REPLICATION SLAVE, REPLICATION CLIENT, CREATE VIEW, SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, CREATE USER, TRIGGER ON and GRANT OPTION
It looks very much like ALL PRIVILEGES translated into individual privileges, but obviousely something is missing. After reviewing the privileges listed, i've found that all the users were missing EVENT privilege.
mysql> SELECT * FROM mysql.user WHERE Event_priv='Y'\G
Empty set (0.01 sec)
Now, this privilege was added in MySQL 5.16 and is defined as enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N', so probably UPDATE on existing users have failed (or is missing in the upgrade scripts).
After realizing what was wrong, i started to look for a solution here (I mean, if NO user has this privilege, how do i GRANT it?), and did not find a problem exactly like this one.
A:
So i thought i'd ask, but then i thought "wait a second, what if..." and attempted to UPDATE the users table myself... and VOILA! MySQL actually LET ME do it!
So here it is:
Question: How to recover a missing EVENT privilege?
Answer:
mysql> UPDATE mysql.user SET Event_priv='Y' WHERE User='root';
Query OK, 1 row affected (0.00 sec)
mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.14 sec)
Then login again to MySQL and that's it - SHOW GRANTS shows root having ALL PRIVILEGES again.
So (and this is my guess, correct me if i am wrong), as long as you still have UPDATE privilege that affects mysql privilege tables, you can pretty much grant any privilege to yourself or others by manually).
I'm sure this is conceptually OK (since i do have UPDATE...), but as a side note i'd say this is kinda weird that i can alter my own privileges to a larger set.
| {
"pile_set_name": "StackExchange"
} |
Q:
Vacation Destination
So, a while ago I asked a friend to plan our next vacation. I had to tear him away from his computer and this site to get him to do anything. Which was probably my first mistake. I don't know if he is trying to get even or is actually excited about this vacation.
Anyway, he emailed me this list and said see you there. I have no idea what any of this means, so I went to talk with him (he was only in the other room) but all he kept mumbling about was ordered lists and strings inside of strings. I don't know if its important or if he finally cracked.
4) Waiter
7) End
9) Pause
3) VMD title
5) Fast feathered swimmer
2) Wait in line
8) Ancient
6) Transformation process
1) No pattern
7) Instructions
6) Long lived
3) Aromatic leaf
1) Blue box
2) An arrangement
4) Binary single character
8) Contains pictures
5) Small bite
4) Information
2) Non-standard layout
6) Home Sweet Home
1) Nothing
3) Magical root
5) Multipurpose tool
3) Exterminate
8) Set aside
5) Pile up
2) Coffee
6) Unknown
7) Rules
1) A hat
4) A friend and an enemy
Once you're finished with the list don't forget to cross your I's and dot your T's
What city does he have in mind for our vacation?
My friend is a programmer by trade, but he eat, sleeps, and dreams code anyway. He also likes British science fiction.
A:
No answer yet but perhaps a way to proceed...
It seems like each phrase can be represented as a different word - blue box, for example, is tardis. Tardis has both a t and an i in it so I feel like that's on the right track. I suspect after finding all of the words, you would replace the i's by dashes ones and the t's by dots zeros, place each list in numerical order and then decipher the morse code binary.
A:
NEW ATTEMPT
I'm guessing that the answer to each clue must contain
the letter I and the letter T.
So some attempts at the clues are below.
SET 1
4) Waiter = hesitater (loiterer or maitre d')
7) End = terminate
9) Pause = interrupt? (or intermission or interlude?)
3) VMD title = veterinarian
5) Fast feathered swimmer = gentoo penguin
2) Wait in line = loiter
8) Ancient = prehistoric (or primitive)
6) Transformation process = mutation
1) No pattern = arbitrary (or erratic)
Perhaps instead of using the clue numbers to reorder the clue's answers, we instead use those numbers to
take the corresponding letter from each correct answer.
So if a clue is numbered 4, take the 4th letter. Unfortunately, at the moment for the first set above that gives me: [I/T] A [T/S/E] T O O? [O/V] I [A/E]
I can't really make sense of that, so maybe that use of the numbering isn't correct.
SET 2
7) Instructions = directions
6) Long lived = ancient?
3) Aromatic leaf = cilantro?
1) Blue box = Tardis
2) An arrangement = ?
4) Binary single character = bit
8) Contains pictures = illustrated
5) Small bite = appetizer?
OLD ATTEMPT VERIFIED WRONG
Based on Morgan G's idea, I took a crack at the first set. Nothing definitive, but perhaps if you squint you can see
New York?
Because if you
Reorder them by their number, then figure out a word for each, then take every letter i in the answer to be a morse code dash and every t to be a dot...
1) No pattern = arbitrary → -. → N
2) Wait in line = stand → . → E
3) VMD title = veterinarian → .-- → W
4) Waiter (server?)
5) Fast feathered swimmer (gentoo) penguin .- or - = A or T??
6) Transformation process (mutation would yield U...)
7) End = terminate → .-. → R
8) Ancient = prehistoric → -.- → K
9) Pause (break?)
The trouble is that
if this is the correct approach, there are many possible answers to almost every clue, and thus it's hard to definitively answer this.
| {
"pile_set_name": "StackExchange"
} |
Q:
_BitScanForward64 returns wrong answer in c++.exe (rubenvb-4.7.2-release)
Long time MSVC user, new to gcc (so bear with me).
I am using the rubenvb version of c++ (see version in subject, yes I'm building for 64bit) on Windows 7 and I'm having a problem using _BitScanForward64. Some sample code looks like this:
int __cdecl main(int argc, char* argv[])
{
DWORD d = (DWORD)atoi(argv[1]);
DWORD ix, ix2;
ix2 = _BitScanForward64(&ix, d);
printf("bsf %u %u\n", ix, ix2);
}
I am compiling with:
"C:\Program Files\gcc2\mingw64\bin\c++.exe" -o iTot.exe -mno-ms-bitfields -march=native -momit-leaf-frame-pointer -mwin32 -Os -fomit-frame-pointer -m64 -msse4 -mpopcnt -D WINDOWS main.cpp
When I run iTot.exe using the parameter 8, I expected that _BitScanForward64 would set ix to 3. That's what MSVC does. However, ix is 0 and ix2 is 1.
Also, looking at the assembler, I see:
bsfq QWORD PTR 44[rsp],rax # MEM[(volatile LONG64 *)&ix], Mask
Under the circumstances, why does gcc force a memory write+read here?
So, a few questions:
Is _BitScanForward64 somehow supposed to be called differently under gcc? If I'm just calling it wrong, that would be good to know (although the incompatibility with MSVC would be a pain).
Why does the _BitScanForward64 intrinsic force a memory write?
Staring at the assembler output from -S, I couldn't see anything wrong with the code being generated. However, using objdump.exe -d -Mintel, I see that rather than using the asm code above (which seems like it would work), it actually produced the reverse:
bsf rax,QWORD PTR [rsp+0x2c]
WTF? Why is -S lying to me?
Like I said, I'm new to gcc, so if I'm just doing something dumb, be gentle with me. Thanks.
A:
Ok, I think I've answered my own questions. Thanks to Joachim PileBorg who made me look at where the definition was, and Alexey Frunze who pointed out that the params can't be backward.
While I'm too new to gcc to say this authoritatively, I believe the definition for _BitScanForward64 in winnt.h is very wrong.
The current definition:
__CRT_INLINE BOOLEAN _BitScanForward64(DWORD *Index,DWORD64 Mask) {
__asm__ __volatile__("bsfq %1,%0" : "=r" (Mask),"=m" ((*(volatile LONG64 *)Index)));
return Mask!=0;
}
My definition:
__CRT_INLINE BOOLEAN BSF(DWORD *Index,DWORD64 Mask) {
LONG64 t;
__asm__ ("bsfq %0,%1" : "=r" (Mask),"=r" (t));
*Index = t;
return Mask!=0;
}
Note the removal of the (unneeded) volatile, the reversal of the parameters to bsfq, the change from =m to =r, etc. Basically, it appears this definition is as wrong as it could be and still compile.
I'm guessing the person who wrote this looked at the prototype for BitScanForward64 and "knew" that one of the parameters had to be memory, and since the only one that can be memory for BSF is p2, that's what they did. As written, the code will read the unwritten contents of p2 and scan it for bits. It compiles, but produces the wrong answer.
So, to take my questions in order:
No, I wasn't calling it incorrectly. The definition in winnt.h is just wrong. In fact, there's probably a bunch in that file that have a similar problem (_BitScanForward, _BitScanForward64, _BitScanReverse, _BitScanReverse64, etc).
It forces a memory write because the code in winnt.h was wrong. My proposed change does not force any memory accesses.
-S is writing the output file incorrectly (objdump has it right). Using my definition above produces:
call atoi
lea rcx, .LC0[rip]
/APP
# 7 "m.cpp" 1
bsfq rax,rdx
/NO_APP
call printf
And this isn't what is actually in the executable file. The actual executable file contains the (correct) definition:
bsfq rdx,rax
While I'm not excited about modifying system header files, it appears that's going to be my answer here. If anyone knows how/where to report this problem so it gets fixed (as I mentioned, I'm using reubenvb), I could report these 2 issues so (hopefully) this gets fixed for everyone.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to add an ul element custom event with jQuery?
I have a draggable pair of lists. The design: 2 ul list, interchangable items, with drag and drop.
I am using jquery sortable widget.
The question is that i want to fire an event when an li item drops in the or fire some event when ul list change.
How can i do that??
HTML:
div class="col-lg-4">
<div class="form-group">
<ul id="sortable1" class="connectedSortable">
<li class="ui-state-default">Item 1</li>
<li class="ui-state-default">Item 2</li>
<li class="ui-state-default">Item 3</li>
<li class="ui-state-default">Item 4</li>
<li class="ui-state-default">Item 5</li>
</ul>
</div>
</div>
<div class="col-lg-4">
<div class="form-group">
<ul id="sortable2" class="connectedSortable">
<li class="ui-state-default">Item 1</li>
<li class="ui-state-default">Item 2</li>
<li class="ui-state-default">Item 3</li>
<li class="ui-state-default">Item 4</li>
<li class="ui-state-default">Item 5</li>
</ul>
</div>
</div>
JavaScript:
$(function() {
$("#sortable1, #sortable2").sortable({
connectWith: ".connectedSortable"
}).disableSelection();
})
A:
Please check below snippet. Used stop and receive two events. Stop event will trigger every time element dragged and dropped. And receive event will trigger only when element is moved from one list to another.
$(function() {
$("#sortable1, #sortable2").sortable({
connectWith: ".connectedSortable",
stop: function(event, ui) {
var dropElemTxt = $(ui.item).text();
alert(dropElemTxt+" moved");
},
receive: function(event, ui) {
var dropElemTxt = $(ui.item).text();
alert(dropElemTxt+" Moved from another list");
},
}).disableSelection();
})
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<div class="col-lg-4">
<div class="form-group">
<ul id="sortable1" class="connectedSortable">
<li class="ui-state-default">Item 1</li>
<li class="ui-state-default">Item 2</li>
<li class="ui-state-default">Item 3</li>
<li class="ui-state-default">Item 4</li>
<li class="ui-state-default">Item 5</li>
</ul>
</div>
</div>
<div class="col-lg-4">
<div class="form-group">
<ul id="sortable2" class="connectedSortable">
<li class="ui-state-default">Item 1</li>
<li class="ui-state-default">Item 2</li>
<li class="ui-state-default">Item 3</li>
<li class="ui-state-default">Item 4</li>
<li class="ui-state-default">Item 5</li>
</ul>
</div>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
UIView creation and positioning
I have in my controller two UIView members, progressLineView and buttonsView. At some point I call this method:
- (void) drawPlayProgressLine{
progressLineView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 1, buttonsView.frame.size.height)];
progressLineView.backgroundColor = [UIColor whiteColor];
[buttonsView addSubview:progressLineView];
}
Everything works fine, and I also have a method that changes the position of the view:
- (void) moveProgressLine{
CGRect frame = progressLineView.frame;
frame.origin.x++;
progressLineView.frame = frame;
}
After the moveProgressLine method is called a few times and I want to call drawPlayProgressLine again, instead of completely moving the view to the starting position, it creates a new view. The more drawPlayProgressLine is called, the more views I get on my screen but I only need one.
I don't understand how this can happen when I'm creating only one object. How can I move the view instead of having a new one created each time? And another question: how can completely remove it (until the drawPlayProgressLine method is called to create it again)
A:
I don't understand how this can happen when I'm creating only one object.
You create a new view every time you call your -drawPlayProgressLine method. Call it 10 times, you get 10 views.
How can I move the view instead of having a new one created each time?
Don't create the view each time through -drawPlayProgressLine. Instead, you can do either of:
Create progressLineView once, when the view controller's view hierarchy is created. -viewDidLoad is a perfect place for that sort of thing.
Check the value of progressLineView and create it only if it is currently nil.
Whichever you choose, assuming progressLineView is an instance variable, you can do exactly what you're doing in your -moveProgressLine method. That is, just use progressLineView as though it already exists, because it does. BTW, an easy way to move a view is to modify it's center property:
CGPoint *c = progressLineView.center;
c.x += 25.0;
progressLineView.center = c;
And another question: how can completely remove it (until the
drawPlayProgressLine method is called to create it again)
One approach is to simply hide the view when you're not using it. Another is to remove it from its super view (and release it if you've retained it), and then set your progressLineView to nil. So, if progressLineView is an ivar, do this:
[progressLineView removeFromSuperview];
[progressLineView release]; // if you're not using ARC and have retained it
progressLineView = nil;
| {
"pile_set_name": "StackExchange"
} |
Q:
Gain EQ for Introverted Person
What method and/or technique is recommended to make an introverted person to gain high emotional intelligence, social skills and social competence in his/her personality?
What I have seen the method is to train specific Japanese martial arts (not all Japanese martial arts), read books, staying in a big city for instance capital city etc.
A:
Basically an introverted or shy person is caught in a viscious circle:
you don't interact with people much because often you don't feel the need
because of this you don't have much practice in interacting with other people
so if you try to interact when you do feel the urge, you feel that you don't interact very successfully or even "fail"
this in turn reinforces your wish to not interact
What you need to do is break out of this self-reinforcing circle. But how?
If you want to become better at speaking a foreign language, reading books about language learning is not going to help you much. What you need to do is practice that language.
The only thing that will help you gain social competence is practice your social skills.
Cognitive-behavioural therapy for pathologically shy people consists of many components, such as psychoeducation (understanding the causes, stabilizing factors, and symptoms of your trait) and correction of dysfunctional beliefs (you are not worth less, on the contrary there are positive aspects of being introverted), which, in self-help, you can do with a book or through meditation, but the one central methodology, and the only thing that will instigate a change, is getting into the situation that you are afraid of: exposition (facing what you fear to lose your fear by realizing nothing bad is happening) and behavior training (building a new habit and competence).
If you want to help youself, you can of course read books on your problem to better understand what is going on and what you might do, but then you need to get out and do it. I would do:
define your ultimate goal (e.g. I want to be able to talk in front of an audience without stuttering)
break this mountain of a goal down into small, manageable goals (e.g. if you are afraid of approaching attractive girls, start with old ladies)
all goals, the ultimate and the subordinate goals, must be concrete and measurable (e.g. not "I want to be more extroverted", but "I want to smile back next time Paul smiles at me"); it must be absolutely clear and unmistakeable when you are in the situation you want to change and when you have achieved your goal; nothing vague and general that no-one can meet
practice regularly (e.g. consciously smile at every person you encounter on your way to work, every day)
this may be hard, so don't force yourself to be friendly to everybody all the time, note that even extroverted people don't interact with everybody always, and certainly are not always friendly; give yourself breaks and allow yourself to rest from your exercises (e.g. plan to not smile on your way home)
slowly increase difficulty (e.g. in week two start to say "hi" to those people that smile back; in week three, mention the wonderful weather; etc.)
accept that you are not extroverted, i.e. don't expect yourself to become what you are not comfortable with; be content with gaining confidence and competence to be outgoing whenever you feel like it, but allow yourself to remain by yourself when that is what you want; just try to observe yourself and take note of when you really want to be alone and when you are only afraid of socializing
accept that not everyone will love you; competent extroverts experience many refusals, they just have many prositive encounters to balance them; you aren't interested in everybody either, are you? so don't take it personal, move on to the next person and see if he is more welcoming -- one of the next persons will be
write a diary of what you did, what happened, any changes in your feeling and behaviour and in the reactions of the other people, and plan the next step
ask yourself: "What would I do if I weren't afraid?", then do that
| {
"pile_set_name": "StackExchange"
} |
Q:
PEM, DER, X509, ASN.1, Oh My. Where to start?
I'm trying to get an understanding of the world of cryptography as its practically used day to day. I'm finding it very hard to get a start footing, And I was wondering if anyone has some good resources that explain things assuming that I know nothing.
For example, I have (I believe, due to limited understanding) a file with X509 certificate and a "SignatureValue" attribute. I think these are encoded with SHA256. I would like to understand exactly what I'm looking at however, because I need to provide a "Timestamp Response File", which contains the DER representation of one Timestamp Authority Message.
Things I somewhat grasp so far:
SHA256 is a hashing algorithm. One way?
X509 is a document that defines how a certificate (whatever that is) should look
ASN.1 is a group of ways to transmit data between systems?
DER is a way of representing data in binary/octal bits.
I'd like a birds eye view of this ecosystem just so I have some concept of how this puzzle fits together, then I can delve better into the nitty gritty of How-Things-Work.
A:
Reading whole bunch of books will take a lot of time.
Imho, the faster way would be to browse Wikipedia and read what is:
hash algorithm (in short, it transform long text/data to fixed-size value, hash, which (almost) unique represents this long text. And, yes, it is one-way.
signature algorithm - calculates something from hash value, which is called 'signature'. The main idea is that correct signature can be calculated only when you have secret key. And, this signature can be verified with public key. Public key is shared amongst people so they can verify your signatures.
So, valid signature proves that text/data was not changed by somebody else.
certificate: this is block of data, which binds user's public key to information about this key: name of the owner, email, address, whatever else. Certificate usually signed by authority (root certificate) - so, if you trust to authority, you should believe that this certificate correctly represents person.
timestamp: this is signature, made by some authority people trust to, which binds time mark to signature, made over other document. So, this will prove that this signature (and, this document) was correct at that time. This is needed since sometimes certificates can become revoked or outdated, and without timestamp you will not know if this is correct signature since you will not know when it was created.
ASN.1 - Abstract Syntax Notation, it defines text rules which describe format of some data structures. It is used in most of cryptography standards.
DER encoding (Distinguished Encoding Rules): set of rules how to encode ASN.1 objects/records to binary data. There is also BER (Basic Encoding Rules), which does almost the same, BUT it allows different encoding for the same value (like BOOL can be encoded by any non-zero value), which can not be used in cryptography since the same message can be encoded in different ways, producing different hashes.
X.509 : standard about format (ASN.1) of public-key certificates.
Hope this helps a bit to understand what's going on :)
Actually, there is a number of cryptography libraries on market, which implement all those timestamping/x.509/signing/verification,etc.
| {
"pile_set_name": "StackExchange"
} |
Q:
Declare variable in two functions but only initialize one of them
Variable a is declared in two separate functions, but only initialized in one of them. The main function calls the function that declares and initializes a, then it calls the second function which redeclares that variable without initializing it. It prints 42, even though a is initialized in a different function scope whose data should have been destroyed after the function's completion. Why is this happening?
#include <stdio.h>
void foo() {
int a = 42;
}
void bar() {
int a;
printf("%d",a);
}
main() {
foo();
bar();
}
A:
Oooo, that's a good one. Officially it's undefined. But I bet a lot of them would print 42 because the a's likely will use the same memory address on the stack.
So that basics of how this works, is when a function is called the value of the PC (program counter) that the program should return to is pushed on the stack along with the parameters. In this case, both foo and bar have no parameters so just one pointer will be pushed onto the stack (so say a total of 4 bytes starting at relative address 0).
Then when a funciton starts, its variables are pushed onto the stack. In this case, both of them have in a which will be pushed, which is again 4 bytes for each (total of 8 bytes, starting at relative address 4).
This is a common way in C/C++ to grab data from other functions / programs that the function otherwise shouldn't be allowed to access.
| {
"pile_set_name": "StackExchange"
} |
Q:
What's McCree's DPS?
Let's say I want to take down a Reinhardt shield (big, no crit-spot) and I'm at a distance outside of his melee range. I expect that I won't take it down in one barrel/volley, so I need to factor in reload time for multiple volleys.
Is it better to hold left-click or right-click? Is it better to fire single shots or repeatedly Fan the Hammer?
Bonus points for factoring in situations such as Bastion's Sentry Configuration's weak point, armor, common distances (e.g., the chokepoints of each map), and Combat Roll (to reload).
A:
The answer is right there in the information you link.
Assuming you're not so far away that you're experiencing damage fall-off and assuming all shots hit (such as shooting at Reinhardt's shield), you're doing 140 DPS with his left click. Factor in reload time (1.5s), and it's 420 damage over 4.5 seconds, or 93.33 DPS (86.667 against an armored target).
If you Fan the Hammer (and all shots hit), you're doing 270 DPS. Factor in reload time (which is the same, but you have to wait .3s after the animation to reload) and you're doing 96.4 DPS (85.7 against an armored target).
So, it looks like Fan the Hammer is marginally better against in armored targets if you're guaranteed to hit with all 6 shots. Miss even one and you're less efficient than LMB. Against an armored target it is about equal. This only makes it useful against can't-miss targets like point-blank tanks (if they already have some damage and you're attempting to finish them in one burst) or Reinhardt's shield.
Once you start to factor in things like crits, if you've got good aim left-mouse button almost certainly becomes better because FTH can't crit. Moreso if you factor in a smaller target that's hard to hit every shot with. I mean, even when I stun a Tracer or Genji at point-blank range, Fan the Hammer seems to miss about half the shots. I'm usually better off 2-tapping them with LMB, one of which can often be a headshot.
Fan the Hammer is really only worth it if you think you can land all the shots and crits aren't a factor, or if you think you can drop the target in a single burst. In my experience it's rare you'll actually land all the shots short of pumping them into a big tank at point blank range, which is not McCree's ideal engagement range or just popping Reinhardt's shield because you have nothing better to do. In most cases, though, you're better off left-clicking. Plus, a bonus of left-clicking Reinhardt is you can aim for the head, and if his shield happens to come down while you're firing, you can land a crit, whereas your FTH shot will probably miss entirely.
| {
"pile_set_name": "StackExchange"
} |
Q:
Integer has incremental value in Excel... how?
So, I'm making a thing for my work whereby I need to work out a total value based on an unit value which increases after X-number of units. Basically;
0-49 is worth A
50-59 is worth B
60-69 is worth C etc etc.
I need to read the quantity from one cell and multiply by the increments to give a total value
For example, if "Quantity" cell = 65 units
I need to work out (49*A)+(10*B)+(6*C), etc.
It's been a while since I've used Excel and formulae, so I'm rusty and this and can't find anything online (mostly because I can't think of the right way to word what I mean).
Any suggestions?
A:
Make a table with the starting numbers, the span and the amount:
Then use this formula that refers to that table
=IFERROR(SUMPRODUCT($D$1:INDEX(D:D,MATCH(A1,C:C)-1),$E$1:INDEX(E:E,MATCH(A1,C:C)-1)),0)+(A1 - VLOOKUP(A1,C:C,1,TRUE)+1)*VLOOKUP(A1,C:E,3)
This method has the benefit that one can add to the search table and not change the formula. The formula is the same if there are 50 lines in the lookup table or 2.
| {
"pile_set_name": "StackExchange"
} |
Q:
Questions about cranks
How should we handle questions like this (Is the Universe real or complex?)?
The question seems very blatantly to be about the work of a crank. Here is an article on Estakhr's website where he claims a conspiracy by American scientists, here is an article where he tries to explain that his made up constant gives a unified force that explains everything physics wants to know, here is an abstract with horrible linguistic issues that tries to explain that the Higgs boson doesn't do exactly what it does do, and so on. While on it's surface the question itself has nothing at all to do with the work of this crank, the blocks of paragraphs that make up the majority of the body of the question are just giving explanations of Estakhr's ideas.
The same question was asked on Physics.Stackexchange and it was closed under their "We deal with mainstream physics here. Questions about the general correctness of unpublished personal theories are off topic, although specific questions evaluating new theories in the context of established science are usually allowed," criterion. I understand the appeal to mainstream physics being something important for the functionality of that site, but of course I can see a lot of reasons why it wouldn't be that great of a/easily decidable criterion for ours. It creates an insular community, it alienates people who aren't familiar with the subject matter intimately, and it is probably not as well of a defined category in philosophy in the first place (Penrose's Gödelian arguments are rejected by the mainstream but Penrose is obviously part of the mainstream himself).
Still, I feel like it is very blatant that this question is not a genuine question in the sense that it was only asked so that the user could promote Estakhr's work (there are a lot of similar questions on Quora). In my mind, this question should absolutely be closed. It is not asked in good faith, it is about the work of a crank, and it serves only to spread those ideas. But, again, I see the issues of trying to impose some sort of 'mainstream' criterion for questions. How should this be handled? Should we adopt a similar close criterion? In this specific case, would it be better to edit out all of the mention of the crank's work that tries to motivate the question and just leave the question itself? I feel like that is a fairer compromise, since of course I cannot be 100% sure that the person asking the question is asking in bad faith, but I think that it's clearly a reasonable assumption.
A:
It is not asked in good faith
Stop. Assuming bad faith is a very bad idea (Even if you turn out to be correct!). There is nothing in that question that eliminates the possibility that the OP stumbled upon the crank's work and simply thinks that this is the best thing since sliced bread. I can write a long essay here on why this is a bad idea, but I don't need to, as other people have already done this.
That said, more important here is the fact that you want to edit/delete a question based on some property of the person who made the question. This isn't a good idea for many reasons (there is probably some discussion about this on meta), one being that we simply want good questions and answers. So if you feel that the 'introduction' to this 'complex universe' theory is inappropriate, but the question (in itself, ignoring who asked it) is appropriate, then you could decide to either summarize the 'introduction' or simply remove it.
While I do understand your worry that this user might contribute nothing or may even engage in harmful behavior, please give the user a chance and simply flag for moderation if you see misconduct.
That's enough for this specific question. Now, for your more general proposal, which I think can be summarized as follows:
Should we take action to prevent this site from being used to promote cranky topics?
I think that we shouldn't, unless this site gets flooded by such questions. A custom close reason is only made if it has to be used quite often. Unless you can show that there are many such questions (or have been), I think the usual quality control tools (editing, voting and normal close reasons) would be sufficient.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I store an image in sqlite?
I want to store an image in a database , but I don't know how , I have tried this but it shows me errors of type , could someone help me to deal with this , I ve create an image with blob type in database here s my code :
var bytes;
var encoded1;
Future pickImage() async {
tempStore = await ImagePicker.pickImage(source: ImageSource.gallery);
bytes = await tempStore.readAsBytes();
encoded1 = base64.decode(bytes);
print(tempStore);
//var tempStore = await ImagePicker.pickImage(source: ImageSource.camera);
setState(() {
pickedImage = tempStore;
isImageLoaded = true;
});
}
and this is where I'm trying to insert the image in a database
final dao = Provider.of<ClientDao>(context);
final client = Client(
typeClientid: idTypeClient,
nom: prenomController.text,
prenom: nameController.text,
ddn: ddnController.text,
ville: adresseController.text,
ncd: numeroController.text,
imageDevant: encoded1,
);
dao.insertClient(client);
A:
You need to encode your bytes before store not decode (base64.encode)
| {
"pile_set_name": "StackExchange"
} |
Q:
Why isn't zxing playing nicely with ant/java8 and the pom.xml?
I changed a pom.xml entry to zxing to 3.3.0
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>zxing-parent</artifactId>
<version>3.3.0</version>
<type>pom</type>
</dependency>
and now I'm getting this:
[artifact:dependencies] Unable to resolve artifact: Unable to get dependency information: Unable to read the metadata file for artifact 'com.github.jai-imageio:jai-imageio-core:jar': Invalid JDK version in profile 'java8-and-higher': Unbounded range: [1.8, for project com.github.jai-imageio:jai-imageio-core
[artifact:dependencies] com.github.jai-imageio:jai-imageio-core:jar:1.3.1
From what I can find this indicates that something is wrong with the pom file for zxing related to the required versions of java (which I'm using java 8)?
The code compiles fine using Maven and Eclipse, but this error occurs when attempting to run a separate ant process.
<artifact:dependencies filesetId="dependency.fileset">
<artifact:pom file="${basedir}/pom.xml"/>
</artifact:dependencies>
The ant task works just fine if I use zxing 2.2 in the pom but then of course my code does not.
Is this a bug in zwing 3.3.0 or am I missing something?
A:
The cause of the problem is the pom of jai-imageio:jai-imageio-core:jar:1.3.1.
Maven has a problem with the following lines
<profile>
<id>java8-and-higher</id>
<activation>
<jdk>[1.8,</jdk>
</activation>
...
For a ugly fix you can open the pom in your local repository and change the activation value to
<profile>
<id>java8-and-higher</id>
<activation>
<jdk>[1.8,)</jdk>
</activation>
...
Another option would be change your maven version. Some versions don't have problems interpreting the false syntax. This should be also the answer why you have experienced different results of building with eclipse and ant.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.