text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
using erase with remove_if
This thing drive me crazy, I couldn't understand it :
// v contains : 101, 1, 2, 3, 4 , 5
v.erase(remove_if(v.begin(), v.end(), bind2nd(less<int>(), 3)), v.end());
// v contains now : 101, 3, 4, 5
Why there is v.end() as a second argument in erase ?? I read that remove_if returns an iterator to the element that follows the last element not removed, what does it mean....
v.erase(v.begin(), v.end()) should erase all the vector elements, but how in the example above it does not erase 3, 4 and 5 ? how this thing works ? I didn't find something edifiying about it in the internet.
A:
remove doesn't actually remove any elements in the vector but it moves them to the end of the vector. It then returns an iterator to the new last element which is the first "removed" element. You then erase from that iterator to the end of the vector to actually get rid of the elements in the vector.
| {
"pile_set_name": "StackExchange"
} |
Q:
Which trees drop apples?
Whenever I start a new survival world in minecraft, I always try to find a tree. But other than wood, I need food, and I know that not all trees drop apples. Which trees do drop apples?
A:
Apples are most commonly dropped by Oak Trees. (Why do oak trees drop apples? Because it's Minecraft.) They're also dropped by Dark Oak Trees, but as these only grow in the Roofed Forest biome, you're far more likely to find regular oaks first.
Apples aren't a very good food source though: they're unreliable, and even a lot of them don't keep you fed for long. Easier and more filling than apples is to simply perpetrate some violence on chickens, pigs, sheep, cows, or rabbits and eat the meat raw or cooked in a furnace. In the first day of Minecraft, meat is the simplest, most abundant, and most filling food source.
For vegetarian playthroughs of Minecraft, the easiest early food is bread made from planted wheat: obtain seeds by breaking tall grass, use a hoe to till dirt into farmland beside water, and plant the seeds. (See the farming tutorial for more.) You'll have to survive several hungry days before your wheat is ready to harvest though.
If you're lucky enough to start near a village, the best early vegetarian food source is harvesting and replanting the villagers' fields for your own benefit.
| {
"pile_set_name": "StackExchange"
} |
Q:
Search input in top-bar foundation cut off
I have a similar issue to someone there: Input with Postfix Button in Top-Bar using Zurb Foundation who was offered an alternative more than an answer. (The second answer on the page is what is described in foundation docs there http://foundation.zurb.com/docs/components/top-bar.html, I've tried and it isn't working either, see the second input in my header).
The issue can be seen here: http://odesktestanswers2013.com/Metareviewer/index.php
Basically, the submit input won't float next to its text input.
Can anybody recommend a fix or help me figure out what's wrong ?
A:
Managed to make it work after a while by floating everything to the left and adding some !important to the inputs.
What I found in foundation docs wasn't helpful but anyways their "has-form" class is useless, this did the trick:
.left .search .button { float:left; width:50px; margin-left:5px;}
.search input {width:200px;float:left;top:5px;}
.search form {float:left !important; width:450px !important;}
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there something like "has_one :through (from Rails)" in Yii Framework?
I had the following tables:
manufacturers
* id
* name
* description
types
* id
* name
* description
* manufacturer_id
cars
* id
* title
* description
* type_id
Now my problem is, I want to list the cars with types and manufacurers, e.g:
* Some Car, Fiat Punto
* Another Car, Ferrari F1
...
In rails i can set the manufacturer relation with sth. like this:
class Car < ActiveRecord::Base
belongs_to :type
has_one :manufacturer, :through => :type
end
Is this also possible in Yii?
A:
As of Yii 1.1.7 (I believe), 'through' support exists in relational active record now.
http://www.yiiframework.com/doc/guide/1.1/en/database.arr#relational-query-with-through
| {
"pile_set_name": "StackExchange"
} |
Q:
Which tags are required in the manifest for registration free COM?
TL;DR Do all registry entries produced by regsvr32 need to be present in a SxS reg-free-COM manifest and vice versa?
I'm trying to get registration free COM going for a third party component.
Reading up on the subject, I find that there are several elements mentioned, that can be put into a manifest:
From the docs, we can add the following tags to a manifest to describe a COM component:
assemblyIdentity - which really just describes the "abstract assembly" as far as I can tell
comClass - describes the COM class (IID Interface). It would appear, this is always needed.
typelib - when?
comInterfaceExternalProxyStub - when?
comInterfaceProxyStub - when?
From the other docs for HKEY_LOCAL_MACHINE\SOFTWARE\Classes we can observe that there are a few categories for the COM registry entries:
HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID\{CLSID} I assume roughly corresponds to comClass
HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Interface\{IID} would correspond to either comInterface[External]ProxyStub, but I have seriously no clue when to use which (or both)
Which regsitry entry corresponds with the typelib manifest entry ??
Using regsvr42 to extract the stuff the dll I'm trying to regfree yields a manifest that only contains comClass entries, no typelib or ProxyStub entries. (And I cross checked the keys written, the DLL in question, pdm.dll, MS's Process Debug Manager only writes those keys, that is, there is no type library or proxy stub info apparent in the registry.)
If the registry only contains the info that pertains to comClass does this then mean that this info will be sufficient in the SxS manifest, or may additional info be needed in the manifest?
As an aside I noticed that the registry contains a VersionIndependentProgId and a ProgId that has a version number appended at the end. The manifest only has a ProgId entry, and the docs state:
progid : Version-dependent programmatic identifier associated with the
COM component. The format of a ProgID is
<vendor>.<component>.<version>.
But the docs also state
The comClass element can have <progid>...</progid> elements as
children, which list the version dependent progids.
and they say that the progid attribute should be the version independent one.
So, what to put here? And does it even matter when the client doesn't request a specific version?
A:
The assemblyIdentity element is always required, part of the manifest plumbing. You must always provide the comClass element, it substitutes the HKLM\Software\Classes\CLSID registry key and is used to make the client's CoCreateInstance() call work. The file element names the COM server executable file.
The rest of the keys are optional, they are needed to make marshaling work. Marshaling occurs when the client call needs to be made on a different thread. That will always happen when the server and the client are in different processes, the case for an out-of-process server or when the server runs on another machine. And it can happen when the ThreadingModel specified in the comClass element demands it. In other words, when the COM object was created on one thread but is called on another and the server is not thread-safe.
RPC implements the marshaling but it has one job to do that it needs help with. It needs to know what the arguments for the function are, as well as the return type. So that it can properly serialize their values into a data packet that can be transmitted across a network or passed to the code in another thread that makes the call. This is the job of the proxy. The stub runs at the receiving end and deserializes the arguments to build the stack frame and makes the call. The function return value as well as any argument values passed by reference then travel back to the caller. The code that makes the call otherwise has no awareness at all that it didn't call the function directly.
There are four basic cases:
The COM server doesn't support being called that way at all and must always be used from the same thread it was created on. Stop there, no need to add anything to the manifest.
The COM server implements the IMarshal interface. Automatically queried by COM when it cannot find another way to marshal the call. This is quite rare, except for a case where the COM server aggregates the free-threaded marshaller. In other words, is completely thread-safe by itself without needing any help and always runs in-process. PDM is likely to work that way. Stop there, no need to add anything to the manifest.
The COM server author started his project by writing the interface description of the server in the IDL language. Which was then compiled by MIDL. One option it has available is to auto-generate code from the IDL declarations, code that can be used to build a separate DLL that implements the proxy and the stub. IDL is sufficiently rich to describe details of the function argument types and usage to allow the marshaling to be done by this auto-generated code. Sometimes IDL attributes are not sufficient, the COM author then writes a custom marshaller. COM loads that DLL at runtime to create the proxy and stub objects automatically.
Specific to the COM Automation subset (IDispatch interface), Windows has a built-in marshaller that knows how to marshal calls that meet the subset requirements. Very common. It uses the type library to discover the function declaration.
The latter two bullets require using HKLM\Software\Classes\Interface, it has entries for the IID for every interface. That's how COM finds out how to create the proxy and the stub for the interface. If it cannot find the key then it falls back to IMarshal. You must use the comInterfaceExternalProxyStub element to substitute the registry key. Using comInterfaceProxyStub is a special case, that's when the proxy and stub code is included with the COM server executable instead of being a separate file. An option in ATL projects for example, turned on with the "Allow merging of proxy/stub" wizard selection.
The last bullet also requires using the typelib element, required so the built-in marshaller can find the type library it needs.
The progId is required when the COM client uses late binding through IDispatch, the CreateObject() helper function in the client's runtime support library is boilerplate. Used in any scripting host for example.
Having some insider knowledge of how the COM server was created certainly helps, always contact the vendor or author for advice. It can be reverse-engineered however by observing what registry keys are written when the server is registered, SysInternals' ProcMon tool is the best way to see that. Basic things to look for:
If you see it write the HKLM\Software\Classes\Interface key then you can assume that you must provide the comInterface|External|ProxyStub element
If you see it write {00020420-0000-0000-C000-000000000046} for the ProxyStubClsid32 key then you can assume it is using the standard marshaller and you must use comInterfaceExternalProxyStub element as well as the typelib element. You should then also see it write the IID's TypeLib registry key as well as the entry in the HKLM\Software\Classes\Typelib registry key. The latter gives the path of the type library. Almost always the same as the COM server, embedding the type library as a resource is very common. If it is separate (a .tlb file) then you must deploy it.
If the ProxyStubClsid32 key value is another guid then you can assume it is uses its own proxy/stub DLL. You should then also see it write the CLSID key for the proxy, its InProcServer32 key gives you the path to the DLL. If that file name matches the server's file name then you can assume that the proxy/stub code was merged and you must use the comInterfaceProxyStub element instead. If not then comInterfaceExternalProxyStub is required and you must deploy the DLL
If you see it write the ProgID in HKLM\Software\Classes then use the progid element, exactly as shown in the trace.
| {
"pile_set_name": "StackExchange"
} |
Q:
Extjs 6: How to forcefully show a tooltip on an element on a button click?
I have a scenario i.e.combobox and a button. I want to show a tooltip on combox when I click on a button and hide it when i click again. How do I do that without using ids on tooltip instance? Also can I specify the position of tooltip i.e x and y relative to combobox and style tooltip a little bit?
Thanks a lot
A:
When you click on button create new tooltip instance as below:
Ext.create('Ext.tip.ToolTip', {
html:<tip contents>,
id:<some id>
});
And showBy() this instance for that combo like tip.showBy(<combo instance>).
Now again you click on button you check if tip instance is present, if yes then hide it else show it again. But you will need some id for tooltip.
| {
"pile_set_name": "StackExchange"
} |
Q:
Winpcap - pcap_next_ex vs pcap_loop
I have a question, Imagine I have a thread which captures packets and process them itself.
With pcap_next_ex: I would use a loop and I would process the packets in each interaction, suppose I call Sleep(200) to simulate the stuff. With pcap_next_ex I would arrive a moment when I would lose packets.
With pcap_loop: I would use a callback to a packet handler for each packet incoming it would work like an event. In the packet handler I would treat the packets and suppose I call Sleep(200) to simulate the stuff. Would I lose packets?.
A:
Yes.
pcap_next_ex and pcap_loop call the same internal function that reads a packet from the ring buffer. The difference is only that the former return the packet but the latter calls a callback with the packet.
pcap_loop calls the callback in the same thread as one called the pcap_loop, and waits for the callback to complete its task before reading the next packet.
So, if the callback takes a long time, the pcap_loop cannot read packets enough frequently, which results in more possibility to lose packets.
| {
"pile_set_name": "StackExchange"
} |
Q:
Mobile taxi service - Ordering transportation through a mobile device (Uber) - Patent Application - PRIOR ART REQUEST
AN OVERBROAD PATENT ON arranging transport amongst parties through use of mobile devices - This application from Uber seeks to patent the idea of...Enabling customers to order drivers from a mobile phone and tracking the location of the driver as it arrives! 10 minutes of your time can help narrow US patent applications before they become patents. Follow @askpatents on twitter to help.
QUESTION - Have you seen anything that was published before 12/4/2009 that discusses:
Mobile phone-based taxi services
If so, please submit evidence of prior art as an answer to this question. We welcome multiple answers from the same individual.
EXTRA CREDIT - Location of driver is displayed on a map on user's phone, user and driver can communicate with one another prior to pickup, and/or user is able to provide feedback on driver's service after the ride.
TITLE: Arranging transportation among parties at different locations using a mobile phone
Summary: [Translated from Legalese into English] User at one location requests driver. From a pool of candidate drivers, the user chooses a driver to pick him up. The user's location is communicated to the driver, the driver's location is communicated to the user as the vehicle progresses.
Publication Number: US20110313804 A1
Application Number: US 12/961,493
Assignee: Uber
Prior Art Date: Seeking prior Art predating 12/4/2009
Link to Google Prior Art Search - "Find Prior Art"
Claim 1 requires each and every step below:
A computer implemented method for arranging transport amongst parties located at different locations, the method being implemented by one or more processors of a server and comprising:
Receiving, at the server from a customer device at a first geographic location a request for transport, the request including information about the first geographic location;
In response to receiving the request, from a pool of candidate respondents, selecting, by the server and for a customer operating the customer device, a driver at a second geographic location based, at least in part, on location information of the candidate driver;
Communicating, by the server, an invitation to a corresponding device of the driver, the invitation enabling the driver to accept the invitation to provide transport for the customer and including (i) the first geographic location, and (ii) identification information of the customer;
Communicating, from the server to the customer device, a status of fulfilling the request for the customer, including communicating one or more notifications that informs the customer that the server is selecting the driver; and
Once the dirver has accepted the invitation, communicating, from the server to the customer device, a location of the driver as the driver progresses to or arrives at the first geographic location.
In English this means:
A method for arranging transport amongst parties located at different locations, comprising:
Receiving, a request for transport, the request including information about the first geographic location;
Selecting a driver at a second geographic location from a pool of candidate driveres based, at least in part, on the location of the driver
Inviting the driver to provide transport for the customer
Informing the customer that the server is selecting the driver; and
Communicating the location of the driver as the driver progresses to or arrives at the first geographic location.
Good prior art would be evidence of a system that did each and every one of these steps prior to 12/4/2009
You're probably aware of ten pieces of art that meet this criteria already... separately, the applicant is claiming Displaying driver location on a map, feedback system for user to rate driver (and vice-versa) after trip
"User-interfaces as transportation is requested and provided" from the Applicant
Uber does not deserve this overly broad set of claims! As just one example:
US 6,356,838 System and method for determining an efficient transportation route
"The driver then proceeds to the pickup point. As the driver continues on her way, she may update the passenger 170 of any changes to the arrival time estimate including, for example, the fact that she has arrived at the pickup point. " from US6356838
Can you help find more Prior Art?
What is good prior art? Please see our FAQ.
Want to help? Please vote or comment on submissions below. We welcome you to post your own request for prior art on other questionable US Patent Applications.
A:
The patent description sounds almost exactly like an iPhone app called Taxi Magic, released 2008 time:
http://techcrunch.com/2008/12/16/taxi-magic-hail-a-cab-from-your-iphone-at-the-push-of-a-button/
| {
"pile_set_name": "StackExchange"
} |
Q:
Python - Sort 4 lists according to the sorting of the first list
I have 4 lists and want to sort the first list from smallest to largest and then apply the same changes to the second, third and fourth list.
For example:
nodeA = ['1', '4', '3', '5' , '2']
nodeB = ['0', '5', '0', '6', '3']
identity = ['R', 'G', 'C', 'L', 'L']
value = ['100', '125', '300', '400', '275']
Would go to:
nodeA = ['1', '2', '3', '4' , '5']
nodeB = ['0', '3', '0', '5', '6']
identity = ['R', 'L', 'C', 'G', 'L']
value = ['100', '275', '300', '125', '400']
(I think I did that right)
Im not sure how to do this, any help is greatly appreciated!!
A:
You could create a version of argsort() for Python lists:
def argsort(seq):
ix = list(range(len(seq)))
ix.sort(key=seq.__getitem__)
return ix
which you can use to reorder all lists:
nodeA = ['1', '4', '3', '5' , '2']
nodeB = ['0', '5', '0', '6', '3']
identity = ['R', 'G', 'C', 'L', 'L']
value = ['100', '125', '300', '400', '275']
ix = argsort(nodeA)
nodeA = [nodeA[i] for i in ix]
nodeB = [nodeB[i] for i in ix]
identity = [identity[i] for i in ix]
value = [value[i] for i in ix]
print(nodeA)
# ['1', '2', '3', '4', '5']
print(nodeB)
# ['0', '3', '0', '5', '6']
print(identity)
# ['R', 'L', 'C', 'G', 'L']
print(value)
# ['100', '275', '300', '125', '400']
| {
"pile_set_name": "StackExchange"
} |
Q:
Show only one record, if value same in another column SQL
I have a table with 5 columns like this:
| ID | NAME | PO_NUMBER | DATE | STATS |
| 1 | Jhon | 160101-001 | 2016-01-01 | 7 |
| 2 | Jhon | 160101-002 | 2016-01-01 | 7 |
| 3 | Jhon | 160102-001 | 2016-01-02 | 7 |
| 4 | Jane | 160101-001 | 2016-01-01 | 7 |
| 5 | Jane | 160102-001 | 2016-01-02 | 7 |
| 6 | Jane | 160102-002 | 2016-01-02 | 7 |
| 7 | Jane | 160102-003 | 2016-01-02 | 7 |
I need to display all values, but stats fields without duplicate according from date field.
Like this
| ID | NAME | PO_NUMBER | DATE | STATS |
| 1 | Jhon | 160101-001 | 2016-01-01 | 7 |
| 2 | Jhon | 160101-002 | 2016-01-01 | null |
| 3 | Jhon | 160102-001 | 2016-01-02 | 7 |
| 4 | Jane | 160101-001 | 2016-01-01 | 7 |
| 5 | Jane | 160102-001 | 2016-01-02 | 7 |
| 6 | Jane | 160102-002 | 2016-01-02 | null |
| 7 | Jane | 160102-003 | 2016-01-02 | null |
I've had trouble getting the hoped. Thanks
A:
From your sample data, it appears you only want to show the stats for po_number ending with 001. If so, this should be the easiest approach:
select id, name, po_number, date,
case when right(po_number, 3) = '001' then stats else null end as stats
from yourtable
If instead you want to order by the po_number, then here's one option using row_number:
select id, name, po_number, date,
case when rn = 1 then stats else null end as stats
from (
select *, row_number() over (partition by name, date order by po_number) as rn
from yourtable
) t
SQL Fiddle Demo
| {
"pile_set_name": "StackExchange"
} |
Q:
How to modiffy output by adding name1.name 2.... in all output of python
to write a code that take input such as
123,143,531,431
and gives output
{"number1":"123","number2":"143","number3":"531","number4":"431"}
any language among java and python can help
for python i tried
data = "123,143,531,431"
x = data.split(", ")
print(x)
and help for java would do too or javascript
A:
IIUC, You can use dict comprehension to create the dictionary in your desired format, to learn more about dict comprehensions in python refer this. Here, we also used the enumerate function, to learn more about this function refer this.
Use:
x = {f"number{i}": v for i, v in enumerate(data.split(","), 1)}
print(x)
This prints:
{'number1': '123', 'number2': '143', 'number3': '531', 'number4': '431'}
Update (To get double quotes instead of single):
import json
print(json.dumps(x))
This prints:
{"number1": "123", "number2": "143", "number3": "531", "number4": "431"}
| {
"pile_set_name": "StackExchange"
} |
Q:
In Perl, how to match two consecutive Carriage Returns?
Hi StackOverflow buddies,
I'm on Windows platform; I have a data file but something wrong happened and (I don't know why) all combinations of "Carriage Return + New Line" became "Carriage Return + Carriage Return + New Line", (190128 edit:) for example:
When viewing the file as plain text, it is:
When viewing the same file in hex mode, it is:
Out of practical purposes I need to remove the extra "0D" in double "0D"s like ".... 30 30 0D 0D 0A 30 30 ....", and change it to ".... 30 30 0D 0A 30 30 ....".
190129 edit: Besides, to ensure that my problem can be reproduced, I uploaded my data file to GitHub at URL (should download & unzip it before using; in a binary \ hex editor you can 0D 0D 0A in the first line): https://github.com/katyusza/hello_world/blob/master/ram_init.zip
I used the following Perl script to remove the extra Carriage Return, but to my astonishment my regex just do NOT work!! My entire code is (190129 edit: past entire Perl script here):
use warnings ;
use strict ;
use File::Basename ;
#-----------------------------------------------------------
# command line handling, file open \ create
#-----------------------------------------------------------
# Capture input input filename from command line:
my $input_fn = $ARGV[0] or
die "Should provide input file name at command line!\n";
# Parse input file name, and generate output file name:
my ($iname, $ipath, $isuffix) = fileparse($input_fn, qr/\.[^.]*/);
my $output_fn = $iname."_pruneNonPrintable".$isuffix;
# Open input file:
open (my $FIN, "<", $input_fn) or die "Open file error $!\n";
# Create output file:
open (my $FO, ">", $output_fn) or die "Create file error $!\n";
#-----------------------------------------------------------
# Read input file, search & replace, write to output
#-----------------------------------------------------------
# Read all lines in one go:
$/ = undef;
# Read entire file into variable:
my $prune_txt = <$FIN> ;
# Do match & replace:
$prune_txt =~ s/\x0D\x0D/\x0D/g; # do NOT work.
# $prune_txt =~ s/\x0d\x0d/\x30/g; # do NOT work.
# $prune_txt =~ s/\x30\x0d/\x0d/g; # can work.
# $prune_txt =~ s/\x0d\x0d\x0a/\x0d\x0a/gs; # do NOT work.
# Print end time of processing:
print $FO $prune_txt ;
# Close files:
close($FIN) ;
close($FO) ;
I did everything I could to match two consecutive Carriage Returns, but failed. Can anyone please point out my mistake, or tell me the right way to go? Thanks in advance!
A:
On Windows, file handles have a :crlf layer given to them by default.
This layer converts CR LF to LF on read.
This layer converts LF to CR LF on write.
Solution 1: Compensate for the :crlf layer.
You'd use this solution if you want to end up with system-appropriate line endings.
# ... read ... # CR CR LF ⇒ CR LF
s/\r+\n/\n/g; # CR LF ⇒ LF
# ... write ... # LF ⇒ CR LF
Solution 2: Remove the :crlf layer.
You'd use this solution if you want to end up with CR LF unconditionally.
Use <:raw and >:raw instead of < and > as the mode.
# ... read ... # CR CR LF ⇒ CR CR LF
s/\r*\n/\r\n/g; # CR CR LF ⇒ CR LF
# ... write ... # CR LF ⇒ CR LF
| {
"pile_set_name": "StackExchange"
} |
Q:
What time and where on earth is the latest solar noon?
For context: I am visiting Portugal from Australia and after observing that people tend to start their days later, I realised that solar noon also seems to occur at a later time - about 1.20pm at the moment. I don't recall solar noon every occurring at such a late time in Australia. When and where is the latest solar noon on earth?
A:
That should be in western China, since all of China uses Beijing's time zone.
Reference: https://en.wikipedia.org/wiki/Time_in_China
--- Edit below ---
In response to the comment by @adrianmcmenamin: I'll leave this as guesswork since I simply don't know the peculiarities of every timezone there is. Here's a back-of-the-envelope calculation for local noon in western China.
The Sun covers 15 degrees in a period of 1 hour. All of China is on Beijing time (UTC + 8 hours). With the above, it's centred on $15 \cdot 8 = 120^{\circ}$ east. As a consistency check, Beijing is at $116^{\circ}$ east. The westernmost part of China is at about $73^\circ$ east (See here). Local noon there is delayed by $(120^\circ - 73^\circ)/(15^\circ/h) \simeq 3h$.
So, local noon is a little later than 3pm. This is discounting daylight savings time, which is not currently observed in China.
A:
I believe that honor may belong to Adak, Alaska where solar noon does not occur during DST until 2:52 PM, or 1:52 Standard Time. All of Alaska is on Juneau time. You can check it here.Edit:There are maps here that show the offset between local and solar time. It's pretty informative. There may be other areas besides western China where solar noon is very late (maybe I'll modify a spreadsheet and see if I can some up with something).
| {
"pile_set_name": "StackExchange"
} |
Q:
What did Monica do to violate the CoC?
According to SO, they
removed a moderator for repeatedly violating our existing Code of Conduct and being unwilling to accept our CM’s repeated requests to change that behavior.
As Monica says,
Representatives of the company including executives, a director, and the Community Management team have failed to respond to my repeated requests to be shown these alleged violations and warning...
So, what did Monica actually do?
Previous content so comments make sense:
What did Monica say, according to SO?
What did Monica actually say that violated the existing Code of Conduct (pending Monica's acceptance, of course)? We've heard a lot about how she did, but not what she did.
A:
She didn’t do anything to violate the CoC.
Given leaked transcripts some have seen and been unable to identify CoC violations, and many mods here from the TL also not being able to identify any clear violations, and no one being able to come up with anything that was not either customary in the TL or "pre-thoughtcrime" concerns of "maybe she won't follow the future CoC", the clear reason the “CoC violation” has not been shared is that there was not one. The claim that there was a violation is simply cover for getting rid of a voice bold enough to disagree with an SE employee’s plans.
And of course when threatened with legal action they released a statement saying "whoops, it was a mistake." (A mistake they took unilateral and extreme action on, refused feedback, and refused to undo went unsaid.)
In the end the only CoC that applies to this situation is the whim of people like Sara and David. They see no need to justify their removal of a voice they found annoying with anyone here; their contempt for meta, mods, CMs, and the larger community has been made amply clear through many communications and actions over these months in late 2019 and early 2020.
If anyone saw Monica clearly violate the CoC, feel free to say so; you don’t have to share the secret TL details. But no one has, so the obvious answer is that it did not happen.
I don't know why it's not obvious to people in the world that when people make claims that lack specific details, proof, witnesses, or substantiation of any sort that it's just a garden variety lie, but for some reason people have trouble getting their heads around that. But given not a shred of evidence from any of these sources, it's clear that the claims that Monica violated the CoC is simply a convenient ginned up statement designed to provide a veneer of legitimacy to an otherwise arbitrary and dictatorial move, to fragment opposition and ablate the effects of their actions somewhat in the community. Because of course you can't prove a negative, so the deck is already stacked against a claim of innocence (except for those of us that live in places that believe in "innocent until proven guilty").
| {
"pile_set_name": "StackExchange"
} |
Q:
What happens when reattching under 30 minutes?
Why should you only reattach after at least 30 minutes? What happens when you don't wait 30 minutes and what's the danger of it?
A:
When your transaction is younger than 30 minutes, there is a significant chance that other transactions will use it as a tip for their transaction (and therefore confirm it). So, first, if you reattach early, you are wasting your PoW resources.
To make matters worse, when you reattach really early (maybe even multiple times), there are two transactions on the tangle (perhaps even different ones of them arrive first on different nodes) that cannot both be confirmed, but some nodes might not know that already. So it can happen that some transactions choose to verify your original transaction, and some choose to verify the reattachment. At some point, the network (or the coordinator) will decide which of your transactions will get confirmed, and every transaction who tried to confirm the other one is essentially lost (will never confirm and need reattachment). Therefore, by reattaching too early, you will inevitably create "time-bombs" in the tangle which will force others to reattach more often, too.
To be fair, the tangle is able to handle some kind of "misuse" (be it deliberate or not), but if all users started to reattach their transactions immediately, it would surely be noticable.
So, be a nice neighbor and just don't do it :-)
| {
"pile_set_name": "StackExchange"
} |
Q:
Right way to use && and || in javascript
I've made a little web-application. And want to make when I push 'enter' there must be check if there is empty or space value. In this case I have 'alert'.
So I used event listener. But it works incorrect. Alert appears when I push not only 'enter'. Need your help!
const convert = document.getElementById('convert');
currentValue.addEventListener('keypress', function(event) {
if (event.which === 13 && currentValue.value === '' ||
currentValue.value === ' ') {
alert('value is empty');
} else {
convertTemperature();
}
}, false);
<div id="application">
<input id="currentValue" type="number">
<select id="select">
<option value="celsius">Celsius</option>
<option value="fahrenheit">Fahrenheit</option>
<option value="kelvin">Kelvin</option>
</select>
</br>
<button id="convert">Convert</button>
</br>
<input id="value1" type="text">
</br>
<input id="value2" type="text">
</div>
A:
&& has higher priory than || so you have to add () for || condition as following (currentValue.value === '' || currentValue.value === ' ')
const convert = document.getElementById('convert');
currentValue.addEventListener('keypress', function(event) {
if (event.which === 13 )
if(currentValue.value === '' || currentValue.value === ' ') {
alert('value is empty');
} else {
convertTemperature();
}
}, false);
| {
"pile_set_name": "StackExchange"
} |
Q:
Does Minecraft have an API?
I'm now sure if this is the correct place for this question (or something like StackOverflow) but I'll ask it here first in any case. Does Minecraft have an API for obtaining information about it's craftable items?
A:
No, there is no API that exposes in-game recipes to an external program. It would be feasible to write a mod that created such an interface, though I don't believe any such mod exists yet. That would require users to install a mod in order to use the external tool though, which would make such a tool useless to the majority of players with a "vanilla" (unmodded) version of Minecraft.
| {
"pile_set_name": "StackExchange"
} |
Q:
Laravel with JWT Auth: Get error message with status code
I try to implement JWT Auth in my Laravel + Vue SPA.
In my Controller I check the credentials like
try {
if (!$token = JWTAuth::attempt($credentials)) {
return response()->json(
[
'error' => 'Invalid Credentials',
], 401
);
}
} catch (JWTException $e) {
return response()->json(
[
'error' => 'Could not create token!',
]
);
}
return response()->json(
[
'token' => $token,
]
);
My API call look like this:
axios.post('/api/user/signin', payload)
.then((res) => {
console.log(res)
})
.catch((err) => {
console.log(err)
})
If I pass valid credentials with the payload I get the token in the then block and can log this in the console.
If I pass invalid credentials I get an error in the console:
Error: Request failed with status code 401
at createError (app.js:10562)
at settle (app.js:21378)
at XMLHttpRequest.handleLoad (app.js:10401)
How I can get the error "Invalid Credentials"? If I remove the status code from the response or set it to 200 I get the error "Invalid Credentials".
A:
You can use response key of error. To get the response.
axios.post('/api/user/signin', payload)
.then((res) => {
console.log(res)
})
.catch((err) => {
console.log(err.response)
})
Check Here : https://github.com/mzabriskie/axios/blob/master/UPGRADE_GUIDE.md#012x---0130
| {
"pile_set_name": "StackExchange"
} |
Q:
Trying to show all contacts related to salesforce account
I'm using the databasedotcom gem to sync my app with salesforce, it pulls a list of all accounts perfectly, but I need to have a primary contact for each account, I currently have this:
<p>
<b>License Contact:</b>
<%= Account.contact(@customer.Id).Name %>
</p>
<p>
<b>Email:</b>
<%= Account.contact(@customer.Id).Email %>
</p>
<p>
<b>Phone:</b>
<%= Account.contact(@customer.Id).Phone %>
</p>
and @customer is defined in my controller as @customer = Account.find(params[:id])
A:
Had a look at this link : http://www.salesforce.com/us/developer/docs/apexcode/Content/langCon_apex_SOQL_variables.htm
Which shows a few parameters and how to call them, I updated my code to this:
@contact = Contact.find_by_AccountID(params[:id])
Then called it in my view: <%= @contact.Name %> etc.
| {
"pile_set_name": "StackExchange"
} |
Q:
Expanding ad.fly links?
I was using this site via a PHP request from my own script to decode more than one ad.fly link at a time:
http://www.kassio.altervista.org/deadfly.php
But its been updated and won't handle direct PHP requests anymore. There seem to be a lot of sites out there that can decode ad.fly links. Does anyone know what the method is to do this. I'd quite like to include it in my own script rather than rely on a 3rd party to expand/decode the link?
TIA
A:
The URL is likely a key in their database. Without their tools you cannot do it yourself.
This: http://pastebin.com/zFB6iUcq leads me to believe they have some API that you can access.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the error in DELETE query when using joins
Code is running fine when commenting DELETE statement and trying with SELECT statement.
Please help
DELETE FROM
--select * from
Site as s
join
(select SiteID,Code, Name, Dense_rank() over (partition by Code order by SiteID ) as Rank from Site
) as t
on s.SiteID = t.SiteID
WHERE t.Rank != 1
Getting following error message
Msg 156, Level 15, State 1, Line 5
Incorrect syntax near the keyword 'as'.
Msg 156, Level 15, State 1, Line 8
Incorrect syntax near the keyword 'as'.
A:
You can't alias a delete table, but delete can refer to an alias. Instead of this:
delete from Site as s
...
Try:
delete from s
from Site as s
...
| {
"pile_set_name": "StackExchange"
} |
Q:
Customizing the Rendering of a Zend_Form_Element_Radio
I have an object that's an instance of a Zend_Form_Element_Radio. I'd like to customize how these radio buttons are displayed. The manual remarks
Radio elements allow you to specify several options, of which you need a single value returned. Zend_Form_Element_Radio extends the base Zend_Form_Element_Multi class, allowing you to specify a number of options, and then uses the formRadio view helper to display these.
However, I'm not picking on the context of a HOW the formRadio helper should be used, and how that would allow me to customize the display.
Before I dig too deeply into the Zend source, is there something obvious I'm missing, and/or a straight forward explanation of the intended use?
A:
I did a bit of misreading there. Objects instantiated from Zend_Form_Element_Radio
have a property named $helper, which defaults to formMyhelper. This property determines the name of the helper that a Zend_Form_Element_Radio will use while rendering itself.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to send tmp_file from Uploadify to other PHP page
I am making a script to upload image files to one of many albums(dynamic). But i stuck at end, cannot retrive tmp_file(uploaded file) to move it to album. I am using uploadify v2.1.4
Here is my script. This is my javascript upload form.
$(document).ready(function(){
//aleart('I am Ready!');
$("#file_upload").uploadify({
'uploader': 'upload/uploadify.swf',
'cancelImg': 'upload/cancel.png',
'auto': false,
'multi' :true,
'folder': 'uploads',**strong text**
'method' : 'post',
'queueSizeLimit' : 10,
'onQueueFull' : function(event, queueSizeLimit){
alert(" You can upload " + queueSizeLimit + " files at once");
return false;
},
'onComplete': function(event, ID, fileObj, response, data) {
var album_id = $("#album_id option:selected").val();
$.post("uploadify.php", { "name": fileObj.name, "tmp_name": fileObj.tmp_name, "path": fileObj.filePath, "size": fileObj.size, "album_id":album_id}, function(info){
alert(info);
});
}
});
});
</script>
</head>
<body>
<form method="post" action="" enctype="multipart/form-data">
<input type="file" name="file_upload" id="file_upload" />
<select id="album_id" name="album_id">
<?php foreach ($albums as $album) {
echo '<option value="', $album['id'], '">', $album['name'],'</option>';
} ?>
</select>
<a href="javascript:$('#file_upload').uploadifyUpload();">Upload File</a>
</form>
</body>
</html>
On my uploadify.php when i echo $image_temp = $_POST['tmp_name']; its giving me no results but it gives me correct output for all other fields send via POST.
Hence at the end i stuck & no image file to move toalbum!! Kindly provide guidance.
I am using uploadify.php to insert data in database & moving image from temp to album folder.
A:
You're getting two scripts muddled up. "tmp_name" belongs to $_FILES in PHP, not the file object in uploadify.
The script you have doesn't actually upload the file; your call to uploadify.php simply notifies that the file has been done.
The actually file receiver is specified in a "script" parameter:
$("#file_upload").uploadify({
'uploader': 'upload/uploadify.swf',
'script': 'upload/uploadify.php', //-- This bit is where the file gets uploaded to
'cancelImg': 'upload/cancel.png',
'auto': false,
'multi' :true,
.
Then check $_FILES in 'upload/uploadify.php' for 'tmp_name' etc - this is where your file is.
| {
"pile_set_name": "StackExchange"
} |
Q:
HID Device. Best way to do event handling?
I'm using an HID device to connect to a CAN bus with several different types of sensors attached. Some of them respond quickly, others have more latency.
I'm using this USB HID Component for C# as a .dll in visual basic, which works great. http://www.codeproject.com/KB/cs/USB_HID.aspx
My current code for sending and receiving commands is somewhat troublesome. Sometimes commands and sent but not received fast enough. The problem can be with the sensor, not the actual vb code. We want the program to continue monitoring the other sensors, and not hang for too long.
Currently I'm using event handlers and loops, but I'm wondering if this might be better done by threading? or if my routine is the best for this situation.
Code Snippets:
CANUSB_Class.vb
Public Sub DataReceivedHandler(ByVal sender As Object, ByVal dataReceived As DataRecievedEventArgs)
For Each byteReceived As Byte In dataReceived.data
rxDataStruct.dataPacket(rxDataStruct.InPacketLength) = byteReceived
rxDataStruct.InPacketLength += 1
Next
rxDataReady = True
MainParsingRoutine.vb
sendCommand = False
CANPort.rxDataReady = False
Try
Do
Tries += 1
If Tries > 4 Then
Exit Do
End If
CANTimer.Start()
CANPort.transmitPacket(OutCANPacket)
'Wait for Return Packet
Do Until CANPort.rxDataReady = True Or _
CANTimer.ElapsedMilliseconds > timeout
System.Threading.Thread.Sleep(0)
Loop
If CANPORT.rxDataReady = True Then
sendCommand = True
Loop Until sendCommand = True
A:
If anyone is developing a HID device and stumbles across this page I ended up using the ManualResetEvent.
In the CANUSB class the next line would be:
resetEvent.Set()
and then in the MainParsingRoutine.vb I changed:
Do Until CANPort.rxDataReady = True Or _
CANTimer.ElapsedMilliseconds > timeout
System.Threading.Thread.Sleep(0)
Loop
If CANPORT.rxDataReady = True Then
sendCommand = True
to:
CANUSB.resetEvent.WaitOne(100)
which times out after 100ms.
Works very well with our HID device, much better than our previous FTDI usb-serial device.
| {
"pile_set_name": "StackExchange"
} |
Q:
Absolute positioned elements on high dpi display out of alignment
I am working on a project for one of my classes and have ran into an odd positioning issue. I have two gear icons from the font-awesome library displayed with a text logo. One gear is sized larger and positioned slightly offscreen while the other is positioned almost touching the larger gear. On my laptop in chrome the elements displays correctly at the default 16px font size. When I switch to my desktop (with a 50 inch 4k tv display with chrome set to increase font sizes at 20px) the gears are out of alignment.
My question: how can I position the two icons so that they are consistent regardless of user-defined text size?
Relevant CSS:
div.logo i.cog-logo-small {
font-size: 1.5em;
top: 20px;
left: 32px;
}
div.logo i.cog-logo, div.logo i.cog-logo-small {
position: absolute;
}
div.logo i, div.logo a {
color: #c06014;
}
.fa {
display: inline-block;
font: normal normal normal 14px/1 FontAwesome;
font-size: inherit;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
div.logo i.cog-logo {
font-size: 3em;
top: -15px;
left: -15px;
}
Relevant HTML
<nav class="top-bar clearfix">
<div class="logo">
<a href="index.html">
<i class="cog-logo fa fa-cog gear-spin fa-3x" aria-hidden="true"></i>
<i class="cog-logo-small fa fa-cog gear-spin-reverse fa-2x" aria-hidden="true"></i>
<span class="logotext">logotext</span>
</a>
<span class="tagline">tagline</span>
</div>
</nav>
A:
The problem is with the fixed unit (px) positioning. Fixed units often do not scale as expected when zooming in the browser. A better approach is to use relative units (em, %, etc) that will change relatively as the zoom level changes.
Here's a solution using em for your top/left
div.logo i.cog-logo-small {
font-size: 1.5em;
top: 1em;
left: 1em;
}
div.logo i.cog-logo, div.logo i.cog-logo-small {
position: absolute;
}
div.logo i, div.logo a {
color: #c06014;
}
.fa {
display: inline-block;
font: normal normal normal 14px/1 FontAwesome;
font-size: inherit;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
div.logo i.cog-logo {
font-size: 3em;
top: -.25em;
left: -.5em;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<nav class="top-bar clearfix">
<div class="logo">
<a href="index.html">
<i class="cog-logo fa fa-cog gear-spin fa-3x" aria-hidden="true"></i>
<i class="cog-logo-small fa fa-cog gear-spin-reverse fa-2x" aria-hidden="true"></i>
<span class="logotext">logotext</span>
</a>
<span class="tagline">tagline</span>
</div>
</nav>
Or here is another using % in combination with transform: translate()
div.logo i.cog-logo-small {
font-size: 1.5em;
transform: translate(20%,20%);
}
div.logo i.cog-logo,
div.logo i.cog-logo-small {
position: absolute;
}
div.logo i,
div.logo a {
color: #c06014;
}
.fa {
display: inline-block;
font: normal normal normal 14px/1 FontAwesome;
font-size: inherit;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
div.logo i.cog-logo {
font-size: 3em;
transform: translate(-85%,-65%);
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<nav class="top-bar clearfix">
<div class="logo">
<a href="index.html">
<i class="cog-logo fa fa-cog gear-spin fa-3x" aria-hidden="true"></i>
<i class="cog-logo-small fa fa-cog gear-spin-reverse fa-2x" aria-hidden="true"></i>
<span class="logotext">logotext</span>
</a>
<span class="tagline">tagline</span>
</div>
</nav>
| {
"pile_set_name": "StackExchange"
} |
Q:
Succes with compiling Error JVM Oracle Database Move Data
I have a Data in a specific folder. I only know the id. But the name of the data contain more then an ID, because of that I am using "listFiles". For security reason only the database can enter the file system, because of that I want to upload the java class into my oracle. But my Oracle DB always says that it success compiling with Error and I don't know why.
Here is my code:
CREATE OR REPLACE AND RESOLVE JAVA SOURCE NAMED MOVEFILE as `import java.io.*`;
public class MOVEFILE {
/**
* Eigentliche Methode zum Verschieben
*/
public static int moveFile(String orgPath, String gewPfad, String dateiID) {
File folder = new File(orgPath);
File[] listOfFiles = folder.listFiles(new FilenameFilter(){
@Override
public boolean accept(File folder, String name){return name.toLowerCase().contains(dateiID);}});
String orgDatei = listOfFiles[0].toString();
File org = new File(orgDatei);
File gew = new File(gewPfad);
if (!org.exists())
return 0;
if (gew.exists())
return 0;
if (copyFile(orgDatei, gewPfad) == 1)
if (deleteFile(orgDatei) == 1)
return 1;
return 0;
}
I have methods copyFile and deleteFile. When I compile them without moveFile it compiles successfully.
Can you help me? Sorry for my bad english. If you have any question I will answer them as soon as I can. Thank you :)
A:
Berger got it right in the comments, I think.
You cannot reference dateiID in the anonymous inner class you define for listOfFiles, unless you make dateiID final.
Also, you don't need single quotes around the import line.
You could have discovered this for yourself by asking the database what the problem was, like so:
select *
from dba_errors
where name = 'MOVEFILE'
order by sequence;
| {
"pile_set_name": "StackExchange"
} |
Q:
Match repeated 3 or more times
This a quiz exercise
I'd like to know if a text contains words with 4 characters or more which are repeated 3 or more times in the text (anywhere in the text). If so, set one (and only one) backreference for each word.
I tried the code
(?=\b(\w{4,}+)\b.*\1)
Results returns
Test 10/39: Not working, sorry. Read the task description again. It matches notword word word
Tried
(?=(\b\w{4,}\b)(?:.*\b\1\b){2,})
Test 22/39: If a certain word is repeated many times, you're setting more than 1 backreference (common mistake, I know). You don't necessarily need to match the first occurrence of the word. Can you avoid a match in >word< word word word, and match word >word< word word? (Hint: match if it's followed by 2 occurences, don't match if it's followed by 3)
Regex demo
A:
If I understand your question correctly, this should do what you want:
(?=(\b\w{4,}\b)(?:.*\b\1\b){2})(?!(\b\w{4,}\b)(?:.*\b\1\b){3})
It is essentially the same as your regex, looking for a word of 4 characters that is repeated, but it looks for 2 extra occurrences (so it appears 3 times). The words which match will be captured in group 1. The regex includes a negative lookahead for 3 repeats, so that it won't match the same word twice if it occurs 4 or more times.
Demo on regex101
| {
"pile_set_name": "StackExchange"
} |
Q:
Avoid nesting of functions
is there a way to avoid the "nesting" of functions like
f[f[f[a, b], c], d]
where a, b, c, d are lists and f is a function that merges two lists with certain rules using a For-Loop
For[i = 1, i <= len, i++,
L[[i]] = func[x[[i]], x[[i]] ];
Any help would be much appreciated.
EDIT
Included code
f[x_, y_] :=
[L = x;
For[i = 1, i <= len, i++,
L[[i]] = x[[i]]*y[[i]]] //. Rules; L]
A:
ClearAll["Global`*"]
(* create four random lists for example *)
{a, b, c, d} = RandomInteger[100, {4, 20}];
(* some rules... *)
rules = {1 -> 0, 2 -> 3, 3 -> 5};
(* some function *)
f[a_, b_] := a*b;
(* do it *)
result=Fold[f /. rules, {a, b, c, d}]
Notes:
Don't use uppercase initials for user-defined symbols. You may clash
with built-ins.
Operations on lists of same length (implied by yourOP) can almost
always be vectorized. Using For is generally inefficient and poor
Mathematica coding (there are exceptions).
Read the documentation, tutorials, and tutorial-like questions on
this site and get a basic understanding of how Mathematica works. This is not an interactive documentation source...
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I list the files inside a python wheel?
I'm poking around the various options to setup.py for including non-python files, and they're somewhat less than intuitive. I'd like to be able to check the package generated by bdist_wheel to see what's actually in it--not so much to make sure that it will work (that's what tests are for) but to see the effects of the options I've set.
How do I list the files contained in a .whl?
A:
You can take the wheel file change the extension to .zip and then extract the contents like any other zip file.
from PEP 427
A wheel is a ZIP-format archive with a specially formatted file name
and the .whl extension.
Example
the Django python package has a wheel file. Try Django-1.8.4-py2.py3-none-any.whl as an example. Their package contains non-python files if you wanted to see where they end up being stored in the archive.
Code
The following code works correctly in python2 and python3. It will list the files in any wheel package. I use the pep8 wheel package as an example.
from zipfile import ZipFile
path = '/tmp/pep8-1.7.0-py2.py3-none-any.whl'
print(ZipFile(path).namelist())
Output
['pep8.py', 'pep8-1.7.0.dist-info/DESCRIPTION.rst', 'pep8-1.7.0.dist-info/entry_points.txt', 'pep8-1.7.0.dist-info/metadata.json', 'pep8-1.7.0.dist-info/namespace_packages.txt', 'pep8-1.7.0.dist-info/top_level.txt', 'pep8-1.7.0.dist-info/WHEEL', 'pep8-1.7.0.dist-info/METADATA', 'pep8-1.7.0.dist-info/RECORD']
A:
unzip -l dist/*.whl (credit)
Since a wheel is a ZIP file, unzip works. Tab completion for the file name won't work, unless the extension is renamed to zip. The from zipfile import ZipFile approach assumes only the presence of Python in the system, but a one-liner in the shell is more practical.
| {
"pile_set_name": "StackExchange"
} |
Q:
python-docx: Insert a paragraph after
In python-docx, the paragraph object has a method insert_paragraph_before that allows inserting text before itself:
p.insert_paragraph_before("This is a text")
There is no insert_paragraph_after method, but I suppose that a paragraph object knows sufficiently about itself to determine which paragraph is next in the list. Unfortunately, the inner workings of the python-docx AST are a little intricate (and not really documented).
I wonder how to program a function with the following spec?
def insert_paragraph_after(para, text):
A:
Trying to make sense of the inner workings of docx made me dizzy, but fortunately, it's easy enough to accomplish what you want, since the internal object already has the necessairy method addnext, which is all we need:
from docx import Document
from docx.text.paragraph import Paragraph
from docx.oxml.xmlchemy import OxmlElement
def insert_paragraph_after(paragraph, text=None, style=None):
"""Insert a new paragraph after the given paragraph."""
new_p = OxmlElement("w:p")
paragraph._p.addnext(new_p)
new_para = Paragraph(new_p, paragraph._parent)
if text:
new_para.add_run(text)
if style is not None:
new_para.style = style
return new_para
def main():
# Create a minimal document
document = Document()
p1 = document.add_paragraph("First Paragraph.")
p2 = document.add_paragraph("Second Paragraph.")
# Insert a paragraph wedged between p1 and p2
insert_paragraph_after(p1, "Paragraph One And A Half.")
# Test if the function succeeded
document.save(r"D:\somepath\docx_para_after.docx")
if __name__ == "__main__":
main()
| {
"pile_set_name": "StackExchange"
} |
Q:
Properly compiling modules in subfolders (ocamlbuild)
I recently decided to organize the files in my project directory. I moved the parsers I had for a few different file types into their own directory and also decided to use ocamlbuild (the as the project was getting more complicated and the simple shell script was not sufficient any longer).
I was able to successfully include external projects by modifying myocamlbuild with some basic rules (calling ocaml_lib, I'll use ocamlfind some other time), but I am stuck on how to include the folder as a module into the project properly. I created a parser.mlpack file and filled it with the proper modules to be included (eg, "parser/Date", et cetera), wrote a parser.mli in the root of the directory for their implementations, and modified the _tags file (see below).
During the compilation, the parser directory is traversed properly, and parser.cmi, parser.mli.depends were both created in the _build directory; as well as all *.cm[xio] files in the parsers subdirectory.
I feel I might be doing something redundant, but regardless, the project still cannot find the Parser module when I compile!
Thanks!
_tags
debug : true
<*.ml> : annot
"parser" : include
<parser/*.cmx>: for-pack(Parser)
<curlIO.*> : use_curl
<mySQL.*> : use_mysql
<**/*.native> or <**/*.byte> : use_str,use_unix,use_curl,use_mysql
compilation error
/usr/local/bin/ocamlopt.opt unix.cmxa str.cmxa -g -I /usr/local/lib/ocaml/site-lib/mysql mysql.cmxa -I /usr/local/lib/ocaml/curl curl.cmxa curlIO.cmx utilities.cmx date.cmx fraction.cmx logger.cmx mySQL.cmx data.cmx project.cmx -o project.native
File "\_none\_", line 1, characters 0-1:
Error: **No implementations provided for the following modules:**
Parser referenced from project.cmx
Command exited with code 2.
You'll notice -I parser is not included in the linking phase above; actually none of the parser related files are included!
edit: Added new details from comments and answer below.
A:
You need to "include" the parser directory in the search path. You can do this in _tags:
"parser": include
Then ocamlbuild can search the parser directory for interesting files.
A:
I wonder if parser.mli is somehow interfering with the dependencies in processing the mlpack file. parser.cmi will be generated from the pack operation when parser.mlpack is processed and compiled. Try building with the parser.mli file removed. If that works, then this can be re-processed into a real answer.
Also, you don't need parser/ as a prefix to your modules in parser.mlpack if parser.mlpack is in the parser directory and you have the include tag set. But that shouldn't make a difference for this.
Update: this worked around the problem, but wasn't the root cause. Root cause, per comment below, was a file mentioned in the .mlpack that had been relocated.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why EPSILON is used in comparing two floating point numbers
I'm googling about how to find if a number y is power of x and came across this link
Java
public class Solution {
public boolean isPowerOfThree(int n) {
return (Math.log10(n) / Math.log10(3)) % 1 == 0;
} }
Common pitfalls
This solution is problematic because we start using doubles, which
means we are subject to precision errors. This means, we should never
use == when comparing doubles. That is because the result of
Math.log10(n) / Math.log10(3) could be 5.0000001 or 4.9999999. This
effect can be observed by using the function Math.log() instead of
Math.log10().
In order to fix that, we need to compare the result against an
epsilon.
Java
return (Math.log(n) / Math.log(3) + epsilon) % 1 <= 2 * epsilon;
There I didn't understand return (Math.log(n) / Math.log(3) + epsilon) % 1 <= 2 * epsilon;
What is the meaning of that line?
Why EPSILON is used while comparing floating points?
A:
As the quoted section says, because of floating point imprecisions, you can have two numbers that should be exactly equal (if the calculations that created them were carried out with mathematical exactness), but that are instead slightly different.
When you compare them, you want to account for that slight difference and still treat numbers as equal if they differ only by a small amount, called epsilon.
How to choose an appropriate epsilon, though, is a tricky question and highly dependent on the nature of your calculations. I suppose that for this reason, Java does not include a "standard" epsilon constant (some other languages do).
| {
"pile_set_name": "StackExchange"
} |
Q:
Why data is not rendered on refresh in react js with asynchronous call?
I am creating edit form.First i have to get data to edit form and i am calling it in componentDidMount().Please see code below.
import React from 'react';
import CompanyForm from './CompanyForm';
import { connect } from 'react-redux';
import { companyActions } from '../../../redux/actions/company-action';
class EditCompanyPage extends React.Component {
constructor(props){
super(props);
};
componentDidMount () {
const { id } = this.props.match.params
const { dispatch } = this.props;
dispatch(companyActions.getCompany(id));
}
render(){
const {editUser } = this.props;
return(
<div>
<h1>Edit Company</h1>
{
editUser && <CompanyForm handleActionParent={this.handleAction} companyDataFP={editUser} />
}
</div>
);
};
}
function mapStateToProps(state) {
const { editUser } = state.companyReducer;
return {
editUser
};
}
const EditCompany = connect(mapStateToProps)(EditCompanyPage);
export default EditCompany;
see code for CompanyForm component below:
import React from 'react';
class CompanyForm extends React.Component {
constructor(props){
super(props);
this.state = {
company :{
name : this.props.companyDataFP.name || '',
address1 : this.props.companyDataFP.address1 || '',
}
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
};
handleChange(e) {
const { name, value } = e.target;
const newState = Object.assign({}, this.state);
newState.company[name] = value;
this.setState(newState);
}
handleSubmit(e) {
e.preventDefault();
return false;
}
render(){
return(
<div className="col-md-12">
<form onSubmit={this.handleSubmit}>
<div className="row">
<div className="col-md-6">
<div className='form-group'>
<label htmlFor="name">Name</label>
<input type="text" name="name" className="form-control" onChange={this.handleChange} value={this.state.company.name} />
</div>
</div>
<div className="col-md-6">
<div className='form-group'>
<label htmlFor="address1">Address 1</label>
<input type="text" name="address1" className="form-control" onChange={this.handleChange} value={this.state.company.address1} />
</div>
</div>
</div>
<div className="row">
<div className="col-md-12">
<div className='form-group'>
<input type="submit" className="btn btn-info" value="submit" />
</div>
</div>
</div>
</form>
</div>
);
};
}
export default CompanyForm;
It works fine when i access this form with
<Link to="/edit-form/:id" >Edit</Link>
but when i refresh the current page then values are not rendering into form to edit.
I am using redux approach for state management, please guide me i am new to react.
A:
Probably ComponyForm initializes form on its componentDidMount lifecycle function, so when editUser arrives nothing will change.
A way to handle this is changing:
<CompanyForm handleActionParent={this.handleAction} companyDataFP={editUser} />
to:
{editUser.name && <CompanyForm handleActionParent={this.handleAction} companyDataFP={editUser} />}
| {
"pile_set_name": "StackExchange"
} |
Q:
Cold Crashing in the bottle?
Is it possible or advantageous to cold crash after bottling? I am aftaid if I cold crash for 2-3 weeks before I bottle that all the yeast will settle out and I wont have any to provide carbonation in the bottle.
If I cold crash in the bottle, will the increased sediment contribute to long-term storage issues?
Assume that I hit my FG and that no additional fermentation will take place (other than bottle carbing)
A:
You will want to dry-hop at normal/fermentation temps for the best hop oil extraction. Dry-hopping cold is going to be an inefficient use of precious hops.
If you're worried about (or better: experience via experiment) low bottle carbonation/refermentation, you can always pitch new yeast during bottling. Some highly-flocculant strains might be sufficiently reduced during cold crashing to limit bottle carbonation, but I don't say that with high confidence.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can we say that no matter what philosophy a person holds, it must break down sometimes, because human must hold double standards?
Can we say that no matter what philosophy a person holds, ultimately, all humans use double standards to live? The reason is: all continuously living human beings, will prefer to eat other living things, and not want to be eaten by other living things. Because if there is any human that is not using this way of thinking, and not eat other living things (plants, or animals), he or she will not live past a few days or weeks.
Or can we say that no matter what philosophy a person holds, it needs to break down sometimes, because, ultimately, all humans use double standards in order to live? Unless, if the philosophy itself already include this double standard element in it.
A:
The reason is: all continuously living human beings, will prefer to eat other living things, and not want to be eaten by other living things.
Alternative wordings of your question might include, "Is it practical to live without hypocrisy?", or, "Is it possible to apply the golden rule to all acts consistently?"
If I understand you as you mean, then you would define "holding a double standard" as
desiring to act upon a self-like class of entities while desiring not to be samely acted upon by that class of entities.
For example,
class LivingThing
{
public void Eat(LivingThing& anotherLivingThing);
};
Instantiations of this class would be holding a double standard if they desired to invoke LivingThing::Eat while desiring not to become the parameter themselves.
I use this example not (only) because you have 17,874 reputation on Stack Overflow :p, but because, for me at least, it isolates the major ambiguity: What constitutes a LivingThing?
Would you consider microorganisms in the air LivingThings? Or only multicellular organisms? Or perhaps, only multicellular organisms with sentience, i.e. not plants?
To be "eligible for double-standardness," do two entities need to be LivingThings, as in, be instantiations of the base or a derived class, i.e. must they be linked by a nature of what they are? Or, do two entities simply need to do things that LivingThings do, as in, implement a common interface (er, abstract class), e.g. is it a double standard for us to desire to destroy a computer, if we also desire not to be destroyed by a computer? (In this context, personally, I believe the object-oriented and functional views are the same.)
I understand that "living things" was only one example. But generally speaking, and maybe this is what Rex Kerr was getting at too, I believe that no matter what you talk about, the same ambiguities would arise, because lumping and distinction are operations local and subjective to our brains.
| {
"pile_set_name": "StackExchange"
} |
Q:
Insert Select Sql Server
Ligação e Historico_ligacao
Tenho um script que copia todos os dados da tabela Ligacao para Historico_ligacao.
Quando comparo os dados entre as tebalas, a tabela historico_ligacao esta ordernado de uma forma diferente da Ligacao, não sei se isso influência em alguma coisa, mas gostaria que a ordenação de ambas fossem iguais.
Segue abaixo o código do insert:
SET IDENTITY_INSERT HISTORICO_LIGACAO ON
INSERT HISTORICO_LIGACAO (CDLIGACAO,CDLOTE,CDATRIBUTOLOTE,CDCAMPANHA,CDROTA,CDCONTATO,CDTELEFONE,CDESTADOLIGACAO,DURACAO,DTINICIO,DTFINAL,NUMERO_DISCADO,TECLAS_VALIDAS,TECLAS_TODAS, timezone)
output inserted.CDLIGACAO into #temp (num)
SELECT * FROM LIGACAO WHERE CDLOTE <= @CDLOTE order by cdligacao;
SET IDENTITY_INSERT HISTORICO_LIGACAO OFF
A:
Crie índice clusterizado na coluna CDLIGACAO
Se os registros forem únicos coloca ela também como chave primária.
CREATE CLUSTERED INDEX idx_name ON HISTORICO_LIGACAO (CDLIGACAO);
| {
"pile_set_name": "StackExchange"
} |
Q:
onERC721Recieved implementation
As per the ERC721 requirements, I have to implement onERC721Recieved. This is how I did it:
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes calldata _data
)external returns(bytes4) {
return bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"));
}
This seems to be in line with what is required of the function. However, this raises two questions:
If this does not actually use any of the parameters, why pass the parameters to the function at all? It is now throwing errors every time I test the contract.
What is the reason behind this function?
A:
You can remove the errors with this implementation:
function onERC721Received(
address,
address,
uint256,
bytes calldata
)external returns(bytes4) {
return bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"));
}
The parameters are there for implementations that want to use them. Perhaps for doing an accounting of incoming assets. Or perhaps for denying receipt of certain assets.
| {
"pile_set_name": "StackExchange"
} |
Q:
Spring Data MongoDB "_class" bad design pattern
I have problems with Spring Data MongoDB project. My problem is _class property in all collection records. My user collection size is nearly 1.3 million records. All records have a _class property. This is problem and bad design for project. Because MongoDB is a document-based system. Size is a problem each record in the collections. User collection:
{ "_class" : "com.myproject.xxx.yy.aaa.bb.User", … }
What if I want to move the User class to another package? Why does Spring Data add a _class property to all records?
A:
I don't know what leads you to the assumption to improve the chances of getting advice if you're bashing the project your seeking advice for. Beyond that, when using a software library you might wanna assume that implementation details have been thought through and are the way they are for a reason.
If you had taken the time to consider read up the reference documentation you would have discovered the section explaining why the _class attribute is there in general as well as how to tweak the values written, how to customize the key or even turn off the type information written at all.
After reading up that stuff you can now go back to write perfectly fine software again in turn. Thanks!
PS: I've taken a bit of time to polish up your badly designed way of asking a question. ;)
| {
"pile_set_name": "StackExchange"
} |
Q:
multiply 2 values in javascript where one value has comma separated input
Hi all can some one help me I need to multiply comma separated values using javascript, I tried the following but it is not giving the actual result
function calculateLinePrice(s, e) {
var unitPrice = 2,222.00;
var price = unitPrice.replace(/[^0-9\.,]/g, '')
var quantity = 10
if (price != '' && quantity != '') {
var totalPrice= parseFloat(price) * parseFloat(quantity);
alert(totalPrice);
}
}
A:
Try this
var unitPrice = '2,222.00';
var price = unitPrice.replace(/\,/g,'');
var quantity = 10;
if (price != '' && quantity != '') {
var totalPrice = parseFloat(price,20) * parseFloat(quantity,20);
alert(totalPrice);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Counter Example about Continuous Functions
(James Munkres page 104 Theorem 18.1) Let $X$ and $Y$ be topological spaces; let $f: X \rightarrow Y$. If $f$ is continuous, then for every subset $A$ of $X$, one has $f(\overline{A})\subset \overline{f(A)}$. I can follow the argument in the book. My question is why cannot one has equality here, that is, $f(\overline{A}) = \overline{f(A)}$, please? Is there an easy counter example, please? Thank you!
A:
Let $A=\mathbb{Z}_+\subset \mathbb{R}_+$ with the standard topology, and let $f(x) = \dfrac{1}{x}$.
The closure of $A$ is $A$, so the image of $f$ does not change. The closure of $f(A)$ is $\{0\} \cup f(A)$.
A:
There is a nice symmetry here: $f$ is continuous iff for all $A \subset X$ we have $f[\overline{A}] \subset \overline{f[A]}$ (which means intuitively that a point "close to" $A$ has an image "close to" $f[A]$), and $f$ is closed (maps closed sets to closed sets) iff for all $A \subset X$ we have $\overline{f[A]} \subset f[\overline{A}]$.
Proof of the latter: suppose $f$ is closed, and $A \subset X$. Then $\overline{A}$ is closed in $X$, so $f[\overline{A}]$ is closed in $Y$, and it contains $f[A]$, so it also contains its closure. For the reverse, suppose we have the inequality for all $A \subset X$, and $C \subset X$ is closed. Then $\overline{f[C]} \subset f[\overline{C}] = f[C] \subset \overline{f[C]}$, showing that $f[C]$ is closed.
So we have equality for all $A$ exactly when $f$ is closed and continuous, so we just have to find non-closed continuous maps. And this is what the other answers provide...
| {
"pile_set_name": "StackExchange"
} |
Q:
NHibernate Query Execution Plan?
HI all,
How does NHibernate executes the queries? Does it manipulates the queries and uses some query optimization techniques? And what is the query execution plan followed by NHibernate?
A:
How does NHibernate executes the queries?
Not exactly sure about the question. But NH executes queries using normal ADO.NET with all the data passed as parameters.
Does it manipulates the queries and uses some query optimization techniques?
It generates as optimal queries as possible with the information provided for it.
It caches not only the queries, but also the data returned by them if configured so.
And what is the query execution plan followed by NHibernate?
NH takes into account that the execution plan should not be generated on the server if not required. So the execution plan will be the same for all queries of of the same kind.
| {
"pile_set_name": "StackExchange"
} |
Q:
My if statement gives me the wrong output
window.onload = start;
function start() {
document.getElementById("kalk").onclick = find;
find(1, 9999);
}
function find(min, max) {
var factor = document.getElementById("tall").value;
var factor2 = document.getElementById("tall2").value;
var x = factor * factor2;
document.getElementById("utskrift").innerHTML = x;
if (x >= min && x <= max) {
document.getElementById("msg").innerHTML = "Number is in interval."
} else {
document.getElementById("msg").innerHTML = "Number is not in interval."
}
}
<h2>Gang to tall</h2>
T1 <input type="number" id="tall" /> T2 <input type="number" id="tall2" />
<button id="kalk">Finn tall i intervall</button> Sum: <span id="utskrift"></span>
<p id="msg"></p>
So by reading this code.. what Im trying to do is have two inputs where i multiply the numbers typed in them. In my "Find()" Parameter i have two arguments that says the numbers should be between 1-9999. In my "function find" i called these arguments min and max. Further down the code Im asking if the output is between these numbers are between min and max give "Number is in interval". The problem is that when i even when the numbers are in these arguments i get my else statement. Is there anyway to fix this or put an input felt in the parameter?
Thanks
A:
You are attaching the function find directly to the click event listener. The function is expecting two parameters min and max:
function find(min, max)
But when a click happens, it recieves, being an event listener, only one parameter which is the event object. Thus min is going to be an event object, and max will be undefined and your if statement won't work. You can check this out by logging min and max inside find to the console.
Wrap the function find call in another function and attach the latter as the event listener:
document.getElementById("kalk").onclick = function(event) { // the event listener function recieves the event object as the only parameter (not that argument event here is not necessary, I just added it for explanation)
find(1, 90000); // when this function get executed (when a click happens) then call find with proper parameters
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Get partial object list from JSON C#
I am calling a RESTful service in C# and the result is similar to this:
{
"blabla":1,
"bbb":false,
"blabla2":{
"aaa":25,
"bbb":25,
"ccc":0
},
"I_want_child_list_from_this":{
"total":15226,
"max_score":1.0,
"I_want_this":[
{
"A":"val1",
"B":"val2",
"C":"val3"
},
{
"A":"val1",
"B":"val2",
"C":"val3"
}
...
]
"more_blabla": "fff"
...
}
I want to get the "I_want_this" part as a list of object or JObject
Is there something like
(JObject)responseString["I_want_child_list_from_this"]["I_want_this"]
more generically:
(JObject)responseString["sub"]["sub_sub"]
I am using Newtonsoft.Json
Thanks!
A:
First off, I would create a class that represents the JSON structure returned from the service call. (http://json2csharp.com/ great utility for auto-generating classes from JSON)
Second, if you are not using Newtonsoft.Json library, I would recommending grabbing that library.
Lastly, use Newtonsoft to deserialize the JSON from the service call into the class you created:
var json = Service.GetJson();
var yourDesiralizedJson = JsonConvert.DeserializeObject<YourJsonToCSharpClass>(json);
var listYouWant = yourDesiralizedJson.IWantChildList.IWantThis;
A:
The below link is appears to be close to the solution as the requester using NewtonSoft.Json as his api to manipulate the object. Appreciate the solutions from other users as well.
look at e.g. here newtonsoft.com/json/help/html/SerializingJSONFragments.htm
| {
"pile_set_name": "StackExchange"
} |
Q:
Require change of file for every commit
Is it possible to demand change of specific file in every commit? E.g. I have "version.txt" file in my repo, indicating the current version of code and I need to change it every time I commit new changes. Can I make something to remind me to change version file, if I forgot to do that?
A:
I'm not sure exactly how to do that or if that is possible, but I did a little research and found this link that might be useful: https://pre-commit.com/
you could potentially create hooks to run before a commit to ensure your code is free of certain bugs and I'm sure you could add a check for the version.txt file as well!
Anyone please feel free to edit my answer!
| {
"pile_set_name": "StackExchange"
} |
Q:
What is primary assembly
I am trying to use ILMerge in our build process.
ILMerge has the Kind enumeration, which contains the SameAsPrimaryAssembly field.
What is the this primary assembly? How can I set the primary assembly?
A:
ILMerge takes a set of input assemblies and merges them into one target assembly. The first assembly in the list of input assemblies is the primary assembly. When the primary assembly is an executable, then the target assembly is created as an executable with the same entry point as the primary assembly. Also, if the primary assembly has a strong name, and a .snk file is provided, then the target assembly is re-signed with the specified key so that it also has a strong name. Check this:
http://rongchaua.net/blog/c-how-to-merge-assembly/
http://www.microsoft.com/downloads/details.aspx?FamilyID=22914587-B4AD-4EAE-87CF-B14AE6A939B0&displaylang=en
Here's how to set it:
ilmerge /out:Merged.dll /keyfile:key.snk Primary.dll Secondary.dll
| {
"pile_set_name": "StackExchange"
} |
Q:
how to get python to not append L to longs or ignore in django template
Is there a way to get around python appending an "L" to Ints short of casting every time they come out of the database? (Note: I'm using Mysql)
OR, is there a way to ignore the L in django templates? (I keep getting invalid formatting errors because of this, but I'd rather not do list comprehension/casting EVERY time)
e.g. I have a dict with the object's pk as the key and I get the following in firebug:
invalid property id
alert({183L: <Vote: colleen: 1 on Which best describes your wardrobe on any g...
Model: Question object, other attributes don't matter because the attribute in question is the pk
View: I didn't write the code and I can't follow it too well, so I can't post the section where the variable is being created, but it is a dict with Question pks as keys and Vote objects as values (code in question is from http://code.google.com/p/django-voting/wiki/RedditStyleVoting)
Template:
{% votes_by_user user on questions as vote_dict %} to produce the dict in question
alert({{vote_dict}}); is triggering the error
While in this particular case I'm just trying to alert the dict I got back, this has been a recurring problem for me when passing dicts or arrays into js functions where the function call fails because of the L. (Just to give you motivation behind the question)
A:
There's nothing wrong with Django here. However, it's going to be difficult to provide you with a relevant solution as we don't really know what you're trying to achieve.
Anyway, calling {{ vote_dict }} will call said dict's __str__ method, which is the common {key_repr:value_repr} pattern.
If you were to do the following:
{% for key, value in vote_dict.items %}
{{ key }} : {{ value }}
{% endfor %}
You'd get what you expect, without the L's.
On a sidenote, alert({{vote_dict}}) will almost always raise a JS error: alert's parameter is supposed to be a string.
Regarding Django - JS interoperability
If what you're trying to achieve is to pass Django items into JS funcitons seamlessly (which could indeed be possible with list instances), you could define a template filter that would return what you need.
For a list (or any kind of iterable that you'd want to represent as a list), you could use the following:
def js_list(iterable):
return '[%s]' % ', '.join(str(item) for item in iterable)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to call a function onClick which is defined in React Hooks useEffect()?
useEffect(() => {
//Calling this function
const handleClick = () => {
const lazyApp = import("firebase/app")
const lazyStore = import("firebase/firestore")
//Some code here
}
}, [])
//Calling the function here
<MDBBtn
to=""
className="btn p-0 btn-white bg-transparent"
title="Add To Cart"
onClick={handleClick}
>
<FontAwesomeIcon
icon={faShoppingCart}
style={{ fontSize: "1.3rem" }}
/>
</MDBBtn>
I am trying to call a function after a button click event. But, I want that function to be defined inside useEffect() due to some reasons. I get the error that handleClick is not defined. What is the solution for this?
A:
Because you can't. That's not how it works. useEffect — without a second param— works like componentDidMount lifecycle. The function you're calling has already been called when the component is mounted.
I don't know for what reason you're trying to call an onclick function inside of an useEffect, I've never seen anything like that.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to extract all the columns from a data frame based on a column in another data frame?
I have two data frames. I want to extract all the columns from a data frame based on another data frame column.
df1:
sample
GY
AP
A9
MB
AU
df2:
num start end length GY A9 MB AP JK GH AU
2 23 24 567 5 6 7 8 9 0 1
2 3 44 57 8 6 7 3 4 0 9
2 234 54 67 5 6 7 8 9 0 1
result:
num start end length GY A9 MB AP AU
2 23 24 567 5 6 7 8 1
2 3 44 57 8 6 7 3 9
2 234 54 67 5 6 7 8 1
I tried in this way but it didn't work out:
u <- df1[df1$sample %in% colnames(df2),]
Can anyone tell me how to do this?
A:
With:
df2[, c(1:4, which(colnames(df2) %in% df1$sample))]
you get:
num start end length GY A9 MB AP AU
1 2 23 24 567 5 6 7 8 1
2 2 3 44 57 8 6 7 3 9
3 2 234 54 67 5 6 7 8 1
And this also works:
df2[, c(rep(TRUE,4), tail(colnames(df2) %in% df1$sample, -4))]
| {
"pile_set_name": "StackExchange"
} |
Q:
Paramaters of Functions Imported Using the DllImport Attribute
I am trying to import some winapi functions into my wpf project(written in c#) but I do not know how to "convert" some of their paramaters, for example the function
BOOL WINAPI GetClientRect(
_In_ HWND hWnd,
_Out_ LPRECT lpRect
);
takes a pointer to a RECT struct and modifies its contents. If I were to import this function using the DllImport attribute it would look like:
[DllImport("user32.dll"]
public static extern bool GetClientRect(IntPtr hwnd, ???);
How do I handle the pointer to RECT object?
A:
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left, Top, Right, Bottom;
}
[DllImport("user32.dll")]
static extern bool GetClientRect(IntPtr hWnd, out RECT lpRect);
| {
"pile_set_name": "StackExchange"
} |
Q:
Directional derivatives of a function with respect to different directions
Is it true that for the directional derivatives of a function u in $R^{n}$ the following formula holds
$ \partial u /\partial \nu = \partial u /\partial \xi \,\cos \alpha$ where $ \alpha $ is the angle formed between the directions $ \xi, \, \nu $. If yes, can you suggest a quick proof of this formula?
Thanks.
A:
Why do you think this is true?
Let $f(x,y)=xy$, $v=(1,0)$, $\xi=(0,1)$, then, one has:
$$\frac{\partial f}{\partial v}(x,y)=y,\frac{\partial f}{\partial\xi}(x,y)=x,\cos(\alpha)=0.$$
If you want to keep it abstract, notice that if your formula holds true, then:
$$\frac{\partial f}{\partial v}=\frac{\partial f}{\partial\xi}$$
for all $f$, $v$ and $\xi$, which is not to be excepted. Indeed, your formula implies:
$$\frac{\partial f}{\partial v}\leqslant\frac{\partial f}{\partial\xi}.$$
| {
"pile_set_name": "StackExchange"
} |
Q:
UINavigationBar weird color change animation when dismissing UIViewController
I have a FirstViewController and a SecondViewController. They have different colors for their UINavigationBar. When I show SecondViewController, the color fades in fine. I recorded the animation with the simulator and slow animations.
However, when I go back from SecondViewController to FirstViewController, the color does not animate and everything just changes at once.
This is how I set the code for the UINavigationBar in SecondViewController.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let navBar = self.navigationController?.navigationBar {
navBar.barStyle = UIBarStyle.black
navBar.barTintColor = NavBarColor.red
navBar.backgroundColor = NavBarColor.red
navBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
navBar.isTranslucent = false
navBar.tintColor = .white
}
}
In my FirstViewController class, I created a struct NavBarSettings and save the information of the UINavigationBar. I then apply them in viewWillAppear.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let navBar = self.navigationController?.navigationBar,
let navBarSettings = self.navBarSettings {
navBar.barStyle = navBarSettings.barStyle
navBar.barTintColor = navBarSettings.barTintColor
navBar.backgroundColor = navBarSettings.backgroundColor
navBar.titleTextAttributes = navBarSettings.titleTextAttributes
navBar.isTranslucent = navBarSettings.isTranslucent
navBar.tintColor = navBarSettings.tintColor
}
}
I also tried to change the UINavigationBar information in SecondViewController viewWillDisappear but it had the same effect.
I've also tried to set a backgroundColor but it had did not change anything either.
How do I get the second animation to work like the first one?
Update
The segue to SecondViewController is of kind show.
I simply call it with self.performSegue(withIdentifier: "SecondViewControllerSegue", sender: nil)
I didn't add any custom code to the back button, it's the default UINavigationController implementation.
A:
Try replacing the back button with a custom back button and add an action to it.
let backButton = UIButton()
backButton.addTarget(self, action: #selector(self.backButtonClicked), for: UIControlEvents.touchUpInside)
navBar.navigationItem.leftBarButtonItem = barButton
func backButtonClicked() {
// try implementing the same thing here but with the self.navigationController?.popViewController(animated: true)
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Chrome smooth scroll and requestAnimationFrame?
I have built a drag-drop autoscroller where the user drags and element over a hidden div which triggers the scrolling action of the scrollable div. I am using scrollBy({top: <val>, behavior: 'smooth'} to get smooth scrolling and requestAnimationFrame to prevent the function from calling too often. This works fine in Firefox and should be supported in Chrome natively according to caniuse; however, it fails to work properly in chrome. It only fires the event once when the user leaves the hidden div. No errors in the console. console.log() indicates that the function containing the scrollBy() is being called. If I remove behavior: 'smooth' it works, but of course no smooth scrolling. same result if I remove the option and set the css scroll-behavior: smooth on the scrollable div. I'm at a complete loss. MWE of the scroll function (this is in a Vue app, so any this.'s are stored in a data object.
scroll: function () {
if ( this.autoScrollFn ) cancelAnimationFrame( this.autoScrollFn )
// this.toScroll is a reference to the HTMLElement
this.toScroll.scrollBy( {
top: 100,
behavior: 'smooth'
}
this.autoscrollFn = requestAnimationFrame( this.scroll )
}
A:
Not sure what you did expect from your requestAnimationFrame call to do here, but here is what should happen:
scrollBy having its behavior set to smooth should actually start scrolling the target element only at next painting frame, just before the animation frames callback get executed (step 7 here).
Just after this first step of the smooth scrolling, your animation frame callback will fire (step 11), disabling the first smooth scrolling by starting a new one (as defined here).
repeat until it reaches the top-max, since you are never waiting enough for the smooth 100px scrolling to happen entirely.
This will indeed move in Firefox, until it reaches the end, because this browser has a linear smooth scrolling behavior and scrolls from the first frame.
But Chrome has a more complicated ease-in-out behavior, which will make the first iteration scroll by 0px. So in this browser, you will actually end up in an infinite loop, since at each iteration, you will have scrolled by 0, then disable the previous scrolling and ask again to scroll by 0, etc. etc.
const trigger = document.getElementById( 'trigger' );
const scroll_container = document.getElementById( 'scroll_container' );
let scrolled = 0;
trigger.onclick = (e) => startScroll();
function startScroll() {
// in Chome this will actually scroll by some amount in two painting frames
scroll_container.scrollBy( { top: 100, behavior: 'smooth' } );
// this will make our previous smooth scroll to be aborted (in all supporting browsers)
requestAnimationFrame( startScroll );
scroll_content.textContent = ++scrolled;
};
#scroll_container {
height: 50vh;
overflow: auto;
}
#scroll_content {
height: 5000vh;
background-image: linear-gradient(to bottom, red, green);
background-size: 100% 100px;
}
<button id="trigger">click to scroll</button>
<div id="scroll_container">
<div id="scroll_content"></div>
</div>
So if what you wanted was actually to avoid calling multiple times that scrolling function, your code would be broken not only in Chrome, but also in Firefox (it won't stop scrolling at after 100px there either).
What you need in this case is rather to wait until the smooth scroll ended.
There is already a question here about detecting when a smooth scrollIntoPage ends, but the scrollBy case is a bit different (simpler).
Here is a method which will return a Promise letting you know when the smooth-scroll ended (resolving when successfully scrolled to destination, and rejecting when aborted by an other scroll). The basic idea is the same as the one for this answer of mine:
Start a requestAnimationFrame loop, checking at every steps of the scrolling if we reached a static position. As soon as we stayed two frames in the same position, we assume we've reached the end, then we just have to check if we reached the expected position or not.
With this, you just have to raise a flag until the previous smooth scroll ends, and when done, lower it down.
const trigger = document.getElementById( 'trigger' );
const scroll_container = document.getElementById( 'scroll_container' );
let scrolling = false; // a simple flag letting us know if we're already scrolling
trigger.onclick = (evt) => startScroll();
function startScroll() {
if( scrolling ) { // we are still processing a previous scroll request
console.log( 'blocked' );
return;
}
scrolling = true;
smoothScrollBy( scroll_container, { top: 100 } )
.catch( (err) => {
/*
here you can handle when the smooth-scroll
gets disabled by an other scrolling
*/
console.error( 'failed to scroll to target' );
} )
// all done, lower the flag
.then( () => scrolling = false );
};
/*
*
* Promised based scrollBy( { behavior: 'smooth' } )
* @param { Element } elem
** ::An Element on which we'll call scrollIntoView
* @param { object } [options]
** ::An optional scrollToOptions dictionary
* @return { Promise } (void)
** ::Resolves when the scrolling ends
*
*/
function smoothScrollBy( elem, options ) {
return new Promise( (resolve, reject) => {
if( !( elem instanceof Element ) ) {
throw new TypeError( 'Argument 1 must be an Element' );
}
let same = 0; // a counter
// pass the user defined options along with our default
const scrollOptions = Object.assign( {
behavior: 'smooth',
top: 0,
left: 0
}, options );
// last known scroll positions
let lastPos_top = elem.scrollTop;
let lastPos_left = elem.scrollLeft;
// expected final position
const maxScroll_top = elem.scrollHeight - elem.clientHeight;
const maxScroll_left = elem.scrollWidth - elem.clientWidth;
const targetPos_top = Math.max( 0, Math.min( maxScroll_top, Math.floor( lastPos_top + scrollOptions.top ) ) );
const targetPos_left = Math.max( 0, Math.min( maxScroll_left, Math.floor( lastPos_left + scrollOptions.left ) ) );
// let's begin
elem.scrollBy( scrollOptions );
requestAnimationFrame( check );
// this function will be called every painting frame
// for the duration of the smooth scroll operation
function check() {
// check our current position
const newPos_top = elem.scrollTop;
const newPos_left = elem.scrollLeft;
// we add a 1px margin to be safe
// (can happen with floating values + when reaching one end)
const at_destination = Math.abs( newPos_top - targetPos_top) <= 1 &&
Math.abs( newPos_left - targetPos_left ) <= 1;
// same as previous
if( newPos_top === lastPos_top &&
newPos_left === lastPos_left ) {
if( same ++ > 2 ) { // if it's more than two frames
if( at_destination ) {
return resolve();
}
return reject();
}
}
else {
same = 0; // reset our counter
// remember our current position
lastPos_top = newPos_top;
lastPos_left = newPos_left;
}
// check again next painting frame
requestAnimationFrame( check );
}
});
}
#scroll_container {
height: 50vh;
overflow: auto;
}
#scroll_content {
height: 5000vh;
background-image: linear-gradient(to bottom, red, green);
background-size: 100% 100px;
}
.as-console-wrapper {
max-height: calc( 50vh - 30px ) !important;
}
<button id="trigger">click to scroll (spam the click to test blocking feature)</button>
<div id="scroll_container">
<div id="scroll_content"></div>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
Heteroplasmy Calculation
For calculating heteroplasmy in mtDNA I was using MitoSeek, the tool provides position wise heteroplasmy percentage. So, will it be wise to add up all sites to get a position-wise percentage in a single sample, or calculate it by adding up all counts (variants) from an aligned file and divide it by total read count?
A:
Heteroplasmy at any site (as long as it's a reliable variant) suggests that there is mitochondrial heteroplasmy, it doesn't matter where it is. In that case, the "mitochondrial heteroplasmy" statistic would simply be the maximum value at any [reliable] location.
Due to the low amount of variation in the mitochondrial genome, and because it's a haploid genome, I don't think that a calculation like "average heteroplasmy" makes much sense for mitochondria.
| {
"pile_set_name": "StackExchange"
} |
Q:
"Permission Denied" From Python Server
So basically, I'm a bit new to Python. I created a server and have it up and running just fine, have the files and everything showing up.
But the problem is, every time I try to open a file, in Python, for reading/writing, my terminal throws an "access denied" error.
You know, it's a basic server:
#!/usr/bin/env python
import BaseHTTPServer
import CGIHTTPServer
import cgitb
cgitb.enable();
server = BaseHTTPServer.HTTPServer;
handler = CGIHTTPServer.CGIHTTPRequestHandler;
address = ("",80);
handler.cgi_directories = ["/home"];
httpd = server(address,handler);
print("Working . . . ");
httpd.serve_forever();
Nothing too fancy. So I start the server up, and then when the user navigates to the page, "/home/file.py" that contains the code:
#!/usr/bin/env python
f = open("asdf.txt","w");
Nothing at all happens, and when I check the terminal that's running the server, it says,
localhost - - [27/Aug/2012 17:58:18] "GET /home/file.py HTTP/1.1" 200 -
Traceback (most recent call last):
File "/home/SERVER/home/file.py", line 4, in <module>
f = open("asdf.txt","w");
IOError: [Errno 13] Permission denied: 'asdf.txt'
I've been looking up this for awhile now, but I've yet to find a solution. It's probably a very simple solution that would make professional Python users facepalm, but take into account that all self-taught programmers have to start somewhere. And for me, I'm a bit at the bottom right now, in Python terms at least.
I have tried a couple solutions I've found from the internet (and from the "Questions that may already have your answer"), like importing "os" and using that to specify the exact location to create file. I've tried using "sudo chmod g+w" on the SERVER folder and the folder that contains the Python scripts. But none of these interwebs solutions are helping me.
I'll also remember to accept the answer.
I tried to make the question as precise as I could. So if there's anything else you'd need to know, I can just update it.
Since it's a "permission denied" error, I'm doubting it's Python's fault, and probably some permissions I didn't setup somewhere. But I don't know which or where they'd be.
A:
If you read the python docs on CGIHTTPServer:
Note that CGI scripts will be run with UID of user nobody, for security reasons. Problems with the CGI script will be translated to error 403
So this seems a little tricky unless you're willing to leave all best practices behind and let
anyone do stuff in your folder.
| {
"pile_set_name": "StackExchange"
} |
Q:
robots.txt parser java
I want to know how to parse the robots.txt in java.
Is there already any code?
A:
Heritrix is an open-source web crawler written in Java. Looking through their javadoc, I see that they have a utility class Robotstxt for parsing the robots.txt file.
| {
"pile_set_name": "StackExchange"
} |
Q:
NotSupportedException when casting Membership.GetAllUsers() to generic list
I am trying to use LINQ on the .NET Membership.GetAllUsers() collection, for example when getting all usernames:
var usernames = Membership.GetAllUsers().Cast<MembershipUser>().Select(x=>x.UserName).ToList();
But VS tells me that it is not supported..
Membership is a part of Web.Security, same as MembershipUser
Here is my connection string (if that is of any relevance):
<add name="ApplicationServices" connectionString="Data Source=somerserver.xx\SQLEXPRESS;Initial Catalog=bedriftsmelding;User Id=SomeUser;Password=SomePassword;Integrated Security=False" providerName="System.Data.SqlClient" />
Stack trace:
System.NotSupportedException was unhandled by user code
Message=Specified method is not supported.
Source=System.Web.Extensions StackTrace:
at System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider.GetAllUsers(Int32
pageIndex, Int32 pageSize, Int32& totalRecords)
at System.Web.Security.Membership.GetAllUsers(Int32 pageIndex, Int32 pageSize, Int32& totalRecords)
at System.Web.Security.Membership.GetAllUsers()
at Bedriftsmelding.Nettside.Models.CompanyUsers.GetUserIdFromUserName(String
username) in
C:\Projects\Bedriftsmelding\Bedriftsmelding.Nettside\Models\CompanyUsers.cs:line
26
at Bedriftsmelding.Tests.DTO.CompanyUsersTest.TestGetUserIdFromUserName()
in
C:\Projects\Bedriftsmelding\Bedriftsmelding.Tests\DTO\CompanyUsersTest.cs:line
16 InnerException:
A:
Looks like you're using a ClientFormsAuthenticationMembershipProvider rather than the default SqlMembershipProvider.
According to the docs for ClientFormsAuthenticationMembershipProvider, GetllAllUsers is not supported and throws a not supported exception.
http://msdn.microsoft.com/en-us/library/system.web.clientservices.providers.clientformsauthenticationmembershipprovider.getallusers.aspx
It appears that only the basic ValiateUser and a few other functions work with this provider, as it's designed for use with the Ajax extensions. None of the user functions work, such as GetUser, GetAllUsers, DeleteUser, CreateUser, etc...
| {
"pile_set_name": "StackExchange"
} |
Q:
Spring MVC HashMap Form Integration
I have a hash map in model object. How to bind the hash map when form submission.
Map<String, List<Employee>> employeeMap= new HashMap< String, List<Employee>>();
List<Employee> employeeList;
//getters and setters of employeeMap and employeeList
the Employee Object is
class Employee{
String name;
String pincode;
String organization;
//getters and setter
}
the form input value is
List{ //list iteration here
<input type="text" name="employeeMap[${emp.id}].employeeList[list_index].name" value=""/>
}
but it didn't work. please help me how to give the proper input name for binding with the hash map
A:
In my opinion you have two mistakes:
Your map has key as String but your ${emp.id} is probably int or long, try use quotes.
In map you have list of employees, this list can't have a name, you can just remove it.
Try like this:
<input type="text" name="employeeMap["${emp.id}"][list_index].name" value=""/>
Here is my similar working example:
User u1 = new User();
u1.setEmailAddress("email1");
User u2 = new User();
u2.setEmailAddress("email2");
u1List.add(u1);
u1List.add(u2);
u2List.add(u2);
u2List.add(u1);
userMap.put("1", u1List);
userMap.put("2", u2List);
model.addAttribute("userMap", userMap);
JSP:
Email of second user from map with key=1 = ${employeeMap["1"][1].emailAddress}
| {
"pile_set_name": "StackExchange"
} |
Q:
cakephp passing a variable to another controller
I am hoping to get pointed in the right direction. I want to pass a variable from one controller into another controller.
what I want to do is have a person register a business then they are taken to a form to register a user. a business is a different controller/table to a user however the user requires the id/primary key of the business as a foreign key in the user table. How would I go about changing controllers and carrying the foreign key over?
the primary key for the business table is an autogenerated/autoincremented int in the database
i am unsure on how I would approach this but have a feeling it is to do with session data?
A:
Why dont you pass the id in the url?. I'd do it like this:
Display /business/add. This is the form used to create a "business".
After saving the business in your controller, redirect to /business/add_user/123 (where "123" is the id of your business). This page displays and saves the users. Since you have passed the business_id in the url you'd have to add it as a foreign key manually into the $this->request->data before saving the user.
Of course that inside the controller of /business/add_user/123 you should verify a few thing: check if the business_id was passed as parameter in the url, check if the business exist, maybe check that the connected user was the one that created the businnes, etc
Hope this helps
| {
"pile_set_name": "StackExchange"
} |
Q:
Select2 strange behavior with objects
I'm trying to make an assisted multiselect with select2.
And something strange is happening when i'm using javascript function object.assign to merge my object.
I have a collection of multiselect select2 input :
Merged object response
[…]
0: Object { id: 1, text: 1 }
1: Object { id: 2, text: 2 }
2: Object { id: 3, text: 3 }
3: Object { id: 4, text: 4 }
length: 4
__proto__: Array []
Onscreen traduction
Merged object for Plot 18 selection
[…]
0: Object { id: 1, text: 1 }
1: Object { id: 2, text: 2 }
2: Object { id: 3, text: 3 }
3: Object { id: 4, text: 4 }
4: Object { id: 5, text: 5 }
5: Object { id: 6, text: 6 }
6: Object { id: 7, text: 7 }
7: Object { id: 8, text: 8 }
8: Object { id: 9, text: 9 }
9: Object { id: 10, text: 10 }
length: 10
__proto__: Array []
Onscreen Plot 18 Selection
Merged Object for Plot 1 & 18 Selection
{…}
0: Object { id: 1, text: 1 }
1: Object { id: 2, text: 2 }
2: Object { id: 3, text: 3 }
3: Object { id: 4, text: 4 }
8: Object { id: 5, text: 5 }
9: Object { id: 6, text: 6 }
10: Object { id: 7, text: 7 }
11: Object { id: 8, text: 8 }
12: Object { id: 9, text: 9 }
13: Object { id: 10, text: 10 }
__proto__: Object { … }
Onscreen Plot 1 & 18 selection
Source Code :
$.ajax({
url: "<?php echo base_url()?>main/api_filters",
data: {PlotsSelected : PlotsSelected, CensusYearsSelected : CensusYearsSelected, VernNamesSelected : VernNamesSelected, FamiliesSelected : FamiliesSelected, GenusSelected : GenusSelected, SpeciesSelected : SpeciesSelected },
datatype: 'json',
async: true
}).done(function(dataajax){
dataajax = JSON.parse(dataajax);
var VernNamesObj = $("#VernName").select2('data');
var FamiliesObj = $("#Family").select2('data');
var GenusObj = $("#Genus").select2('data');
var SpeciesObj = $("#Species").select2('data');
var PlotObj = $("#Plot").select2('data');
var SubPlotObj = $("#SubPlot").select2('data');
var CensusYearObj = $("#CensusYear").select2('data');
// Merge Selected options with received data to avoid unselection
let mergedVernNames = Object.assign(dataajax.VernName, VernNamesObj);
let mergedFamily = Object.assign(dataajax.Family, FamiliesObj);
let mergedGenus = Object.assign(dataajax.Genus, GenusObj);
let mergedSpecies = Object.assign(dataajax.Species, SpeciesObj);
let mergedSubPlot = Object.assign(dataajax.SubPlot, SubPlotObj);
console.log(mergedSubPlot);
if (dataajax) {
$("#VernName").html("");
$('#VernName').select2({
closeOnSelect: false,
data : mergedVernNames
});
$("#Family").html("");
$('#Family').select2({
closeOnSelect: false,
data : mergedFamily
});
$("#Genus").html("");
$('#Genus').select2({
closeOnSelect: false,
data : mergedGenus
});
$("#Species").html("");
$('#Species').select2({
closeOnSelect: false,
data : mergedSpecies
});
$("#SubPlot").html("");
$('#SubPlot').select2({
closeOnSelect: false,
data : mergedSubPlot
});
The taxonomics inputs are functionnals, only #SubPlot field is problematic
A:
Object.assign return an object of objects when all arguments are defined, Select2 seems to use array and not object.
I converted mergedSubPlot to an array and it worked
// Merge Selected options with received data to avoid unselection
let mergedVernNames = Object.assign(dataajax.VernName, VernNamesObj);
let mergedFamily = Object.assign(dataajax.Family, FamiliesObj);
let mergedGenus = Object.assign(dataajax.Genus, GenusObj);
let mergedSpecies = Object.assign(dataajax.Species, SpeciesObj);
//let mergedPlot = Object.assign(dataajax.Plot, PlotObj);
let mergedSubPlot = Object.assign(dataajax.SubPlot, SubPlotObj);
//let mergedCensusYear = Object.assign(dataajax.CensusYear, CensusYearObj);
mergedSubPlot = Object.keys(mergedSubPlot).map(function(key) {
return mergedSubPlot[key];
});
console.log(mergedSubPlot);
if (dataajax) {
$("#VernName").html("");
...
| {
"pile_set_name": "StackExchange"
} |
Q:
how to organize MySQL database connection when not using Entity Framework (or similiar)
Based on these two samples
https://github.com/jasontaylordev/CleanArchitecture
https://github.com/jasontaylordev/NorthwindTraders
I added an Application and Infrastructure layer to my API project. The important part is that I will only use the MySQL.Data package for the database stuff (no Entity Framework or other helping libraries).
I thought it would be a good practise to define interfaces for repositories in the Application layer
public interface IUsersRepository
{
Task<IList<User>> GetUsers();
Task<User> GetUserByUsername(string username);
// ...
}
and implement them in the Infrastructure layer. So when it comes to the DI container setup via IServiceCollection I can setup those repositories with services.AddTransient(typeof(IUsersRepository), typeof(UsersRepository));. Due to the fact I'm not using an ORM tool I have to setup the connection by myself. That's why I defined an interface in the Application layer
public interface IDatabaseContext
{
DbConnection DatabaseConnection { get; }
}
and create the connection to the MySQL database in the Infrastructure layer
public class DatabaseContext : IDatabaseContext
{
public DbConnection DatabaseConnection { get; }
public DatabaseContext()
{
DatabaseConnection = new MySqlConnection("server=127.0.0.1;uid=root;pwd=12345;database=test");
}
}
To make this injectable I add it to the services collection with services.AddSingleton(typeof(IDatabaseContext), typeof(DatabaseContext));
I think the implementing repositories should only care for their own query because they might get chained for a transaction. Currently they don't take care for the connection
public class UsersRepository : IUsersRepository
{
private readonly IDatabaseContext databaseContext;
public UsersRepository(IDatabaseContext databaseContext)
{
this.databaseContext = databaseContext;
}
public async Task<IList<User>> GetUsers()
{
using (DbCommand getUsersCommand = databaseContext.DatabaseConnection.CreateCommand())
{
// setup command string, parameters and execute command afterwards
}
}
}
The problem is that now every repository call requires a connection handling before execution in the Application layer. By that I mean I have to wrap the call like so
await databaseContext.DatabaseConnection.OpenAsync();
IList<User> users = await usersRepository.GetUsers();
// ...
await databaseContext.DatabaseConnection.CloseAsync();
so the calling class needs to inject the repository and the IDatabaseContext. I'm also not sure if opening/closing the connection for each query / transaction is a good idea.
Maybe there are some better approaches to enhance the current one. I would like to create a self managing database connection. The application layer shouldn't open/close connections. It should only call the repository methods. The repository methods shouldn't do it neither because they might run in a transaction and only the first query should open it and the last one closes it.
It would be awesome to define new repository methods with the SQL logic only and all the connection stuff is handled once. Any ideas?
A:
First, if you enable connection pooling on the MySql connector then you can skip the CloseAsync call and Dispose the connection each time you have used it, that will allow the pooling mechanism of the connector to reuse connections as needed. To enable it add Pooling=True to your connection string.
Second, to avoid all the extra code you can create a base class for the repositories and implement all the connection handling on it, I would create a function that takes a Func<DbConnection,Task<T>> and some type of static factory to reduce code rewrite:
//static DB factory
public static class DBFactory
{
public async Task<DBConnection> GetConnection()
{
//Create here your connection
var newCon = //..
await newCon.OpenAsync();
return newCon;
}
public async Task ExecuteTransaction(Func<DBConnection, MySqlTransaction, Task<bool>> TransactedCode)
{
using(var dbConnection = await GetConnection())
{
var transact = dbConnection.BeginTransaction();
try
{
if(await TransactedCode(dbConnection, transact))
transact.Commit();
else
transact.RollBack();
}
catch{ transact.RollBack(); }
}
}
}
//Base class for repositories
public abstract class BaseRepository
{
protected async Task<T> ExecuteResultWithConnection<T>(Func<DBConnection, MySqlTransaction, Task<T>> RepositoryMethod)
{
using(var dbCon = await DBFactory.GetConnection())
{
return await RepositoryMethod(dbCon, null);
}
}
protected async Task ExecuteWithConnection(Func<DBConnection, MySqlTransaction, Task> RepositoryMethod)
{
using(var dbCon = await DBFactory.GetConnection())
{
await RepositoryMethod(dbCon, null);
}
}
}
//Example of repository
public class TestRepository : BaseRepository
{
public async Task<IList<TestObject>> GetTestObjects(DBConnection con = null, MysqlTransaction Transact = null)
{
if(con != null)
{
//execute the code without calling the base function
//using con as your connection and transact if supplied
return yourResult;
}
else
{
return await ExecuteResultWithConnection(async (dbCon, transact) => {
//Here you have your connection ready to be used as dbCon
//without transaction
return yourResult;
});
}
}
public async Task AddTestObject(TestObject NewObject, DBConnection con = null, MysqlTransaction Transact = null)
{
if(con != null)
{
//execute the code without calling the base function
//using con as your connection and transact if supplied
}
else
{
await ExecuteWithConnection(async (dbCon, transact) => {
//Here you have your connection ready to be used as dbCon
//without transaction
});
}
}
}
Now, calling a repository is totally clean:
var repo = new TestRepository();
var objs = await repo.GetTestObjects();
await repo.AddTestObject(new TestObject{ /* whatever */ });
Also, you can create transactions:
await DBFactory.ExecuteTransaction(async (dbCon, transact) => {
var someObject = repo.GetTestObjects(dbCon, transact);
await repo.AddTestObject(new TestObject{ /* whatever */ }, dbCon, transact);
await repo.AddTestObject(new TestObject{ /* whatever */ }, dbCon, transact);
await repo.AddTestObject(new TestObject{ /* whatever */ }, dbCon, transact);
return true;
//If any of the inserts fails with an exception the transaction
//will be automatically rolled back.
//You can also return false if the transaction must be rolled back.
});
Remember, this is just an example, in the real world you will have a more complex infrastructure, this only gives you an idea of what you could do.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to insert a column of ones and zeros into a matrix using Octave?
Suppose I have a matrix with a set of integers. I want to use the check rand > 0.5 to prepend a random vector of 1s and 0s to my matrix. How could I do this?
A:
Only a 6x1 matrix but you should get the point.
octave:1> a = [7;8;2;3;6;7];
octave:2> a = [a, rand(size(a))>0.5]
a =
7 0
8 1
2 1
3 0
6 1
7 0
| {
"pile_set_name": "StackExchange"
} |
Q:
Extracting SVG tag/node from file
I have an SVG:
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 17.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" id="Filled_Icons" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px"
y="0px" width="24px" height="24px" viewBox="0 0 24 24" enable-background="new 0 0 24 24" xml:space="preserve">
<path d="M21.499,2.506c-0.827,0-1.5,0.671-1.5,1.5c0,0.827-0.673,1.5-1.5,1.5c-0.827,0-1.5-0.673-1.5-1.5c0-1.653-1.346-3-2.999-3
c-1.654,0-3,1.347-3,3v2H9.5c-0.276,0-0.5,0.223-0.5,0.5v1.09c-3.005,1.217-5,4.15-5,7.41c0,4.411,3.589,8,8,8s7.999-3.589,7.999-8
c0-3.26-1.994-6.193-4.999-7.41v-1.09c0-0.277-0.224-0.5-0.5-0.5H12v-2c0-1.104,0.896-2,2-2c1.102,0,1.999,0.896,1.999,2
c0,1.378,1.122,2.5,2.5,2.5c1.379,0,2.5-1.122,2.5-2.5c0-0.275,0.225-0.5,0.5-0.5c0.276,0,0.5-0.225,0.5-0.5
C21.999,2.73,21.775,2.506,21.499,2.506z M9.141,10.904c-2.262,1.577-2.819,4.699-1.242,6.962C8.056,18.092,8,18.402,7.773,18.561
c-0.087,0.06-0.186,0.089-0.285,0.089c-0.158,0-0.313-0.073-0.41-0.212c-0.917-1.316-1.267-2.908-0.984-4.486
C6.375,12.373,7.255,11,8.569,10.084c0.227-0.158,0.538-0.103,0.696,0.124C9.423,10.434,9.367,10.747,9.141,10.904z"/>
</svg>
I'm trying to extract only the <svg>..</svg> tag using:
$xml = simplexml_load_file( $file );
// (string) $xml->svg
echo print_r($xml,1);
.. but the returned object looks quite different:
SimpleXMLElement Object
(
[@attributes] => Array
(
[version] => 1.1
[id] => Filled_Icons
[x] => 0px
[y] => 0px
[width] => 24px
[height] => 24px
[viewBox] => 0 0 24 24
[enable-background] => new 0 0 24 24
)
[g] => SimpleXMLElement Object
(
[path] => SimpleXMLElement Object
(
[@attributes] => Array
(
[d] => M9.188,2.609c0.255,0.104,0.378,0.396,0.274,0.652C9.358,3.516,9.065,3.639,8.811,3.535 C7.571,3.031,6.031,3.083,4.979,3.665C4.679,3.833,4.322,4.102,4.132,4.496C5.438,5.14,5.905,6.313,5.905,6.958 c0,0.277-0.224,0.5-0.5,0.5c-0.275,0-0.5-0.223-0.5-0.5c0-0.018-0.152-1.763-2.592-1.907C1.812,5.042,1.226,5.292,0.778,5.733 C0.29,6.215,0.01,6.852,0.01,7.479c0,0.015-0.008,0.029-0.009,0.044C0.009,8.449,0.499,9.261,1.316,9.7 c0.647,0.346,1.399,0.389,2.064,0.138c0.374,0.593,0.997,1.051,1.83,1.341c1.334,0.463,3.067,0.419,4.18-0.068 c0.547,0.613,0.603,1.024,0.608,2.39c-0.405,0.001-0.812,0.1-1.183,0.299C7.992,14.242,7.499,15.064,7.499,16 c0,0.914,0.476,1.726,1.271,2.175c0.378,0.214,0.79,0.322,1.203,0.325c-0.225,2.024-1.87,2.381-4.289,2.67 c-1.728,0.207-3.686,0.441-3.686,2.329c0,0.275,0.225,0.5,0.5,0.5h19c0.276,0,0.5-0.225,0.5-0.5c0-1.888-1.957-2.122-3.685-2.329 c-2.419-0.29-4.064-0.646-4.289-2.67c0.413-0.003,0.825-0.111,1.203-0.325c0.796-0.449,1.271-1.262,1.271-2.175 c0-0.936-0.492-1.758-1.316-2.201C14.811,13.602,14.404,13.502,14,13.5c0.006-1.366,0.062-1.779,0.608-2.392 c0.955,0.41,2.43,0.516,3.649,0.229c0.885-0.209,1.594-0.596,2.078-1.132c0.685,0.367,1.498,0.396,2.224,0.057 C23.447,9.847,23.999,8.98,23.999,8c0-0.652-0.252-1.286-0.737-1.767c-0.417-0.406-0.997-0.691-1.558-0.682 c-2.417,0.143-2.569,1.889-2.569,1.906c0,0.277-0.224,0.5-0.5,0.5s-0.5-0.223-0.5-0.5c0-0.669,0.503-1.909,1.919-2.534 c-0.211-0.565-0.239-0.842-0.993-1.259c-1.052-0.582-2.591-0.635-3.831-0.129c-0.256,0.104-0.547-0.019-0.651-0.274 c-0.104-0.256,0.019-0.548,0.274-0.652c0.476-0.192,0.989-0.311,1.511-0.369c-1.118-1.092-2.683-1.74-4.364-1.74 c-1.679,0-3.241,0.646-4.358,1.736C8.174,2.292,8.701,2.411,9.188,2.609z
)
)
)
)
How to extract only the svg tag, so the expected output is:
<svg version="1.1" id="Filled_Icons" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px"
y="0px" width="24px" height="24px" viewBox="0 0 24 24" enable-background="new 0 0 24 24" xml:space="preserve">
<path d="M21.499,2.506c-0.827,0-1.5,0.671-1.5,1.5c0,0.827-0.673,1.5-1.5,1.5c-0.827,0-1.5-0.673-1.5-1.5c0-1.653-1.346-3-2.999-3
c-1.654,0-3,1.347-3,3v2H9.5c-0.276,0-0.5,0.223-0.5,0.5v1.09c-3.005,1.217-5,4.15-5,7.41c0,4.411,3.589,8,8,8s7.999-3.589,7.999-8
c0-3.26-1.994-6.193-4.999-7.41v-1.09c0-0.277-0.224-0.5-0.5-0.5H12v-2c0-1.104,0.896-2,2-2c1.102,0,1.999,0.896,1.999,2
c0,1.378,1.122,2.5,2.5,2.5c1.379,0,2.5-1.122,2.5-2.5c0-0.275,0.225-0.5,0.5-0.5c0.276,0,0.5-0.225,0.5-0.5
C21.999,2.73,21.775,2.506,21.499,2.506z M9.141,10.904c-2.262,1.577-2.819,4.699-1.242,6.962C8.056,18.092,8,18.402,7.773,18.561
c-0.087,0.06-0.186,0.089-0.285,0.089c-0.158,0-0.313-0.073-0.41-0.212c-0.917-1.316-1.267-2.908-0.984-4.486
C6.375,12.373,7.255,11,8.569,10.084c0.227-0.158,0.538-0.103,0.696,0.124C9.423,10.434,9.367,10.747,9.141,10.904z"/>
</svg>
Ofcourse I could just use regex (/(<svg.*?\/svg>)/s) but I'm looking for an elegant approach.
A:
I am really not into php, but here is what a small search lead me to.
In order to remove the doctype associated with your root <svg> element, you would have to import this element inside a new, clean, DOMDocument.
From there, you'll be able to call this DOMDocument's ::saveXML(DOMNode) method, and the original noise will be gone.
$xml = simplexml_load_file($file);
$cleanDom = new DOMDocument();
$node = dom_import_simplexml($xml);
$clone = $cleanDom -> importNode($node, true);
$cleanMarkup = $cleanDom -> saveXML($clone);
| {
"pile_set_name": "StackExchange"
} |
Q:
Uniform convergence of power series with decreasing coefficients
Let $\{a_n\}$ be a monotone decreasing sequence of real numbers, with limit $0$.
Prove that, for each $0<\delta<2$, the power series
$\sum_{n=0}^{\infty} a_n z^n$
converges uniformly on each $\Omega_\delta = \{z : |z|\leq 1 , |z-1|\geq \delta\}$
I have no idea on how to deal with the points in the boundary. Thanks in advance!
A:
Since $a_n \downarrow 0$ (trivially uniformly with respect to $z$) the Dirichlet test implies uniform convergence when $\left| \sum_{k=1}^n z^k\right|$ is uniformly bounded for all $z \in \Omega_\delta$ and for all $n$.
In this case,
$$\left| \sum_{k=1}^n z^k\right| = \left|\frac{z - z^{n+1}}{1-z} \right| \leqslant \frac{|z|(1+ |z|^n)}{|1-z|} \leqslant \frac{2}{\delta}$$
| {
"pile_set_name": "StackExchange"
} |
Q:
kissing in the yichud room
After a jewish couple gets married and they go to the yichud room, is the choson allowed to kiss the kallah?
A:
Nit'e Gavriel, Nisuin 1, chapter 37, is about the Yichud room and he mentions no prohibition on kissing that I see.
A:
The whole point of the yichud room is to provide seclusion of sufficient duration so that the marriage could technically be consummated. Traditionally we don't do so, but you certainly could. And kissing is certainly not a problem.
Interesting side note - some traditions invert the order of the yichud room so that instead of taking place after the chuppah, it takes place after the meal (when everyone has pretty much left). The reasoning is that once there is yichud and we consider them fully married, the wife must cover her hair. By shifting it to the end of the wedding feast it allows her to remain with her hair uncovered during the dancing and the meal.
| {
"pile_set_name": "StackExchange"
} |
Q:
TypeError: Cannot read property 'find' of undefined from sequelize model
I'm trying to use sequelize to find a record in my database, but I'm getting this:
.find({ where: { name: email } })
TypeError: Cannot read property 'find' of undefined
This is my models/index.js
var Sequelize = require('sequelize')
, sequelize = new Sequelize(process.env.MYSQL_DB, process.env.MYSQL_USER, process.env.MYSQL_PASSWORD, {
dialect: "mysql", // or 'sqlite', 'postgres', 'mariadb'
port: 3306, // or 5432 (for postgres)
});
// load models
var models = [
'user',
];
models.forEach(function(model) {
module.exports[model] = sequelize.import(__dirname + '/' + model);
});
And this is my models/user.js
var Sequelize = require("sequelize");
module.exports = function(sequelize, DataTypes) {
var User = sequelize.define("User", {
email: DataTypes.STRING,
password: DataTypes.STRING,
token: DataTypes.STRING
}, {
tableName: 'users'
}
);
return User;
};
This is how I'm importing user model in my files:
var User = require('../models/user').User;
EDIT
I'm trying to use User to create signup with passport local.
I'm calling User in config/passport.js
var LocalStrategy = require('passport-local').Strategy;
var SlackStrategy = require('passport-slack').Strategy;
var User = require('../models').User;
var mysql = require('mysql');
var connection = mysql.createConnection({
host : process.env.MYSQL_HOST,
user : process.env.MYSQL_USER,
password : process.env.MYSQL_PASSWORD,
database : process.env.MYSQL_DB
});
module.exports = function(passport) {
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
console.log("abc serializeUser");
console.log(user);
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
console.log("abc deserializeUser");
User.findById(id).then(function(user){
done(null, user);
}).catch(function(e){
done(e, false);
});
});
passport.use('local-signup', new LocalStrategy(
{
// by default, local strategy uses username and password, we will override with email
usernameField : 'name',
passwordField : 'password',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, email, password, done)
{
process.nextTick(function() {
User
.find({ where: { name: email } })
.then(function(err, user) {
if (!user) {
console.log('No user with the username "john-doe" has been found.');
} else {
console.log('Hello ' + user.name + '!');
console.log('All attributes of john:', user.get());
}
});
}
));
passport.use('slack', new SlackStrategy({
clientID: process.env.SLACK_ID,
clientSecret: process.env.SLACK_SECRET,
scope: "users:write"
},
function(accessToken, refreshToken, profile, done) {
User.findOrCreate({ SlackId: profile.id }, function (err, user) {
return done(err, user);
});
}
));
};
A:
You should get your User model after the import method of sequelize does it's job.
So in your case you should do :
var User = require('../models/index').User;
This should work.
| {
"pile_set_name": "StackExchange"
} |
Q:
Generate a alpha-numeric string based on the neighboring column value in Excel VBA
I have two columns 'Sample_No' and 'Result_Name'. Based on the different result name I want to generate a alphanumeric string 'NL-#' in the 'Sample_No' column.
For example.
Sample_No(To be generated) Result_Name
NL-1 ABC
NL-2 ABC
NL-3 ABC
NL-1 XYZ
NL-2 XYZ
NL-1 PQR
NL-4 ABC
NL-5 ABC
Can this be done in Excel_VBA? Please help me with this! Any help will be appreciated! I tried finding a couple of solutions but couldn't reach anywhere.
Thank You!
A:
You could do this either by formula as suggested by BigBen or use VBA function "Countif".
I assume that the data looks like this:
VBA Code:
Sub GenerateAlphaNumber()
Dim lrow As Long
lrow = Cells(Rows.Count, "B").End(xlUp).Row 'find the lastrow in column B
For i = 2 To lrow 'Loop from row 2 until last row
'Check that cell in column B is not empty. If thats' true, then perform countif
If Cells(i, "B").Value <> "" Then Cells(i, 1).Value = "NL-" & WorksheetFunction.CountIf(Range(Cells(2, "B"), Cells(i, "B")), Cells(i, "B").Value)
Next i
End Sub
| {
"pile_set_name": "StackExchange"
} |
Q:
Excel VBA value remains string format after replacment
I am a total newbie in Excel VBA. I find a script that can help me map data from one worksheet to another, but after the mapping is done, the value format just changed.
I have two sheets, Sheet 1 is the raw data sheet, and Master Data sheet is where the mapping data are stored. Please see the table structures below:
Sheet 1:
Description:
Home Use
Business Owner
Professional
CFO
Secretary
Master Data sheet:
code Description
001 Home Use
002 Business Owner
003 Professional
004 CFO
005 Secretary
As you may see the values in the first column in the Master Data sheet are in text format, ie 001, 002, etc
The code below does the trick to map the data in the first column in Master Data sheet and use them to replace the description in Sheet 1.
Sub mapping()
Dim rng1 As Range, rng2 As Range, cel As Range
Dim StrMyChar As String, StrMyReplace As String
With ActiveWorkbook.Worksheets("Master Data")
Set rng1 = .[B1:B5]
End With
With ActiveWorkbook.Worksheets("Sheet1")
Set rng2 = .[A2:A6]
End With
'loop down list of texts needing replacing
For Each cel In rng1.Cells
StrMyChar = cel.Value
StrMyReplace = cel.Offset(0, -1).Value
'replace text
With rng2
.Replace What:=StrMyChar, Replacement:=StrMyReplace,_
SearchOrder:=xlByColumns, MatchCase:=False
End With
'Next word/text to replace
Next cel
End Sub
After running the code, I find all the 001, 002, etc all got changed to 1, 2, etc.
Is there a way for me to preserve the 001 string format?
Thanks.
A:
Try this below. Note that it still forces the replacement format, so that the values in the cells are still technically numbers. This is a drawback of Excel's replace functionality--its just how it works because it wants to assume that everything is numeric.
Note that you also had the rng1 set to the wrong range, it should be b2-b6 not b1-b5
With ActiveWorkbook.Worksheets("Master Data")
Set rng1 = .[B2:B6] ' Note that you had the wrong range here
End With
'this will force two leading zeros if necessary call it before the replace
Application.ReplaceFormat.NumberFormat = "00#"
'then add ReplaceFormat:=true to your replace string
.Replace What:=StrMyChar, Replacement:=StrMyReplace, _
SearchOrder:=xlByColumns, MatchCase:=False, ReplaceFormat:=True
Unfortunately ReplaceFormat.NumberFormat = "@" does not work with Excel's built in replace. The better option if we don't want to mess with Excel's built in replace method, we can do it ourselves, quick and easy:
Option Compare Text 'use this for case insensitive comparisons
Sub Mapping()
Dim rngLookup As Range
Set rngLookup = ActiveWorkbook.Worksheets("Master Data").[B2:B6]
Dim rngReplace As Range
Set rngReplace = ActiveWorkbook.Worksheets("Sheet1").[A2:A6]
Dim cell As Range, cellLookup As Range
For Each cell In rngReplace
Dim val As String
val = cell.Value
For Each cellLookup In rngLookup
If cellLookup.Value = val Then
cell.NumberFormat = "@"
cell.Value = cellLookup.Offset(0, -1).Value
Exit For
End If
Next
Next
End Sub
This code loops through each line in your Sheet 1, and then searches for the proper entry in the master sheet, but sets the Number Format to "@" before it copies it. You should be good.
If you are going to have to work with a LOT of cells, consider turning Application.ScreenUpdating off before running the procedure, and back on after. This will speed things up as it doesn't have to worry about rendering to the screen while it is working.
Another, non VBA idea that keeps both the original value and adds data next to it:
You could also get this information (albeit in a different column) using a Vlookup without any VBA code. If you switch your Descriptions to Column A and your Codes to Column B on the Master Sheet, you can then go to Sheet1, highlight the cells in Column B and type this formula:
=VLOOKUP(A2:A6,'Master Data'!A2:B6,2,FALSE)
Do not hit enter, but rather hit Control+Shift+Enter. This creates what is called an Array formula. This doesn't do a replace for you, but offers the data in the column next to it. Just throwing this out there as some extra information if you needed another way of getting it.
You could also set the formula for a cell in VBA using the Range.Formula property and setting it to the vlookup formula above
| {
"pile_set_name": "StackExchange"
} |
Q:
Cutting a subset from middle of NumPy array
I work with raster images and the module rasterio to imprt them as numpy arrays. I would like to cut a portion of size (1000, 1000) out of the middle of each (to avoid the out-of-bound masks of the image).
image = np.random.random_sample((2000, 2000))
s = image.shape
mid = [round(x / 2) for x in s] # middle point of both axes
margins = [[y + x for y in [-500, 500]] for x in mid] # 1000 range around every middle point
The result is a list of 2 lists, for the cut range on each axis. But this is where I stump: range() doesn't accept lists, and I'm attempting the following brute force method:
cut_image = image[range(margins[0][0], margins[0][1]), range(margins[1][0], margins[1][1])]
However:
cut_image.shape
## (1000,)
Slicing an array loses dimension information which is exactly what I don't want.
Consider me confused.
Looking for a more tasteful solution.
A:
As the other answer points it out, you're not really slicing your array, but using indexing on it.
If you want to slice your array (and you're right, that's more elegant than using list of indices) , you'll be happier with slices. That objects represents the start:end:step syntax.
In your case,
import numpy as np
WND = 50
image = np.random.random_sample((200, 300))
s = image.shape
mid = [round(x / 2) for x in s] # middle point of both axes
margins = [[y + x for y in [-WND, WND]] for x in mid] # 1000 range around every middle point
# array[slice(start, end)] -> array[start:end]
x_slice = slice(margins[0][0], margins[0][1])
y_slice = slice(margins[1][0], margins[1][1])
print(x_slice, y_slice)
# slice(50, 150, None) slice(100, 200, None)
cut_image = image[x_slice, y_slice]
print(cut_image.shape)
# (100,100)
Indexing ?
You might wonder what was happening in your question that resulted in only 1000 elements instead of the expected 1000*1000.
Here is a simpler example of indexing with lists on different dimensions
# n and n2 have identical values
n = a[[i0, i1, i2],[j0, j1, j2]]
n2 = np.array([a[i0, j0], a[i1, j1], a[i2, j2]]
This being clarified, you'll understand that instead of taking a block matrix, your code only returns the diagonal coefficients of that block matrix :)
| {
"pile_set_name": "StackExchange"
} |
Q:
Replace thermostat with rasberry pi and Solid state relay
I want to replace my thermostat with raspberry pi board. I have already connected solid state relay to rasberry pi and it works just fine. The only part left to do is to connect solid state relay to the thermostat. I have an idea how to do that but before actually connecting anything I want to ask your advice if I am doing it right.
My solid state relay looks like this
(source: asia.ru)
And the diagram on the thermostat looks like this
I have 4 cables
Blue - N
Red - L
Call - yellow
and ground yellow/red
So I think I should connect Red(L - Red) to SSR contact 1(ac in) and CALL (yellow) to the SSR contact 2 (Load). Is that the right way to do ?
P.S. Its in UK so voltage is 220V therefore I want to be extremely careful
A:
connect Red (L - Red) to SSR contact 1 (ac in) and CALL (yellow) to the SSR contact 2 (Load)?
Yes, that seems correct. You should make safe the neutral wire and prevent it from any possibility of coming into contact with any other wiring, metal parts or the outside.
It's in the UK, so voltage is 220V
The EU standard is 230 V ± 10% but in the UK you'll typically measure 240 V which is within this range and is what substations for UK domestic supplies were previously standardised on. Other EU countries had previously standardised on 220 V, not the UK.
I want to be extremely careful
That means going to the consumer-unit (fuse-box) and switching off the circuit marked "boiler" or "heating", then checking your thermostat connections with a safe voltage tester (preferably non-contact) before rewiring them. keep the Pi well away from 240 V wires, ideally in a separate, well-insulated box.
| {
"pile_set_name": "StackExchange"
} |
Q:
Rename Multiple Variables in Multiple Data sets in ONE SAS Library
Is there a way to the rename the same variables in multiple tables in ONE SAS library, where there are also other tables that do not have that table? All of the tables that have variables that need renamed have the same two characters that start the table name. I've seen macros to rename multiple variables in one dataset but not to rename multiple variables in multiple datasets. Any help as to if this is possible would be appreciated!
A:
No need for macros. You could pull something together using call execute and proc datasets. E.g.
data _null_;
set sashelp.vtable end = eof;
/*Replace xx with your two-letter dataset prefix*/
where libname = upcase('mylib') and memname eq: upcase('xx') and memtype = 'DATA';
if _n_ = 1 then call execute('proc datasets lib = mylib;');
call execute(catx(' ','modify',memname,'; rename var1 = newvar1 var2 = newvar2; run;'));
if eof then call execute('quit;');
run;
This should run more or less instantaneously as it only needs to modify the metadata.
| {
"pile_set_name": "StackExchange"
} |
Q:
iOS how to detect programmatically when top view controller is popped?
Suppose I have a nav controller stack with 2 view controllers: VC2 is on top and VC1 is underneath. Is there code I can include in VC1 that will detect that VC2 has just been popped off the stack?
Since I'm trying to detect the popping of VC2 from within the code for VC1 it seems that something like viewWillAppear or viewDidAppear won't work, because those methods fire every time VC1 is displayed, including when it is first pushed on the stack.
EDIT: it seems I was not very clear with my original question. Here's what I'm trying to do: determine when VC1 is being shown due to VC2 being popped off the top of the stack. Here's what I'm NOT trying to do: determine when VC1 is being shown due to being pushed onto the top of the stack. I need some way that will detect the first action but NOT the second action.
Note: I don't particularly care about VC2, it can be any number of other VCs that get popped off the stack, what I do care about is when VC1 becomes the top of the stack again due to some other VC begin popped off the top.
A:
iOS 5 introduced two new methods to handle exactly this type of situation. What you're looking for is -[UIViewController isMovingToParentViewController]. From the docs:
isMovingToParentViewController
Returns a Boolean value that indicates
that the view controller is in the process of being added to a parent.
- (BOOL)isMovingToParentViewController
Return Value
YES if the view controller is appearing because it was added as a child of a container
view controller, otherwise NO.
Discussion
This method returns YES only when called from inside the
following methods:
-viewWillAppear:
-viewDidAppear:
In your case you could implement -viewWillAppear: like so:
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
if (self.isMovingToParentViewController == NO)
{
// we're already on the navigation stack
// another controller must have been popped off
}
}
EDIT: There's a subtle semantic difference to consider here—are you interested in the fact that VC2 in particular popped off the stack, or do you want to be notified each time VC1 is revealed as a result of any controller popping? In the former case, delegation is a better solution. A straight-up weak reference to VC1 could also work if you never intend on reusing VC2.
EDIT 2: I made the example more explicit by inverting the logic and not returning early.
A:
isMovingTo/FromParentViewController won't work for pushing and popping into a navigation controller stack.
Here's a reliable way to do it (without using the delegate), but it's probably iOS 7+ only.
UIViewController *fromViewController = [[[self navigationController] transitionCoordinator] viewControllerForKey:UITransitionContextFromViewControllerKey];
if ([[self.navigationController viewControllers] containsObject:fromViewController])
{
//we're being pushed onto the nav controller stack. Make sure to fetch data.
} else {
//Something is being popped and we are being revealed
}
In my case, using the delegate would mean having the view controllers' behavior be more tightly coupled with the delegate that owns the nav stack, and I wanted a more standalone solution. This works.
A:
One way you could approach this would be to declare a delegate protocol for VC2 something like this:
in VC1.h
@interface VC1 : UIViewController <VC2Delegate> {
...
}
in VC1.m
-(void)showVC2 {
VC2 *vc2 = [[VC2 alloc] init];
vc2.delegate = self;
[self.navigationController pushViewController:vc2 animated:YES];
}
-(void)VC2DidPop {
// Do whatever in response to VC2 being popped off the nav controller
}
in VC2.h
@protocol VC2Delegate <NSObject>
-(void)VC2DidPop;
@end
@interface VC2 : UIViewController {
id<VC2Delegate> delegate;
}
@property (nonatomic, assign) id delegate;
...
@end
VC2.m
-(void)viewDidUnload {
[super viewDidUnload];
[self.delegate VC2DidPop];
}
There's a good article on the basics of protocols and delegates here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Racket - define one character with token-char
I am working on a project for a class and we are tasked with writing a scanner for numbers, symbols, comments, arithmetic operators, parenthesis, and EOF in both Python and Racket. I am working on the racket version and I have written the following line to define one or more character as a symbol:
[(any-char) (token-CHAR (string->character lexeme))]
I have the following line to define on or more digits as a number:
[(:+ digit) (token-NUM (string->number lexeme))]
I am very new to Racket, this is my third program, so I am not exactly sure how to approach this, so any suggestions are greatly appreciated. I have scoured the Racket documentation, but I wasn't able to find what I was looking for.
Thanks!
A:
Here is a minimal getting-started example - heavily commented.
#lang racket
;;; IMPORT
;; Import the lexer tools
(require parser-tools/yacc
parser-tools/lex
(prefix-in : parser-tools/lex-sre) ; names from lex-sre are prefixed with :
; to avoid name collisions
syntax/readerr)
;;; REGULAR EXPRESSIONS
;; Names for regular expressions matching letters and digits.
;; Note that :or are prefixed with a : due to (prefix-in : ...) above
(define-lex-abbrevs
[letter (:or (:/ "a" "z") (:/ #\A #\Z) )]
[digit (:/ #\0 #\9)])
;;; TOKENS
;; Tokens such as numbers (and identifiers and strings) carry a value
;; In the example only the NUMBER token is used, but you may need more.
(define-tokens value-tokens (NUMBER IDENTIFIER STRING))
;; Tokens that don't carry a value.
(define-empty-tokens op-tokens (newline := = < > + - * / ^ EOF))
;;; LEXER
;; Here the lexer (aka the scanner) is defined.
;; The construct lexer-src-pos evaluates to a function which scans an input port
;; returning one position-token at a time.
;; A position token contains besides the actual token also source location information
;; (i.e. you can see where in the file the token was read)
(define lex
(lexer-src-pos
[(eof) ; input: eof of file
'EOF] ; output: the symbol EOF
[(:or #\tab #\space #\newline) ; input: whitespace
(return-without-pos (lex input-port))] ; output: the next token
; (i.e. skip the whitespace)
[#\newline ; input: newline
(token-newline)] ; ouput: a newline-token
; ; note: (token-newline) returns 'newline
[(:or ":=" "+" "-" "*" "/" "^" "<" ">" "=") ; input: an operator
(string->symbol lexeme)] ; output: corresponding symbol
[(:+ digit) ; input: digits
(token-NUMBER (string->number lexeme))])) ; outout: a NUMBER token whose value is
; ; the number
; ; note: (token-value token)
; returns the number
;;; TEST
(define input (open-input-string "123+456"))
(lex input) ; (position-token (token 'NUMBER 123) (position 1 #f #f) (position 4 #f #f))
(lex input) ; (position-token '+ (position 4 #f #f) (position 5 #f #f))
(lex input) ; (position-token (token 'NUMBER 456) (position 5 #f #f) (position 8 #f #f))
(lex input) ; (position-token 'EOF (position 8 #f #f) (position 8 #f #f))
;; Let's make it a little easier to play with the lexer.
(define (string->tokens s)
(port->tokens (open-input-string s)))
(define (port->tokens in)
(define token (lex in))
(if (eq? (position-token-token token) 'EOF)
'()
(cons token (port->tokens in))))
(map position-token-token (string->tokens "123*45/3")) ; strip positions
; Output:
; (list (token 'NUMBER 123)
; '*
; (token 'NUMBER 45)
; '/
; (token 'NUMBER 3))
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I install translation on vuetify?
Where is the script to install translation on the vuetify?
I check this : https://vuetifyjs.com/en/customization/internationalization, but i don't find it
I find some reference, it like this : npm install vue-i18n
and some reference like this : vue create vue-internationalization
and if I see on the documentation, it seems that there are 2 options for doing that
which option is the best and how to do it?
A:
Its not necessary to add a new library vue-i18n for internationalization, you can add a plugin in vuetify to get it done.
vue-i18n can be used if you need granule control and additional features over basic options
Its pretty straight forward, just create a new file in this path
src/plugins/vuetify.js and set up the configuration with atleast 2
languages and you can update the current language using
this.$vuetify.lang.current = "selected language"
| {
"pile_set_name": "StackExchange"
} |
Q:
Convert number to degrees in ngStyle using Angular 8
{{result.percentage}} gives me a number from 0 to 100.
If I get 25, I want it to convert to -45 degrees or if I get 0, I want it to convert to -90 degrees or if I get 75, then it gets converted to 45 degrees.
[ngStyle]="{'transform': 'rotate(' + result.percentage + 'deg)'}"
Current, this gives an output style="transform: rotate(25deg);" which I want to convert to style="transform: rotate(-45deg);"
How do I go about this?
FYI, I need to bind the data of this speedometer: https://jsfiddle.net/bcgzrdfL/
A:
Looks like you need a math whiz, not a framework expert, however I'm going to take a shot at an answer:
[ngStyle]="{'transform': 'rotate(' + ((result.percentage * 1.8) - 90) + 'deg)'}"
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to get the full page html when using React/Enzyme/Jest with Nextjs?
I've got a React component that looks like:
import React from 'react';
import Head from 'next/head';
export default class extends React.Component {
static defaultProps = {
language: 'en',
country: 'us'
};
...
render () {
const language = this.props.language || 'en';
const country = this.props.country || 'us';
return (
<div className="edf-header">
<div className="desktop-header"></div>
<div className="mobile-header"></div>
<Head>
<script dangerouslySetInnerHTML={{__html: `
var secure = "//local-www.hjjkashdkjfh.com";
var perfConfig = {
LOCALE: '${language}_${country}',
I want to confirm, via a test, that the perfConfig is built correctly. I'm testing it with:
import React from 'react';
import Enzyme from 'enzyme';
import Foo from '../../components/Foo';
import Adapter from 'enzyme-adapter-react-16';
import enzymify from 'expect-enzyme';
import Head from 'next/head';
const {mount, shallow, render} = Enzyme;
Enzyme.configure({adapter: new Adapter()});
expect.extend(enzymify());
...
it('renders correct nsgConfig', () => {
const foo = render(<Foo country='ca' language='fr'/>);
console.dir(foo.html());
expect(foo.find('Head')).toExist();
expect(foo.html().indexOf("LOCALE: 'fr_ca'")).toBeGreaterThan(0);
});
The problem is that the html doesn't contain a head tag. The html has the divs but that's it.
How do I get Next/Enzyme to work together here to render the full page? Tried shallow and mount with no luck.
A:
The Head component adds its children to the actual once the page is mounted. You would have to render the full page starting from the _document component. In my tests mount seems to be using a "div" tag where it inserts the component and complains if you actually mount a "head" component so I'm not sure this is even possible.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the best sort algorithm for continuously (NOT FIXED) input of random numbers?
Suppose I have a system that receives one by one as an input continuously random numbers all the time (0,5,2,10,6,20......) ,
My purpose is to sort them with the best performance.
So the output size will be increased after each iteration and the input is sequential .
I thought to use either insertion sort or BST , but I don't sure what is better for this issue ,as i know insertion sort is O(n-n^2) and BST insertion is O(log(n))
Please , any suggestions ?
A:
I think that using some BST that promises O(log n) performacne (like AVL, black-red, etc.) is your best option.
Printing out the current data is done using an in-order traversal of the tree.
A:
If you need to sort every time an element is added, this is not a sorting problem but an insertion problem. Any sorting algorithm will be overkill.
If your data must be stored in an array, you can't spare shifting the elements and the solution is Ω(N). This is efficiently achieved by straight insertion (O(N)). (Dichotomic search followed by insertion will take less comparisons but it is not sure that you will notice a difference.)
If you have more freedom, a BST is indeed a more efficient solution. If you need absolute guarantee on the worst-case cost (O(Log N)), the BST needs to be balanced (so AVL, Red-Black... up to your taste). If your data is sufficiently random, this might be unnecessary.
If your data has special properties (for example small discrete range), ad-hoc solutions can do. In the given example, a simple counting histogram will achieve O(1) update time.
| {
"pile_set_name": "StackExchange"
} |
Q:
Very slow guards in my monadic random implementation (haskell)
I was tried to write one random number generator implementation, based on number class. I also add there Monad and MonadPlus instance.
What mean "MonadPlus" and why I add this instance? Because of I want to use guards like here:
-- test.hs --
import RandomMonad
import Control.Monad
import System.Random
x = Rand (randomR (1 ::Integer, 3)) ::Rand StdGen Integer
y = do
a <-x
guard (a /=2)
guard (a /=1)
return a
here comes RandomMonad.hs file contents:
-- RandomMonad.hs --
module RandomMonad where
import Control.Monad
import System.Random
import Data.List
data RandomGen g => Rand g a = Rand (g ->(a,g)) | RandZero
instance (Show g, RandomGen g) => Monad (Rand g)
where
return x = Rand (\g ->(x,g))
(RandZero)>>= _ = RandZero
(Rand argTransformer)>>=(parametricRandom) = Rand funTransformer
where
funTransformer g | isZero x = funTransformer g1
| otherwise = (getRandom x g1,getGen x g1)
where
x = parametricRandom val
(val,g1) = argTransformer g
isZero RandZero = True
isZero _ = False
instance (Show g, RandomGen g) => MonadPlus (Rand g)
where
mzero = RandZero
RandZero `mplus` x = x
x `mplus` RandZero = x
x `mplus` y = x
getRandom :: RandomGen g => Rand g a ->g ->a
getRandom (Rand f) g = (fst (f g))
getGen :: RandomGen g => Rand g a ->g -> g
getGen (Rand f) g = snd (f g)
when I run ghci interpreter, and give following command
getRandom y (mkStdGen 2000000000)
I can see memory overflow on my computer (1G). It's not expected, and if I delete one guard, it works very fast. Why in this case it works too slow?
What I do wrong?
A:
Your definition of (>>=) is certainly wrong, but I cannot point to where because it is so complicated! Instead I will explain why it cannot be defined correctly using an example. Consider:
Rand (\g -> (42,g)) >>= const mzero
We need to get that 42 out, so we need a g. The place to get the g is from the return value of the bind, so the answer is definitely:
Rand (\g -> ...)
For some ..., responsible for returning a (b,g) pair. Now that we have 42, we can evaluate const mzero 42 and find that we have RandZero But where are we going to get that b? It is nowhere (in fact, so nowhere in this example that it can be any type whatsoever, since the type of the expression is forall b. Rand b).
What is the purpose of RandZero for your monad? Are you just trying to make StateT g Maybe? My guess is that you are. In that case, you might have more luck trying to implement this type:
newtype Rand g a = Rand (g -> Maybe (a, g))
| {
"pile_set_name": "StackExchange"
} |
Q:
selenium doesn't set downloaddir in FirefoxProfile
i want to auto download files and save them in directory, everything is done but firefox stills save files in User download folder e.g. C:\users\root\Downloads
the function in class PyWebBot
@staticmethod
def FirefoxProfile(path, handlers):
from selenium import webdriver
profile = webdriver.FirefoxProfile()
profile.set_preference("browser.download.folderList",1)
profile.set_preference("browser.download.manager.showWhenStarting",False)
profile.set_preference("browser.download.dir", path)
profile.set_preference("browser.download.downloadDir", path)
profile.set_preference("browser.download.defaultFolder", path)
profile.set_preference("browser.helperApps.alwaysAsk.force", False)
profile.set_preference("browser.helperApps.neverAsk.saveToDisk", handlers)
profile.set_preference("pdfjs.disabled", True)
profile.update_preferences()
return profile
then
def setUp(self):
self.profile = PyWebBot.FirefoxProfile(config['downloads'], config['handlers'])
self.driver = webdriver.Firefox(self.profile)
...
...
config:
config['downloads'] = 'Q:/web2py_src/web2py/applications/internet2letter/private/testing/selenium/downloads'
config['handlers'] = 'application/pdf'
A:
There are couple methods to a solution for this problem,
Make sure that the path is valid. Use something like, os.path.exists or os.isfile
When the Firefox launches with the selenium driver, navigate to about:config and check the look up browser.download.dir, to make sure there was a change.
Finally, make sure that profile.set_preference (profile.set_preference("browser.download.folderList",2) has 2 as a second argument, since 0 means to download to the desktop, 1 means to download to the default "Downloads" directory, 2 means to use the directory you specify in "browser.download.dir"
Make sure your path is noted with back slashes '\' not forward
slashes '/'
| {
"pile_set_name": "StackExchange"
} |
Q:
Why do I get "Can't locate Sub/Identify.pm in @INC" when I use the DateTime module even though I installed the perl-DateTime RPM?
I am trying to use the module DateTime in CentOS so I installed it like this:
yum install perl-DateTime
and then added use DateTime to my script, but I get this error:
Can't locate Sub/Identify.pm in @INC (@INC contains:
/root/perl5/lib/perl5/5.16.3/x86_64-linux-thread-multi
/root/perl5/lib/perl5/5.16.3
/root/perl5/lib/perl5/x86_64-linux-thread-multi /root/perl5/lib/perl5
/usr/local/lib64/perl5 /usr/local/share/perl5
/usr/lib64/perl5/vendor_perl /usr/share/perl5/vendor_perl
/usr/lib64/perl5 /usr/share/perl5 .) at
/root/perl5/lib/perl5/namespace/autoclean.pm line 200. Compilation
failed in require at /root/perl5/lib/perl5/DateTime/Locale.pm line 11.
BEGIN failed--compilation aborted at
/root/perl5/lib/perl5/DateTime/Locale.pm line 11. Compilation failed
in require at /usr/lib64/perl5/vendor_perl/DateTime.pm line 45. BEGIN
failed--compilation aborted at
/usr/lib64/perl5/vendor_perl/DateTime.pm line 45. Compilation failed
in require at myscript.pl line 8. BEGIN failed--compilation aborted
at myscript.pl line 8.
I have no idea what's going on. I already installed several packages through the CPAN. This is the first time I've tried with yum install and it doesn't work. Any ideas?
A:
TL;DR
This is why it's a bad idea to mix modules installed via a package manager and via CPAN.
It looks like you installed DateTime with yum, but DateTime::Locale with CPAN. You can see this by following the dependency chain in your error message:
/root/perl5/lib/perl5/namespace/autoclean.pm --> CPAN
/root/perl5/lib/perl5/DateTime/Locale.pm --> CPAN
/usr/lib64/perl5/vendor_perl/DateTime.pm --> yum
The newest version of namespace::autoclean depends on Sub::Identify, which seems to be missing from @INC.
So did yum install a package with missing dependencies? Nope, it installed an older version of DateTime::Locale, when namespace::autoclean wasn't a dependency:
$ cpan -D DateTime::Locale | grep -oP '[\d.]+(?=\s+up)' # newest version
1.14
$ yum info perl-DateTime-Locale | grep -oP 'Version\D+\K.+' # yum version
0.45
$ rpm -q --requires perl-DateTime-Locale | grep autoclean
$
But since you put /root/perl5/lib/perl5 before the system perl directories in @INC, you're loading the version installed by CPAN, which does need namespace::autoclean and Sub::Identify. Of course, yum has no way to know that.
I'm not sure why Sub::Identify is missing...you may have deleted it, or it may simply be installed outside of @INC. You could try to re-install it with CPAN, but it would be better to:
remove /root/perl5/* from @INC and only install modules in the system perl with yum
use perlbrew or plenv to create your own local installation of perl and install modules with cpan
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get Image Resource Id for images from String ArrayList
In my activity i'm getting list of images that should be display in a slideshow,
now Source for list of images that should display comes from JSON so I have parse json and got list of images that i need to show from Appfolder/app_content
I have Class:
MainActivity:
public class MainActivity extends Activity {
ArrayList<String> imageSlideList = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Get Intent- Extra
Intent intent = getIntent();
String swpImgSImgs = intent.getStringExtra("swpImgS");
try {
JSONArray array = new JSONArray(swpImgSImgs);
for (int i = 0 ; i< array.length(); i++){
String imageList = array.getString(i);
FileOperation fo= new FileOperation();
File dir=fo.createFileManagerInsidePackage(AppContext.getAppContext());
String imagePath = dir+"/"+imageList;
imageSlideList.add(imagePath);
}
} catch (JSONException e) {
e.printStackTrace();
}
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return false;
}
}
Adapter:
public class SwipingImageSlidesAdapter extends PagerAdapter {
Context context;
//I need to use files that are in json
private int[] GalImages = new int[] {
R.drawable.camera,
R.drawable.camera
};
SwipingImageSlidesAdapter(Context context){
this.context=context;
}
@Override
public int getCount() {
return GalImages.length;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(R.dimen.activity_horizontal_margin);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setImageResource(GalImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
Now what changes do i have to make to display images from Application-folder(App/app_content) instead of using R.id.imageName using that ArrayList that I created imageSlideList in MainActivity?
A:
Pass the list of path to the constructor of the adapter.
ImageAdapter adapter = new ImageAdapter(this,imageSlideList)
Then in Adapter
ArrayList<String> mList;
SwipingImageSlidesAdapter(Context context,ArrayList<String> list){
this.context=context;
mList = list;
}
Then in getView
Bitmap b = BitmapFactory.decodeFile(mlist.get(position));
imageView.setImageBitmap(b);
public static Bitmap decodeFile (String pathName)
Decode a file path into a bitmap. If the specified file name is null, or cannot be decoded into a bitmap, the function returns null.
Parameters
pathName complete path name for the file to be decoded.
Returns
the resulting decoded bitmap, or null if it could not be decoded.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I access the enumeration OracleDbType?
My C# (.NET 4.0) application is calling a stored procedure in a PL/SQL database. I have added the namespace System.Data.OracleClient, and added the parameters however whenever I run it, I get an exception saying parameters don't match.
I believe the issue is because my parameters have been of type DbType.String or OracleType.VarChar. Reading online revealed that people use another enumeration called OracleDbType (eg. OracleDbType.VarChar2).
So, how can I access this enumeration?
OracleParameter returnParam = new OracleParameter("result", DbType.Xml);
returnParam.Direction = ParameterDirection.ReturnValue;
objCmd.Parameters.Add(returnParam);
OracleParameter param1 = new OracleParameter("pivequivalentinstrument", DbType.String);
param1.Direction = ParameterDirection.Input;
param1.Value = EquivalentInstrKey;
objCmd.Parameters.Add(param1);
A:
The OracleDbType is ODP: Oracle.DataAccess.Client not the deprecated System.Data.OracleClient, try using ODP and it shall be there.
| {
"pile_set_name": "StackExchange"
} |
Q:
Compare if a date is less than 24 hours before
I am trying to compare two calendars in java to decide if one of them is >= 24 hours ago. I am unsure on the best approach to accomplish this.
//get todays date
Date today = new Date();
Calendar currentDate = Calendar.getInstance();
currentDate.setTime(today);
//get last update date
Date lastUpdate = profile.getDateLastUpdated().get(owner);
Calendar lastUpdatedCalendar = Calendar.getInstance();
lastUpdatedCalendar(lastUpdate);
//compare that last hotted was < 24 hrs ago from today?
A:
tl;dr
Instant now = Instant.now();
Boolean isWithinPrior24Hours =
( ! yourJUDate.toInstant().isBefore( now.minus( 24 , ChronoUnit.HOURS) ) )
&&
( yourJUDate.toInstant().isBefore( now )
) ;
Details
The old date-time classes (java.util.Date/.Calendar, java.text.SimpleDateFormat, etc.) have proven to be be confusing and flawed. Avoid them.
For Java 8 and later, use java.time framework built into Java. For earlier Java, add the Joda-Time framework to your project.
You can easily convert between a java.util.Date and either framework.
java.time
The java.time framework built into Java 8 and later supplants the troublesome old java.util.Date/.Calendar classes. The new classes are inspired by the highly successful Joda-Time framework, intended as its successor, similar in concept but re-architected. Defined by JSR 310. Extended by the ThreeTen-Extra project. See the Tutorial.
The Instant class represents a moment on the timeline in UTC. If you meant to ask for literally 24 hours rather than "a day", then Instant is all we need.
Instant then = yourJUDate.toInstant();
Instant now = Instant.now();
Instant twentyFourHoursEarlier = now.minus( 24 , ChronoUnit.HOURS );
// Is that moment (a) not before 24 hours ago, AND (b) before now (not in the future)?
Boolean within24Hours = ( ! then.isBefore( twentyFourHoursEarlier ) ) && then.isBefore( now ) ;
If you meant "a day" rather than 24 hours, then we need to consider time zone. A day is determined locally, within a time zone. Daylight Saving Time (DST) and other anomalies mean a day is not always 24 hours long.
Instant then = yourJUDate.toInstant();
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime now = ZonedDateTime.now( zoneId );
ZonedDateTime oneDayAgo = now.minusDays( 1 );
Boolean within24Hours = ( ! then.isBefore( oneDayAgo ) ) && then.isBefore( now ) ;
Another approach would use the Interval class found in the ThreeTen-Extra project. That class represents a pair of Instant objects. The class offers methods such as contains to perform comparisons.
Joda-Time
The Joda-Time library works in a similar fashion to java.time, having been its inspiration.
DateTime dateTime = new DateTime( yourDate ); // Convert java.util.Date to Joda-Time DateTime.
DateTime yesterday = DateTime.now().minusDays(1);
boolean isBeforeYesterday = dateTime.isBefore( yesterday );
Or, in one line:
boolean isBeforeYesterday = new DateTime( yourDate).isBefore( DateTime.now().minusDays(1) );
A:
you could use Date.getTime(), here's an example:
public final static long MILLIS_PER_DAY = 24 * 60 * 60 * 1000L;
public static void main(String args[]) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = sdf.parse("2009-12-31");
Date date2 = sdf.parse("2010-01-31");
boolean moreThanDay = Math.abs(date1.getTime() - date2.getTime()) > MILLIS_PER_DAY;
System.out.println(moreThanDay);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Type classes vs algebraic data types?
I frequently start thinking about a problem in terms of type classes to be defined, and realize when I start coding that I don't need type classes and can solve my problem with algebraic data types instead, which seems more straightforward. As a result, I am wondering when type classes are necessary.
As I understand them, type classes are a way to say that certain functions exist for certain types. For example, when a type MyType is an instance of Monoid, then I can use the functions mempty :: MyType and mappend :: MyType -> MyType -> MyType, such that the monoid laws hold.
We could acheive the same with algebraic data types, by defining Monoid as a type rather than a typeclass:
data Monoid a = Monoid { mempty :: a
, mappend :: a -> a -> a}
and then say that a type MyType is a monoid by defining a new value of type Monoid MyType (which with typeclasses is done by declaring it an instance):
monoidMyType :: Monoid MyType
monoidMyType = Monoid { mempty = ...
, mappend = \a b -> ... }
Then, we can write functions that operate on monoids like:
dummyFun :: Monoid a -> a -> a
dummyFun m x = mempty m x
And use those functions by explicitly passing the appropriate "monoid value":
result = dummyFun monoidMyType valueOfMyType
The equivalent last two steps would happen very similarly with typeclasses:
dummyFun :: (Monoid a) => a -> a
dummyFun x = mempty x
result = dummyFun valueOfMyType
The only substantial difference that I see is that with algebraic data types, the monoid value must be passed explicitly when we call the function dummyFun. Although it is a bit more practical not to have to pass it explicitly, it doesn't look to me like a major obstacle.
In fact, I see an advantage that algebraic data types have over type classes: you can relate together types accross different functions:
data Bla a b = Bla {f1 :: a -> b, f2 :: b -> a, ...}
Doing this with typeclasses would (i believe) require using the multiple parameter type classes extension.
Is there a reason to use type classes that I'm not seeing here?
When designing software, can you interchangeably chose to use type classes or algebraic data types, or are there situations where you can't do without type classes?
A:
You just invented type classes! A class is a dictionary of functions. During compilation, code like
class Monoid a where
mempty :: a
mappend :: a -> a -> a
instance Monoid [a] where
mempty = []
mappend = (++)
mconcat :: Monoid a => [a] -> a
mconcat = foldr mappend
main = print $ mconcat ["foo", "bar"]
is translated into explicit dictionary-passing style.
data Monoid a = Monoid { mempty :: a, mappend :: a -> a -> a }
list_monoid = Monoid [] (++)
mconcat :: Monoid a -> [a] -> a
mconcat monoid = foldr (mappend monoid)
main = print $ mconcat list_monoid ["foo", "bar"]
That translation is exactly the most important difference between type classes and dictionaries: classes are implicit. You don't have to explicitly pass the monoid variable around - the compiler takes care of the plumbing for you. It would be especially tedious to build composed instances like Ord a => Ord [a] by hand.
There's one other key difference between classes and dictionaries, and that's coherence. Basically, there's always at most one "best" instance to satisfy a given constraint, that instance is global and unique, and you can't override it. With dictionary-passing style, on the other hand, the function will just use whatever dictionary you passed in and there are no guarantees of uniqueness. This is sometimes good and sometimes bad.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does order matter when catching exceptions?
I had to answer this question with some code:
Suppose I wrote the following method specification:
public void manipulateData ( ) throws java.sql.SQLException, java.sql.SQLDataException
You are writing code for a database
program that will use this method and you want to handle each
specifically. What should the try/catch clause look like?
You can use no-ops-- empty blocks {}--for the catch clause contents.
We are only interested in the syntax and structure of the statements here.
I answered with this:
try {
} catch(java.sql.SQLException e) {
}
catch(java.sql.SQLDataException e) {
}
He did not accept the answer for this reason:
"Your catch clauses are in the wrong order. Can you explain why the order matters?"
Is he correct in his answer?
A:
Yes he is correct. As you can see in the Javadoc, SQLDataException is a subclass of SQLException. Therefore, your answer is wrong, since it would create a block of unreachable code in the second catch.
In Java, this code would not even compile. In other languages (e.g. python) such code would create a subtle bug, because SQLDataException would actually be caught in the first block, and not in the second one (as would be the case if it was not a subclass).
Had you answered catch(java.sql.SQLException | java.sql.SQLDataException e) { }, it would still be incorrect, since the question asks to handle each exception specifically.
The correct answer is in Grijesh's answer
A:
In Java you have to put the least inclusive Exception first. The next exceptions must be more inclusive (when they are related).
For instance: if you put the most inclusive of all (Exception) first, the next ones will never be called. Code like this:
try {
System.out.println("Trying to prove a point");
throw new java.sql.SqlDataException("Where will I show up?");
}catch(Exception e){
System.out.println("First catch");
} catch(java.sql.SQLException e) {
System.out.println("Second catch");
}
catch(java.sql.SQLDataException e) {
System.out.println("Third catch");
}
will never print the message you'd expect it to print.
A:
Order matter when catching exceptions because of following reason:
Remember:
A base class variable can also reference child class object.
e is a reference variable
catch(ExceptionType e){
}
The lowercase character e is a reference to the thrown (and caught) ExceptionType object.
Reason why your code not accepted?
It is important to remember that exception subclass must come before any their superclasses. This is because a catch statement that uses a superclasses will catch exception of that type plus any of its subclasses. Thus, a subclass would never be reached if it came after its superclass.
Further, in Java, Unreachable code is an error.
SQLException is supperclass of SQLDataException
+----+----+----+
| SQLException | `e` can reference SQLException as well as SQLDataException
+----+----+----+
^
|
|
+----+----+----+---+
| SQLDataException | More specific
+----+----+----+---+
And if your write like having error Unreachable code (read comments):
try{
}
catch(java.sql.SQLException e){//also catch exception of SQLDataException type
}
catch(java.sql.SQLDataException e){//hence this remains Unreachable code
}
If you try to compile this program, you will receive an error message stating that the first catch statement will handle all SQLException-based errors, including SQLDataException. This means that the second catch statement will never execute.
Correct Solution?
To fix it reverse the order of the catch statements.That is following:
try{
}
catch(java.sql.SQLDataException e){
}catch(java.sql.SQLException e){
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I make Selenium Python click on a button element?
So I just started using Selenium for Python and I am trying to click on a button element that is buried into a few div elements; I've tried so many things but nothing works. Everything in the code works besides the last part which is waiting for the button to be clickable and then clicking it. I would greatly appreciate some help here, thanks. :)
HTML:
Code trials:
Error stacktrace:
A:
To click on **Maybe Later** button.
Induce WebDriverWait() and element_to_be_clickable() and following XPATH or CSS Selector.
XPATH:
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//div[@class='modal-footer']//button[@Class='btn btn-danger x' and text()='Maybe Later']"))).click()
CSS Selector:
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"div.modal-footer button.btn.btn-danger.x[style='danger']"))).click()
You need to import following libraries.
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
| {
"pile_set_name": "StackExchange"
} |
Q:
DLCleanerlite.exe launches at Windows startup but is not in startup folder or in msconfig.exe startup tab
I don't know how i got DLCleanerLite.exe installed in my Windows 7 computer, but every time my Windows loads up, DLCleanerLite loads up.
I have checked
Add/Remove Program feature in the Window's Control Panel.
Startup Folder.
MSConfig.exe Startup Tab.
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
But I don't see anything related to DLCleanerLite.exe
DLCleanerLite.exe is at location
C:\Program Files (x86)\CBS Interactive\Download App\DLCleanerLite\DLCleanerLite.exe
Does anyone know how I can safely remove it? Can I just delete that exe file?
thanks
A:
Many experts agree, if you don't use it you should remove it!.
You can uninstall DL Cleaner Lite from your computer by using the Add/Remove Program feature in the Window's Control Panel.
| {
"pile_set_name": "StackExchange"
} |
Q:
EAV structure explained in Layman's terms
I've read several articles online that explain how EAV structures work, but there are different interpretations of them. Some articles mention that it's a representation of a data model metadata (or schema). Other articles describe an EAV structure as being an ontology. I picture an ontology as either a conceptual model (showing relationships among "things" in the world), or class instances to the actual data in a database.
Can someone explain what each table in this model represents in Layman's Terms and how one would use this EAV data model?
I didn't see this as a representation of a data model, because [Object] is not directly linked to [Attribute]. You need an actual value to relate those two. So there's nothing to enforce that you could use a [Attribute] A with [Object] O if A is a field/column of table O in your data model. Now I did see the RI tables. I assumed that meant "Referential Integrity". But if we're talking about ontologies, then we could call it relationship identity. I'm merely referring to the relationship or predicate when talking about an ontology triple--meaning Subject/Predicate/Object. Note, that the joins are not connected with attribute, which would represent more of a relational data model FK/PK relationship with table columns, so I expected it to be connected to Attribute, not Object. It's connected with [Object].
Please shed some light on this if you're able. Maybe I'm thinking too much into this. If you have a different EAV model that's useful, let me know.
Reference: http://eav.codeplex.com
A:
Here is what I think is intended in this model:
Category is a kind of thing. In a data model it would be an entity type, in a database it would be a table.
Attribute is a facet of a thing. In a data model it would be a predicate type, in a database it would be a column.
Object is an instance of a thing. In a data model it would be an entity, in a database it would be a row (in a particular table).
Value is an instance of a predicate or a column value in a database table.
Domain Lookup is a mechanism that allows you to constrain attribute values. This implementation works by constraining the value to one in a set of legal values. In a database this could be likened to a check constraint or a lookup table. Obviously there are other types of constraints that could be imposed (but aren't in this metadata model) such as range constraints.
RIConfig is a relational constraint between two kinds of things. This is a relationship type in a data model or a foreign key constraint in a database. At this level it is describing the relational rule, not the instances of relationships.
RI is an instance of a relationship between to specific entities. In a physical database, this would be a record in a foreign key index (perhaps?)
You are quite right to observe that the modeling of relationships is flawed insofar as it doesn't account for the implementation of these relationships. RIConfig should join to Attribute not to Category - or rather, there should be an intersection table between RIConfig and Attribute to allow for compound primary/foreign key relationships.
As I noted above, domain constraints are also not handled with realistic flexibility.
Given the limitations of this model, it would not be adequate as a metadata repository for many real-world databases.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can a button be 'secondary' on one page but 'primary' on another?
For example, an "Edit" button. In most pages, it is a secondary button ("Submit" may be the primary one). But there can be a case where in "Edit" is primary action for the page.
Is it good practice to make it stand-out on such pages? Or should secondary buttons remain secondary on every page for consistency?
A:
Choose the buttons to be primary or secondary depending upon the context of the page. Your buttons must align with the objective of the page and the styling,design and placement must be done accordingly to ensure that they help the page achieve its objective.
To quote this article about call to actions
Choose contrasting colors and size your call-to-action button
accordingly to help set it apart from other visual elements on your
pages
If offering two call-to-action choices (such as a Sign Up button and a
Free Trial), make the buttons color-coded according to the most
important action you want users to take first.
Hence dont get caught up in the aspect of maintaining the design for all similar buttons even though their expected impact on the page might be different.
A:
When you want the 'Edit' button to be primary you need a secondary button like 'Cancel' the edit button will act as a Submit button. so in other terms something like 'Save'
So instead of changing the 'Edit' button to primary you should make a new Primary button called something like 'Save edit' or something similar to that.
In my opinion it is better to leave the normal 'Edit' button secondary so you have a better structure in your pages.
| {
"pile_set_name": "StackExchange"
} |
Q:
Inversion method for generating random variates.
Suppose you have a cdf
$$
F(X)=\frac{1}{2} (x-1)^3 + \frac{1}{2}
$$
$$
0\leq x\leq 2
$$
How, would one find the inversion to create random variants?
I tried rearranging and inverting the equation into
$$
X=(2u-1)^\frac{1}{3}+1
$$
$$
0\leq u\leq 1
$$
Graphing this inverted equation clearly only show half of the equation. I am not sure how to get the second half. Thanks :D
A:
You inverted the equation correctly. Unfortunately you didn’t show the graph you obtained that seemed to indicate a problem, so it’s hard to say what went wrong. Just in case you used Wolfram|Alpha to plot the inverse function, note that by default the principal root is used, which yields this graph, but when you click on “Use the real-valued root instead” you get this graph, which is what you want for the inversion method.
| {
"pile_set_name": "StackExchange"
} |
Q:
Resizing a button
I have a "button" that I wish to use all throughout my site, but depending on where in the site the button is, I want it to display at different sizes.
In my HTML I have tried (but its not working):
<div class="button" width="60" height="100">This is a button</div>
And the matching CSS:
.button {
background-color: #000000;
color: #FFFFFF;
float: right;
padding: 10px;
border-radius: 10px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
}
I assumed that if each time I call this class I can just pass in a size and hey-presto!....but not....
By adding the width and height as I call the button class seems to do nothing to the size of it. Does anyone know how I can do this? And if I put the width and height in the CSS then the button will be the same size everywhere.
A:
You should not use "width" and "height" attributes directly, use the style attribute like style="some css here" if you want to use inline styling:
<div class="button" style="width:60px;height:30px;">This is a button</div>
Note, however, that inline styling should generally be avoided since it makes maintenance and style updates a nightmare. Personally, if I had a button styling like yours but also wanted to apply different sizes, I would work with multiple css classes for sizing, like this:
.button {
background-color: #000000;
color: #FFFFFF;
padding: 10px;
border-radius: 10px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
margin:10px
}
.small-btn {
width: 50px;
height: 25px;
}
.medium-btn {
width: 70px;
height: 30px;
}
.big-btn {
width: 90px;
height: 40px;
}
<div class="button big-btn">This is a big button</div>
<div class="button medium-btn">This is a medium button</div>
<div class="button small-btn">This is a small button</div>
jsFiddle example
Using this way of defining styles removes all style information from your HTML markup, which in will make it easier down the road if you want to change the size of all small buttons - you'll only have to change them once in the CSS.
A:
If you want to call a different size for the button inline, you would probably do it like this:
<div class="button" style="width:60px;height:100px;">This is a button</div>
Or, a better way to have different sizes (say there will be 3 standard sizes for the button) would be to have classes just for size.
For example, you would call your button like this:
<div class="button small">This is a button</div>
And in your CSS
.button.small { width: 60px; height: 100px; }
and just create classes for each size you wish to have. That way you still have the perks of using a stylesheet in case say, you want to change the size of all the small buttons at once.
| {
"pile_set_name": "StackExchange"
} |
Q:
Does Evasion work against Elemental Adept'ed spells?
I really think its a silly question, but does evasion from a ranger reduce damage from a spell (Dex save), cast from a caster with Elemental adept?
A:
Yes, Evasion still applies to spells cast by an Elemental Adept
Elemental Adept states that:
Spells you cast ignore resistance to damage of the chosen type.
And the ranger's Evasion feature states that:
When you are subjected to an effect, such as a red dragon’s fiery breath or a lightning bolt spell, that allows you to make a Dexterity saving throw to take only half damage, you instead take no damage if you succeed on the saving throw, and only half damage if you fail.
Evasion doesn't grant you resistance or immunity to the damage, it simply halves or zeroes the damage you take - which has the same numerical effect as resistance or immunity, but is not actually resistance or immunity. Since Evasion doesn't grant resistance, it's not overcome by Elemental Adept - the two features don't have any interaction with each other.
Aside, this also means that, while multiple sources of resistance to the same damage do not stack together, Evasion and resistance can both apply to incoming damage, so a ranger with a relevant resistance might halve and halve again damage from a hostile effect, reducing it to only a quarter (or most likely a little less, due to rounding down twice).
A:
Evasion is not resistance
While both would halve the damage taken, they are not the same. Elemental Adept would let the spell's damage ignore resistance, but it does not do the same to other sources of damage halving.
| {
"pile_set_name": "StackExchange"
} |
Q:
AST trees semantic analyzer
The last nodes of an AST tree must have the information of the traduction of the semantic analyzer or the non-last nodes also can have this information?
A:
Your question seems not quite well formed.
Under the assumption you mean "leaf nodes" where you wrote "last nodes", yes, you can associate semantic information not only with leaves but with interior nodes.
A simple example would be "the type of this expression". It is clear that leaf node containing the literal TRUE would have an expression type "boolean" associated with it. The expression "if e then 2.7 else 9.3 endif" has a corresponding AST, and the internal node corresponding to the if-expression would have an associated type of "float".
There are lots of "semantic" properties one could propose: "uses variables X, Y, Z", "side effect-free", "forks parallel subprocesses", etc. any of which might apply to interior tree nodes.
| {
"pile_set_name": "StackExchange"
} |
Q:
Print Stack Trace to Logcat
How can you print the stack trace to the logcat?
When the app is running through Eclipse and the app crashes I get a series of messages in the logcat window like "FATAL EXCEPTION: main" and stack trace is printed. However, when I use the adb logcat command from the command line I do not see any of these messages? All I see is a message saying example.app has died.
How can I get the same stack trace that shows up in the Eclipse logcat window with the adb logcat command?
Edit to clarify:
The stack trace is printed to the log when I reproduce the crash while the device is connected to the computer, but not when I reproduce the crash when the device is not connected to the computer.
After reproducing the crash while the device is not connected to the computer, I plug in the usb cable and use: 'adb logcat -d' and instead of a nice stack trace the only thing I see related to the crash is:
I/WindowManager( 656): WIN DEATH: Window{42aba898 XXXXXXXXXX.XXXXXXX.XXXXX.XXXXXX/XXXXXXXXXX.XXXXXXX.XXXXX.XXXXXX.XXXXXXXXXXXX paused=false}
I/ActivityManager( 656): Process example.app (pid 28681) has died.
I/WindowManager( 656): WIN DEATH: Window{42aa9548 XXXXXXXXXX.XXXXXXX.XXXXX.XXXXXX/XXXXXXXXXX.XXXXXXX.XXXXX.XXXXXX.XXXXXXXXXXXXXX paused=true}
Is there a way to have it still print the stack trace to logcat when the device is not connected to the computer?
A:
Maybe the method you are looking for to show the whole exception in Logcat being able to track it down and Tag it is this one:
android.util.Log.e("Your TAG," , "Your Message", exceptionReference);
If you want to know about any uncaught exception whether you know where it happened or not, this is what you have to do at some point when your application just starts (Application Context class would be a good place...):
UncaughtExceptionHandler uncaughtExceptionHandler = new UncaughtExceptionHandler(){
@Override
public void uncaughtException(Thread thread,
Throwable ex) {
//Here print the log...
}
};
Thread.setDefaultUncaughtExceptionHandler(uncaughtExceptionHandler);
This will let you know if an exception have been unhandled by the end of the stack...
Hope this helps...
| {
"pile_set_name": "StackExchange"
} |
Q:
Move dataItem (row) to first place in Kendo grid
I want to be able to move specific row to first place on first page in a paginated Kendo grid. I have found the dataItem via jQuery but I am not sure how to append it as the first element in the grid. I couldn´t find anything similar to this in the documentation but only on how to removeRow. Can anyone perhaps help me in moving the dataItem to firstplace?
Here´s my script where I´ve found the dataItem:
function onFetchItem(gridName) {
var ids = gridName.split("_");
var item = $("#ItemSearch_" + ids[1]).val();
var grid = $("#" + gridName).data("kendoGrid");
var data = grid.dataSource.data();
var dataItem = $.grep(data, function (d) {
return d.Item == item.toUpperCase();
});
//TODO: move dataItem as first record in grid
}
I found in this thread that I could use greb as I suggest above.
A:
You could first remove the item and then insert it at first index:
grid.dataSource.remove(dataItem);
grid.dataSource.insert(0, dataItem);
| {
"pile_set_name": "StackExchange"
} |
Q:
Nutch: Data read and adding metadata
I recently started looking apache nutch. I could do setup and able to crawl web pages of my interest with nutch. I am not quite understanding on how to read this data. I basically want to associate data of each page with some metadata(some random data for now) and store them locally which will be later used for searching(semantic). Do I need to use solr or lucene for the same? I am new to all of these. As far I know Nutch is used to crawl web pages. Can it do some additional features like adding metadata to the crawled data?
A:
Useful commands.
Begin crawl
bin/nutch crawl urls -dir crawl -depth 3 -topN 5
Get statistics of crawled URL's
bin/nutch readdb crawl/crawldb -stats
Read segment (gets all the data from web pages)
bin/nutch readseg -dump crawl/segments/* segmentAllContent
Read segment (gets only the text field)
bin/nutch readseg -dump crawl/segments/* segmentTextContent -nocontent -nofetch -nogenerate - noparse -noparsedata
Get all list of known links to each URL, including both the source URL and anchor text of the link.
bin/nutch readlinkdb crawl/linkdb/ -dump linkContent
Get all URL's crawled. Also gives other information like whether it was fetched, fetched time, modified time etc.
bin/nutch readdb crawl/crawldb/ -dump crawlContent
For the second part. i.e to add new field I am planning to use index-extra plugin or to write custom plugin.
Refer:
this and this
| {
"pile_set_name": "StackExchange"
} |
Q:
Programmatically Push VC on Table Row Tap
I am attempting to do a onRowTap method without using a storyboard segue to push to a new View Controller, however when tapped it only displays information from the first item of the indexPath no matter which row is tapped. Here is my code:
- (void)tableView:(UITableView *)theTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
NSInteger row = [[self tableView].indexPathForSelectedRow row];
NSDictionary *insta = [self.instaPics objectAtIndex:row];
UIStoryboard* sb = [UIStoryboard storyboardWithName:@"Main"
bundle:nil];
InstaPicDetailViewController* vc = [sb instantiateViewControllerWithIdentifier:@"InstagramDetail"];
vc.detailItem = insta;
[self.navigationController pushViewController:vc animated:YES];
}
A:
Move your deslectRowAtIndexPath message call below the assignment of your row variable:
NSInteger row = [[self tableView].indexPathForSelectedRow row];
[self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to upload image to firebase storage using URL instead of SDK in Android?
I'm trying to upload files to firebase storage from android app using url instead of SDK using Retrofit. This is my upload image method,
fun uploadImageToUrl() {
val url = "https://firebasestorage.googleapis.com/v0/b/xxxxxxx-xxxx.appspot.com/o/${bean.firebaseUid}/idProofs/${bean.documentTitle}.jpg/"
var client = OkHttpClient.Builder().build()
val retrofit = Retrofit.Builder()
.baseUrl(url).addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
var service = retrofit.create(UploadService::class.java)
var params = HashMap<String, RequestBody>()
var reqFile = RequestBody.create(MediaType.parse("image/*"), photoFile)
var header = "Bearer ${bean.firebaseToken}"
var body = MultipartBody.Part.createFormData("image", bean.documentTitle, reqFile)
var response = service.uploadDocument(header, body)
response.enqueue(object: Callback<ResponseBody> {
override fun onResponse(call: Call<ResponseBody>?, response: Response<ResponseBody>?) {
Log.e("Upload Response", response!!.message())
}
override fun onFailure(call: Call<ResponseBody>?, t: Throwable?) {
Log.e("Upload Failed", t!!.localizedMessage)
}
})
}
This is the method in service interface.
interface UploadService {
@Multipart
@Headers("Accept: application/json")
@POST("/?alt=media")
fun uploadDocument(@Header("Authorization") header: String, @Part image: MultipartBody.Part): retrofit2.Call<ResponseBody>
}
But nothing is happening, no error messages, onResponse, onFailure methods not called, image not appearing.
A:
My bad. The URL should be like this
https://firebasestorage.googleapis.com/v0/b/xxxxxxx-xxxx.appspot.com/o/${bean.firebaseUid}%2FidProofs%2F${bean.documentTitle}.jpg/
instead of this
https://firebasestorage.googleapis.com/v0/b/xxxxxxx-xxxx.appspot.com/o/${bean.firebaseUid}/idProofs/${bean.documentTitle}.jpg/
I don't know why, but it's working.
| {
"pile_set_name": "StackExchange"
} |
Q:
Prevent GNU Screen from closing
Is there any way to make GNU Screen not close if I end all its subprocesses? Ideally, it would create a new window running a shell if I accidentally closed the last window.
A:
Assuming you're using bash and accidentally closes the shell with Ctrl-D, you can
export IGNOREEOF=1
This will give you a warning and require you to press Ctrl-D twice, or type exit instead.
A:
I don't know of a way to do that specifically, but I find zombie {} useful; when I close a window, it prompts me to hit { or } to close or reopen it, respectively.
| {
"pile_set_name": "StackExchange"
} |
Q:
Offset of a specific listed partition
Building off a question found here:
How to get the offset of a partition with a bash script? in regards to using awk,bash and parted for a GPT partition
Being pretty new to scripting languages I am not sure if and how to build off the existing request.
I am looking to grab a specific partition listed by the parted command. Specifically I need the start sector of the ntfs partition for setting a offset in mount within my bash script.
root@workstation:/mnt/ewf2# parted ewf1 unit B p
Model: (file)
Disk /mnt/ewf2/ewf1: 256060514304B
Sector size (logical/physical): 512B/512B
Partition Table: gpt
Number Start End Size File system Name Flags
1 1048576B 525336575B 524288000B fat32 EFI system partition boot
2 525336576B 659554303B 134217728B Microsoft reserved partition msftres
3 659554304B 256060162047B 255400607744B ntfs Basic data partition msftdata
A:
Using grep with PCRE:
parted ewf1 unit B p | grep -Po "^\s+[^ ]+\s+\K[^ ]+(?=\s.*ntfs)"
Output:
659554304B
| {
"pile_set_name": "StackExchange"
} |
Q:
XNA, direct X , OpenGL
I have been wanting to give game programming ago for a long while and never got round to it, and i have finally decided to give it ago. I have decided to try and create a simple to 2D platform game. I have had a quick play with XNA and I do like it. What i am looking for tho is a comparison between XNA, directx, OpenGL. mainly the strengths and weakness between them. I have been a .net developer for the last 4 years and that's were my knowledge mainly is.
A:
If you want to do Direct X, say hello to Win32 and COM as your new best buddies. You'll be spending lots of time early on learning ins and outs of the win32 API. DirectX with Win32 provides you all the features needed for sound, game input, and graphics display. You'll also be writing in C or C++, and you'll get to learn all about memory management and the C mindset - not something you should consider giving up lightly. Learning and using C as a language for a major project can be very illuminating, and make you thankful for modern programming language features and design elements. You aren't actually forced to use C or C++ for development here; there are various .NET wrappers and other language wrappers for Direct X, but if you've got .NET experience, you might as well use the framework made for .NET: XNA.
XNA is a much newer, .NET based set of tools. It provides many of the same features that straight use of Win32 and DirectX does (sound, input, etc) but natively on a managed platform. For most games (especially one when just starting out) you can get great framerates with an XNA game (even though a native app can give you more), and is very good for learning the ins and outs of game development -- you can't really go wrong. Most of the fundamental data structures you'll need (quad/oct trees, Model-view-controller architecture, handling of events, structure of your program) you will still need to learn and implement yourself, and doing it in .NET will most certainly be easier than in C and C++. As a nice side bonus, if you have an Xbox 360, XNA community games can, with some work, be released through Xbox Live marketplace. Basically, as a .NET developer, you would probably feel most comfortable here.
OpenGL is a cross-platoform library for drawing polygons. It has a different framework and API from Direct X, and does not provide any any OS interaction tools. There's packages that let you program in OGL in many different languages. However, as others have said, this will probably be just as much work as writing with Win32 and DirectX. For other features besides graphics (keyboard, mouse, joystick, audio) you could consider using a framework like SDL some of the missing DirectX features. There's a pretty decent community surrounding the library that can give you pointers and tips if you go this route.
More thoughts on this can be found in an almost identical article, here: Suggested Gaming Platform to Learn direct-x, C Open GL, or XNA.
A:
XNA is going to be the easiest/quickest way to get a game up and running for the 360 or Windows platforms. It will allow you to continue developing in a way that you are already familiar (C#.NET) and it will provide you with a sizable framework that will take care of the commonly used stuff automatically. With this ease comes some limitations though, as you will be limited to only the aforementioned platforms and due to it being a large framework there will be a lot of overhead that will go largely unused causing performance hits, however with a simple 2D platformer, this probably isn't going to be an issue.
DirectX is going to limit you in platform as well, and is going to be a lot more complicated to learn and develop in. Also you will most likely be programming in C or C++ here. The advantages will be in performance, since you are handling everything you will be in control of everything and able to optimize everything for what you need. I would think that for a first game, you're going to be much better off starting with XNA and moving to DirectX after you've "outgrown" XNA. Especially with the goal of creating a simple 2D platformer.
OpenGL will allow your game to run on most platforms but will be as complicated (if not moreso) as DirectX (although I should mention there are graphic engines for OpenGL which are pretty simple to use like OGRE. You'll also be developing in C/C++ for OpenGL. Again I would think XNA would be the better choice until you feel you're ready for the next step.
A:
If your experience has been mostly with .NET as you say, XNA would have the shortest barrier to entry although you won't get quite as good of performance as you can with other options. As you say that you're planning on making a 2D platformer, however (assuming that the implication here is "non-hardware intensive"), then XNA would be more than sufficient and probably the most suitable choice for your project.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.