text stringlengths 70 452k | dataset stringclasses 2 values |
|---|---|
What's the word for someone who consistently replies to positive statements in a contrarian manner?
An example of this would be,
"I like [x]."
And, unprompted, the other party replies,
"I don't like [x], I think [y] about it and that's what makes it bad."
They persist to find reasons to malign or belittle whatever it is that's positive. The contrarian aspect is what's stumping me, otherwise, I'd just say contrarian. If this or naysayer are accurate enough, let me know! I just didn't know if they had the right nuance.
Hello and welcome. You mention that the contrarian aspect is stumping you, but being contrary seems to be exactly the behaviour you’re seeking a word to describe. Please [edit] your question to explain why it stumps you. For example, do you want to exclude the mirrored case where the other party supports a position precisely because you speak against it?
A smellfungus, perhaps.
There are lots of words for argumentative/contrarian, and for negative/pessimistic/eeyorish, and general terms like malignant/poisonous/hostile. Or if it was someone who tells you all the bands you like are terrible, they might be a music snob or an elitist. Not sure you'll get better than naysayer or contrarian but there may be some obscure slang.
From the duplicate: argumentative; contentious; controversial[ist]; gainsayer; quarrelsome; cantankerous; antagonist[ic]; contrarian; disputatious ...
| common-pile/stackexchange_filtered |
sed with multiple expression for in-place argument
I am trying to replace multiple words in a file by using
sed -i #expression1 #expression2
file
Something 123 item1
Something 456 item2
Something 768 item3
Something 353 item4
Output (Desired)
anything 123 stuff1
anything 456 stuff2
anything 768 stuff3
anything 353 stuff4
Try-outs
I can get the following output by using sed -i two times.
sed -i 's/Some/any/g' file
sed -i 's/item/stuff/g' file
Can I have any possible way of making this as a single in-place command like
sed -i 's/Some/any/g' -i 's/item/stuff/g' file
When I tried the above code it takes s/item/stuff/g as a file and tries working on it.
If your files are similar to the example above (i.e they follow the same pattern) you can do it with a single substitution: sed - i 's/Some\(.*\)item/any\1stuff/' file
Depending on the version of sed on your system you may be able to do
sed -i 's/Some/any/; s/item/stuff/' file
You don't need the g after the final slash in the s command here, since you're only doing one replacement per line.
Alternatively:
sed -i -e 's/Some/any/' -e 's/item/stuff/' file
Or:
sed -i '
s/Some/any/
s/item/stuff/' file
The -i option (a GNU extension now supported by a few other implementations though some need -i '' instead) tells sed to edit files in place; if there are characters immediately after the -i then sed makes a backup of the original file and uses those characters as the backup file's extension. Eg,
sed -i.bak 's/Some/any/; s/item/stuff/' file
or
sed -i'.bak' 's/Some/any/; s/item/stuff/' file
will modify file, saving the original to file.bak.
Of course, on a Unix (or Unix-like) system, we normally use '~' rather than '.bak', so
sed -i~ 's/Some/any/;s/item/stuff/' file
Note that you're describing the GNU variant. The BSD variant (as in FreeBSD or OS/X) requires an argument for -i. So sed -i '' 's/a/b/;s/c/d/' file or sed -i .back 's/a/b/;s/c/d/' or sed -i.back 's/a/b/;s/c/d/' there. Other sed implementations generally don't support -i.
Thanks @StéphaneChazelas for clarifying that. And I guess I should have been more explicit in saying that in GNU sed there cannot be a space between the -i and the extension.
sed -i 's/$username = "root"/$username = "newuser"/; s/$password = "password"/$password = "passwd"/; s/$dbname="handicraftstore"/$dbname="handicraft"' Web/database.php results sed: -e expression #1, char 141: unterminated s' command`
@alhelal Sorry, comments are not the proper place to ask questions. But anyway, your last s command is missing its final /.
@PM2Ring as I didn't notice that I guessed it is related your solution. However, thank you.
You can chain sed expressions together with ";"
%sed -i 's/Some/any/g;s/item/stuff/g' file1
%cat file1
anything 123 stuff1
anything 456 stuff2
anything 768 stuff3
anything 353 stuff4
Multiple expression using multiple -e options:
sed -i.bk -e 's/Some/any/g' -e 's/item/stuff/g' file
or you can use just one:
sed -i.bk -e 's/Some/any/g;s/item/stuff/g' file
You should give an extension for backup file, since when some implementation of sed, like OSX sed does not work with empty extension (You must use sed -i '' to override the original files).
You can use Vim in Ex mode:
ex -sc '%s/Some/any/|%s/item/stuff/|x' file
% select all lines
s substitute
x save and close
| common-pile/stackexchange_filtered |
Any problems that may happen if I give my Wi-Fi extender the same SSID (and password) as my router
I recently installed a Netgear EX3700 Wi-Fi extender. After finding a spot to install it, I changed the SSIDs to the one of my router. (Verizon Fios Quantum). No speed or interference problems.
Can you tell me any problems that may crop up with this config?
Usually this not a problem (actually this is wanted so your device can stay in the same WLAN without adding a second one - I assume this is also what you wanted).
However roaming between different AP cells might cause problems with some cheap/old AP and/or devices. But you can check this: when your device switches from one AP 1 to AP 2 as soon as the signal strength from AP 2 is better you should be all set. If not it might be more feasible to use different SSIDs and do the switch manually.
I checked it but it doesn't work, but disconnecting and reconnecting does switch to the closest cell
@MashoorAiyaan Just a guess, but try to assing different SSIDs, save both networks, and check if the roaming works better. Otherwise, the only other choice is to check if you can tweak the roaming by changing the thresholds (I haven't tried this myself, I'm not sure if this is possible at all with consumer-grade products or even with pro products) or use devices that have better support for automatic roaming between cells.
Maybe a script that does a dis/reconnect at low signal strengths would work as well.
How will I set the thresholds? Are you talking about wifi signal power?
Also, what percentage should I set it if the ISP installed at the back of the house in the basement. (The extender is mounted nearby on the 1st floor.)
What does "assing different SSIDs" mean
Either signal power or signal quality, but I'm not sure if those setting are available at all, if they are it will be trail and error to find the right setting, since it depends on your particular layout. Assigning different SSIDs would mean to give AP1 a different SSID then AP2 has.
Let us continue this discussion in chat.
| common-pile/stackexchange_filtered |
Crash when returning a char array from a function
A freind and I are working together on an ESP32 webserver, and we have hit a wall. My buddie has pretty much given up on it, and I am less skilled than him.
We have the following functions, which compile fine, but cause the ESP32 to crash.
After lots of debugging I am pretty certain the crash occurs when trying to return c
void handle_logs_view(String path){
char** list = sdcard_list_files(path);
for (int i=0;list[i]!=NULL;i++){
Serial.println(list[i]);
}
}
char** sdcard_list_files(String path){
Serial.println("Listing files for "+path);
if (path.compareTo("/")){
char* c[]={"dir1","file1.log","file2.log","file3.log","file4.log","file5.log",NULL};
return c;
}
return NULL;
}
#endif
The results from the exception decoder are as follows:
PC: 0x400d1d1b: handle_logs_view(String) at C:\Users\MickW\Downloads\Front_End-11_create_file_explorer\Front_End-11_create_file_explorer\sample_code\WIFITest/WIFITest.ino line 45
EXCVADDR: 0x00000000
Decoding stack results
0x400d1d1b: handle_logs_view(String) at C:\Users\MickW\Downloads\Front_End-11_create_file_explorer\Front_End-11_create_file_explorer\sample_code\WIFITest/WIFITest.ino line 45
0x400d1e7e: std::_Function_handler >::_M_invoke(const std::_Any_data &) at C:\Users\MickW\AppData\Local\Temp\arduino_build_351256\sketch\WebServer.cpp line 32
0x400d68ff: std::function ::operator()() const at c:\users\mickw\appdata\local\arduino15\packages\esp32\tools\xtensa-esp32-elf-gcc\1.22.0-97-gc752ad5-5.2.0\xtensa-esp32-elf\include\c++\5.2.0/functional line 2271
0x400d69a5: FunctionRequestHandler::handle(WebServer&, HTTPMethod, String) at C:\Users\MickW\Documents\Arduino\hardware\espressif\esp32\libraries\WebServer\src\detail/RequestHandlersImpl.h line 45
0x400d6a12: WebServer::_handleRequest() at C:\Users\MickW\Documents\Arduino\hardware\espressif\esp32\libraries\WebServer\src\WebServer.cpp line 633
0x400d6b8d: WebServer::handleClient() at C:\Users\MickW\Documents\Arduino\hardware\espressif\esp32\libraries\WebServer\src\WebServer.cpp line 314
0x400d1d6e: loop() at C:\Users\MickW\Downloads\Front_End-11_create_file_explorer\Front_End-11_create_file_explorer\sample_code\WIFITest/WIFITest.ino line 22
0x400d8ad5: loopTask(void*) at C:\Users\MickW\Documents\Arduino\hardware\espressif\esp32\cores\esp32\main.cpp line 23
0x40089552: vPortTaskWrapper at /Users/ficeto/Desktop/ESP32/ESP32/esp-idf-public/components/freertos/port.c line 143
This is from the espressif website:
LoadProhibited, StoreProhibited
This CPU exception happens when application attempts to read from or write to an invalid memory location. The address which was written/read is found in EXCVADDR register in the register dump. If this address is zero, it usually means that application attempted to dereference a NULL pointer.
I would be greatful for any help or advice
Select one language target: either C or C++.
You are returning a pointer to an automatic (i.e. stack-based) variable. That variable goes away when sdcard_list_files returns, leaving the pointer 'dangling`.
One solution is to declare c as static. Another (in C++) would be to return a std::optional <std::array<std::string>, 6>>.
I tested declaring as a static, and it worked. Which is the better solution?
It's up to you. If you are primarily coding in C then static is fine.
Thanks a bunch :)
c should be declared static, preferably at the top level of your code. In your example, c is declared on the stack and will disappear when sdcard_list_files() returns. Declaring c with the static attribute will fix that.
| common-pile/stackexchange_filtered |
Function with Enumeration Parameter (and Default value)
I wanted to create an extension method function called toCurrencyString that has one parameter that is actually an integer enumeration of type CurrencyFormatType. The enum and code would be:
enum CurrencyFormatType: Int {
/// Formats a standard currency string (localized) such as $45.35 or *45,00
case Standard = 1,
///Rounded currency format (rounds up last decimals and does not return any decimals in string)
Rounded,
///Will not include the thousands separator (, or .) in a string. Retains localized currency symbol.
WithoutThousandsSeparator
}
func toCurrencyString(currencyFormat: CurrencyFormatType = 1) -> String
{
..my switch code w/ default to the first option if nothing passed in
}
I'd like to do this so that I can call .toCurrencyString on NSDecimalNumbers without having to pass in the optional parameter (most of the time I won't need it), but on the few times I do, i'd like to use an enum to select other options.
It complains at me telling me that my enum doesn't conform to IntegerLiteralConvertible. I did a little reading on how this would work but couldn't figure out the code.
Could anyone shed some light on how to get this working?
thanks for your help!
Have you considered using the built-in NSNumberFormatter? (See http://stackoverflow.com/questions/19773733/how-to-get-nsnumberformatter-currency-style-from-isocurrencycodes)
I'm using it in my code actually, yes! :) This switch function then proceeds to make use of it accordingly. Thanks though!
My apologies, no sooner did I ask it than I figured it out. I should have waited a bit longer.
In hopes of helping others out, just a reminder about the 'Raw' aspect of enums:
Adding this to my function signature helped:
CurrencyFormatType.Raw = 1
Thanks!
alternately you could have done:
func toCurrencyString(currencyFormat: CurrencyFormatType = CurrencyFormatType.Standard) -> String
{
...
| common-pile/stackexchange_filtered |
Ionic 4 IOS platform Send SMS without opening SMS app
I am using Ionic 4 and l have managed to send an SMS without using the SMS application on ANDROID now i want to implement this on IOS platform and l have done it and it keeps on opening the SMS application.
The reason l want to send SMS in the background is because when you tap an alert button it makes a call and at the same time send SMS in the background with the users current location.
IOS is giving SMS view and call screens at the same time.
Your assistance will be much appreciated.
You should send SMS via server side not from users Mobile. If what user have no credit in his mobile then sms will not be send and your use case will get messed up. Secondly there is security and privacy issue. i doubt Apple will not approve your application.
Thanks for the quick response, so i have to use an api for sending SMS like buying sms?.
Yes. You can check firebase for sending sms.
It is a privacy restriction on iOS. You cannot send a text message, from the user's number without them seeing the message and having the opportunity to edit or cancel the message. You can use a service, such as Twilio, to send a text message from your own number via an api.
| common-pile/stackexchange_filtered |
MobSF (Mobile-Security-Framework-MobSF) installation problems
I spent last days striving with MobSF (Mobile-Security-Framework-MobSF) installation, which finally fails without reaching the target.
My work laptop is Windows 10 with i5-8250U and 16G memory.
I tried it using
git clone https://github.com/MobSF/Mobile-Security-Framework-MobSF.git
then running setup.bat
Meanwhile installing Python (Python 3.11.2), OpesnSSL (64 bit) and Visual studio.
The BAT file runs slowly ... unfortunately fails
[ERROR] Installation Failed!
throwing errors:
ERROR: Could not find a version that satisfies the requirement yara-python-dex>=1.0.1 (from apkid==2.1.4->-r requirements.txt (line 24)) (from versions: none)
ERROR: No matching distribution found for yara-python-dex>=1.0.1 (from apkid==2.1.4->-r requirements.txt (line 24))
and
Traceback (most recent call last):
File "c:\Users\ij\tools\Mobile-Security-Framework-MobSF\manage.py", line 12, in <module>
from django.core.management import execute_from_command_line
ModuleNotFoundError: No module named 'django'
Trying to kludge it around:
pip install -r requirements.txt
python -m pip install django
But it still does not work.
Another attempt was installation using
docker build -t mobsf .
But it finishes:
#9 [ 5/15] RUN ./install_java_wkhtmltopdf.sh
#9 sha256:dfd7a75b84c7012f1ce18ad20ea32f7e4921afdc40b5cc22287585713c5f8bd2
#9 0.688 /bin/sh: 1: ./install_java_wkhtmltopdf.sh: not found
#9 ERROR: executor failed running [/bin/sh -c ./install_java_wkhtmltopdf.sh]: exit code: 127
------
> [ 5/15] RUN ./install_java_wkhtmltopdf.sh:
------
executor failed running [/bin/sh -c ./install_java_wkhtmltopdf.sh]: exit code: 127
Google hardly shows anything about it.
I will appreciate any hint to solve. May be there is another way to install MobSF
Install python 3.8 or 3.9 your issue will be solved
| common-pile/stackexchange_filtered |
How do I create a Progress bar using the value of an ID
Before the code below, a user enters the title of a book they read. There is then a total count automatically populated in id="bookcount".
I have a progressbar for the book count, but how can I make it automatically grab the number in bookcount...so the progress bar can update as more books are entered. (Basically, value="2" needs to somehow pull the number instead of manually assigning the value.)
<div id="bookcount">2</div>
<label for="bookprogress">progress:</label>
<progress id="bookprogress" max="5" value="2"> 70% </progress>
JS
$(document).ready(function(){
$("#bookprogress").val("#bookcount");
});
Get the number with var bookCount = +$('#bookcount').text() and then set it using $('#bookprogress').attr('value',bookCount);.
First line of code takes content of a div and casts it to the number using simple + in front of it. The other line just sets the value of the progress bar to the div value.
var bookCount = +$('#bookcount').text()
$('#bookprogress').attr('value',bookCount);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="bookcount">2</div>
<label for="bookprogress">progress:</label>
<progress id="bookprogress" max="5" value="0"> 70% </progress>
| common-pile/stackexchange_filtered |
php count grouped values
I have searched around and have found many solutions to my question, but I am still having one problem. I am trying to create a table that will have four images per row. This has been done. I have told the script to group by rewardid and it does that so now duplicate images do not appear (the steps to do these I have found on the site). What I am having problems with is that I m trying to put a multiplier under each image to count how many was in each group. (i.e. Lets say I have 5 medals. On my page, it only shows one medal, but I really have 5, so I would like for it to say x5 below the image.) This is what I have so far:
print "<div class='style1'><br> <br><h2>User Medals</div></h3><br />
<table width='80%' class='table' border='0' cellspacing='1'><tr bgcolor='gray'><th></th><th></th><th></th><th></th></tr>";
$result=mysql_query("SELECT * FROM awardsearned WHERE userid=$userid group by rewardid");
$count = 0;
while($res=mysql_fetch_array($result))
{
$award = $res['rewardpic'];
$award2 = $res['rewardid'];
$result2=mysql_query("SELECT awardid, count(rewardid) FROM awardsearned WHERE rewardid=$award2 AND userid=$userid");
$count2 = count($result2);
if($count==4) //three images per row
{
print "</tr>";
$count = 0;
}
if($count==0)
print "<tr>";
print "<td>";
print "<center><img src='$award' width='100' height='100'/><br />x$count2</center> ";
$count++;
print "</td>";
}
if($count>0)
print "</tr>";
print "
</table>";
Sorry if this is messed up, never posted here before. Here it is on pastebin if needed http://pastebin.com/iAyuAAzV
You never fetch the result of the second query. You cannot call PHP's count on a MySQL result. And even if you could, it would always return 0 or 1, as it returns 0 or 1 row with the record count in it.
Can you please paste your table structure, sample data and expected result as per sample data proviced?
Update your query like this:
SELECT *,COUNT(rewardid) no_of_rewards
FROM awardsearned WHERE userid=$userid group by rewardid
$res['no_of_rewards'] will hold your number.
This will also eliminate the need for the second query.
These things are called "aggregate functions". More in the documentation.
To answer your question:
The value of $result2 would only give TRUE(1) or FALSE(0). If your query executed correctly $count2 will return 1, therefore you always get 1 in your code.
Try and change
$result2=mysql_query("SELECT awardid, count(rewardid) FROM awardsearned WHERE rewardid=$award2 AND userid=$userid");
$count2 = count($result2);
TO:
$result = mysql_query("SELECT awardid, count(rewardid) FROM awardsearned WHERE rewardid=$award2 AND userid=$userid");
$arr = mysql_fetch_array($result);
$count2 = count($arr);
This should give you the actual numbes of records from the resultset.
There are better ways of doing this (look at Bart Friederichs answer!) , like doing only SELECT and loop through resultset once. This would be for performance and for flexibility.
Also take in my consideration that mysql_query is deprecated now, and should not be used. (The preferal methods are to use PDO or mysqli instead)
| common-pile/stackexchange_filtered |
Inverting string-based binary number in one line in Python
I want to read two strings on separate lines, each string the same length and containing only 0's and 1's, and determine if the first is the one's complement of the second. How succinctly can this be done in Python3? (Sorry to specify the language, but this is for my son who's studying Python)
A list comprehension seems to work but is quite ugly.
if ['0' if x=='1' else '1' for x in input()] == list(input()): print('yep')
Is there a slicker/shorter way to do this?
Here's a simple, consice way: Try it online!
If we're trying to do this for the shortest possible code, here's 52 bytes: Try it online! But that isn't so clear.
Do you just want short code, or do you also want it to be elegant and/or readable?
Your example code will produce a syntax error, you can't have then without an else, perhaps you meant to use :? Removing spaces gets you if['0'if x=='1'else'1'for x in input()]==list(input()):print('yep') for 67 bytes, but that can be improved upon.
@JonathanAllan You simply can't have then, whether you have an else or not.
@Steffan is right, then won't work :)
Thanks guys. I tried my code, noticed the error and fixed it, but forgot to fix it in my question above. Edited my question to correct it!
Python 3, 51 44 43 41 bytes
-7 thanks to loopy walt's suggestion to use *open.
-1 thanks to xnor's suggestion to replace any(...) with 1in ...
-2 thanks to dingledooper's suggestion of using str.find instead of str.__eq__
0in map(str.find,*open(0))or print('yep')
Try it online!
This is a full program that takes input from stdin until an EOF (which we assume the user provides at the end of the second line) with open(0) and maps across the two strings by splatting (*), calling str.find on each pair of characters in turn. If 0 is in the result (i.e. the characters are equal and so the index of the first in the second is 0 rather than -1 for "not found") then the right-hand clause of the or is not evaluated, and so we don't print.
My previous version, with xnor's and dingledooper's suggestions, at \$48\$, is interactive without the EOF faff:
0in map(str.find,input(),input())or print('yep')
You could save one more byte by printing to stderr instead of stdout by exiting the program early using exit in place of print.
A note to your son - this is not how I'd want someone in my team at work to write code :) - readability counts, a lot.
Don't you mean unless any of the pairs are equal to each other?
@Neil thanks, I got there in the end :p (many edits)
any(map(str.__eq__,*open(0)))or print('yep')
@loopywalt Oh yeah, I always wondered - how does that know when to stop taking input? Is it EOF?
Good question, actually. Perhaps CTRL-D? (Just a wild guess.)
Windows seems to need CtrlZ CtrlZ - :/ :o
On Linux, Ctrl+D seems to work.
Ctrl+Z works fine on Windows. You just need to make sure you suffix the previous input with a newline, or the Ctrl+Z is included as part of that input.
@Steffan Tried that but it produced no output for me, while the double use with no newline worked.
Yes, it seems to only work if you finish the previous input. So Ctrl+Z . (relevent: https://stackoverflow.com/a/16136924/10914124)
@Steffan nope, that does not work, but typing \n at the end of the second line does (facepalm). EDIT or indeed an x :/
that's exactly what I said lol. edit: wait, you mean literally typing a backslash and n?
Let us continue this discussion in chat.
print(all(map(str.__ne__,*open(0)))*'yep') saves another 2 but prints an empty line in case of failure.
Looks like the any(...) can be 1in ..
@loopywalt I thought of that, but don't think it's really in keeping with the intention.
41 bytes: 0in map(str.find,*open(0))or print('yep').
Nice one @dingledooper :)
Aside: stdin , stdout, and stderr are each just single words, there're no internal spaces.
@Noodle9 - updated.
Python3, 62 bytes
Since the bits at the similar position need to be set in one of the inputs and unset in the other, their bitwise XOR must have all bits set.
x=input()
int(x,2)^~-(1<<len(x))^int(input(),2)or print("yep")
Try it online!
-5 bytes thanks to Arnauld
Updated from my previous answer where I incorrectly assumed that checking bitwise AND = 0 was a sufficient condition.
62 bytes
| common-pile/stackexchange_filtered |
'sort' not working on a populated subcomponent in a Strapi v4 Service
I have working code inside a controller that pulls a populated component from a Singletype Element and sorts the elements of this component by one of its properties.
When i make this same code more flexible and move it to a service instead of the controller the code still works. I still get the populated component with sub components, but the sorting has no effect on the resulting array.
I have multiple controller actions in the form :
async destroyElement(ctx) {
const { textelements } = await strapi
.query("api::service.service")
.findOne({
populate: {
textelements: { populate: ["pictures"], sort: ["order:asc"] },
},
}); .....
This works fine and results in "textelements" beeing an array sorted by the textelement property "order"
Since i have multiple such actions i intend to move the "Get all textelements" part out of the action itself and create a service function to do this.
async getTextelements(apiName, model) {
const { textelements } = await strapi
.query(`api::${apiName}.${model}`)
.findOne({
populate: {
textelements: { populate: ["pictures"], sort: ["order:asc"] },
},
});
// textelements.sort((a, b) => a.order - b.order);
return textelements;
},
When i call this service function from the controller action the resulting array has the correct content but is not sorted by the "order" property.
I can ofcourse manually sort the array with the commented out function before returning it, but i would prefer to have this handled by the strapi query as the sort: ["order:asc"] should do, and did while the functionality was part of the controller action.
What am i missing here?
| common-pile/stackexchange_filtered |
Property 'sectionsnap' does not exist on type 'JQuery<HTMLElement>'
Am getting issue when i add jquery code in ts file. (already i have include jquery)
Issue:
Property 'sectionsnap' does not exist on type 'JQuery HTMLElement'
jquery:
(function($) {
$.fn.sectionsnap = function( options ) {alert();
var settings = $.extend({
'delay' : 100 // time dilay (ms)
, 'selector' : ".sec" // selector
, 'reference' : .9 // % of window height from which we start
//, 'animationTime' : 400 animation time (snap scrolling)
, 'offsetTop' : 0 // offset top (no snap before scroll reaches this position)
, 'offsetBottom' : 0 // offset bottom (no snap after bottom - offsetBottom)
}, options);
var $wrapper = this
, direction = 'down'......
..................................
How do you your jquery import? You might need to extend its interface, or declare let $ : any; (but you'll loose types)
import * as sectionsnap from '../../assets/js/sectionsnap.js'; is it right?
How do you import jquery ? See here if this helps: https://stackoverflow.com/questions/49821320/bootstrap-w-angular-error-collapse-is-not-a-function/49822252#49822252
| common-pile/stackexchange_filtered |
columns in expandable listview
I have used this tutorial to do the expandable list view. http://www.androidhive.info/2013/07/android-expandable-list-view-tutorial/.
But i want to make a small change as shown in the below image. I dnt know to implement the items underlined in red. Is it possible to have columns in the expandable list view?
.xml file
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#f4f4f4"
android:orientation="vertical" >
<ExpandableListView
android:id="@+id/lvExp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:cacheColorHint="#00000000" />
</LinearLayout>
can any one help me with this. any help will be appreciated.
It's really the same thing as customizing a ListView row. Set up a custom layout and use the ViewHolder pattern: http://developer.android.com/training/improving-layouts/smooth-scrolling.html
I have edited my question n posted the .xml file. can u tell me how to add textview in that. it crashed when i did
I see you like androidhive. So, among the billions of results of a 5 secs search, here's a androidhive tutorial link: http://www.androidhive.info/2014/07/android-custom-listview-with-image-and-text-using-volley/
haha.. let me try this
Beware... It's for ListView, not ExpandableListView, so you must adapt it to your needs. But, after all, an ExpandableListView is like a ListView which holds a ListView for each of its items...
@Der Golem yup i got it
You need two layouts: expandable header and child items. In your example they are list_item and group_item.
Edit them and add the rest of fields.
If you use weights for fields widths, you can make header and rows to to look as a grid.
Briefly:
For header (group_layout) use a LinearLayout containing four TextViews (start with weights 2, 1, 1, 1 and adapt it according with tests).
For row (list_item) use a RelativeLayout containing:
LinearLayout exactly as the one in group layout (four TextViews with same weights as you set there) aligned to Top.
Two TextViews (toppings) aligned to left. Set property below accordingly.
The other two ImageViews. Align them accordingly as well (right and one next to the other)
Have a look into RelativeLayout parameters to set your views.
| common-pile/stackexchange_filtered |
How can I use Spring 3.2.3 JavaConfig to read an environment variable?
I am trying to use Spring 3.2.3 release JavaConfig in my app and I need to read the value of an environment variable.
I have read the JavaConfig 1.0.0.M4 documentation which seems to be exactly what I need but cannot find how to import or resolve the referenced @EnvironmentValueSource or @ExternalValue annotations.
Can someone show me how to do this please? Thanks.
You should be able to use the @Value annotation with a SpEL expression to retrieve the environmental variable from the systemEnvironment properties object, e.g.:
@Value("#{ systemEnvironment['MY_PROPERTY'] }")
private String myProperty;
If you need a system properties, use systemProperties['MY_PROPERTY'] instead.
Additionally, the documentation you should be looking at is here - what you have linked to is quite old.
You could use Springs EnvironmentAware interface:
public class ClazzWithEnvironmentInfo implements EnvironmentAware{
private Environment environment;
private String getSomeProperty(){
return environment.getProperty("SOME_ENV_PROPERTTY");
}
@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
}
}
| common-pile/stackexchange_filtered |
Prolog: making a 4-argument add function
I am trying to code a 4-argument function myadd(A, B, C, D) which holds true when A + B + C = D in prolog.
I am completely new to prolog and had no clue what to do, so what I did was some extention from a similar function but with 3 arguments:
add(0, Y, Y).
add(s(X), Y, s(Z)) :- add(X, Y, Z).
myadd(0, B, C, D) :- add(B, C, D).
myadd(s(A), B, C, s(D)) :- myadd(A, B, C, D).
Then when I execute this code, it starts to list what is untrue from some point:
?- myadd(A, B, C, s(s(0))).
A = B, B = 0,
C = s(s(0)) ;
A = 0,
B = C, C = s(0) ;
A = C, C = 0,
B = s(s(0)) ;
A = s(0),
B = 0,
C = s(s(0)) ; <- obviously this should not be true since s(0) + s(s(0)) != s(s(0))
A = B, B = C, C = s(0) ;
A = s(0),
B = s(s(0)),
C = 0 ;
A = C, C = s(s(0)),
B = 0 ;
A = s(s(0)),
B = C, C = s(0) ;
A = B, B = s(s(0)),
C = 0 ;
A = s(s(s(0))),
B = 0,
C = s(s(0)) ;
...
I have no idea why this (1. the code works until some point, 2. and then it doesn't) happens, I highly appreciate it if someone kindly points out the flaw.
Or, I'd be really grateful if you could tell me where to start.
Which of the arguments would be supplied? For the general case, could use https://github.com/ridgeworks/clpBNR (which can handle floating-point as well as integers) with constraint {A+B+C==D}.
Your latest edit shows the output of code which is no longer in the question...
Edits must not invalidate the existing answers. Reverted.
I cannot reproduce the answers you are getting.
Using SWI-Prolog 8.4.3:
?- myadd(A, B, C, s(s(0))). % A + B + C = 2
A = B, B = 0, C = s(s(0)) % 0 + 0 + 2 = 2
; A = 0, B = C, C = s(0) % 0 + 1 + 1 = 2
; A = C, C = 0, B = s(s(0)) % 0 + 2 + 0 = 2
; A = C, C = s(0), B = 0 % 1 + 0 + 1 = 2
; A = B, B = s(0), C = 0 % 1 + 1 + 0 = 2
; A = s(s(0)), B = C, C = 0 % 2 + 0 + 0 = 2
; false.
This part of your program seems to work properly!
Tried again and now it works properly... Now that I have discarded the log there's no way to see what really happened, but I might have run a code without updating the file. I now feel sad for my dumbness, but anyways I thank you for your help.
| common-pile/stackexchange_filtered |
Randomly Timeout(TimeSpan) doesn't work in Rx
The earlier post seems not very clear, so after some testing, I reopened this post with much more simplified words, hope somebody could help.
My singleton observable was turned from multiple source of I/O events, means they're concurrently raised up in underlying, based on testing (to prove Rx is not thread safe) and RX design guideline, I made it serialized, see that lock(...):
public class EventFireCenter
{
public static event EventHandler<GTCommandTerminalEventArg> OnTerminalEventArrived;
private static object syncObject = new object();
public static void TestFireDummyEventWithId(int id)
{
lock (syncObject)
{
var safe = OnTerminalEventArrived;
if (safe != null)
{
safe(null, new GTCommandTerminalEventArg(id));
}
}
}
}
This is the singleton Observable:
public class UnsolicitedEventCenter
{
private readonly static IObservable<int> publisher;
static UnsolicitedEventCenter()
{
publisher = Observable.FromEventPattern<GTCommandTerminalEventArg>(typeof(EventFireCenter), "OnTerminalEventArrived")
.Select(s => s.EventArgs.Id);
}
private UnsolicitedEventCenter() { }
/// <summary>
/// Gets the Publisher property to start observe an observable sequence.
/// </summary>
public static IObservable<int> Publisher { get { return publisher; } }
}
The scenario of Subscribe(...) can be described by following code, you can see the Subscribe(...) could be called concurrently in different threads:
for (var i = 0; i < concurrentCount; i++)
{
var safe = i;
Scheduler.Default.Schedule(() =>
{
IDisposable dsp = null;
dsp = UnsolicitedEventCenter.Publisher
.Timeout(TimeSpan.FromMilliseconds(8000))
.Where(incomingValue => incomingValue == safe)
.ObserveOn(Scheduler.Default)
//.Take(1)
.Subscribe((incomingEvent) =>
{
Interlocked.Increment(ref onNextCalledTimes);
dsp.Dispose();
}
, ex =>
{
Interlocked.Increment(ref timeoutExceptionOccurredTimes);
lock (timedOutEventIds)
{
// mark this id has been timed out, only for unit testing result check.
timedOutEventIds.Add(safe);
}
dsp.Dispose();
});
Interlocked.Increment(ref threadPoolQueuedTaskCount);
});
}
As pointed out times by experienced people, call Dispose() in OnNext(...) is not recommended, but let's ignore it here since the code was from production.
Now the problem is randomly that .Timeout(TimeSpan.FromMilliseconds(8000)) is not working, the ex was never called, anyone could see any abnormal in the code?
for testing, I setup the stress testing, but so far, I didn't reproduced it, while in production, it appeared several times per day. Just in case, I pasted all the testing code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Rx
{
class Program
{
static void Main(string[] args)
{
// avoid thread creation delay in thread pool.
ThreadPool.SetMinThreads(200, 50);
// let the test run for 100 times
for (int t = 0; t < 100; t++)
{
Console.WriteLine("");
Console.WriteLine("======Current running times: " + t);
// at meantime, 150 XXX.Subscribe(...) will be called.
const int concurrentCount = 150;
// how many fake event will be fire to santisfy that 150 XXX.Subscribe(...).
const int fireFakeEventCount = 40;
int timeoutExceptionOccurredTimes = 0;
var timedOutEventIds = new List<int>();
int onNextCalledTimes = 0;
int threadPoolQueuedTaskCount = 0;
for (var i = 0; i < concurrentCount; i++)
{
var safe = i;
Scheduler.Default.Schedule(() =>
{
IDisposable dsp = null;
dsp = UnsolicitedEventCenter.Publisher
.Timeout(TimeSpan.FromMilliseconds(8000))
.Where(incomingValue => incomingValue == safe)
.ObserveOn(Scheduler.Default)
//.Take(1)
.Subscribe((incomingEvent) =>
{
Interlocked.Increment(ref onNextCalledTimes);
dsp.Dispose();
}
, ex =>
{
Interlocked.Increment(ref timeoutExceptionOccurredTimes);
lock (timedOutEventIds)
{
// mark this id has been timed out, only for unit testing result check.
timedOutEventIds.Add(safe);
}
dsp.Dispose();
});
Interlocked.Increment(ref threadPoolQueuedTaskCount);
});
}
Console.WriteLine("Starting fire event: " + DateTime.Now.ToString("HH:mm:ss.ffff"));
int threadPoolQueuedTaskCount1 = 0;
// simulate a concurrent event fire
for (int i = 0; i < fireFakeEventCount; i++)
{
var safe = i;
Scheduler.Default.Schedule(() =>
{
EventFireCenter.TestFireDummyEventWithId(safe);
Interlocked.Increment(ref threadPoolQueuedTaskCount1);
});
}
// make sure all proceeding task has been done in threadPool.
while (threadPoolQueuedTaskCount < concurrentCount)
{
Thread.Sleep(1000);
}
// make sure all proceeding task has been done in threadPool.
while (threadPoolQueuedTaskCount1 < fireFakeEventCount)
{
Thread.Sleep(100);
}
Console.WriteLine("Finished fire event: " + DateTime.Now.ToString("HH:mm:ss.ffff"));
// sleep a time which >3000ms.
Thread.Sleep(8000);
Console.WriteLine("timeoutExceptionOccurredTimes: " + timeoutExceptionOccurredTimes);
Console.WriteLine("onNextCalledTimes: " + onNextCalledTimes);
if ((concurrentCount - fireFakeEventCount) != timeoutExceptionOccurredTimes)
{
try
{
Console.WriteLine("Non timeout fired for these ids: " +
Enumerable.Range(0, concurrentCount)
.Except(timedOutEventIds).Except(Enumerable.Range(0, fireFakeEventCount)).Select(i => i.ToString())
.Aggregate((acc, n) => acc + "," + n));
}
catch (Exception ex) { Console.WriteLine("faild to output timedout ids..."); }
break;
}
if (fireFakeEventCount != onNextCalledTimes)
{
Console.WriteLine("onNextOccurredTimes assert failed");
break;
}
if ((concurrentCount - fireFakeEventCount) != timeoutExceptionOccurredTimes)
{
Console.WriteLine("timeoutExceptionOccurredTimes assert failed");
break;
}
}
Console.WriteLine("");
Console.WriteLine("");
Console.WriteLine("DONE!");
Console.ReadLine();
}
}
public class EventFireCenter
{
public static event EventHandler<GTCommandTerminalEventArg> OnTerminalEventArrived;
private static object syncObject = new object();
public static void TestFireDummyEventWithId(int id)
{
lock (syncObject)
{
var safe = OnTerminalEventArrived;
if (safe != null)
{
safe(null, new GTCommandTerminalEventArg(id));
}
}
}
}
public class UnsolicitedEventCenter
{
private readonly static IObservable<int> publisher;
static UnsolicitedEventCenter()
{
publisher = Observable.FromEventPattern<GTCommandTerminalEventArg>(typeof(EventFireCenter), "OnTerminalEventArrived")
.Select(s => s.EventArgs.Id);
}
private UnsolicitedEventCenter() { }
/// <summary>
/// Gets the Publisher property to start observe an observable sequence.
/// </summary>
public static IObservable<int> Publisher { get { return publisher; } }
}
public class GTCommandTerminalEventArg : System.EventArgs
{
public GTCommandTerminalEventArg(int id)
{
this.Id = id;
}
public int Id { get; private set; }
}
}
And this is the "much more simplified words" version of your question?? I gave up half-way thru - it's just too hard to understand what you're trying to do. You need to write some brand-new code that minimally displays the problem you are having so that we can help you solve it. Right now this question is just way too much hard work to answer.
Most likely the Timeout is not triggering because you have it before the Where filter. This means that all events are flowing through and resetting the timer, and then most of the events get filtered by the Where clause. To your subscribing observer, it will seem like it never gets a result and the timeout never triggers. Move the Timeout to be after the Where and you should now have a system that times out individual observers if they do not get their expected event on time.
this sounds really reasonable, it also explains why the stress testing can't reproduce the problem, since the testing always have an ending, while in production environment, it always have events raise up to refresh that timer. I didn't noticed that method's sequence to cause the problem, I'll try and let you know.
| common-pile/stackexchange_filtered |
Syntax problems in Matrix addition and multipication program
i am trying to compile this program where i entered two 3*3 arrays and i am multipyling and adding both of them. However it is giving me some errors at the end due to which its not running. I cant remove these errors and i need help regarding how can i remove them.
import java.util.Scanner;
public class Matrix{
public static void main(String [] args){
int a [][]= new int [3][3];
int b [][]= new int [3][3];
int C [][]= new int [3][3];
int d [][]= new int [3][3];
Scanner in= new Scanner(System.in);
System.out.println("Enter Numbers in first matrix");
for( int r=0; r<3; r++){
for( int c=0; c<3; c++){
a [r][c]= in.nextInt();
}
}
System.out.println("Matrix 1 : ");
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
System.out.print(" "+ a[i][j]);
}
System.out.println();
}
System.out.println("Enter Numbers in 2nd matrix");
for( int n=0; n<3; n++){
for( int m=0; m<3; m++){
b [n][m]= in.nextInt();
}
}
System.out.println("Matrix 2 : ");
for(int k = 0; k < 3; k++) {
for(int l = 0; l < 3; l++) {
System.out.print(" "+b[k][l]);
}
System.out.println();
}
//for multiplication of the matrices
for(int f = 0; f < 3; f++) {
for(int s = 0; s < 3; s++) {
for(int d = 0; d < 3; d++){
C[f][s] += a[f][d]*b[d][s];
}
}
}
System.out.println("Multiplication of both matrix : ");
for(int x = 0; x < 3; x++) {
for(int y = 0; y < 3; y++) {
System.out.print(" "+C[x][y]);
}
System.out.println();
}
}
// for addition of both matrices
for(int w=0; w < 3; w++) {
for(int u=0; u < 3; u++) {
d[w][u] = a[w][u]+b[w][u];
}
}
System.out.println("Addition of both matrix : ");
for(int p = 0; p < 3; p++) {
for(int q = 0; q < 3; q++) {
System.out.print(" "+ d[p][q]);
}
System.out.println();
}
}
}
Well what are the errors?
"...due to some errors" what errors? How other people with same problem would find your question and potential solutions if you will not include any informations about problem you are trying to solve?
BTW, you need to check number of your braces { }. Hint: start using indentation properly, of if you don't know how let your IDE handle it for you (in Eclipse you just can press Ctrl+I).
Use an IDE and indent your program. You would see the issues. You have two issues issues:
You have an extra parenthesis. I would not tell you where.
You have "d" defined twice as a variable.
Again, it it time to download and use an IDE and indent code.
If you'd ident your code properly, you'll see that you have an extra "}":
System.out.println("Multiplication of both matrix : ");
for(int x = 0; x < 3; x++) {
for(int y = 0; y < 3; y++) {
System.out.print(" "+C[x][y]);
}
System.out.println();
}
} // Remove this
You also have the variable d declared twice:
int d [][]= new int [3][3];
...
for(int d = 0; d < 3; d++){
| common-pile/stackexchange_filtered |
Loop through XML Nodes using XmlStringStreamer in PHP
I have an XML file which is something like this:
(fileName : abc.xml)
<Envelope>
<Body>
<SResponse>
<Body>
<SResponseDetails>
<SItem>...</SItem>
<SItem>...</SItem>
<SItem>...</SItem>
<SItem>...</SItem>
</SResponseDetails>
</Body>
</SResponse>
</Body>
</Envelope>
I want to store all <SItem> in a db table (1 record for each SItem). I am using PHP for it and using XmlStringStreamer.
Here is my code for reading this file and processing it.
$streamer = \Prewk\XmlStringStreamer::createStringWalkerParser(__DIR__ . "/tempFile.xml");
$stream = new Stream\File(__DIR__ . "/abc.xml", 1024);
$parser = new Parser\StringWalker();
$streamer = new XmlStringStreamer($parser, $stream);
while ($node = $streamer->getNode()) {
$simpleXmlNode = simplexml_load_string($node);
//-- code here for getting single node
}
I am using XmlStringStreamer and did not get any answer from any forum, I also tried but could not get what I want so, can anyone please help me.
Thanks Alot.
I have solved it, here is my answer for it.
For looping for specific item, we can directly use this in xmlStringSteamer:
$stream = new Stream\File(__DIR__ . "/abc.xml", 1024);
$options = array(
"uniqueNode" => "SItem"
);
$parser = new Parser\UniqueNode($options);
// Create the streamer
$streamer = new XmlStringStreamer($parser, $stream);
$countNodes = 0;
while ($node = $streamer->getNode())
{
print_r($node);
}
The only problem is that it converts xml tags to lowercase. like <SItem> becomes <sitem>. So, anyone have idea about this problem?
I didn't executed your code but i think you can use PHP logic. If anything doesn't work for you then last solution will be exploding $simpleXmlNode to get some array structure and then process it according to your need. By the way can you share what you got after $simpleXmlNode = simplexml_load_string($node)?
For others, i can't add comments so posting this as answer.
for processing I also tried this in while loop:
foreach($simpleXmlNode->SResponse->Body->SResponseDetails->SItem as $item)
And I am getting each node in xmlObject so, I am converting xml object to xml using asXML() function but it convert characters in lowercase.
can you provide $simpleXmlNode sample value? i will see if find some time to validate it for you?
can you let me know how I can use asXML() without changing text to lowercase. It is converting xml tags to lowercase.
| common-pile/stackexchange_filtered |
Popstate not working as expected(needs multiple clicks)
I am trying to learn History Web API, but already have problems at the first hurdle.
I am able to get history.pushState working, but have issues with popstate. It works fine when clicked for the first time after AJAX page load, but if I load that same page again, I need to click back button twice. If I load it one more time, I need to click back three times, and so on.
Here is my code:
$(function(){
var $main = $('#main');
$(window).on('popstate', function () {
loadPage(location.href);
});
$(document).on('click', 'a', function(){
var href = $(this).attr('href');
history.pushState({}, '', href);
loadPage(href);
return false;
})
loadPage = function(href){
$main.load(href);
}
})
It sounds like you may want .replaceState() instead...
Thanks for the suggestion. It works now without the need for multiple clicks. But I am still curious what is wrong with this code of mine, especially since I saw examples on the net using pushState and not having the need to click back button multiple times.
Guess I jumped the gun a bit. It doesn't do what I want. The back button functionality is now completely messed up.
How are you loading the same page multiple times? Just clicking the same link over and over?
@ryan0319 Yep, same link over and over.
You need the state Object. In your case you using a empty Object wich will not work proberly. Just test is with a Object like this : {"url":yourUrlVar}
Reference: History.pushState - MDN
Thanks for the help, but no luck. Same issue persists.
| common-pile/stackexchange_filtered |
VS 2008 web services generating wrong url
Haven't done much web service development so this is probably an easy fix. Created both a mobile device project and web service project. When I add the service to my mobile project the soap document method attribute is wrong. All other info is correct. It generates service/method when it should actually be service?op= method. it will not work unless I manually change this url
You can try changing the URL you are using from http://whatevertoyourwebservice.asmx to http://localhost/whateverwebservice.asmx If you have the ability to use localhost this will work without having to change the url in the app.config folder. the other way is to use JavaScript to call your web service.
Here is an example is use for UTCTime webservice:
var portalUrl = window.location.href.substring(0, window.location.href.indexOf('/', 8));
var serviceUrl = portalUrl + "/your_webservice_location/";
var utcTimeOffsets = [];
function GetUtcOffsets(timezones, func) {
var proxy = new ServiceProxy(serviceUrl);
proxy.isWcf = false;
proxy.invoke("GetUTCOffsets",
{ tzName: timezones },
function(result) {
utcTimeOffsets = result;
if (func) func();
},
function(error, i, request) {
alert(error);
//setTimeout(function() { GetUTC(location) }, 1000);
},
false);
}
Other then that there is going to be no way, that I have found anyways, to make the C# webservice call dynamic. If you find a way please let me know. I know that these two options will work.
| common-pile/stackexchange_filtered |
How to allow directory program code to only display the differences between directory paths for C# Windows Application?
For this section of the code, I'm comparing each of the directories as entered by the user. Currently, the codes lists all files within each directory. I was looking for a way to list only the files and folders that are different and not present with one folder, but is in the other.
Code:
private void btnCompare_Click(object sender, EventArgs e)
{
// Clear previous results.
dgvFiles.Rows.Clear();
// Get sorted lists of files in the directories.
string dir1 = txtDir1.Text;
if (!dir1.EndsWith("\\")) dir1 += "\\";
string[] file_names1 = Directory.GetFileSystemEntries(dir1, "*",
SearchOption.AllDirectories); ;
for (int i = 0; i < file_names1.Length; i++)
{
file_names1[i] = file_names1[i].Replace(dir1, "*.*");
}
Array.Sort(file_names1);
string dir2 = txtDir2.Text;
if (!dir2.EndsWith("\\")) dir2 += "\\";
string[] file_names2 = Directory.GetFileSystemEntries(dir2, "*",
SearchOption.AllDirectories);
for (int i = 0; i < file_names2.Length; i++)
{
file_names2[i] = file_names2[i].Replace(dir2, "*.*");
}
Array.Sort(file_names2);
// Compare.
int i1 = 0, i2 = 0;
while ((i1 < file_names1.Length) && (i2 < file_names2.Length))
{
if (file_names1[i1] == file_names2[i2])
{
// They match. Display them both.
dgvFiles.Rows.Add(new Object[] { file_names1[i1], file_names2[i2] });
i1++;
i2++;
}
else if (file_names1[i1].CompareTo(file_names2[i2]) < 0)
{
// Display the directory 1 file.
dgvFiles.Rows.Add(new Object[] { file_names1[i1], null });
i1++;
}
else
{
// Display the directory 2 file.
dgvFiles.Rows.Add(new Object[] { null, file_names2[i2] });
i2++;
}
It is pretty simple with Linq.
// Get all entries in file_name1 not in file_names2
var diff1 = file_names1.Except(file_names2);
// Get all entries in file_name2 not in file_names1
var diff2 = file_names2.Except(file_names1);
// Union the two diffs
var result = diff1.Union(diff2);
// Get files in both directory
var common = file_names1.Intersect(file_names2);
foreach(string file in common)
dgvFiles.Rows.Add(new Object[] { file, file });
foreach(string file in diff1)
dgvFiles.Rows.Add(new Object[] { file, null });
foreach(string file in diff2)
dgvFiles.Rows.Add(new Object[] { null, file });
This looks helpful. Where would I put this code in the above code snippet?
After you have loaded the two list of file names and before the adding to the grid. You need only to loop over result and add each item in result to the grid
Oh ok. Before the compare section?
No you don't need anymore that section. Answer updated
Anything else I should take out? Such as the display remaining directory 1 files? And thank you so much. Hope I'm not a bother for you.
No need for these lines if (!dir1.EndsWith("\")) dir1 += "\"; and the Array.Sort ones
What about i1 and i2? Those are the only errors popping up at this point?
| common-pile/stackexchange_filtered |
UIDocumentPickerViewController iOS13 not Working
On my application, i use UIDocumentPickerViewController to allow the user to pick files (import), but starting from iOS 13 that functionality stop working, basically the document picker is open, but the user can't choose a file (taping the file does nothing).
I made a simple sample just to isolate the code:
class ViewController: UIViewController, UIDocumentPickerDelegate {
@IBAction func openDocumentPicker(_ sender: Any) {
let types = [String(kUTTypePDF)]
let documentPickerViewController = UIDocumentPickerViewController(documentTypes: types, in: .import)
documentPickerViewController.delegate = self
present(documentPickerViewController, animated: true, completion: nil)
}
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
print("Cancelled")
}
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
print("didPickDocuments at \(urls)")
}
}
Sample project:
https://github.com/Abreu0101/document-picker-iOS13-issue
Reference:
Which version of Xcode and iOS 13 are you using? Also make sure you test this on a real iOS device.
@rmaddy to make the sample project iOS 11 beta 6 (but for my app, im using Xcode 10.2). It's happening both on Simulator and real Device (iPhone 7 iOS 13.1)
I'm experiencing a very similar issue, although the failure doesn't happen every time. Usually documentPicker(_, didPickDocumentAt) gets called the first time after a fresh launch of my app, but fails on all subsequent attempts. This happens both in the Recents and Browse tab, with iCloud Drive and Dropbox.
I'm running on a physical iPhone X with iOS 13.1 beta 3, building with Xcode 11.0 GM.
@JamieA Looks like is a bug on iOS 13 beta. After upgrading to official iOS 13 start working. Btw notice that this wasn't specific of my App, was also happening in other apps (i.e Slack).
any fixes for this? i am facing this issue
Same issue for our application, but not for all devices. Waiting for solution. Thanks in advance.
Does anybody know if this is fixed in iOS 13.2?
Same issue with iPadOS 13.2.3. Prior versions didn't work only on simulators, now it doesn't work on an actual device.
I downloaded the "Particles" app demo package from Apple, and it acts the same way.
Same issue still exist. Nothing seems to work to fix it. But if I open document in our app from apples archive app it works fine and the file that was opened this way is unlocked and can now we opened through documentpicker again. This is quite frankly VERY frustrating.
When I got this issue, I realised that it's working when choosing files from "Browse" tab because I implemented the method "didPickDocumentAt", but it was not working when I tapped on files from "Recent" tab.
To make it work on "Recent" tab, I'd to implement the method "didPickDocumentsAt", which makes the same thing, but it handles an array of URLs.
On Mojave there's the problem, make sure you upgrade your os to Catalina.
https://github.com/Elyx0/react-native-document-picker/issues/246
UIDocumentBrowserViewController error "Cannot create urlWrapper for url" on iOS13 simulator
Author asks for iOS 13
@Softlion the problem is not about ios 13 it's about the os running(Mojave or below), so to fix the problem just upgrade your mac os and problem will be fixed
I enountered this issue on iOS 13.2.2. Updated to iOS 13.2.3 fixed this issue without any code changes.
I take that you meant to say that updating to iOS 13.2.3 fixed the issue? As of today (6 December 2019), I don't believe that a version 13.3.3 has been released yet.
| common-pile/stackexchange_filtered |
SSIS Delete and Recreate Destination Table
I was creating a trigger and accidentally ran it on production instead of testing. I have a backup where no information will be lost in this specific table, but I only need to restore this single table.
Using SSIS how can I simply:
Only update a single column to make it match the backup table. -or
Drop and recreate the table exactly the same as the one I have?
[Disclaimer: I am assuming you have a database back up]
If you have a QA or Dev environment you could restore your production copy on it and then use SSIS to update using SCD or do a truncate/delete and copy the data over
What I eventfully did was restore the entire database back to my development machine. After that I created a new table within the production database and transferred the restored table to it. I then ran an update statement to correct the broken column from the new table
| common-pile/stackexchange_filtered |
VirtualBox doesn't restore saved Ubuntu machine state?
I'm running Ubuntu 12.04 inside Virtualbox on Windows XP Prof. Everything works fine. I'm running it at startup, but I have a problem with rebooting.
When I reboot my computer (WinXP) now the state of the virtual Ubuntu 12.04 isn't saved. After the reboot the virtualbox starts from the beginning.
Is there an option that Windows XP could send some signal to the virtual box to safely close the instance before the host reboot?
which version of VirtualBox?
This is a known bug with VirtualBox prior to versions 3.2.6 which has bit me as well. This occurs if you have a non-standard install path
The problem seems to be caused by not using the standard locations for
snapshots etc. Humour Virtualbox and allow it to keep all its files in
the standard directory, i.e. c:\Documents and Settings\%user%\.VirtualBox\.
The easy fix would be to upgrade VirtualBox - right now it's at 4.x version. Another alternative is to create symlinks, but that's a bit tricky.
And finally, to ensure all bases - I hope you've not set the VM to boot from the Live ISO - silly mistake but I've seen that happen.
| common-pile/stackexchange_filtered |
Is there a Magento debug tool that lets me see database queries displayed in a similar manner to template path hints?
I have some corrupted data, an individual entry, in the database for my Magento installation. Since I can see the corrupted data displaying, I'd like to use a Magento extension to show me the database call displaying that data onscreen. Does such a tool exist? If not, what would be the best tool for SQL to gather this information?
You can see the SQL statement used to load a collection by using $collection->getSelect(). You'd have to narrow down the collection call first though, which might not be much help in your case.
http://blogs.ifuelinteractive.com/2009/10/18/logging-all-sql-in-magento/
I had that enabled. I suppose I was looking for something a little more "to-the-point" but it's possible this is the only option available.
| common-pile/stackexchange_filtered |
unordered_map to have three elements
I am trying to have three elements in an unordered_map. I tried the following code
#include <iostream>
#include <string>
#include <algorithm>
#include <boost/unordered_map.hpp>
typedef boost::unordered_map<int, std::pair<int, int>> mymap;
mymap m;
int main(){
//std::unordered_map<int, std::pair<int, int> > m;
m.insert({3, std::make_pair(1,1)});
m.insert({4, std::make_pair(5,1)});
for (auto& x: m)
std::cout << x.first << ": "<< x.second << std::endl;
}
but I get many errors in the print statement something like
‘std::pair’ is not derived from ‘const std::__cxx11::basic_string<_CharT, _Traits, _Alloc>’
std::cout << x.first << ": "<< x.second << std::endl;
Why not create a structure and add that instead of the pair? I think code would be more readable.
The insert is ok, because that is where I see a problem. It should be m.insert(3, std::make_pair(1,1)); Without {}
The title says "unordered map to have three elements". I only see two elements in the code though. Or do you mean that a map which maps an integer to a pair of integers has a value type with three ints in it?
@MartinBonner I mean a key have two ints as values
@DragosPop Does {} have any side effect
I checked, I was wrong. Well, it does have a side effect in runtime, I debugged in VS 2013 and it creates an intermediary pair. but other than that it is correct.
The problem in your printing statement. It should be like this:
std::cout << x.first << ": "<< x.second.first << ","<< x.second.second << std::endl;
_______________________________^^^^^^^^^^^^^^__________^^^^^^^^^^^^^^^_______________
You can not just print std::pair directly. You need to print each item separately.
There is no ostream& operator<< overload for std::pair but there is one for int.
| common-pile/stackexchange_filtered |
Is iOS keychain API thread safe? Getting duplicate item exceptions
I am working on an iOS app where potentially an SDK can send notifications to the app simultaneously in many different threads and try to write some items in the keychain. Before adding an item to the keychain, my code (obviously) checks if the item is already present in the keychain and if so it throws a errSecDuplicateItem duplicate item exception.
Off-late, I have noticed crashes pertaining to the duplicate item exception while some process tries to add/write a value to the keychain.
Now, my question is, AFAIK, keychain APIs are thread-safe and reentrant in nature.
https://developer.apple.com/documentation/security/certificate_key_and_trust_services/working_with_concurrency
However, since the exception in my case is thrown by errSecDuplicateItem, it definitely looks like a thread sync issue. Perhaps, even if keychain APIs themselves are thread-safe, the usage flow (things happening in different threads, etc.) in my case might cause that sync issue. For now, I have decided that it's a good idea to treat the adding of the item in the keychain piece as a critical section (so I have but the whole code inside @synchronized(self) {}) and to see if we can reproduce the error again.
Am I on the right track?
Sure “thread safe” doesn’t mean you get to stop following best practices for avoiding accessing shared resources. The usual way is just use GCD to ensure all accessed are on the same serial queue.
"Thread safe" in other words does not relieve you of the responsibility of making your own code thread safe! You must still behave coherently for your own usage. "Thread safe" just means the thing you are talking to won't crash just because you're using threads.
| common-pile/stackexchange_filtered |
Call one function after another function having a async function in itself
How to call one function a() after another function b() when b() contains a async function c()?
A() {
}
B() {
//do sometihng
c(); //async function
//do something
}
I want to call A() if B() including c() is done executing. But I can not modify function B().
what is in c()?
async function b(){
await c();
}
function a(){}
(async function(){
await b();
a();
})()
make b await c, then you can await b and execute a. another way would be:
function b(){
return c();
}
b().then(a);
note that async and await not supported in all browsers
no, not at all... lots of legacy browsers that don't support them
@charlieftl no , i based my use of async on the question, where the op is talking about async functions ...
but I can not modify anything inside b()...Its already defined.
@avinash then its impossible
@Avinash, then b is badly designed, and you are without hope.
@trincot what about with({b:_=>b().then(a)}){c)} ? !)
@Jonas, an object with a b property? I don't see (besides the syntax errors) where you want to go to with that.
@trincot yep, that is used for variable lookup... oh and theres just a ( missing :/
the keyword awaitis what you're looking for.
From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await :
If a Promise is passed to an await expression, it waits for the Promise's resolution and returns the resolved value.
async function c() {
await b();
a();
}
| common-pile/stackexchange_filtered |
Docusaurus strips some attributes from inline SVGs; need ID for accessibility
I'm using inline SVGs like this:
Content of icon-checkmark.svg:
<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" viewBox="0 0 46 46"><title id="myTitleID">An accessible title</title><path {…} /></svg>
Import & inline:
import CheckmarkSvg from '/img/site-components/icon-checkmark.svg';
<CheckmarkSvg role="image" aria-labelledby="myTitleID" className="myClass" />
But Docusaurus strips the title's ID attribute from the rendered SVG.
Is there a workaround for this? Without it, the title is not accessible in some browsers.
It's what I suspected: There is a dependency in @docusaurus/core for @svgr/webpack, which in turn ultimately loads SVGO. This one will strip "unused" ids from SVG files unless the module cleanupIds is deactivated. Good look finding where this config is supposed to go.
Good to know. Turns out it was easier (and a good learning opportunity) to create a custom component and inline the SVGs that way.
Post your comment as an answer & I'll mark it as correct.
As @ccprog stated in their comment, Docusaurus depends on SVGR, which depends on SVGO. SVGO was the library ultimately doing this. However, recent versions of Docusaurus no longer remove the <title> anymore, as Docusaurus preconfigured SVGR/SVGO to omit that behavior.
Reference: fix(utils): make SVGO not remove title
Regarding the removal of <title> in general, indeed this is a flaw with SVGO, and this behavior will be disabled in the next major release.
While this is no longer an ongoing issue, I'll drop an answer for how to address issues like this, in case someone wants to reconfigure other SVGO plugins through Docusaurus.
I recommend resolving this through Docusaurus' Lifecycle APIs. One can use the configureWebpack function to alter the SVGO options.
To do this, create a custom plugin for Docusaurus in your repository.
src/plugins/configure-svgo.js
/**
* Docusaurus uses SVGR internally, which in turn uses SVGO. This alters the
* SVGO config and merges the changes back into Docusaurus' webpack config.
*
* @returns {Object}
*/
function configureSvgo() {
return {
name: 'configure-svgo',
configureWebpack(config) {
/** @type {object[]} */
const rules = config.module.rules;
const rule = rules.find((rule) => {
/** @type {string|undefined} */
const loader = rule.oneOf?.[0]?.use?.[0]?.loader;
return loader && loader.includes("/@svgr/");
});
const svgoConfig = rule.oneOf[0].use[0].options.svgoConfig;
// alter svgoConfig with whatever changes you need
return {
mergeStrategy: {
"module.rules": "replace"
},
module: { rules }
};
}
};
}
module.exports = configureSvgo;
You can alter svgoConfig by appending plugins to the plugins array, or disabling plugins in the default preset, etc. In this case, you'd want to disable a plugin.
Once you've created the plugin, you'd then need to enable it in your Docusaurus config:
docusaurus.config.js
// …
plugins: [
// …
"./src/plugins/configure-svgo.js"
],
// …
Docusaurus will now pass your SVGO config to SVGR/SVGO, so SVG's will still be optimized, but will also fulfil your project requirements.
| common-pile/stackexchange_filtered |
Issue with combining multiple separate data points in R
I have X number of spreadsheets with information spreading out over two tabs.
I am looking to combine these into one data frame.
The files have 3 distinct cells on tab 1 (D6, D9, D12) and tab 2 has a grid (D4:G6) that i want to pull out of each spreadsheet into a row.
So far i have made the data frame, and pulled a list of the files. I have managed to get a for-loop working that pulls out the data from sheet1 D6, i plan to copy this code for the rest of the cells I need.
file.list <-
list.files(
path = "filepath",
pattern = "*.xlsx",
full.names = TRUE,
recursive = FALSE
)
colnames <- c( "A","B","C","etc",)
output <- matrix(NA,nrow = length(file.list), ncol = length(colnames), byrow = FALSE)
colnames(output) <- c(colnames)
rownames(output) <- c(file.list)
for (i in 1:length(file.list)) {
filename=file.list[i]
data = read.xlsx(file = filename, sheetIndex = 1, colIndex = 7, rowIndex = 6)
assign(x = filename, value = data)
}
The issue i have is that R then pulls out X number of single data points, and I am unable to bring this out as one list of multiple data points to insert in to the dataframe.
I'd strongly advise using a list rather than assign. See, e.g., my answer at How to make a list of data frames?. Beyond that, without your spreadsheet we can't run any of this code. Can you share a data frame for one of the files? dput() is nice for sharing a copy/pasteable version of a data frame. And, when you say "R then pulls out X number of single data points", what code do you have that does that?
@Gregor - thanks. I'm going to look at the link and see if that helps. - for loop currently pulls out X number of single cells from each of the excel files in the appropriate folder. In this case D6 is a name. So I have X number of "names" in the data part of excel (when i click them a new tab pops up on Rstudio) - but i want one list of all names
| common-pile/stackexchange_filtered |
Proving that $L-\{x\}$ is not connected.
Problem: Let L be a linearly ordered set and give it the order topology. Suppose $x$ is an element of L which is not maximal or minimal. Prove the $L-\{x\}$ is not connected.
So I have to show that there exists some separation of $L-\{x\}$. But isn't $(-\infty,x)\cup (x,\infty)=$$L-\{x\}$ or in the case where L has a largest and or smallest element $a_0$ and $b_0$ respectively, the separation would be $(a_0,x)\cup (x,b_0)=$$L-\{x\}$. These sets are open in the order topology, and open rays are open too, hence it is a separation right?
It's almost correct. To be almost pedantic:
$L \setminus \{x\} = L_x \cup R_x$, where $L_x = \{y \in L: y < x\}$ and $R_x = \{y \in L: y > x\}$. These sets are subbasic open (open rays) in the order topology, so open sets of $L$ in the order topology.
And if $z \in L\setminus\{x\}$ then either $z > x$ or $z < x$ according to the axioms of a linear order. This proves the union.
The sets are also disjoint: otherwise we'd have $p < x < p$, when $p\in L_x \cap R_x$ which cannot be.
Both are non-empty as $x$ is not a minimal element: there is at least one $p < x$< so $L_x \neq \emptyset$, and as it is not maximal, at least one $q > x$, so $q \in R_x \neq \emptyset$. Hence it is a separation.
| common-pile/stackexchange_filtered |
Raspberry Pi 4 does not respond ssh
My setup is a RaspberryPi4 with SSD (Kingston 120GB) as boot drive. It has also a regular HDD connected to it. Both hard drives are connected to a USB dock via 3.0 USB. The dock has also a power supply so no energy problems should arise. Connected via ethernet to router. SSH enabled. I have setup an apache server with Nextcloud (which it hasn't been started to be used because of the problems stated below) and also is setup as a client for a Wireguard VPN.
The problem is that when I turn on the RPi4 I can ssh to it without any issues, but if I leave it powered ON overnight, the next day I try to connect to it, the ssh console (or whatever I try to use) just freezes or behaves abnormally.
One day I could log in but I could not run any "complicated" commands (just cd and ls were working) and trying to run commands like sudo nano just left my ssh window frozen, no output. And today for example it just does not connect. I can ping the RPi4, but ssh refuses to let me in. It just freezes after inputting the password, no output from the RPi4.
I don't know what might be happening, this is the first time something like this happens to me, but I think it could be related to the USB dock with the hard drives in it? How can I know what is happening?
There are many possibilities, from a heavy load that is running to a faulty SD card.
First thing is to examine the logs. Does the syslog give any hints? Errors/warnings? If so: this is probably the first thing you need to correct.
Next would be the filesystems. Any at 100%? What about swap?
Can you run a vmstat 10 > /tmp/vmstat until it crashes? that would give some information about whether the system is extremely loaded. If the vmstat shows extreme load, you might try
#!/bin/bash
while : ; do
top -bn1 >>/tmp/top
sleep 10
done
(or put the output on some external drive if your sdcard is relatively full). That will give you an idea of the process that causes the load.
I'm going to leave the script running tonight to see if tomorrow i still have the same issues. Just a quick note, in my setup I point out that I do not have an sd card to boot, but a SSD instead, don't know if that may be the issue or not. I even also increased the swap size to 2GB so the Raspberry had more space for programs to run
So I have been running it for 2 days and so far no issues... also no weird things on the logs so I don't know... if it does not start failing i think i will mark your answer as the one that "solved" the issue... what a weird thing...
It could be that there is a heavy memory workload, so there is a lot of swapping. I had similiar issues when I executed too many programs at once.
Try disabling swapfile, then the heavy memory application should be killed more likely and ssh should be still available.
Try this day via sudo swapoff -a This disables swap until the next reboot.
The thing is that I do not really have installed that many programs. I mean, there's only wireguard and apache server. I'm going to use the script that @Ljm_Dullaart left on their answer and leave it overnight so i can see which processes were taking the most resources from my Pi. I might have to consider more lightweight options for the pi tho...
I don't really think it might be a swap issue as I have an SSD and I have allocated lots of swap space onto the SSD. Also been checking with top command the most consuming processes and no one had more than 0.5% of the RAM in use... so I don't know
| common-pile/stackexchange_filtered |
SImple solution to Codeigniter image class?
I have some messy code, even i use SimpleImage, i know i can use CodeIgniter image class, but config is little big, can someone post a little elegant and better solution, this is my code for now, i want to get rid of SimpleImage, and image class is initialized in controller.Here is what i have:
// Main config
$config['image_library'] = 'gd2';
$config['maintain_ratio'] = TRUE;
$config['height'] = '1';
$config['master_dim'] = 'width';
$config['overwrite'] = TRUE;
// Resize image with SimpleImage
$novaslika="img/proizvodi/".$last.".jpg";
$image = new SimpleImage();
$image->load($_FILES['slika']['tmp_name']);
$image->resizeToWidth(800);
$image->save($novaslika);
// Create PNG
$config['source_image'] = $_FILES['maska']['tmp_name'];
$config['width'] = 800;
$config['new_image'] = "./img/proizvodi/".$last."_maska.png";
$this->image_lib->initialize($config);
$this->image_lib->resize();
// Create thumb
$config['source_image'] = './img/proizvodi/'.$last.'.jpg';
$config['create_thumb'] = TRUE;
$config['new_image'] = './img/proizvodi/thumbs/'.$last.'_thumb.jpg';
$this->image_lib->initialize($config);
$this->image_lib->resize();
Why don't you just skip the Resize with SimpleImage block of code and have the Create PNG block both create the PNG and resize to 800?
Not to much to do, how to etc put all config in multi array and then do something :)
You can do something like this:
function index()
{
$this->load->library('image_lib');
$a = array(
'source_image' => 'images/1.jpg',
'width' => 100,
'height' => 100,
'new_image' => 'images/2.jpg',
'create_thumb' => TRUE,
'overwrite' => FALSE
);
$image = $this->_image_manipulation($a);
if($image === TRUE)
{
echo "IMAGE OK";
}
else
{
echo $image;
}
}
private function _image_manipulation($configs = '')
{
if($configs)
{
$config['image_library'] = 'gd2'; //static
$config['maintain_ratio'] = TRUE; //static
$config['master_dim'] = 'width'; //static
$config['source_image'] = $configs['source_image'];//required
$config['height'] = (isset($configs['height']))?$configs['height']:NULL;
$config['width'] = (isset($configs['width']))?$configs['width']:NULL;
$config['overwrite'] = (isset($configs['overwrite']))?$configs['overwrite']:NULL;
$config['new_image'] = (isset($configs['new_image']))?$configs['new_image']:NULL;
$config['create_thumb'] = (isset($configs['create_thumb']))?$configs['create_thumb']:NULL;
$this->image_lib->initialize($config);
if ( ! $this->image_lib->resize())
{
return $this->image_lib->display_errors();
}
else
{
return TRUE;
}
}
}
But will still need the SimpleImage library to convert to png's UNLESS, and I can't confirm, SimpleImage is using ImageMagick. If it is, that means it's installed on the system and you can change
$config['image_library'] = 'gd2';
to
$config['image_library'] = 'ImageMagick';
and CodeIgniter will handle the image conversion for you too; all you need to do is rename the file:
$a = array(
'source_image' => 'images/1.jpg',
'new_image' => 'images/1.png',
);
| common-pile/stackexchange_filtered |
Hindi unicode text incorrect on Android 4.1
I have a piece of Hindi text:
हाइड्रोजन परआॅक्साइड 3%
(Image of the text in case the quote is rendered incorrectly)
On Android API 16 a character is wrong and a dotted circle is shown instead. This is regardless of the font used. On Android API 26 the text is rendered correctly. This makes me wonder if there's something wrong with the original text or if Android's Unicode handling is at fault.
I don't speak Hindi myself so this is hard for me to reason about.
Well i do not know hindi too but i would not say 'an error occurs' but 'all is displayed well except for one character'. Or am i wrong?
@greenapps, Right, that's a more precise description of the issue. I've changed the question.
And after that i would have made clear which character exactly.
which font are you using? We have an app which supports Hindi locale. We use Noto Sans Devanagari.
Can you try this font and check if it solves the problem
https://stackoverflow.com/q/16108088/4407266
https://stackoverflow.com/q/25456932/4407266
| common-pile/stackexchange_filtered |
CLLocationManager not very accurate inital updates
This is stated in CLLocationManager class reference:
When requesting high-accuracy location data, the initial event delivered by the location service may not have the accuracy you requested.
This is really affecting my app. How can I make sure that the location found is the one with the correct accuracy?
I tried to use the 4th or 5th update rather than first retrieved location but this is not a good solution. Any idea?
You should check the accuracy of the updates, CLLocation
contains a property horizontalAccuracy which you can use to check the accuracy.
When the CLLocation has an accuracy that you find accurate enough you use and ignore al others.
Als you should tel CLLocationManager your desired accuracy. To do this set the desiredAccuracy property in CLLocationManager.
Thanks for you answer. I read about this solution somewhere else and I will try this soon although I don't how it calculates an unknown location accuracy.
I think you will have to live with that. That's how Apple implemented it. Getting a fine grained position takes time, just think about how long any windshield-mounted GPS devices in cars take to fix up their position.
So instead of letting your application wait for a longer time, they provide with what accuracy is available almost immediately, based on cell-towers and WiFi hotspots in the vicinity. Only when there has been a more reliable GPS fix will they call into your app again and let you know.
In the end, it is just a question of where the waiting for the fine-grained position is: In your app, where you have the chance of doing something with the more coarse-grained data you get quickly, or in their framework with no chance for apps to do anything useful in the meantime. I think, letting you decide is the better choice.
Depending on the type of app, you could have a map that automatically zooms in deeper as soon as better position data comes in, draw a smaller circle around the position you are expecting etc. For the end user, nothing's worse than waiting without getting any feedback. So even though this is probably not the answer you would have liked, I advise to make the best of it from a user's perspective.
I agree that enforcing waiting time to the user is crazy. But the problem is, my app just needs a location and does not need any more update. There's nothing to be shown on the map. It just get a location and finds nearest bus stop and it's worthless if you have a bus stop within 100m but first couple of location updates will give you a bus stop somewhere in the next neighborhood.
| common-pile/stackexchange_filtered |
Cron job to invoke HTTP restful api
I am using J2EE with Jboss server. I am trying to finding a way to invoke sendEmail api in my code every month.
@GET
@Path("/sendEmail")
@Transactional
public String test(){
I want to invoke this test api which can be accessed using web-browser http://localhost:8181/api/calc/sendEmail
I found some ways to do this:
https://cloud.google.com/appengine/docs/java/config/cron
https://www.mkyong.com/java/how-to-run-a-task-periodically-in-java/
Using cron job looks intuitive way to do this but I find it difficult to search resources to find a way to schedule invoking of the APIs using it.
Please point me to some resources where I can find a way to do so by just adding single dependency for this purpose in pom.xml
You can use Spring Framework for this.
Something like this:
@Scheduled(cron = "0 0 12 1 1/1 ? *")
public void doScheduledWork() {
Check the following link: Spring cron expression for every day 1:01:am
I am using bean, is there similar thing in bean
It's on a method, but yes you can. See https://spring.io/guides/gs/scheduling-tasks/
Another example: http://websystique.com/spring/spring-job-scheduling-with-scheduled-enablescheduling-annotations/
When the application is deployed in multiple boxes or multiple pods(in case of kubernetes) then in each pods the cron expression gets set.
This results in the cron getting triggered n(number of pods) times which results in error case. Better option is to call the cron from external monolith configuration systems by calling through an api.
Applying on a method with the annotation is apt if application runs in only one box(pure monolith).
| common-pile/stackexchange_filtered |
Connect two UIElement with Arc
I have two UIElements(i.e. rectangles) in Canvas and their coordinates. How can I connect them with arc in code behind?
I use google and i could not find anythin useful. I tried to create ArcSegment but without any success. It would be great to have: ArcSegment arc = new ArcSegment(x1, y1, x2, y2);
No need to get an exact hit on the rectangles (or other objects): make sure the Z ordering is correct. arc.SetValue(Canvas.ZIndex, -1) will push it to the background. If you want a perpendicular hit, you'll need to break out the algebra :/
For the arc: (see http://msdn.microsoft.com/en-us/library/ms751808.aspx), it needs to be contained in a PathFigure.
Edit: this shows two connected rectangles. The line simple runs between the two centers. The arc starts on one center (the pathFigure startpoint), first argument is the center of the second object.
r1 = new Rectangle();
r1.Margin = new Thickness(50, 50, 0, 0);
r1.VerticalAlignment = System.Windows.VerticalAlignment.Top;
r1.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
r1.Height = 50;
r1.Width= 50;
r1.Fill = new SolidColorBrush(Colors.Red);
r2 = new Rectangle();
r2.Width = 50;
r2.Height = 50;
r2.Fill = new SolidColorBrush(Colors.Blue);
r2.Margin = new Thickness(350, 450, 0, 0);
r2.VerticalAlignment = System.Windows.VerticalAlignment.Top;
r2.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
l = new Line();
l.X1 = 75;
l.Y1 = 75;
l.X2 = 375;
l.Y2 = 475;
l.Fill = new SolidColorBrush(Colors.Purple);
l.Stroke = new SolidColorBrush(Colors.Purple);
l.StrokeThickness = 2;
l.SetValue(Canvas.ZIndexProperty, -1);
PathGeometry myPathGeometry = new PathGeometry();
// Create a figure.
PathFigure pathFigure1 = new PathFigure();
pathFigure1.StartPoint = new Point(75, 75);
pathFigure1.Segments.Add(
new ArcSegment(
new Point(375, 475),
new Size(50, 50),
45,
true, /* IsLargeArc */
SweepDirection.Clockwise,
true /* IsStroked */ ));
myPathGeometry.Figures.Add(pathFigure1);
// Display the PathGeometry.
Path myPath = new Path();
myPath.Stroke = Brushes.Black;
myPath.StrokeThickness = 1;
myPath.Data = myPathGeometry;
myPath.SetValue(Canvas.ZIndexProperty, -1);
LayoutRoot.Children.Add(r1);
LayoutRoot.Children.Add(r2);
LayoutRoot.Children.Add(l);
LayoutRoot.Children.Add(myPath);
Not if you hide the line behind the two other shapes. The arc can run between the centers of the two other objects. The z ordering takes care of the rest.
The math is contained in the Arc object.
| common-pile/stackexchange_filtered |
Varnish and Connection Flood (DoS - DDoS)
I've been playing around with the Varnish cache server and I got my webpage up lightning fast, it gets 97 Points in Google's Pagespeed and 100 @ Pingdom's. I used Varnish (proxies to nginx), NGINX (only locally available, proxies *.php to php-fpm (but I think about moving to HipHop PHP Compiler)).
So as my page was fast and only ~500/1GB of Ram were used I asked a friend of mine to perform a stress test on this machine's HTTP server. I've configured the following Anti-DDoS-mechanisms:
iptables Firewall limiting Connections / second
some more iptables checks (Sessions starting with a SYN, ICMP and so on)
Varnish caching
Re-coded the small webpage to store some values that may be fetched often in the alternate php cache (i.e.: the currently playing song, ttl of 120 should be fine)
There is no dynamic data on the webpage except for the currently playing song which is APC-powered, and definetly no need for sessions.
So now to my problem, my friend started a DoS attack from some machine he was authorized to use and my server went down VERY fast. I was umable to get on SSH so I used a serial console and checked the varnishd logs, which showed:
session start
session end
And this repeating all the time. I took advance of my console access and banned the IPs, ê voila my page was back.
Now since there is no need for session I need the VCL Syntax for prohibiting all sessions except for scripts in the subdir /user.
What kind of friends do you have?
He is familiar with some kinds of malware I guess, but he definetly is not a blackhat. He used 4 machines, not 4 or 40 thousand.
Check nginx-naxsi.
Naxsi sadly is a WAF and it will 'only' prevent Web Hacking attacks / intrusions like XSS (cross-site-scripting) or SQLi (Injecting malcious SQL into user-given SQL querys, i.e search forms) and thus won't prevent me from D(D)oS, but still thanks for the hint.
IIRC varnish uses threads to handle connections, and is configured with a limit. So all an attacker has to do is open, say, 200 connections to the cache to block every thread (see also slowloris). On the other hand, nginx (which will happily run as a caching reverse proxy) is an event based server; the context switching is demand driven - it's only limited by the number of sockets it can have open and is hence much, MUCH more resistant to such attacks.
(varnish is still better than pre-fork or even worker apache at turning around requests without a big per-request footprint, hence you'll see a lot of people talking about using it to mitigate such DOS attacks).
You can do some stuff to mitigate DOS attacks at the networking layer using iptables and/or QOS based routing, but I'd recommend starting by using nginx as the proxy.
You can install a tool like fail2ban or OSSEC (my favorite) to automatically block this kind of attacks. It doesn't save you from attacks with spoofed IP's (it's really difficult to defend against these), but it's a start.
| common-pile/stackexchange_filtered |
Foundation contact form with abide - php is not working
I have tried everything to get this form to work but no luck.
I guess abide is working now but my php is not sending the email. I don't even think that my php is getting called anyway.
my code is below
form code
line 434
<form id="myForm" data-abide action="mail.php" method="post">
<div class="contactform">
<div class="item item-pair">
<label for="name">Full Name
<input type="text" name="name" id="name" class="small-input cat_textbox" required pattern="[a-zA-Z]+" maxlength="255">
<small class="error small-input">Name is required and must be a string.</small>
</label>
<label for="email">Email Address
<input type="text" name="email" id="email" class="small-input cat_textbox" maxlength="255" required >
<small class="error small-input">An email address is required.</small>
</label>
</div>
<div class="item">
<label>Comments</label>
<textarea cols="10" name="message" id="message" rows="4" class="cat_listbox" required ></textarea>
<small class="error">Please enter your comments</small>
</div>
<div class="item">
<input class="button alert small" type="submit" value="Submit" id="catwebformbutton">
</div>
</div>
</form>
javascript code
line 627
<script>
$('#myForm').submit(function(e) {
//prevent default form submitting.
e.preventDefault();
$(this).on('valid', function() {
var name = $("input#name").val();
var email = $("input#email").val();
var message = $("textarea#message").val();
//Data for reponse
var dataString = 'name=' + name +
'&email=' + email +
'&message=' + message;
//Begin Ajax call
$.ajax({
type: "POST",
url:"mail.php",
data: dataString,
success: function(data){
$('.contactform').html("<div id='thanks'></div>");
$('#thanks').html("<h2>Thanks!</h2>")
.append("<p>Dear "+ name +", I will get back to you as soon as I can ;)</p>")
.hide()
.fadeIn(1500);
},
}); //ajax call
return false;
});
});
</script>
html link
http://tayrani.com
Please help
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$comments = $_POST["message"];
$msg = "
Name:$name
Email:$email
Comment:
$comments";
$to =<EMAIL_ADDRESS>$subject = "website email";
$message = $msg;
$headers = "form";
mail($to,$subject,$message,$headers);
?>
Is your ajax function is working well..? Try to put var_dump($name); on mail.php to find $name is getting its value or not.
I just want to confirm that ajax call is working or not..so put var_dump($name); on your mail.php page and retry. so we can find the actual problem.
I put it there but it didn't do anything
is it supposed to do a specific action ?
if I access tayrani.com/mail.php it gives NULL
change $headers = "form"; to $headers =<EMAIL_ADDRESS>
Are u getting any error related to javascript in your console.?
Thanks for the help I got it working. It turned out to be Hotmail that is not accepting emails for some reason. So, I replaced the Hotmail account with a Gmail account and it worked. I also updated my code with the following
html code for the form
<form id="myForm" data-abide="ajax" action="mail.php" method="post">
<div class="contactform">
<div class="item item-pair">
<label for="name">Full Name
<input type="text" name="name" id="name" class="small-input cat_textbox" required pattern="[a-zA-Z]+" maxlength="255">
<small class="error small-input">Name is required and must be a string.</small>
</label>
<label for="email">Email Address
<input type="email" name="email" id="email" class="small-input cat_textbox" maxlength="255" required >
<small class="error small-input">An email address is required.</small>
</label>
</div>
<div class="item">
<label>Comments</label>
<textarea cols="10" name="message" id="message" rows="4" class="cat_listbox" required ></textarea>
<small class="error">Please enter your comments</small>
</div>
<div class="item">
<input class="button alert small" type="submit" value="Submit" id="catwebformbutton" name="btnSubmit">
</div>
</div>
</form>
My javascript code including fixing the submitting twice issue
<script>
$('#myForm').submit(function(e) {
//prevent default form submitting so it can run the ajax code first
e.preventDefault();
$(this).on('valid', function() { //if the form is valid then grab the values of these IDs (name, email, message)
var name = $("input#name").val();
var email = $("input#email").val();
var message = $("textarea#message").val();
//Data for reponse (store the values here)
var dataString = 'name=' + name +
'&email=' + email +
'&message=' + message;
//Begin Ajax call
$.ajax({
type: "POST",
url:"mail.php", //runs the php code
data: dataString, //stores the data to be passed
success: function(data){ // if success then generate the div and append the the following
$('.contactform').html("<div id='thanks'></div>");
$('#thanks').html("<br /><h4>Thanks!</h4>")
.append('<p><span style="font-size:1.5em;">Hey</span> <span class="fancy">'+ name +'</span>,<br />I´ll get back to you as soon as I can ;)</p>')
.hide()
.fadeIn(1500);
},
error: function(jqXHR, status, error){ //this is to check if there is any error
alert("status: " + status + " message: " + error);
}
}); //End Ajax call
//return false;
});
});
</script>
<script>
$(document).foundation('abide', 'events'); // this was originally before the above code, but that makes the javascript code runs twice before submitting. Moved after and that fixes it.
</script>
Here is the php code
<?php
if(isset($_POST["name"])){
$name = $_POST["name"];
$email = $_POST["email"];
$comments = $_POST["message"];
$msg = "
Name: $name
Email: $email
Comments:
$comments";
$to =<EMAIL_ADDRESS> $subject = "Tayrani.com Contact Form";
$headers = "From: <$email>";
mail($to,$subject,$msg,$headers);
}else{
}
?>
I struggled for 3 days to get this done but thanks to my colleague/friend Adam as he really helped me with it.
I hope this is useful for other people.
Thanks,
Hussein
tayrani.com
| common-pile/stackexchange_filtered |
How to preview a cms page in Magento 2 admin panel
Is it possible to preview the CMS page before push live?
I can't preview my page while creating a page on cms page in admin panel Magento 2.
How can I preview?
"View" link should be already there which shows the preview of CMS page from CMS pages grid.
@MohitKumarArora But the issue is View option is available after publishing the cms page, as it requires to save.. and after saving the page it gets publish and i am only able to preview it after publishing it.
Nice feature (y). I have bookmarked your question.
Are you going to create a pull request for this feature I am waiting :D
If it gets done, I will be interested to pull. :) BTW you can have a look at https://marketplace.magento.com/mageside-admin-useful-links.html
@MohitKumarArora but this extension doesn't provide a preview before publishing the page.
Are you using Page Builder?
@brentwpeterson yes
You can update and preview changes using the schedule update
You can see that you can schedule your update, in this you get to update your content without going live, you can save and preview
| common-pile/stackexchange_filtered |
Syntax error for link in nested content_tag :div
I'm new to rails. I'm trying to add a link to a div that is being generated with the content_tag. I'm getting a syntax error but I can't seem to figure out why.
I used this reference
- flash.each do |name, msg|
- if msg.is_a?(String)
= content_tag :div, msg content_tag(:a, "Close", :href => '', :class => 'close'), :id => "flash_#{name}", :class => 'alert-box alert'
What am I doing wrong?
You're trying to produce something like <div>msg <a>Close</a></div>?
Yes. I should've mentioned that. Thanks.
you forgot to concatenate msg with your content_tag :a. try this:
- flash.each do |name, msg|
- if msg.is_a?(String)
= content_tag :div,
"#{msg} #{content_tag(:a, 'Close', :href => '', :class => 'close')}",
:id => "flash_#{name}", :class => 'alert-box alert'
hint:
you can use a block with content_tag to improve readability.
content_tag :div do
# the content of this block will be captured
end
Thanks! I did have to make it html_safe. Please update your sample incase another n00b comes across this ;)
| common-pile/stackexchange_filtered |
distinguish - transitive or intransitive
Merriam-webster dictionary says that in:
distinguish X from Y - distinguish is transitive
distinguish between X and Y - distinguish is intransitive
Do you agree? If it's true, what's the difference between the two:
It’s hard to distinguish an apple from a pear.
It’s hard to distinguish between an apple and a pear.
Why is this a question. What is unclear about the dictionary, Or why do you doubt the dictionary? Yes the first is transitive and the second is intransitive. But there isn't much difference in the meaning. It's like "give an apple to him" (one object) and "give him an apple (two objects) but much the same meaning.
With only a few exceptions, a transitive verb (or clause) is defined as one that has a direct object. If there is no direct object present, then the verb/clause is intransitive. Thus in the first of your examples, "an apple from a pear" is direct object of "distinguish", while in the second, it is object of the preposition "between".
@ James K - I am afraid your example doesn't fit in with mine. "Give" is transitive in both of your examples.
It is ditransitive in one of the examples. So the verb "give" has valency of 2 in one form and valency of 1 in the other. You have a verb with a valency of 1 in one form and of 0 in another.
Your example is correct but I'm not sure that it helps to make the meaning of "transitive" and "intransitive" clear.
A transitive verb is a verb that takes an object. The verb acts on something. An intransitive verb does not take an object.
For example, "Bob bought a car." The verb is "bought". It takes an object, "a car". What did Bob buy? He bought a car.
With some verbs, it doesn't make sense to have an object. The verb doesn't act on any particular object. It just happens. Like, "Bob slept." What is the object of "slept"? There is none. He didn't sleep something. The sleep didn't act on anything. He just slept.
Sometimes a verb can take an object but it doesn't have to. Like I could say, "Bob sang a love song." What did he sing? A love song. But I could also just say, "Bob sang." I don't specify what he sang.
In your first example, "We distinguish an apple from a pear", "distinguish" is acting on something. What do we distinguish? We distinguish an apple. In real life if I just said, "We distinguish an apple", that prompts the question, "Distinguish an apple from what?", so we need to add some words to say what we are distinguishing it from. But that's not required by the grammar, that's required by the meaning of the word "distinguish". And technically, it can be valid to just end with the object. Like if the eye doctor said, "Can you read this eye chart?", you might answer, "I can distinguish an 'R'." In that case you mean, you can see that there is an 'R', without regard to what it is not.
In your second example, "distinguish between an apple and a pear", the verb is not taking an object. Rather, we are using a prepositional phrase to say what the two things are that we are distinguishing. The practical meaning is the same as the first example, it's just different grammar to express the same idea.
I see. It just appears to be strange to have a verb both as intransitive and as transitive and have the same meaning.
| common-pile/stackexchange_filtered |
Executable file set root suid, but access(path, W_OK) still return -1?
Why executable file set root suid, but access(path, W_OK) still return -1?
Code:
#include <stdio.h>
#include <unistd.h>
int main()
{
printf("privilege => %d\n", access("/usr/local/etc/t.conf", W_OK));
return 0;
}
Test run:
[www@mypy access]$ ll
总用量 12
-rwsrwxr-x. 1 root root 6600 1月 22 10:05 access
-rw-rw-r--. 1 www www 135 1月 22 10:05 access.c
[www@mypy access]$ ./access
privilege => -1
[root@mypy access]# ./access
privilege => 0
One simple reason is that the specified pathname does not exist at all.
the file really exists, as you can see, root execute it return zero
The access library function deliberately checks the access rights of the real user, ignoring the fact that the executable has a different effective UID/GID.
If you only want to know whether read or write access is possible, you can open the file and see if there was an error. However, careful setuid executables often want to know whether the real user would have been able to perform an action on the file. To find out, they can use the access library function.
This is explained in man 2 access:
The check is done using the calling process's real UID and GID, rather than the effective IDs as is done when actually attempting an operation (e.g., open(2)) on the file.…
This allows set-user-ID programs and capability-endowed programs to easily determine the invoking user's authority. In other words, access() does not answer the "can I read/write/execute this file?" question. It answers a slightly different question: "(assuming I'm a setuid binary) can the user who invoked me read/write/execute this file?", which gives set-user-ID programs the possibility to prevent malicious users from causing them to read files which users shouldn't be able to read.
thanks rici's answer!I completed it as follow
int accesswriteable(char const *path)
{
if(access(path, F_OK))
{
return 1;
}
FILE *fp = fopen(path, "a");
if(fp == NULL)
{
return 1;
}
fclose(fp);
return 0;
}
#define PATH_WRITE_ABLE(path) (accesswriteable(path) == 0)
| common-pile/stackexchange_filtered |
Header and Footer template in CKEditor
I have implemented CKEditor in my project as per the requirement. I need to covert my html file to word document at the end on user input and my system is creating the document file perfectly. Now my client wants me to implement header and footer functionality same as word in my ckeditor edit area. What is the options available to implement such header footer functionality in ckeditor.?
Allow the client to input header and footer content is separate textarea/editor?
Hi I made a patch for this solution.
i have created a table where i inserted all the information related to the file with the full path, the header text and the footer text and created one .net processes to pick the file from the path and add the header and footer to the file and at the end application will replace the new file with existing one. .net has very nice functionality to implement it.
| common-pile/stackexchange_filtered |
Count how many UL Elements there are in a Div with Javascript?
I am dynamically adding UL elements to a DIV element. I would like to be able to count how many UL elements there are inside the DIV so that once all the ULs are removed dynamically I can delete the DIV that they are contained in.
<div id="000">
<ul id="000-1">
<li>Stuff</li>
<li>Stuff</li>
</ul>
<ul id="000-2">
<li>Stuff</li>
<li>Stuff</li>
</ul>
</div>
Is there a simple Javascript solution that counts the amount of ULs so that I can do something like this.. ?
if(ulcount == 0){
var remove = document.getElementById("000");
remove.innerHTML = '';
results.parentNode.removeChild("000");
}
Thanks.
@Cheeso's answer is a good pure-JS solution. But, if you're using jQuery, the process can be made simpler.
jQuery('div#000').children('ul').length;
The above code will return the number of child ul elements of the div#000.
To update the count when you add elements dynamically, you will have to create a function and call it to update the number whenever a change occurs:
function countUls() {jQuery('div#000').children('ul').length;}
Bind that to an event so that it will be called when you want to update the number.
Can I use this jQuery solution in conjunction with exsisting javascript functions?
@Wezly Certaily! jQuery is a JavaScript library, so it can be used alongside standard JavaScript.
A simpler solution could be $("#000 > ul").length - an ID is unique and there is a child selector as well.
Code:
function getDirectChildrenByTagName(elt,tagname) {
var allChildren = elt.children, wantedChildren=[], i, L;
tagname = tagname.toUpperCase();
for(i=0, L=allChildren.length; i<L; i++) {
if (allChildren[i].tagName.toUpperCase() == tagname) {
wantedChildren.push(allChildren[i]);
}
}
return wantedChildren;
}
use it like this:
var zero = document.getElementById("000");
var uls = getDirectChildrenByTagName(zero, 'UL');
var ulCount = uls.length;
....
Try this:
var x = document.getElementById("000-1").querySelectorAll("li").length
console.log(">>>>", x);
| common-pile/stackexchange_filtered |
how to hide Player slider in MPMoviePlayerViewController
I have a video app in that i use MPMovieplayerViewcontroller. In that i want to hide Player Slider.So user can not seek video forward or backward.
and I use
self.videoPlayerViewController.moviePlayer.controlStyle=MPMovieControlStyleEmbedded;
Thanks in advance.
but i want play pause button and hide only seeking bar.
| common-pile/stackexchange_filtered |
using IN statement in mysql php queries
Hi guys I hope everyone doing well.
I want to know how can I use IN statement in PHP Mysql query,
I have this example inside DB table where the column name is Model
Model column in mytable
A901:Y921:L102
I want to remove: and use it in PHP SQL queries like
SELECT * FROM mytable WHERE model IN (A901,Y921,L102)
I know it's not possible to call like this it should be IN ('A901','Y621','L102')
But how can I convert it to this way? I want to make this call in order to get all the related rows from different tables.
my humble try like this
<?php
if($mytable->model)
$mod = explode(':', $mytable->model);
foreach($mod as $ac)
{
echo $ac;
?>
RESULT: A901 Y921 L102
I approach your help guys.
$mod = explode(':', $mytable->model);
$pp = array_fill(0, count($mod), '?');
$paramPlaceholders = implode(',', $pp);
Now we have a string like '?,?,?'. These are parameter placeholders to use in SQL syntax. You can pass your array as the parameter values to a prepared statement:
$query = "SELECT * FROM mytable WHERE model IN ({$paramPlaceholders})";
$stmt = $pdo->prepare($query);
$stmt->execute($mod);
Re your comment:
I use PDO, and I recommend it over mysqli. The equivalent code for mysqli would be similar:
$query = "SELECT * FROM mytable WHERE model IN ({$paramPlaceholders})";
$stmt = $mysqli->prepare($query);
$stmt->bind_param(str_repeat("s", count($mod)), ...$mod);
$stmt->execute();
I am using mysqli to get the data from DB now I am confusing .
after several try it seems it's not working.
| common-pile/stackexchange_filtered |
A global version of evil C-w
In vim and evil mode, normal-state C-w prefixes various window-related
commands. For example, C-w l moves focus to the right, and C-w L
moves the currently focused window to the right.
I would like access these commands in buffers that do not play well with
evil mode (such as PDF buffers). Is it possible to make C-c w act
globally as C-w does in evil normal state? It should be possible to
use prefixes and counts.
All you need to do is assign your keybinding of choice to
evil-window-map, whose docstring is:
Prefix command (definition is a keymap associating keystrokes with commands).
In your case, the following should work:
(global-set-key (kbd "\C-c w") #'evil-window-map)
| common-pile/stackexchange_filtered |
How does enable_if works in this case
#include <iostream>
#include <functional>
#include <memory>
using namespace std;
template<typename T = int> std::enable_if_t<!std::is_arithmetic<T>{}, T> nope() {}
int main() {
nope();
}
This is a simple code which does't compile. If one changed this:
int main() {
nope();
}
to
int main() {
nope<std::string>();
}
it starts to compile.
The question is why does this work like it works? To be more specific why does compiler tells me:
no matching function for call to 'nope()'
instead of something like
enable_if::type not found
(which is true as it really does not exist if condition is not satisfied)?
Thank you.
Since your asking about why the compiler favors one error message over another, you should tag this question with the compiler you are using.
What you're seeing is called SFINAE.
Both GCC and Clang give decent error messages on this. Clang even gives note: candidate template ignored: disabled by 'enable_if' [with T = int] using enable_if_t = typename enable_if<_Cond, _Tp>::type;
It probably does tell you that. At least it does on clang, gcc.
@nwp. Gcc does not, in my case (7.2)
That's odd, because coliru uses gcc 7.2 too and produces the warning just fine.
If you call nope(), your template type defaults to int. std::enable_if_t<!std::is_arithmetic<T>{}, T> returns false for !std::is_arithmetic<int>{} and fails.
A call to nope<int>() would also fail, for the same reasons as why nope() fails.
On the other hand, nope<std::string> gets true in is_arithmetic and returns a working function.
The compiler error that is triggered with clang++ version 5.0 explains the outcome quite clearly:
candidate template ignored: requirement '!std::is_arithmetic<int>{}' was not satisfied [with T = int] std::enable_if_t<!std::is_arithmetic<T>{}, T> nope() {}
Yes, I got this. But as I understand std::enable_if_t<!std::is_arithmetic{}, T> does't return false as it's defined like so:
template< bool B, class T = void >
using enable_if_t = typename enable_if<B,T>::type;
Should it not raise compiler error since type is not defined in case B == false?
It does raise a compiler error, see @nwp's comment above. My GCC isn't too clear either, but the clang message is clear.
| common-pile/stackexchange_filtered |
How to use propositional logic on a list of values in sml
I am trying to use propositional logic on a list of values. I will have a list of true or false values. I have a logical expression and I am trying to apply it to a list of values. For example, the logical expression T ^ F v T ^ T will be applied to a list of values(true and false).I will be substituting my values with the T and F in the logical expression. So a list of [true ,true ,false , false] when the expression is applied to it will be like "true ^ true v false ^ false". I will have different combination of the list of values.
fun take(a::b::c::d::rest) =
(a andalso b) orelse (c andalso not d);
(*Test *)
take([false , false , true, false]);
val it = true : bool
The function works but I am wondering if I can use recursion instead to apply the logical expression to the list.
Yes, you can use recursion.
You can, but it gets convoluted and unclear, so what would be the point? (And if you always have four values, a tuple would probably be a better choice than a list.)
| common-pile/stackexchange_filtered |
Ktor: "io.ktor.util.pipeline.ContextDsl" in ktor 2.0
This annotation is documented here but not marked deprecated, however in the migration guide there's no mention of why it was removed, and what should be used instead.
I am totally new to Ktor, and I am supposed to port a 1.6 project to 2 while learning Ktor from scratch. Some leads in this direction will be much appreciated. Thanks
Multiple DSL markers were unified so you can use the KtorDsl annotation instead.
| common-pile/stackexchange_filtered |
electron js - serving html
I am trying to serve another html file so that browser can access it from electronjs. this is file directory:
app folder:
- index.js // this is the init file for electron.
- index.html // main interface.
- ip.js // <-- included in index.html, codes for serving the static html to browser.
- package.json
-- node_modules
-- pad: // <-- this is the root folder I want to access via browser
- index.html // <-- browser will get to see this page.
- pad_index.js
index.js will have basic electron js stuffs.
'index.html' will import and run ip.js, which contain codes to serve ./pad/index.html to browser.
ip.js:
var os = require("os");
const http = require("http");
var path = require("path");
var url = require("url");
var fs = require("fs");
const port = 3000;
var staticBasePath = "./pad/";
var staticServe = function(req, res) {
var resolvedBase = path.resolve(staticBasePath);
var safeSuffix = path.normalize(req.url).replace(/^(\.\.[\/\\])+/, "");
var fileLoc = path.join(resolvedBase, safeSuffix);
var stream = fs.createReadStream(fileLoc);
stream.on("error", function(error) {
res.writeHead(404, "Not Found");
res.write("404: File Not Found!");
res.end();
});
res.statusCode = 200;
stream.pipe(res);
};
var httpServer = http.createServer(staticServe);
httpServer.listen(port, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
When I test it with electron ., everything works. I can go to browser and type http://localhost:3000/index.html and it will show the content from ./pad/index.html.
but after I use electron builder to build the app, then run the built app, I get 404: file not found! in the browser. I am sure I missed out something very important but not sure what.
How can I resolve this?
According to electron builder configuration you have to change directories section to allow your files being packed together with the app.
Take a look in the directories section at: https://www.electron.build/configuration/configuration#configuration
This answer might be helpful
Electron index.html not loading after building the app
thanks for the pointer, but I am not sure if this is what I am looking for. notice I have 2 index.html? those have different content in it. I can see root/indext.html fine, just that can't access to my localhost:3000/index.html, which is in root/pad/index.html.
| common-pile/stackexchange_filtered |
.htaccess is redirecting to original URL
i have following .htaccess file and i am trying to rewrite URL www.example.com/play/tribe-test instead of www.example.com/love/tribe-world/tribe-test.
Now when i am hitting www.example.com/play/tribe-test its redirecting me to www.example/love/tribe-world/tribe-test which is original URL.
RewriteEngine on
RewriteRule ^play/(tribe-test.*)$ /love/tribe-world/$1 [L] // This rule is getting redirected to original URL
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(we-are-stereotribes.*)$ /love/tribe-world/$1 [L,QSA]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(for-the-lovers.*)$ /love/tribe-world/$1 [L,QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(for-the-campaigners.*)$ /love/tribe-world/$1 [L,QSA]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(for-the-funders.*)$ /love/tribe-world/$1 [L,QSA]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(terms-of-use.*)$ /love/tribe-world/$1 [L,QSA]
RewriteRule ^(privacy-policy.*)$ /love/tribe-world/our-support/$1 [L,QSA]
# prevent httpd from serving dotfiles (.htaccess, .svn, .git, etc.)
RedirectMatch 403 /\..*$
# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
#RewriteCond %{REQUEST_URI} !(\.png|\.jpg|\.gif|\.jpeg|\.bmp|\.css|\.js)$
#RewriteRule ^theme/anther/? sthemes/anther/index.html
RewriteRule !html|\.(pdf|php|js|ico|txt|gif|swf|jpg|png|css|rss|zip|tar\.gz)$ index.php
will highly appreciate your help
Thanks in advance
yes url is also getting changed to /love/tribe-world/tribe-test
/love/tribe-world is directory and tribe-test is my page name..
I don't see any rule here using R flag so redirection from above rules is not possible. Is there any other .htaccess in your system?
Let us continue this discussion in chat.
| common-pile/stackexchange_filtered |
How to sort multi-index pandas data frame using one top level column?
I have a multi-index dataset like this:
mean std
Happiness Score Happiness Score
Region
Australia and New Zealand 7.302500 0.020936
Central and Eastern Europe 5.371184 0.578274
Eastern Asia 5.632333 0.502100
Latin America and Caribbean 6.069074 0.728157
Middle East and Northern Africa 5.387879 1.031656
North America 7.227167 0.179331
Southeastern Asia 5.364077 0.882637
Southern Asia 4.590857 0.535978
Sub-Saharan Africa 4.150957 0.584945
Western Europe 6.693000 0.777886
I would like to sort it by standard deviation.
My attempt:
import numpy as np
import pandas as pd
df1.sort_values(by=('Region','std'))
How to fix the problem?
What is df.columns for you?
Sorry for late reply, df.columns gives MultiIndex(levels=[['mean', 'std'], ['Happiness Score']], labels=[[0, 1], [0, 0]])
OK, think you're good to go. Just try any of the two solutions given below in my answer.
Setup
np.random.seed(0)
df = pd.DataFrame(np.random.choice(10, (5, 2)))
df.columns = pd.MultiIndex.from_arrays([['mean', 'std'], ['Happiness Score'] * 2])
df
mean std
Happiness Score Happiness Score
0 5 0
1 3 3
2 7 9
3 3 5
4 2 4
You can use argsort and reindex df:
df.loc[:, ('std', 'Happiness Score')].argsort().values
# array([0, 1, 4, 3, 2])
df.iloc[df.loc[:, ('std', 'Happiness Score')].argsort().values]
# df.iloc[np.argsort(df.loc[:, ('std', 'Happiness Score')])]
mean std
Happiness Score Happiness Score
0 5 0
1 3 3
4 2 4
3 3 5
2 7 9
Another solution is sort_values, passing a tuple:
df.sort_values(by=('std', 'Happiness Score'), axis=0)
mean std
Happiness Score Happiness Score
0 5 0
1 3 3
4 2 4
3 3 5
2 7 9
I think you had the idea right, but the ordering of the tuples incorrect.
solution1: AttributeError: 'DataFrame' object has no attribute 'argsort'
@astro123 There OK, so it looks like your actual data is different from the sample posted here. Please figure out what changes to make to get it to work. If the columns are different, you will certainly need to change the column names before accessing. Also, regarding the argsort error, that is bizarre and all I can do is ask you to check and see if you ran my code correctly. Thanks.
@astro123 Make sure you passed a tuple for ('std', 'happiness score'), (and not a list). That is important.
Yeah, you are right sir!, there was little mismatch between data. Now it works.
| common-pile/stackexchange_filtered |
How to draw several regions using one function returning List of True's and False's?
This is what I want:
RegionPlot[
{
y < x^2,
y < 0.5 + 0.5 x
},
{x, 0, 2},
{y, 0, 4}
]
This code does not work (draws only one region):
rf[x_, y_] := {
y < x^2,
y < 0.5 + 0.5 x
};
RegionPlot[
rf[x, y],
{x, 0, 2},
{y, 0, 4}
]
Actual function rf is very complex (CPU consuming), and I don't want to calculate it twice like here:
(* it works, but calculates rf twice *)
rf[x_, y_] := {
y < x^2,
y < 0.5 + 0.5 x
};
RegionPlot[
{rf[x, y][[1]], rf[x, y][[2]]},
{x, 0, 2},
{y, 0, 4}
]
Using Map does not help:
rf[x_, y_] := {
y < x^2,
y < 0.5 + 0.5 x
};
RegionPlot[
{#[[1]], #[[2]]}& /@ rf[x, y],
{x, 0, 2},
{y, 0, 4}
]
ImplicitRegion::bcond: {y,x^2}&&{y,0.5 +0.5 x} should be a Boolean combination of equations, inequalities, and Element statements.
RegionPlot[Evaluate@rf[x, y], {x, 0, 2}, {y, 0, 4}]
closely related: 113958
You can memoize the complex function so that it is only called once for a particular value of $x$ and $y$:
Clear[z];
z[x_, y_] := z[x,y] = {y<x^2, y<.5+.5x}
RegionPlot[
{Indexed[z[x, y], 1], Indexed[z[x, y], 2]},
{x, 0, 2},
{y, 0, 4}
]
| common-pile/stackexchange_filtered |
DataList - how to get the ClientID for another control other than the one your on?
Have a datalist with several textboxes, a series of "Time1" and "Time2"
So Im trying to attach a javascript onblur event to each one, and pass the client id values to a function, but how to reference the clientid of another control than the one your editing?
<asp:TextBox runat="server" ID="txtTimeFrameFrom" onblur='javascript:updateTimeFrame(val1, val2,val3);' style="width:50px;font-size:x-small;" Text='<%# DataBinder.Eval(Container.DataItem, "TimeFrameFrom")%>'></asp:TextBox>
<asp:TextBox runat="server" ID="txtTimeFrameTo" onblur='javascript:updateTimeFrame(val1, val2,val3);' style="width:50px;font-size:x-small;" Text='<%# DataBinder.Eval(Container.DataItem, "TimeFrameTo")%>'></asp:TextBox>
Where:
val1 = numeric value from dataset
val2 = client id of txtTimeFrameFrom
val3 = client id of txtTimeFrameTo
How can I get the client id in each case, while within the DataList? Is there an easier way?
You could use jQuery Parent, and search the sibling textboxes. Without seeing the generated html code, I could not say the exact answer.
I think I have a solution using the ItemDatabound event to handle this in the codebehind. Ill update after I have it working
| common-pile/stackexchange_filtered |
Why, although these functions have the same derivative, do they not differ by a constant?
I calculated the derivative of $\arctan\left(\frac{1+x}{1-x}\right)$ to be $\frac{1}{1+x^2}$. This is the same as $(\arctan)'$. Why is there no $c$ that satisfies $\arctan\left(\frac{1+x}{1-x}\right) = \arctan(x) +c$?
Why do you say that there is no $c$?
This seems like one of those cases where trig identities involving constants are not obvious...
Plotting the two clearly shows they don't differ by a constant but also provides a hint as to why not.
Piecewise, they do differ by a constant. Just with a discontinuity at x=1. And we explicitly define arctan(t) to have a discontinuity at t=+/-inf
The problem is that $\arctan \frac{1+x}{1-x}$ isn't defined at $x = 1$, and in particular isn't differentiable there. In fact, we have
$$
\arctan \frac{1+x}{1-x} - \arctan x = \begin{cases} \frac{\pi}{4} & x < 1, \\ -\frac{3\pi}{4} & x > 1. \end{cases}
$$
So the difference is piecewise constant.
While formally you are right in the first sentence, note that $\frac x{x^2}$ is not defined at $0$, but it has a continuation there, which is also differentiable at $0$. Here the discontinuity is not a removable one, which is why this doesn't work.
@AsafKaragila: I don't think you are talking about the function which you meant to talk about. The function you mentioned cannot be extended continuously at $x=0$.
@Marc: You're right, I wrote that comment from my phone, so MathJax mistakes are easy to come by. And of course, that I meant $\frac{x^2}{x}$. Thanks for pointing that out!
d00d, what a kewl constant! It's like not even constant!
Hint: $$\tan(x+y)=\frac{\tan x + \tan y}{1-\tan x\tan y}$$
What happens when $\tan y=1$?
The problem is that $\arctan$ always returns an answer in $(-\pi/2,\pi/2)$.
Piecewise, they do differ by a constant. Just with a discontinuity at x=1.
And we explicitly define arctan(t) to have that discontinuity at t=+/-inf
| common-pile/stackexchange_filtered |
how to take mysql backup using vb.net code
I want to take a backup from mysql workbench using vb.net. I am using MySql Workbench 5.2 CE. and below is my code.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'
Process.Start("C:\Program Files\MySQL\MySQL Server 5.5\bin\mysqldump.exe", " -u root -p mypass dbname -r ""C:\dbname.sql""")
End Sub
but after running my project it makes the sound "beep" but no backup is created... Please provide me the correct solution.
What exactly is your question?
I just want to take backup from mysql from vb.net.
| common-pile/stackexchange_filtered |
How to change box-shadow to similar command in css?
I have problem because shadow in my components doesnt work on safari.
I tried to change box-shadow to filter: drop-shadow() but this doesnt work in internet explorer 11.
box-shadow: 0 1px 7px 0 rgba(0, 0, 0, 0.12);
Do you know some similar command that I can swap and show same effect as box-shadow?
You can see actual browser support & known issues for the box-shadow here: https://caniuse.com/#feat=css-boxshadow
Here's a good link: https://css-tricks.com/almanac/properties/b/box-shadow/
.shadow {
-webkit-box-shadow: 0 1px 7px 0 rgba(0, 0, 0, 0.12); /* Safari 3-4, iOS 4.0.2 - 4.2, Android 2.3+ */
-moz-box-shadow: 0 1px 7px 0 rgba(0, 0, 0, 0.12); /* Firefox 3.5 - 3.6 */
box-shadow: 0 1px 7px 0 rgba(0, 0, 0, 0.12); /* Opera 10.5, IE 9, Firefox 4+, Chrome 6+, iOS 5 */
}
Update:
You can see the actual browser support and known issues here:
https://caniuse.com/#feat=css-boxshadow
Update2:
You can check this thread also - it may contain relevant info to you regarding the safari problem (color, sizes, etc.). The 0.12 may be a to small shadow for safari, according to the 1st answer.
css box shadow property is not working in safari
How to set shadows for many browsers that them don't duplicate themself? Eg ie, mozilla, chrome, safari on mac etc
What do you mean by "duplication"? The shadow is darker, or what happens? It shouldn't be duplicated - because each browser should have it's on rule from above. Maybe you can find this one useful: https://stackoverflow.com/questions/13127748/box-shadow-on-inputs-in-chrome
If in mozilla work box-shadow, and in my css there are box-shadow, and -moz-box-shadow, what will happen then?
It will first try to use the simple "box-shadow", if possible (I think). If the browser version is older (and "box-shadow" is not recognized in the given browser) it will use the -moz / -webkit alternative. Check this page to see what&where will work: https://caniuse.com/#feat=css-boxshadow
| common-pile/stackexchange_filtered |
Unwanted code being inserted into pages
Some of our ColdFusion sites are having the words "coupon" inserted into their footer with a link to another site. Is there anything I can do to prevent this? Is there any software I can run to help detect any vulnerabilities? It doesn't seem to be SQL injection as the databases seem fine and nothing unusual is showing up in the logs.
Have your ColdFusion templates actually been modified? Check them to see if you can find the "coupon" reference. This could be an issue on the end user's machine. They may have some malware installed that is injecting that code into your pages on their machine, not really on your server.
yeah the templates themselves are being modified on our server. it always seems to be in the footer next to the company logo.
"are being modified" or "have been modified"?
the files are being modified, the client then tells us they can see the coupon code on the website. we remove the code it happens again. we've checked the sites files and there isn't anything unusual in the code so we cant work out how it is being done.
As an initial step I'd be changing the passwords you use to access the server.
Check your site at http://hackmycf.com/. That should be the first step you do.
There are several variations of attacks that produce this sort of result (appending a link to some malicious or nefarious site). For example, this one (Script Injection) uses the latency between a file upload and checking to insert executable code on your server.
Other attack vectors include FTP (which is why you should not use it), or other file transfer protocols. In your case the infected machine may not be the server. It could be a client machine with access to the server - a developer who has set up FTP to the server for example.
Let me know if you need formal help - we have a good track record fixing this sort of thing. If you get more clues post them and I'll try to help. I will warn you that if this is a server infectionit is at the root level and is so pervasive your only option is to start with a pristine install and reinstall your code. Bad news I know - sorry :(
thanks for the advice mark. is there any software/malware checker you would recommend to run on the developer machines to help narrow down the problem? If it is a developer machine are there any logs I should be looking at on the server to narrow the problem down?
Unfortunately the answer is probably no. These attack vectors have a small footprint - they are not worth chasing for most scan companies since they only apply to servers. The weblogs, FTP logs (shut down FTP if you can) and all the CF logs (especially the cfusion-out.log) might yeild some info. But anyone with this level of control over your server can certainly alter logs :)
Years ago, a major hosting company was targeted like this. After they patched their servers, we had to re-upload a number of sites on fresh servers. If this is your own server and you're not sure how it's vulnerable, I'd recommend hiring someone to help.
@csber3 - this is self interested but since Adrian brought it up, we have 3 folks here specializing in this. We'll be glad to help. :)
We had something similar happen when one of our servers was hit by the hack Charlie Arehart describes here:
http://www.carehart.org/blog/client/index.cfm/2013/1/2/serious_security_threat
Have you had these patches?
Upvoted. When answer was posted, person did not have a high enough rep to post comments.
yeah we're running CF10 with all the latest patches applied.
Another option that I would recommend is searching your site(s) for any use of the <cffile> tag that isn't expected. I had a customer that somehow got a single file that was a backdoor to their site. It was particularly dangerous because it could upload files to any location on the server as well as execute any SQL command against any datasource on the server. In other words, this single file opened the door to all of the sites and databases that were running on that server.
This backdoor file (which was named vision.cfm) was often used to update footers with links to coupon and spam sites. vision.cfm was only 210 lines of code.
The entire server had to be sanitized after this was discovered.
| common-pile/stackexchange_filtered |
WPF Binding nested objects
I'm very new to WPF and I'm having difficulties binding a request object with nested objects which was derived from a WSDL to a XAML textbox. Programmatically I was able to bind to a textbox but I would like to understand the syntax needed to bind via XAML. Once I have some direction It'll make it much easier to research a full solution. Thanks
The ResultSet and Message Object will always be [0].
Code
MainWindow()
{
InitializeComponent();
GetMarketingMessagesResponse request = new GetMarketingMessagesResponse();
request = (GetMarketingMessagesResponse)XMLSerializerHelper.Load(request, @"C:\SSAResponse.xml");
DataContext = request;
Binding bind = new Binding();
bind.Source = request.ResultSet[0].Message[0];
bind.Path = new PropertyPath("SubjectName");
this.txtbSubject.SetBinding(TextBox.TextProperty, bind);
}
The return value in the Visual Studio Watch bind.Source = request.ResultSet[0].Message[0];
is
bind.Source = {GetMarketingMessagesResponseResultSetMessage} which is the class name.
XAML
I'm looking for direction on how to bind to this class and the properties inside
<TextBox Name="txtbMessageDetails" HorizontalAlignment="Right" Margin="0,50.08,8,0" TextWrapping="Wrap" Text="{Binding Source=ResultSet[0].Message[0], Path=SubjectName}" VerticalAlignment="Top" Height="87.96" Width="287.942"/>
Use a converter which will receive the request and extract the message.
<Window.Resources>
<local:MessageExtractorConverter x:Key="messageExtractorConverter" />
</Window.Resources>
<TextBox Name="txtbMessageDetails" HorizontalAlignment="Right" Margin="0,50.08,8,0" TextWrapping="Wrap" Text="{Binding Converter={StaticResource messageExtractorConverter}" VerticalAlignment="Top" Height="87.96" Width="287.942"/>
Converter implementation:
public class MessageExtractorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var val = value as GetMarketingMessagesResponse;
if (val != null)
{
// You can modify this code to extract whatever you want...
return val.ResultSet[0].Message[0];
}
else
{
return null;
}
}
You already put the request object in your DataContext, making it the default Source for all bindings. So, instead of specifying another Source (which would just override the DataContext), you use the binding's Path to make your way from the DataContext to the property you need:
<TextBox Name="txtbMessageDetails" Text="{Binding Path=ResultSet[0].Message[0].SubjectName}" />
Here is an article explaining how the DataContext works, and how it is "inherited" from control to control in your Window: http://www.codeproject.com/Articles/321899/DataContext-in-WPF
| common-pile/stackexchange_filtered |
When an author sells the underlying copyright to a third party, where does the publisher now send the royalties?
A book publishing contract typically starts with an author who owns a copyright and licenses it to a publisher for the term of the copyright. The publisher (or the literary agent) sends royalty checks to the author. (I'm using royalties as a stand-in here for all the various obligations the publisher typically owes under a contract.)
Here's the wrinkle: Suppose the author, while alive, transfers the underlying copyright to a third party. Where does the publisher send the royalty check? To the author, or to the new copyright owner?
Another way of asking the question: Does the publisher's contractual obligation flow to the individual person (the author) who signed the publishing contract, or does it flow to the owner of the copyright, whoever that may be? If the first is true, then a separate transfer of contractual obligations would presumably be needed to vest the third party with all rights. But if the second is true, then the shift of royalties (obligations) would be automatic.
(A related question: In the normal case, the author still owns the copyright when he dies, at which point the heirs succeed to the author's rights under the publishing contract. No problem. But if the copyright ownership has been transferred to a third party during author's lifetime, does that third party have any claim to the royalties going forward?)
Geographically, this question pertains to the U.S. (but it would be interesting to hear if other jurisdictions have different approaches).
Any obligation to pay royalties comes from the agreement between the publisher and the copyright holder. In a particular agreement, "the Author" is defined as the specific person, and the royalties clause says that "During the legal period of copyright Publisher shall pay to the Author...". Whether or not Author retains copyright (merely grants a non-exclusive license) or transfers copyright to Publisher is specified in the agreement. If (per the hypothetical) Author has the right to transfer copyright i.e. has not transferred copyright to the Publisher, this does not extinguish the Publisher's original obligation to pay royalties – unless that is what the copyright agreement says (I've never seen such a clause, but who knows). Change the Royalties clause to read "shall pay the owner of the copyright", then you get a different result.
If the contract says "publisher pays the author..." then publisher would have to pay the author. The author is unchanged. Problem is that the copyright holder and demand that the publisher stops publishing.
Which goes to the question of whether author is actually empowered to fully transfer copyright, thereby disavowing the prior contract.
One who purchases a copyright or accepts a transfer does so subject to any existing valid licenses, and may not cancel them except as th original author couldf have. However, the new owner can probably demand that the previous owner also transfer any royalty payments received subsequent to the date of the transfer.
@user6726 since transfers are subject to existing licenses (much as a sale of property is subject to existing leases) a transfer does not impair the publication contract, or would not in any usual case at least.
"an author who owns a copyright and licenses it to a publisher for the term of [that contract, not the] copyright." ... "If (per the hypothetical) Author has the right to transfer copyright i.e. has not transferred copyright to the Publisher." +1. - Does any publisher actually do business if they don't have an airtight lease on the copyright?
One reason to get a lawyer is that you might unintentionally create an unholy mess.
@Mazura it can happen through inheritance: heirs might not know if a work was under contract to be published somewhere but had not yet been published.
@Mazura, actually publishers routinely publish with little more than a Plan B in case the author doesn't read and understand the contract. Even in direct dealing with the original author, the publisher has no knowledge of prior contracts that the author has made regarding the work.
Where does the publisher send the royalty check? To the author, or to
the new copyright owner?
To the new owner, as soon as the publisher is informed of the change in ownership of the copyright.
If the published sends to check to the author because the published hasn't yet been informed of the transfer (usually something that only happens once or twice until it is cleared up), the author has to hold the funds received in a constructive trust for the new copyright owner and pay them over to the new copyright owner promptly.
Does the publisher's contractual obligation flow to the individual
person (the author) who signed the publishing contract, or does it
flow to the owner of the copyright, whoever that may be? If the first
is true, then a separate transfer of contractual obligations would
presumably be needed to vest the third party with all rights. But if
the second is true, then the shift of royalties (obligations) would be
automatic.
The contract of sale would make this fine distinction irrelevant 99% of the time anyway by expressly providing for an assignment of all contracts licensing the copyright, but this assignment would very likely be implied in law even if the transfer of copyright contract was very poorly drafted and omitted this provision (unless the contract expressly provided for some other disposition of the license fees which would be extremely unlikely since it defeats the point of transferring the copyright anyway, except for a possible reservation of a final payment covering some time period before and after the transfer for administrative expediency - for example, I have some works for which I earn royalties of about $25 every four months, and it wouldn't be worth the trouble to split the transition period check if I sold my copyrights in those works).
In the normal case, the author still owns the copyright when he dies,
at which point the heirs succeed to the author's rights under the
publishing contract. No problem. But if the copyright ownership has
been transferred to a third party during author's lifetime, does that
third party have any claim to the royalties going forward?
If the copyright has been sold to a third-party during life then this intellectual property isn't part of the estate of the author and doesn't pass to the author's heirs, just like any other property that someone transfers during life. The heirs have no claim to the royalties going forward.
In non-U.S. jurisdictions, there are two separate kinds of rights associated with copyright. A transferrable economic right that can be transferred to third-parties and works as explained above, and separate noneconomic rights called "moral rights" that are non-transferrable. As explained at that U.S. government link discussing the possibility of amending U.S. law to provide for moral rights:
Chief among these rights are the right of an author to be credited as
the author of their work (the right of attribution) and the right to
prevent prejudicial distortions of the work (the right of integrity).
U.S. practice, rather than treating moral rights as something legally enforceable, treats moral rights as a question of academic ethics and industry custom (sometimes further implemented in the performing arts by collective bargaining agreements between industry-wide labor unions of people in professions who are legally "authors" in countries with a moral rights regime, and associations of the people who hire them).
I am not familiar with the law governing moral rights after an author's death because U.S. copyright law doesn't give rise to moral rights, so I've never had occasion to deal with the issue.
US law, specifically 17 USC 106A does grant "moral rights" of attribution and integrity, but only to "the author of a work of visual art" and that term is limited by 17 USC 101 to works existing only in a single copy, or only in a single edition limited to 200 copies or less, and further limited to "a painting, drawing, print, or sculpture" or "a still photographic image produced for exhibition purposes only" . These rights are granted only for the life of the author, so any heirs never enjoy them.
@DavidSiegel Thanks. Good to know.
Also, the author, or the author's heirs, have the right in US law ( 17 USC 203) to cancel any license, or any transfer of copyright to a third party, during a period of 5 years, starting 35 years from creation of the work, or from publication in some cases. Two years notice must be given. This replaces the right under the 1909 Copyright Act, to cancel transfers when a copyright was renewed. This right may not be contracted away or waived in advance, any agreement purporting to do so is void.
@DavidSiegel I definitely wasn't aware of that rule. Thanks for the heads up.
@DavidSiegel and at.ohwilleke thank you so much for your responses! These are amazingly helpful. It sounds like sec. 203's termination rights would still accrue to the author's heirs, despite a transfer of the copyright during author's life -- indeed, that's the exact situation sec. 203 is designed to address. So, even though the copyright might not initially descend to the heirs, they can claw it back into the estate using sec. 203 (assuming that the timing is right).
In Australia, moral rights in a film end on death, in all other works they last as long as the copyright does. They cannot be inherited but the author’s legal representative can enforce them.
@Tom Bowdenm after a valid sec 203 termination, when the author is deceased the rights revert to the author's widow(er), children, and/or grandchildren (if any are alive) not to the author's estate, even if the author's will left his estate to others. Note also that the author or heirs may terminate one license and not another, if s/he/they so choose.
It would need to be in the contract in germany
In Germany, all royalties stem from a license contract for usage rights. Due to how usage rights are handled, you can't sell the exclusive usage right twice: once you sold it, you can't even use the work yourself unless it is specified that you can. You can't sell a non-time-limited non-exclusive usage right and then an exclusive right without canceling the other license first. As a result, there's no situation where you can sell your copyright, which takes the shape of an exclusive, non-cancelable contract without royalties, while such other license exists. It takes a special contract that accounts for the previous contract, and that would also address how incoming royalties from the previous contract are to be handled - if they are to be forwarded or allowed to be kept would need to be spelled out.
| common-pile/stackexchange_filtered |
How to read local .json file and display data in Window Phone 7/8?
I have tried couple of different methods, no luck yet. Note:In second if statement, I have entered long json string. However, I dont want to write long json string, instead, I want to read from json file.
private void Pivot_LoadingPivotItem_1(object sender, PivotItemEventArgs e)
{
try
{
if(e.Item == item1)
{
list1.Items.Clear();
//string stopslist1 = @"[{""Name"":""Communication Sciences""},{""Name"":""Hope Lodge""},{""Name"":""Juniper-Poplar""}]";
IsolatedStorageFile mysfile = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream fs = mysfile.OpenFile(@"c:\users\prime\documents\visual studio 2012\Projects\BullRunnertest3\BullRunnertest3\stopsA.json",FileMode.Open, FileAccess.Read);
using (StreamReader re = new StreamReader(fs))
{
string stopslist1 = re.ReadToEnd();
}
List<RouteStops> stops = JsonConvert.DeserializeObject<List<RouteStops>>(stopslist1);
foreach(RouteStops em in stops)
{
string name = em.Name;
list1.Items.Add(name);
}
}
else if (e.Item == item2)
{
list2.Items.Clear();
string stopslist2 = @"[{""Name"":""Computer Sciences""},{""Name"":""Hope for Lodge""},{""Name"":""Juniper and Poplar""}]";
List<RouteStops> stops = JsonConvert.DeserializeObject<List<RouteStops>>(stopslist2);
foreach (RouteStops em in stops)
{
string name = em.Name;
list2.Items.Add(name);
}
}
else......
you have any constraint of language. As F# already having json data provider to read. if you can dump json file to it will good.
no, I'm only using c#, do u have any advise for this? thnks
i think you got the answer. :), if still anything let me know.
it looks like you are trying to access the C:// drive on Windows phone...which does not exist. Watch this video: http://channel9.msdn.com/Series/Building-Apps-for-Windows-Phone-8-Jump-Start/Building-Apps-for-Windows-Phone-8-Jump-Start-04-Files-and-Storage-on-Windows-Phone-8
to learn how to access files from local storage.
| common-pile/stackexchange_filtered |
How to get random value from property from one List?
I have a List of 10,000 entries of type Element:
public class Element
{
public Element()
{
this.Id = Guid.NewGuid();
}
public Guid Id { get; set };
}
And I have another List of 5,000 entries of type Link:
public class Link
{
public Link(Guid ElementOne, Guid ElementTwo)
{
this.ElementOne = ElementOne;
this.ElementTwo = ElementTwo;
}
public Guid ElementOne { get; set; }
public Guid ElementTwo { get; set; }
}
I am populating my Lists here:
for (int i = 0; i < 10,000; i++)
this.ListOfElements.Add(new Element());
for (int i = 0; i < 5,000; i++)
{
this.ListOfLinks.Add(new Link(need ElementOne, need ElementTwo));
}
I am not sure what to pass for ElementOne and ElementTwo. I want to grab a random Id from the Element List (Element.Id) for both parameters and ensure they're unique (ElementOne could never be ElementTwo).
You need to keep track of elements you are adding or quering ListOfLinks everytime you want to add something, and adding a method to give you next one to add
So, can ElementOne and ElementTwo NEVER repeat? Or do you just want to avoid linking 1 - 1. Is linking 1-2 and then 1-3 ok? Do you need to avoid linking 1-2, then later linking 1-2 again?
Oh sorry, I wasn't clear - I just don't want 1 - 1. 1 - 2 repeated is fine.
Sounds like you just need two random numbers. You can compare and repoll if you happen to get a duplicate.
for (int i = 0; i < 5,000; i++)
{
int ele1 = Random.NextInt(10000);
int ele2 = Random.NextInt(10000);
while(ele1 == ele2){
ele2 = Random.NextInt(10000);
}
this.ListOfLinks.Add(new Link(ListOfElements[ele1], ListOfElements[ele2]));
}
The code below will give a random array of the index to your list. So you can take randIndex[0] and randIndex[1] to get two random items.
Random rand = new Random();
List<string> myList = new List<string>() { "a","b","c"};
int[] randIndex = myList.Select((x,i) => new {i = i, rand = rand.Next()}).OrderBy(x => x.rand).Select(x => x.i).ToArray();
You need to find next element which is not used, also using .OrderBy(i => Guid.NewGuid()) to get random element
private Element GetNextAvaibaleElement() {
var usedElementIds = listOfLinks.Select(i => i.ElementOne).Union(listOfLinks.Select(i => i.ElementTwo));
return listOfElements.Where(i => !usedElementIds.Contains(i.Id)).OrderBy(i => Guid.NewGuid()).FirstOrDefault();
}
and then get two available elements
for (int i = 0; i < 5,000; i++)
{
this.ListOfLinks.Add(new Link(GetNextAvaibaleElement().Id,GetNextAvaibaleElement().Id));
}
See this dotnet fiddle here
Create an instance of the Random class somewhere.
E.g.
static Random rdm = new Random();
Then, use this rdm instance to generate a random integer, delete that element from the list (so as not to reuse it), and keep going until you deplete your list.
List<Element> listOfElements; // list of 10k Elements
for (int i = 0; i < 5,000; i++)
{
int r = rdm.Next(listOfElements.Count);
Element elementOne = listOfElements[r];
listOfElements.RemoveAt(r);
r = rdm.Next(listOfElements.Count);
Element elementTwo = listOfElements[r];
this.ListOfLinks.Add(new Link(elementOne, elementTwo));
}
One approach to solving this is to create a list of integers representing the indexes into the ListOfElements, then order that list in a random way. Then you can simply reference items in the ListOfElements by index, sequentially walking through the randomized index list:
private static void Main()
{
for (int i = 0; i < 10000; i++) ListOfElements.Add(new Element());
// Create a randomly-ordered list of indexes to choose from
var rnd = new Random();
var randomIndexes = Enumerable.Range(0, ListOfElements.Count)
.OrderBy(i => rnd.NextDouble()).ToList();
// Now use our random indexes to pull unique items from the Element list
for (int i = 0; i < 10000; i += 2)
ListOfLinks.Add(new Link(ListOfElements[randomIndexes[i]].Id,
ListOfElements[randomIndexes[i + 1]].Id));
GetKeyFromUser("\nDone! Press any key to exit...");
}
| common-pile/stackexchange_filtered |
How to combine property init and set depending on access modifier?
I want a class/record with protected set and public init access restriction?
To my knowledge this even cannot be done by explicitly implementing a "Set" interface like this:
public interface ISetData<T>
{
T Value { get; set; }
}
public class Data : ISetData<bool>
{
bool ISetData<bool>.Value { get => Value; set => Value = value; } // Error The property Value has no setter
public bool Value { get; init; }
}
Downside is, set functionality is public when using the interface. Not good. (for internal components the interface can be made internal, but that's mostly no option)
Given that only derivations of Data should be able to set data after initialization, the only solution I see is to use an backing field for the property, which is annoying.
Which looks like:
public interface ISetData<T>
{
T Value { get; set; }
}
public class Data : ISetData<bool>
{
bool ISetData<bool>.Value { get => Value; set => _value = value; } // Fine
private bool _value;
public bool Value
{
get { return _value; }
init { }
}
}
That seems odd to me. Would it not be better CLR/c# allows to use access modifiers independently of set/init this like:
public class Data
{
public bool Value { get; init; protected set; }
}
I know this would better be addressed by a feature request, but this is not what this post is about.
So what solutions are available for the scenario "public init, but protected set"?
See https://stackoverflow.com/questions/64783995/init-private-set-accessors-on-the-same-property#64783995
A simple answer is none.
In C# 9.0, you could have either init or protected set, not both.
You could have a separate property that is protected set and then the public property can be based on your protected property. Example below.
using System;
public class Program
{
public static void Main()
{
var example = new Example{Test = "hello world"};
example.PrintProtectedTest();
Console.WriteLine(example.Test);
example.SetProtectedTest("goodbye world");
Console.WriteLine(example.Test);
}
}
class Example
{
public Example()
{
}
protected string ProtectedTest { get; set; }
public string Test
{
get => ProtectedTest;
init => ProtectedTest = value;
}
public void SetProtectedTest(string test)
{
ProtectedTest = test;
}
public void PrintProtectedTest()
{
Console.WriteLine(ProtectedTest);
}
}
You can run the example here https://dotnetfiddle.net/odGwDj
Sorry, realizing now this is just a slight variation of using a backing field like you were describing and may not add much.
| common-pile/stackexchange_filtered |
Creating word document with photos and descriptions with VBA
I am trying to create a word document report that includes photos with an associated description using Excel VBA. The photo names are in column A and the descriptions are in columns B:I of the excel spreadsheet. The current macro opens the FileDialogFolderPicker and the user pick the folder that contains the pictures they want. The macro picks the associated picture based off the photo name in coulmn A then creates the word document and inserts the photos and descriptions. I am having trouble with inserting the correct photos and descriptions into the word document in the correct locations. I would also like to lock the aspect ratio of each photo and be able to specify the size of the photo in inches. I have included photos of what is currently happening with the word document and also what I would like the final result to look like. Any help would be greatly appreciated.
Sub Module2()
Dim ws As Worksheet, lastR As Long, rngPict As Range, rngP As Range, cel As Range
Dim myDialog As FileDialog, myFolder As String, myFile As String, myPicture As String
Dim x As Single, y As Single, W As Single, h As Single
Const picturesColumn As String = "A" 'the column keeping the pictures name list
Set ws = ActiveSheet
lastR = ws.Cells(ws.Rows.Count, picturesColumn).End(xlUp).Row 'last row for photo names
Set rngPict = ws.Range(ws.Cells(2, picturesColumn), ws.Cells(lastR, picturesColumn)) 'the photo names range
Set myDialog = Application.FileDialog(msoFileDialogFolderPicker)
With myDialog
.Title = "Select the folder with structure photos"
.AllowMultiSelect = False
If .Show <> -1 Then Exit Sub 'nothing has been selected...
myFolder = .SelectedItems(1) & Application.PathSeparator
End With
Dim wdApp As Word.Application
Set wdApp = New Word.Application
With wdApp
.Visible = True
.Activate
.Documents.Add
End With
'Iterate between each cell of pictures range and insert if picture exists in myFolder:
For Each cel In rngPict.Cells
myFile = Dir(myFolder & cel.Value & "?") 'with extension in cel.value...
If myFile <> "" Then
myPicture = myFolder & myFile
With wdApp.Selection
.ParagraphFormat.Alignment = wdAlignParagraphCenter
.ParagraphFormat.SpaceAfter = 0
.Font.Name = "Times New Roman"
.Font.Size = 12
Dim wrdPic As Word.InlineShape
Set wrdPic = .Range.InlineShapes.AddPicture(Filename:=myPicture, LinkToFile:=False, SaveWithDocument:=True)
.TypeText (ThisWorkbook.Sheets("Sheet1").Cells(2, 10).Text)
.TypeText (ThisWorkbook.Sheets("Sheet1").Cells(2, 11).Text)
.TypeText (ThisWorkbook.Sheets("Sheet1").Cells(2, 12).Text)
.TypeText (ThisWorkbook.Sheets("Sheet1").Cells(2, 2).Text)
.TypeText ". "
.TypeText (ThisWorkbook.Sheets("Sheet1").Cells(3, 2).Text)
.TypeParagraph
.TypeParagraph
End With
End If
Next cel
End Sub
Here are photos of my current spreadsheet, current word document produced and expected word document to be produced:
Your code does not move the cursor in Word, resulting in all the content being inserted at the beginning of the document.
Instead of using Selection, which is highly inefficient, use a Range. In the example below Characters.Last is the range being worked with.
Sub Module2()
Dim ws As Worksheet, lastR As Long, rngPict As Range, rngP As Range, cel As Range
Dim myDialog As FileDialog, myFolder As String, myFile As String, myPicture As String
Dim x As Single, y As Single, W As Single, h As Single
Const picturesColumn As String = "A" 'the column keeping the pictures name list
Set ws = ActiveSheet
lastR = ws.Cells(ws.Rows.Count, picturesColumn).End(xlUp).Row 'last row for photo names
Set rngPict = ws.Range(ws.Cells(2, picturesColumn), ws.Cells(lastR, picturesColumn)) 'the photo names range
Set myDialog = Application.FileDialog(msoFileDialogFolderPicker)
With myDialog
.Title = "Select the folder with structure photos"
.AllowMultiSelect = False
If .Show <> -1 Then Exit Sub 'nothing has been selected...
myFolder = .SelectedItems(1) & Application.PathSeparator
End With
Dim wdApp As Word.Application
Set wdApp = New Word.Application
Dim wdDoc As Word.Document
With wdApp
.Visible = True
.Activate
Set wdDoc = .Documents.Add
End With
'the following only needs to be set once
With wdDoc.Content
.ParagraphFormat.Alignment = wdAlignParagraphCenter
.ParagraphFormat.SpaceAfter = 0
.Font.Name = "Times New Roman"
.Font.Size = 12
End With
'this only needs to be declared once - not in a loop
Dim wrdPic As Word.InlineShape
Dim picDesc As String
'Iterate between each cell of pictures range and insert if picture exists in myFolder:
For Each cel In rngPict.Cells
myFile = Dir(myFolder & cel.Value & "?") 'with extension in cel.value...
If myFile <> "" Then
myPicture = myFolder & myFile
Set wrdPic = wdDoc.InlineShapes.AddPicture(Filename:=myPicture, LinkToFile:=False, _
SaveWithDocument:=True, Range:=wdDoc.Characters.Last)
picDesc = vbCr & ThisWorkbook.Sheets("Sheet1").Cells(2, 10).Text
picDesc = picDesc & ThisWorkbook.Sheets("Sheet1").Cells(2, 11).Text
picDesc = picDesc & ThisWorkbook.Sheets("Sheet1").Cells(2, 12).Text
picDesc = picDesc & ThisWorkbook.Sheets("Sheet1").Cells(2, 2).Text & ". "
picDesc = picDesc & ThisWorkbook.Sheets("Sheet1").Cells(3, 2).Text & vbCr & vbCr
wdDoc.Characters.Last.Text = picDesc
End If
Next cel
End Sub
Thank you very much! This seems to work well with the formatting but still has the issue of the photo description being the same for each picture.
@KyleAnderson - You need to change the cell references for the description text.
I'm still having trouble getting the photos description in word to match the correct photos. Do you have any further guidance on how I can get the proper descriptions to go with each photo?
@KyleAnderson - see https://learn.microsoft.com/en-us/office/vba/api/excel.range.offset
| common-pile/stackexchange_filtered |
I am trying to implement Pocketsphinx running uClinux, but I keep getting "Phone is missing in acoustic model" errors
I am trying to run Pocketsphinx on a microcontroller running uClinux, I have installed pocketsphinx on the controller, but I keep getting several different errors regarding acoustic models and definitions. The current one I am facing is:
"Phone ... is missing in the acoustic model"
Replace the ... with every possible phonetic combination. It starts
off with A, then AE, then progresses to B etc.
I am trying to take a .wav file as input, and so this is the command I am using to run the software:
pocketsphinx_continuous -hmm /usr/share/pocketsphinx/model/hmm/en/tidigits/ -lm /usr/share/pocketsphinx/model/lm/en/tidigits.DMP -infile 1.wav -samprate 8000 -dict cmu07a.dic
Has anyone encountered this issue? if so, do you know a way to resolve it?
For tidigits model there is a special dictionary tidigits.dic in pocketsphinx/model/lm/en/tidigits.dic, you need to use with -dict option instead of cmu07a.dicin your command line.
| common-pile/stackexchange_filtered |
how to increase the gesture time out time
I have implemented multiple-stroke gestures in my app, but if the pause between strokes is too long it resets the gesture. Is there a way to increase the time allowed between strokes of a single gesture?
You can increase the time between strokes of a single gesture by using this
android:fadeOffset="5000"<-- this value is in milliseconds..
in xml
<android.gesture.GestureOverlayView
so android will wait for 5 sec time and in case no gesture is started.. then what you have drawn so far will be taken into consideration.. else the new gesture will be appended to first one.. makin it a single stroke..
| common-pile/stackexchange_filtered |
Using scriptlet or EL inside an attribute of a tag (Grails UI Plugin)
I want to trigger the same dialog on different ids in my gsp.
So here is the code:
<div class="yui3-widget-bd">
<g:each in="deployments" status="index" var="workflow">
<% def id = "reloadFile"+index %>
<gui:dialog title="Reload File" form="true" modal="true"
controller="admin" action="reloadFile"
triggers="[show:[id:'${id}', on:'click']]">
<p>To reload the file, please...</p><br />
<input type="file" id="deploymentFile" name="deploymentFile" />
</gui:dialog>
</g:each>
</div>
The problem is that the scriptlet code :
triggers="[show:[id:'<%=id %>', on:'click']]"
is not getting evaluated.
The Javascript part that listens for events in the source of the generated html looks like this:
YAHOO.util.Event.addListener("${id}", "click", GRAILSUI.gui_e0100d149e0a7b531017e0decaee9fce.show, GRAILSUI.gui_e0100d149e0a7b531017e0decaee9fce, true);
So how can i manage that the source looks like this ? :
YAHOO.util.Event.addListener("reloadFile1", "click", GRAILSUI.gui_e0100d149e0a7b531017e0decaee9fce.show, GRAILSUI.gui_e0100d149e0a7b531017e0decaee9fce, true);
Thank you.
What about removing the single quotes around ${id}? (triggers="[show:[id:${id}, on:'click']]")
Thanks for your answer Todd, but that's not working. I get a GrailsTagException. Any further ideas ?
Same as jsps:
If you want to execute some code
<% def something = true %>
If you want to use the return of the execution
<%= something ? "This is a truth statement" : "This is false" %>
Beware that this is probably code smell and the code should be in a domain, controller or taglib 99.9% of cases.
Here's the reference documentation for more info.
| common-pile/stackexchange_filtered |
Show that the propositions $\alpha$ and $(Z\rightarrow\alpha) \wedge Z$ are equally satisfiable
I already found that $\alpha \not\equiv (Z\rightarrow \alpha) \wedge Z$ but now I was ask to see if those propositions are equally satisfiable but I don't know how.
Hope someone can help me.
Thank you in advance
I doubt it. Couldn't you have $Z$ false and $\alpha$ true?
@GEdgar Ohhh I found that they are unequal fix it
| common-pile/stackexchange_filtered |
How to access variables of a referenced class library in a Winforms application
I have a Windows Forms application with a reference for the class library in my Win-forms project.
The win-form has a combo-box and a button.
the class library has a global variable value1,value2 and other code which depending on value1 executes some code.
In win-form i make a selection in the combo-box and on button click depending on the selection made i should assign a value to the variable "value1" of class library as value = true .
i created an instance of the class library as
classlibraryname clb = new classlibrary() but after that i am not able to assign true to the class library variable "value1" .
how can i assign a value to variable value1???
I am new to working with c# and class libraries .please help
What do you mean by not able to assign true? Do you get a compiler error, error at runtime? What EXACTLY happens?
The variables must declared public to access. This is quite basic. I recommend reading through programming basics and finding simple examples.
i am not knowing how to assign a value to the class library variable "value1" in winform application
Declare your variable in the class library as public
public bool variable1;
Then in your winform do the following:
classlibraryname clb = new classlibraryname();
clb.variable1 = true;
| common-pile/stackexchange_filtered |
How can I read datamatrix codes using opencv in python?
new python user here. I'm working on a project with a raspberry pi with a picamera to decode Datamatrix codes. I'm trying to recycle some parts of an older project that I did which decodes QR codes and works great but doesn't support datamatrix (pyzbar), but there seems to be an issue that I can't figure out when I try using pylibdmtx.
This code works as intended. Shows a video screen, highlights found barcodes and captures the image.
from pyzbar import pyzbar
import time
import cv2
import os
import numpy as np
def nothing(x):
pass
print("[INFO] starting video stream...")
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
cap.set(cv2.CAP_PROP_FPS, 22)
build = 1
count = True
i=0
time.sleep(2.0)
found = set()
found.clear()
while cv2.waitKey(1) !=27 and cap.isOpened():
_,frame = cap.read()
barcodes = pyzbar.decode(frame)
for barcode in barcodes:
(x, y, w, h) = barcode.rect
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)
barcodeData = barcode.data.decode("utf-8")
barcodeType = barcode.type
text = "{} ({})".format(barcodeData, barcodeType)
cv2.putText(frame, text, (x, y - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
if barcodeData not in found:
build = build+1
print('saving')
cv2.imwrite(os.path.join(str(text) + 'test.jpeg'),frame)
found.add(barcodeData)
cv2.imshow("Barcode Scanner", frame)
key = cv2.waitKey(1) & 0xFF
if key == ord("q"):
break
print("[INFO] cleaning up...")
cap.release()
cv2.destroyAllWindows()
This code prints [INFO] starting video stream... and does nothing else. No errors. Ideally, I could also convert these images to black and white to make decoding a little easier, but haven't gotten it to work at all yet:
from pylibdmtx import pylibdmtx
import time
import cv2
import os
import numpy as np
def nothing(x):
pass
print("[INFO] starting video stream...")
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
cap.set(cv2.CAP_PROP_FPS, 22)
cap = cv2.cvtcolor(cap, cv2.COLOR_BGR2GRAY)
build = 1
count = True
i=0
time.sleep(2.0)
found = set()
found.clear()
while cv2.waitKey(1) !=27 and cap.isOpened():
_,frame = cap.read()
barcodes = decode(frame)
for barcode in barcodes:
(x, y, w, h) = barcode.rect
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)
barcodeData = barcode.data.decode("utf-8")
barcodeType = barcode.type
text = "{} ({})".format(barcodeData, barcodeType)
cv2.putText(frame, text, (x, y - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
if barcodeData not in found:
build = build+1
print('saving')
cv2.imwrite(os.path.join(str(text) + 'test.png'),frame)
found.add(barcodeData)
cv2.imshow("Barcode Scanner", frame)
key = cv2.waitKey(1) & 0xFF
if key == ord("q"):
break
print("[INFO] cleaning up...")
cap.release()
cv2.destroyAllWindows()
Did you get the solution?
The documentation of Pyzbar version 0.1.9 (2022) states 'Read one-dimensional barcodes and QR codes from Python 2 and 3 using the zbar library'. Therefore the only 2D-codes Pyzbar can handle are QR-codes, and not DataMatrix codes.
See https://pypi.org/project/pyzbar/
| common-pile/stackexchange_filtered |
How many shots would it take to sever a limb?
Modern (or near future, 10-20 years) setting. Mostly regular humans. Regular firearms.
The scene goes like this: the Big Bad Villain of the story fought the Big Good Hero in hand-to-hand combat and won. He got his trusty gun, he stands above the defeated hero, he aims his gun at him... But he cannot pull the trigger. Because deus ex machina happens and a friendly character, that was imprisoned by the Villain and freed by the Hero on his way to final battle, comes to the rescue. This character, being a psychic capable of mind-controlling (like I said, mostly regular humans), overpowers weakened Villain and forces him to stop. Then, to repay the Villain for his "hospitality", the psychic forces the Villian to raise the gun and shoot off his own arm.
So here is the question (or rather two questions).
1) Is it even possible (with modern firearms) to shoot off person's limb with a single magazine/load of any one-handed non-automatic firearm? Preferably one without extended magazine.
2) What kind of calibre/ammunition type would be required for this?
Edit: What about explosive rounds? Are there any produced for handguns? Would they be better for this task?
You need to define a calibre, I can think of weapons that will reportedly remove large parts of a human being when they miss by a narrow margin so how big is the gun and then we can probably estimate how many rounds you need to take a limb off.
@Ash First I'd like to know if it's even possible period. Even if it is a monster revolver using .50 (which would probably break everything in users arm anyway) or sawed-off shotgun using 12 gauge.
Either one of those should do the job admirably, so would a solid slug from the sawn-off and a lot of smaller weapons with multiple rounds, you could use blanks from a .22 if the gun was barrel-to-flesh and get there eventually. Hell forget the gun, you could use a compressor at that range and do enough damage, eventually, to tear someones arm off.
@Ash Well, yes, 'eventually' an arm can be severed with pretty much everything. What I need is something reasonable that can 'cut' a limb in one load or magazine, because 17 shots from Glock won't be pleasant, but I doubt they will do the job. And I don't want my psychic to force the mind-controlled Villain with dozen of self-inflicted bullet wounds to reload his gun with one arm.
I'm not sure about explosive rounds since the force is dispersed in a sphere, therefore wasting a lot of punching potential. But you can always go the FPS Russia way... Plus, they are exotic rounds, it's not something you come across everyday and I don't think they are very useful for small calibres.
17 shots from a Glock should be plenty, especially point blank. An arm near the shoulder has less than 17cms thickness (assuming mostly regular humans), so you'd be able to messily perforate it at less than every cm. Plus gas-damage from the muzzle blast - what makes you think there would be anything left to keep the 4-6kg of arm up?
Note that you could make the villain reload by holding the gun with his mouth and reloading with his free hand.
Sorry, but this query is off-topic for so many reasons! No worldbuilding involved; it's a real-world scenario; it's basically a plot or story question. Hence, am voting to close.
@elemtilas Do remember real world questions can be on topic https://worldbuilding.meta.stackexchange.com/questions/3872/is-a-real-world-question-off-topic. I personally think this one is, it asks a specific question about a specific scenario, it may be overly broad in it's lack of restrictions but it is on topic.
@Ash -- yes, "can" being the operative word. Which means that not all real-world questions are, or ought to be, on-topic. Even so, this is still a plot question! And the OP asks two questions, to boot!
@elemtilas Well, there is no Stack Exchange for guns or weapons. This one was the closest by theme I could think of. I doubt Biology or Physics would consider this on-topic.
@elemtilas I didn't say this was automatically on-topic, the way you stated it wasn't suggested that merely by being a real-world question it could not be on-topic so I pointed out that this was not the case. I have stated my reasons for feeling that, in this case, the question should stand, although I'd rather it stood with only the second question and none of the others.
@MrScapegrace Question 2. is really enough for you to get the information you require, you might want to edit accordingly, as is the question rambles which is not doing you any favours on review.
@MrScapegrace -- Well, it's no more on-topic here than biology or physics! Basically: pick a number between 3 and 15; insert into plot; continue with story.
@MrScapegrace I'd say 1-15 and pick a big gun, but yeah elemtilas does have a point there.
@Ash, I'm not arguing with you. I was simply stating one of several reasons why I'd consider this question closeable. There are real-world questions that are appropriate here. This one (and so many many more I've seen recently), just no.
@elemtilas Fair enough, we see this question quite differently so we naturally differ greatly on whether it's on or off topic
I don't understand how this question is plot based. It does not ask anything about the story. It's only looking for a one handed firearm that could sever a limb, with a single magazine. For me, it a bit broad but still a viable question. In addition, it's a near-future question so you can still create fictional weapons and calibres. Did I miss something?
Assuming you mean "off" as in falls on the floor right now and you want it done in one or possibly two shots your best bets are:
a sawn-off shotgun firing, it probably doesn't matter at pointblank range, I'd say 12 gauge, buck and ball, or solid slug, those will get the job done.
any .50 cal handgun that fires actual .50 BMG rounds, purportedly those rounds will take a limb in a near miss.
A lot of lighter weapons will get the job done over the course of several well aimed shots, and some really light rounds could cause later loss of the limb from trauma with a single well aimed shot assuming the villain is in no state to seek immediate medical care. I would suggest that the villain staying conscious would be an issue for multiple shots so I'd go with something that will get the job done no questions asked.
Are there actual .50 BMG handguns? There are things like .50 AE but I've never heard of pistols using .50 BMG.
@Hawker65 According to Wikipedia, Desert Eagle can use those. No idea if it's even possible to use them one-handed though.
@Mr Scapegrace Could you give me a link? The only .50 cal I see is .50 AE, which is way shorter than .50 BMG
@Hawker65 https://en.wikipedia.org/wiki/IMI_Desert_Eagle
@Hawker65 There's also these two https://en.wikipedia.org/wiki/Triple_Action_Thunder, https://en.wikipedia.org/wiki/WTS_.50.
@Mr Scapegrace As I said, this is only .50 AE, not .50 BMG
@Ash Nice, I was not sure .50 BMG pistols were a thing. Are there some with more than 1 shot?
@Hawker65 Not until you go up to carbine class weapons like the Barrett M82CQ which has a 10rnd mag as standard, which you can theoretically fire one-handed but you don't want to they're really heavy for carbines.
@Ash Plus, it probably isn't very handy to point at yourself to shoot your arm off. (I never thought I would say such a thing one day)
@MrScapegrace Saying .50cal doesn't mean the same thing all the time .50 BMG is either that, 50 Browning, or 12.7 x 99mm Nato anything else, including most .510 cal are lighter rounds.
@Hawker65 We all get that "I never thought I'd say that" feeling on this stack eventually, welcome to the club.
You couldn't have a .50BMG handgun - leaving aside recoil and weight issues for a moment, automatic handguns have the magazine in the handgrip. Given that a .50BMG round is 5.5" long, you wouldn't be able to hold it. A revolver would get around this problem, but you'd still need a foot or so of barrel plus a 6" receiver minimum.
@MattBowyer There are in point of fact two single shot bolt-action handguns that do pack a .50 BMG load, they're linked in an above comment, such handguns are not small, approximately 17 and 25 inches from memory, but they do exist.
Sort of proves my point - it's hardly a handgun, just a very short rifle with no butt-stock. I should perhaps clarify that you can't have a practical .50bmg handgun.
@MattBowyer Practical is in the eye of the user and varies with circumstance, the smallest "carbine" that takes a round that big is over 45" which is certainly not a weapon you can conceal on your person, if you want one shot that you can hide and that will settle the argument look no further. Yes personally I'd like something a little smaller with a larger ammo capacity but thankfully for all concerned I'm not a villain.
I would say that 12 gauge would definitely remove all the meat , I'm not sure about severing the limb. If you target a joint, you probably have a better chance of severing a limb.
However, there are not any real one handed 12 gauge weapon. But what about sawn off shotguns? If you want to break your wrist and have the weapon fly off your hand, that is a safe bet but keep in mind that one shot might not be enough to sever a limb.
If you really don't care about that recoil factor, you could also use sawn off rifles (mare's leg style or a semi-auto). Since rifle rounds are much more powerful than pistol rounds, this could get the job done but over-penetration might be an issue (the round is so fast that it simply pierces and does not do major damage). However, since rounds from sawn off riffle tend to tumble a lot (because of the almost non-existent barrel length), this might compensate for this issue.
Otherwise, I would suggest high calibre handguns like a S&W Model 500 or a Desert Eagle. I'm pretty sure these would shatter a bone but you will need multiple shots to tear off the remaining flesh.
These are amongst the most powerful handguns so the recoil will be very strong here as well, so the previous remark about one handed shotguns remains valid here. You could go for less "overkill" handguns which use .44 Magnum for example.
I did not mention lower calibre pistols because I'm not sure of their ability to reliably break bone but I guess that, given the large magazine capacity of modern "low calibre" handguns (15 shots for the M9 or 20 for the FN 5.7), you would have enough bullets to reliably sever an arm if you are accurate enough.
EDIT : When I'm talking about 12 gauge, the preferred ammunition would be buckshot. Never underestimate the power of buckshot.
| common-pile/stackexchange_filtered |
Selfadjointness of the differential operator in a singular potential
The free Dirac operator is the differential operator of the following form
$$ T_0 = i \alpha \nabla + \beta,$$
where $\alpha$ and $\beta$ are Hermitian $4 \times 4$ matrices, and $T_0$ is selfadjoint on some domain $D(T_0)$ on infinite-dimensional Hilbert space. Dirac operator acts on $C^4-$valued functions $\psi(r) = (\psi_i(r))^4_{i=1}$ in Hilbert space $(L^2)^4.$
If we want to include the interaction in the differential equation (which is often the case, since the free Dirac operator is not so physically interesting) one could just use the following type of the interaction:
$$V(r) = \frac{Ze^2}{r^2},$$
where $Z$ and $e$ are just numbers. This is the important (Coulomb) type of the potential in physics.
Now the new 'interacting' differential operator is defined as
$$T = T_0 + V(r).$$
My questions:
Could this type of interaction $V$ somehow 'destroy' the selfadjointness of the operator $T$, even if $T_0$ is selfadjoint on some domain?
If yes, could this be simply avoided by choosing the new domain for $T=T_0 + V$ without the $r=0$, since $V$ is singular there?
Is there a reason why would selfadjointness be ruined only for large coefficients Z, but not for small ones?
More information about $V$: $V$ is a $4 \times 4$ symmetric matrix, whose elements $V_{ij}$ are (complex valued) measurable almost everywhere finite functions on $R^3$.
Could you please add more details about the interaction $V(r)$, including the domain, the role of $r$ etc. In general even if both operators in the sum are self-adjoint it does not mean that so is their sum; here is an example http://mathoverflow.net/questions/122982/sum-of-two-self-adjoint-unbounded-operators.
$V(r)$ is matrix valued measurable potential and $r$ is just the space variable $r=(r_1, r_2, r_3)$. Based on a few math papers I saw on this subject I also think that the following is true for $V$, in most of the physical situations:
$$(V\psi)i(r)=\sum_jV{ij}(r)\psi_j(r),$$
$$D(V)=(\psi \in (L^2)^4|\sum_i \int |(V\psi)_i(r)|^2 dx < \infty). $$
Self-adjointess of $T$ is equivalent to well-posedness of the initial value problem $(i\partial_t + T)\psi=0$. In your generality you could of course lose it. See Thaller's "The Dirac equation", §4.3: "Self-adjointess and essential spectrum".
This is still not enough information about V?
@Nadia: See Theorem 4.2 pag.112 of the aforementioned book by B. Thaller. This result might be interesting for you.
| common-pile/stackexchange_filtered |
how to find memory leak in Tcl/Tk?
a Tcl/Tk (8.6.11) program of mine crashes with the following error:
max size for a Tcl value<PHONE_NUMBER> bytes) exceeded
the tcl/tk program does about the following:
open a TCP/IP socket
proc ::application::create_socket {} {
variable my_socket
if {[catch {set my_socket [socket -server ::application::configure_socket -myaddr localhost 0]}]} {
puts stderr "ERROR: failed to allocate port, exiting!"
exit 3
}
return [lindex [fconfigure $sock -sockname] 2]
}
proc ::application::configure_socket {sock client_addr client_port} {
fconfigure $sock -blocking 0 -buffering none -encoding utf-8;
fileevent $sock readable {::application::readsocket}
}
read the strings received via the socket
evaluate the string as a Tcl/Tk command:
proc ::application::readsocket {} {
variable my_socket
variable rcvd_cmds
if {[eof $my_socket]} {
close $my_socket
exit
}
append rcvd_cmds [read $my_socket]
if {[string index $rcvd_cmds end] ne "\n" || \
![info complete $rcvd_cmds]} {
# the block is incomplete, wait for the next block of data
return
} else {
set docmds $rcvd_cmds
set rcvd_cmds ""
if {![catch {uplevel #0 $docmds} errorname]} {
} else {
# oops, error, alert the user:
global errorInfo
::application::fatal "oops: $errInfo\n"
}
}
}
the string that is received is something like (with \n being replaced by proper newlines)
::application::post {====================: 34124 hello world\n}\n
and the ::application::post procedure is empty:
proc ::application::post {message} {}
if i send a few commands (like ::application::post {====================: %d\n}\n) from my control application, everything works as expected.
however, if i send a very large number of commands in a short time (e.g. driving the above command from an "infinite counter") Tcl/Tk application will eventually crash.
running the tcl/tk script through gdb, i get a backtrace that doesn't tell me anything:
(gdb) run
Starting program: /usr/bin/wish8.6 application.tcl
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
[New Thread 0x7ffff67e9700 (LWP 1445236)]
[Detaching after fork from child process 1445237]
input channels = 0, output channels = 0
app output pipe: Connection reset by peer
max size for a Tcl value<PHONE_NUMBER> bytes) exceeded
Thread 1 "wish8.6" received signal SIGABRT, Aborted.
__GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:50
50 ../sysdeps/unix/sysv/linux/raise.c: No such file or directory.
(gdb) bt
#0 __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:50
#1 0x00007ffff7aaf537 in __GI_abort () at abort.c:79
#2 0x00007ffff7d60690 in Tcl_PanicVA (format=<optimized out>, argList=argList@entry=0x7fffffffd700) at ./generic/tclPanic.c:123
#3 0x00007ffff7d60759 in Tcl_Panic (format=format@entry=0x7ffff7dbec30 "max size for a Tcl value (%d bytes) exceeded") at ./generic/tclPanic.c:160
#4 0x00007ffff7d77c41 in AppendUtfToUtfRep (objPtr=objPtr@entry=0x555555cacaf0,
bytes=0x7ffef58ca020 "::application::post {1.04045e+07}\n::application::post { }\n::application::post {hello}\n::application::post { }\n::application::post {world}\n::application::post {\n}\n::application::post {", '=' <repeats 20 times>, ": }\n::pdwindow::po"..., numBytes=2147450230) at ./generic/tclStringObj.c:1727
#5 0x00007ffff7d74d2b in AppendUtfToUtfRep (numBytes=<optimized out>, bytes=<optimized out>, objPtr=0x555555cacaf0) at ./generic/tclStringObj.c:1394
#6 Tcl_AppendObjToObj (objPtr=0x555555cacaf0, appendObjPtr=appendObjPtr@entry=0x555555cacdf0) at ./generic/tclStringObj.c:1509
#7 0x00007ffff7d8beab in TclPtrSetVarIdx (interp=interp@entry=0x555555574990, varPtr=0x55555564d3e0, arrayPtr=0x0, part1Ptr=part1Ptr@entry=0x0, part2Ptr=<optimized out>,
newValuePtr=0x555555cacdf0, flags=516, index=1) at ./generic/tclVar.c:1976
#8 0x00007ffff7d1e196 in TEBCresume (data=0x555555cad008, interp=<optimized out>, result=0) at ./generic/tclExecute.c:3629
#9 0x00007ffff7c914a2 in TclNRRunCallbacks (interp=interp@entry=0x555555574990, result=0, rootPtr=0x0) at ./generic/tclBasic.c:4493
#10 0x00007ffff7c933de in TclEvalObjEx (interp=interp@entry=0x555555574990, objPtr=<optimized out>, flags=flags@entry=131072, invoker=invoker@entry=0x0, word=word@entry=0)
at ./generic/tclBasic.c:6059
#11 0x00007ffff7c933aa in Tcl_EvalObjEx (interp=interp@entry=0x555555574990, objPtr=<optimized out>, flags=flags@entry=131072) at ./generic/tclBasic.c:6040
#12 0x00007ffff7d40203 in TclChannelEventScriptInvoker (clientData=0x5555558a8740, mask=2) at ./generic/tclIO.c:8945
#13 0x00007ffff7d3fc3b in Tcl_NotifyChannel (channel=0x555555949770, mask=2) at ./generic/tclIO.c:8426
#14 0x00007ffff7da1d0e in FileHandlerEventProc (flags=-3, evPtr=0x555555d21e80) at ./unix/tclUnixNotfy.c:808
#15 FileHandlerEventProc (evPtr=evPtr@entry=0x555555d21e80, flags=flags@entry=-3) at ./unix/tclUnixNotfy.c:764
#16 0x00007ffff7d5c8f9 in Tcl_ServiceEvent (flags=flags@entry=-3) at ./generic/tclNotify.c:670
#17 0x00007ffff7d5cc09 in Tcl_DoOneEvent (flags=-3) at ./generic/tclNotify.c:967
#18 0x00007ffff7e608b2 in Tk_MainLoop () at ./unix/../generic/tkEvent.c:2109
#19 0x00007ffff7e6f8d0 in Tk_MainEx (argc=<optimized out>, argv=0x7fffffffe008, appInitProc=0x5555555551e0, interp=0x555555574990) at ./unix/../generic/tkMain.c:377
#20 0x00005555555550df in ?? ()
#21 0x00007ffff7ab0d0a in __libc_start_main (main=0x5555555550b0, argc=2, argv=0x7fffffffdff8, init=<optimized out>, fini=<optimized out>, rtld_fini=<optimized out>,
stack_end=0x7fffffffdfe8) at ../csu/libc-start.c:308
#22 0x000055555555511a in _start ()
now i have a suspicion that something goes wrong in append rcvd_cmds [read $my_socket] of the ::application::readsocket proc.
is there a way to introspect a given variable in Tcl/Tk to see how much memory it is consuming?
apart from that: are there any obvious memleaks in the Tcl/Tk code?
It's probably the rcvd_cmds variable; that's the only place you're accumulating in the code you've showed.
yes, i tend to agree. after writing the Q and going to sleep, i realized that when doing the loop in tcl, it is much slower than when doing it from my external C-program (which generates the tcl-commands and send them via TCP/IP). so most likely the Tcl/Tk program just cannot keep up with evaluating the code received, and thus the rcvd_commands variable just doesn't get emptied in time.
You can see from the stack trace that it is doing an append (AppendUtfToUtfRep fails; the name is suggestive) and you only have one place where you're doing that. The immediate problem is that you're accumulating too much in that one variable. But why? Fortunately in this case we can take a good guess why.
You appear to be not detecting the end of each command and are consequently never sending them into the evaluation path and clearing down the accumulation variable. Because your blocks are basically line-oriented, you should use gets instead of read. You should also do little things like tracking how much data you have accumulated to ensure that you don't build up too much in one go. The chan pending command helps a lot with this.
proc ::application::readsocket {} {
variable my_socket
variable rcvd_cmds
set MAX_LENGTH 1000000
# Consume whole lines out of the received message
while {[gets $my_socket line] >= 0} {
append rcvd_cmds $line "\n"
if {[info complete $rcvd_cmds]} {
try {
uplevel #0 $rcvd_cmds
} on error {} {
# oops, error, alert the user:
::application::fatal "oops: $::errorInfo\n"
} finally {
set rcvd_cmds ""
}
} elseif {[string length $rcvd_cmds] > $MAX_LENGTH} {
# Too much in one command!
close $my_socket
exit
}
}
# No whole lines remain; can be for several reasons:
# * Simple end of message (normal case!)
# * Socket closed
# * Data there not finished by newline; check for over-length in this case
if {[chan eof $my_socket]} {
close $my_socket
exit
} elseif {[chan blocked $my_socket]} {
if {[chan pending input $my_socket] > $MAX_LENGTH} {
# Too much in one line!
close $my_socket
exit
}
}
}
You probably want to consider running those commands in a child interpreter where you have removed the update and vwait commands.
thanks. three things: 1) in my code-example i missed the terminating \n in the command string from the (remote) control application. so there's probably not a big issue here (i'll update the question to also mention that the problem only appears when doing many commands in a short time). 2) i don't really like the hardcoded MAXLENGTH=1000000; isn't there a way to query the maximum size of a string and use a MAXLENGTH based on that? 3) your code replaces my segfault with an orderly shutdown...i'd rather keep running ;-)
Ad (2): There is nothing to query, this is a constant (in the true meaning of the word) or fractions thereof. Donal has addressed this (many times) before, see, e.g.: https://stackoverflow.com/questions/22932668/storage-capacity-of-tcl-variable ; Ad (3): oh padawan, an orderly shutdown is the first step to consider a true compensation action :) what about chunking the inbound data in a variable bundle, i.e. a Tcl array or list of Tcl string objects.
In any case: separating the concerns would also be an option by designing your protocol different: use a line-based interaction to exchange commands and metadata, then a uninterpreted binary interaction for the body of data. this body of data can then be processed different (by spooling it via [chan copy] into a file or similar?)
| common-pile/stackexchange_filtered |
Probability that an outcome is fair
I have a program which has 3 slots, each that are supposed to output 0 or 1 with 50% probability, so [x] [x] [x], where x = 0 or 1
I think then the probability of all 1's would be 1/(2*2*2)= 1/8, or 12.5%.
If I run this program many times and empirically find that this outcome occurs 20% of the time instead, how do I calculate the probability that the outcome was actually fair according to the model and not tampered with?
Use Bayes' formula.
That will depend on the (prior) probability of tampering. If tampering is very unlikely, then even an unlikely distribution of results may still be most likely fair. If, however, tampering is considered likely to begin with, less likely results will be more likely to imply tampering has taken place. If you know this prior probability of tampering, Lovsos is correct that you can use Bayes' formula to determine the probability that tampering has taken place given a particular empirical result.
hmm makes sense, but what if I don't know the probability of tampering? Should I just give it a value of 50%?
Do you actually think there's a 50% chance the program will be tampered with (before looking at the results)? If you don't know the prior probability, just give it your best educated guess. Btw, In order to use Bayes' Theorem, you also have to know the probability of a given outcome if Tampering has taken place. If the form of tampering in question is deterministic, this may be $1$, if however, it is probabilistic, then it may be something else.
If you run your program $n$ times, with $n\ge30$ and $np>5$ (here $p=\frac18$), the probability that the outcome of 111 will be between $p-\frac{1}{\sqrt n}$ and $p+\frac{1}{\sqrt n}$ should be greater than $95%$. So your result is OK for $n=100$, not OK for $n=1000$...
Is there a way to write the likelihood in probability of 20% outcome for n = 1000? Sorry been a long time since I've done any probability.
@Jake do you mean the probability of getting at least 200 "111" results in 1000 iterations? or exactly 200? In any case the probability (if all results are in fact equally likely) is $$\frac {\text{# of possible favorable results}} {\text{total # of possible results}}$$ So for exactly $k$ "111"'s in $n$ trials the probability is $$\frac {n \choose k} {8^n}$$ and for at least $k$ "111"s it's $$\sum_{i\ge k} \frac {n \choose i} {8^n}$$
@NicolasFRANCOIS 95% confidence is a common bar to set, for sure, but his question isn't about statistical significance, it's about whether or not his process was tampered with. Results will fall outside of the 95% confidence interval naturally 1/20 of the time, and if the probability of tampering is lower than 1/41, then such results are still most likely to the output of an unmolested system. However, if as he suggested the probability of tampering is 50% then even some results in that 95% interval could be suspect, depending on the nature of the tampering.
| common-pile/stackexchange_filtered |
How to track state of user preference from page to page
I'm using Javascript to hide the site map on each page of a site (so that it will be visible on browsers with Javascript disabled). I then use a JQuery toggle to allow the user to reveal the Site Map (using a "Site Map" link in the footer of each page).
The Site Map "re-hides" each time the user navigates to another page, but I'd like to maintain the visibility of the Site Map across pages.
In other words: the Site Map should start out as hidden, but if the user toggles the visibility of the Site Map, it should stay visible while the user navigates from page to page until the user hides it again.
Search about Sessions
Have you tried using cookies?
There's a problem in linking to an old question as cookies were mostly replaced by new storage technologies since. This being said, there might be other and more recent similar questions.
The best solution now is to use localStorage :
// read
var hidden = localStorage['hidden']=='yes'; // defaults to false at first visit
// write
localStorage['hidden']= hidden ? 'yes' : 'no';
Those values are stored and available for all pages of your site (more precisely the origin) and are less prone to "cleaning" (external tools or in browser) than cookies.
Before choosing to use a html5 method, be sure to check the compatibility chart ( see http://www.html5rocks.com/en/features/storage ) and determine if you need support for non-supporting browsers (example: ie7). If you need support for older browsers, this won't work.
ie7 is no longer a supportable browser. Almost no modern page is correct on ie7 and nobody cares.
Thats why I didnt -vote. But as an example: I developed web based software for a hospital that didn't upgrade to ie8, because it breaks existing web based software. It'll probably be atleast another year before they update. It's not an ideal work in web development land..
@DamienOvereem I wasn't saying your comment is bad. There's no problem in pointing limits. But for all normal cases (that is not your hospital and a few companies) I think cookies should be forgotten as an awkward thing from the past.
That will take a while. Server-side can't read localstorage, so we'll still be stuck with cookies for ie. session keys for a long long time.
I don't think so. Many web apps are ajax based now, they manage what is sent to the server in javascript.
Thanks, I've never used cookies, not wanting to leave crumbs behind. New to JS, I was really asking about how to use some sort of global variable, as in: one that initiates on first visit to the site, persists while navigating, then goes away as user leaves. Perhaps that's what "session" means, I just didn't even know what to search for! But now I'll search for session and localStorage.
I'll keep an eye on browser compatibility, of course, but as this is a minor user convenience feature, I'm not too concerned about stubborn IE7 users. They're on their own as far as I'm concerned, and curses on MS and all those maintaining the existence of IE!!
@MarkG Sessions are server based and initiated ie by the session_start() when using php (now you have something to search for). You have no way to remove data as soon as a user leaves, aside from storing data for a limited time and renewing that time on every request. Ie. if you set it for 1 minute and reset 1 minute after each page load, the data will be gone if a user does not reload a page within that minute. There are no solid ways to remove data "when a user leaves the site" because the user leaves after each request, but just comes back shortly after. Thats how web works.
Set a cookie.
Read How do I set/unset cookie with jQuery? discussing how to do just that. discussing how to do just that.
Cookies allow you to track user preferences client side, so you dont have to rely on server based code.
| common-pile/stackexchange_filtered |
refresh the main panel screen in shiny using the action button
I am building a shiny app and I want to refresh the main panel screen. Here is a sample code. I have a submit button to display the data and I have a re-fresh button to clear the screen. I am not so sure how to code the re-fresh button in R and shiny since I am new to this. Thanks for looking into
library(DT)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput("amountTable", "Amount Tables", 1:10),
actionButton("submit1" ,"Submit", icon("refresh"),
class = "btn btn-primary"),
actionButton("refresh1" ,"Refresh", icon("refresh"),
class = "btn btn-primary")
),
mainPanel(
# UI output
uiOutput("dt")
)
)
)
server <- function(input, output, session) {
observeEvent(input$submit1, {
lapply(1:input$amountTable, function(amtTable) {
output[[paste0('T', amtTable)]] <- DT::renderDataTable({
iris[1:amtTable, ]
})
})
})
output$dt <- renderUI({
tagList(lapply(1:10, function(i) {
dataTableOutput(paste0('T', i))
}))
})
}
shinyApp(ui, server)
You could add the possibility of return nothing from the renderUI() if the refresh button is used.
As it is not that straightforward to reset an action button you would have to use a workaround with a reactive variable.
if(global$refresh) return()
This reactive variable you can control with the refresh and submit button
E.g. if(input$refresh1) isolate(global$refresh <- TRUE)
which you wrap in seperate observe functions.
Full code see below:
library(DT)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput("amountTable", "Amount Tables", 1:10),
actionButton("submit1" ,"Submit", icon("refresh"),
class = "btn btn-primary"),
actionButton("refresh1" ,"Refresh", icon("refresh"),
class = "btn btn-primary")
),
mainPanel(
# UI output
uiOutput("dt")
)
)
)
server <- function(input, output, session) {
global <- reactiveValues(refresh = FALSE)
observe({
if(input$refresh1) isolate(global$refresh <- TRUE)
})
observe({
if(input$submit1) isolate(global$refresh <- FALSE)
})
observeEvent(input$submit1, {
lapply(1:input$amountTable, function(amtTable) {
output[[paste0('T', amtTable)]] <- DT::renderDataTable({
iris[1:amtTable, ]
})
})
})
output$dt <- renderUI({
if(global$refresh) return()
tagList(lapply(1:10, function(i) {
dataTableOutput(paste0('T', i))
}))
})
}
shinyApp(ui, server)
This is exactly what I am looking for. Thanks you're a life saver. One more thing, is there a way also to refresh the select input back to 1 once I hit the refresh button. For now it is refreshing the main panel but the selectinput does not initialize to 1. Appreciate it!
just add updateSelectInput(session, "amountTable", "Amount Tables", 1:10, 1) after if(input$refresh1) isolate(global$refresh <- TRUE)
Sorry one more thing, how do I display a text on the main panel such Amount.Table1, Amount.Table2 etc for each individual tables. It seems the paste0 does not work. Appreciate it!
you mean like textOutput(). However, comments are not supposed to discuss (multiple) addit. questions,...thanks for understanding
No worries. Thank you for your time. Appreciate your help!
I do apologise I am new to this website and to R and shiny. Hope you understand. I am learning a lot from here.
| common-pile/stackexchange_filtered |
Avoid repeating certain html tags while rendering a jquery template
In the following code, users in an array of user objects, which have a name property in them:
$.template("listTemplate", "<ul><li>${name}</li></ul>");
$.tmpl("listTemplate", users).appendTo("#app");
My purpose is to generate a html similar to:
<div id="app">
<ul>
<li>Barney</li>
<li>Cartman</li>
<li>Sheldon</li>
</ul>
</div>
However, I'm stuck with:
<div id="app">
<ul><li>Barney</li></ul>
<ul><li>Cartman</li></ul>
<ul><li>Sheldon</li></ul>
</div>
Is there an elegant way to accomplish this directly with a jquery template, and somehow indicate to the templating engine that <ul> need not be repeated?
what plugin/library do you use to make the tempalte ? Or are you only trying to generate the html you showed ? If it is you don't realy need a template but simple jQuery.
simple jQuery li insertion.
http://plnkr.co/edit/HYaV5NxZOQQbjnkYKF1q?p=preview
| common-pile/stackexchange_filtered |
How can I set the background color below (and to the right) of table cells if there are few rows (or colums)?
i have jtable with 5 rows but the size of jtable is more than the jtable containing 10 rows.
when i used table.setBackground(), only 5 rows are colored and rest part is uncolored.
I want to set color in the whole table.
How can i fixed this problem??
Thanks in advance..
Or, make the table fill the whole view port by using the JTable#setFillsViewportHeight( true ) method. This will fix your background color problem, and has some other advantages as described in the Swing tutorial about JTables
+1. I didn't know this property, and this answer is better than mine.
I discovered this property only 2 days ago. Never thought I would be able to use this knowledge on such short notice
What you're seeing below the table is probably the background of the viewport of the JScrollPane which contains the JTable.
Set this viewport's background as well:
scrollPane.getViewPort().setBackground(Color.white);
while technically correct (if you use the table's background instead hard-coding an arbitrary color), it has an usability issue: it appears like all the area is the table but in fact that's not the case. Consequently users expect that f.i. showing popup menus by mouse clicks are working everywhere.
Good point. I just saw Robin's answer, and it's better than mine.
| common-pile/stackexchange_filtered |
Compiling large data structures in Haskell
I have a CSV file with stock trading history, its size is 70 megabytes.
I want to run my program on it, but do not want to wait for 30 seconds every start.
1.
Just translate CSV file into Haskell source file like this:
From | TO
-------------------------------------------
1380567537,122.166,2.30243 | history = [
... |<PHONE_NUMBER>,122.166,2.30243)
... | , ...
... | ]
2.
Use Template Haskell to parse file compile-time.
Trying first approach I found my GHC eat up 12gb of memory after 3 hours of trying to compile one list (70 mb source code).
So is TH the single available approach? Or I can just use hard-coded large data structure in source file?
And why GHC can't compile file? Does it go to combinatorial explosion because of complex optimizations or something?
Using fast libraries like bytestring and attoparsec will reduce time to much lesser than 30 seconds.
Possible duplicate of http://stackoverflow.com/a/6403503/83805
Have you tried cassava?
Don, yes, it is related, but answer on that question was about inserting bytestring-literals into the code and then converting it into a structure; but I wanted to get already compiled structure in my program.
jtobin, question is not about it, but I will try it. Thank you anyway.
Here is my benchmark: http://jsbin.com/ucIbIgu (CSV stands for Data.CSV from MissingH package). Serialization is really blazing fast.
Hard-coding so much data is not a common use-case, so it isn't surprising the compiler doesn't handle it well.
A better solution would be to put the data into some format that is easier to read than CSV. For example, consider writing a program that parses your CSV file and serializes the resulting structure using some package like cereal. Then your main program can read the binary file, which should be much faster than your CSV file.
This approach has the added benefit that running your program on new data will be easier and won't require recompiling.
I assume that built-in-program data would give more performance.
Is it true or boost wouldn't be significant?
Anyway, nice tip. I didn't recall about this possibility.
I really doubt the performance difference is significant. However, I'm not entirely certain--I'd have to run a benchmark or something. More importantly, though, I'm think it is very likely that the cereal approach is fast enough for your purposes, and it sounds much easier to implement. That's what I'd try first.
Here is my benchmark: http://jsbin.com/ucIbIgu (CSV stands for Data.CSV from MissingH package). Serialization is really blazing fast.
| common-pile/stackexchange_filtered |
How to prove $\lim\limits_{(x,y)\to(0,0)}\frac{{x^3{y^2}}}{{{x^4} + {3y^4}}} = 0$?
To prove that $$\lim\limits_{(x,y)\to(0,0)}\frac{{x^3{y^2}}}{{{x^4} + {3y^4}}} = 0$$
I start with
$$\left| {\frac{{{x^3}{y^2}}}{{{x^4} + 3{y^4}}}} \right| \leqslant \left| {\frac{{{x^3}{y^2}}}{{{x^4}}}} \right| = \left| {\frac{{{y^2}}}{x}} \right|.$$
But I do not know how to show $| {\frac{{{y^2}}}{x}}|$ is bounded using the hypothesis that $0<|x|<\delta$, $0<|y|<\delta$ and $0<\sqrt{x^2+y^2}<\delta$ since the quarters powers of $x$ and $y$ are very difficult to manage. Even setting $\delta=1$ gets me nowhere.
Isn't this equivalent to $\lim_{x\to 0} \frac{x^5}{4x^4}$ ?
Start again, and consider separately $|y|\le |x|$ and $|y|\ge |x|$.
Say that $0 < \sqrt{x^2+y^2} < \delta$. We can conclude that $|x|<\delta$ and $|y|<\delta$.
Now $x^4 + 3y^4 \geq x^4 + y^4 \geq 2x^2y^2\geq x^2y^2 $
Thus,
$$ \left| \frac{x^3y^2}{x^4 + 3y^4} \right| \leq \frac{|x|^3y^2}{x^2y^2} = |x| < \delta$$
Now given any $\varepsilon > 0$ if we choose $\delta = \varepsilon$ this would verify the definition of limits.
Note: One is not allowed to work with the function $y^2/x$, as you try to do, because it is not locally defined in a punctured disk.
Perfect!. Nice solution, many thanks
Another approach is to use the fact that for $x\gt0$, we have $\left(\sqrt{x}-\frac1{\sqrt{x}}\right)^2\ge0\implies x+\frac1x\ge2$:
$$
\begin{align}
\left|\frac{x^3y^2}{x^4+3y^4}\right|
&=\frac{|x|}{\sqrt3}\frac{x^2(\sqrt[4]3\,y)^2}{x^4+3y^4}\\[9pt]
&=\frac{|x|}{\sqrt3}\frac1{\left(\raise{2pt}{\frac{x}{\sqrt[4]3\,y}}\right)^2+\left(\frac{\sqrt[4]3\,y}{x}\right)^2}\\
&\le\frac{|x|}{2\sqrt3}
\end{align}
$$
Another idea is using polar coordinates. Then
\begin{align}
\lim_{(x,y)\to (0,0)} \frac{x^3y^2}{x^4+3y^4} &= \lim_{r \to 0^+} \frac{r^5\cos^3x\sin^2x}{r^4\cos^4x+3r^4\sin^4x} \\
&=\lim_{r \to 0^+}r \frac{\cos^3x\sin^2x}{\cos^4x + 3\sin^4x}
\end{align}
Now, since
$$0 \leq \cos^3x\sin^2x \leq 1$$
and
$$\frac{3}{4} \leq \cos^4x+3\sin^4x \leq 3$$
We have
$$\lim_{r \to 0^+}0 \cdot r \leq \lim_{r \to 0^+}r \frac{\cos^3x\sin^2x}{\cos^4x + 3\sin^4x} \leq \lim_{r \to 0^+} \frac{4r}{3}$$
| common-pile/stackexchange_filtered |
javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake Caused by: java.io.EOFException: SSL peer shut down incorrectly
Im trying to read data from a url , my program works fine , it connects and download de data correctly, but only if I run the project from my IDE. The problem is that when I run the program from the executable JAR it breaks on the next line:
connection.connect();
I dont know why it only breaks when it is executed by the executable JAR, but if I run it with the IDE it works.
I have tried to add the https protocols but still breaking on that line.
System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
The exception is the next one:
javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(Unknown Source)
at util.HammerReader.peticion(HammerReader.java:107)
at com.mycompany.getjavaurlinterfaz.Marco.ejecutarActionPerformed(Marco.java:371)
at com.mycompany.getjavaurlinterfaz.Marco.access$800(Marco.java:17)
at com.mycompany.getjavaurlinterfaz.Marco$8.actionPerformed(Marco.java:217)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Caused by: java.io.EOFException: SSL peer shut down incorrectly
Maybe it's a configuration mistake: Maybe your are using different JREs to execute your app. So please make sure that you are launching your JAR with the exact same java.exe as your IDE.
Then you can be sure that they are using the same ssl configuration means Cipher suites etc.
I have checked that I am running my JAR with the exact java.exe that my IDE.
| common-pile/stackexchange_filtered |
YouTube Data API no longer returns deleted videos in playlists?
I am trying to get list of all my liked videos on YouTube (including deleted) using playlistItems.list method.
Last month (Sep. 2018) I've tried it, response from the server contained exact amount of items, including every video with '[Deleted video]' title.
Currently (Oct. 2018), response looks like this: chrome console screenshot (note the '48': means two deleted videos is missing in the array).
I've checked out revision history, but there is no mention about recent changes related to this problem.
So my questions is:
Does playlistItems.list method no longer return deleted videos in playlists?
If yes, does anyone have a link to changelog or any ideas on how to get deleted video id now?
Or it's just me messed up something and everything works the old way?
EDIT: Found related issue on google issue tracker.
But it's dated Jun. 14, 2018 which is strange, since for me everything worked back in June.
Reported another issue on the YouTube bug tracker: https://issuetracker.google.com/issues/121017800
I do remember testing this before June 18' and the total was never reflecting the actual results, I see others acknowledge this as well refer to this
| common-pile/stackexchange_filtered |
Extract data from flutter
I'm building an app with Flutter and a backend server with a Python Flask server..
The data returned from the backend server is in the following format:
(('helloworld',), ('hello',))
I want to extract helloworld and hello from this data.
However, sometimes there is only one piece of data, sometimes two, and sometimes more.
How can I extract data? Below is my code.
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'dart:core';
class messageview extends StatefulWidget {
@override
mymessageview createState() => mymessageview();
}
class mymessageview extends State<messageview> {
void _loadmydata() async {
final dio = Dio();
final response = await dio.get('http://<IP_ADDRESS>:3000/mymessage');
//Here we need code to extract data.
}
@override
void initState() {
super.initState();
_loadmydata();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text("My Messasge View")
),
);
}
}
If you know a way to solve this problem, please let me know how to solve it.
you are getting this data in tuple?
@MunsifAli I don't get the data as tuples, but as strings.
You can modify your _loadmydata() function to extract the data:
void _loadmydata() async {
final dio = Dio();
final response = await dio.get('http://<IP_ADDRESS>:3000/mymessage');
//Here we need code to extract data.
List<String> extractedData = [];
// Extract data from the response
List<dynamic> responseData = response.data;
for (var item in responseData) {
if (item is List && item.isNotEmpty) {
// Extract the first element and add it to the list
extractedData.add(item[0]);
}
}
}
| common-pile/stackexchange_filtered |
Does rails 3 find_by_x sanitize data?
I have a model with a few basic fields:
title
category
etc.
I have seen documentation that says when you do:
Model.where("category = ?", params[:cat])
the code will be sanitized automatically. If I convert the above to:
Model.find_by_category params[:cat]
will the params also be sanitized automatically? I don't want to assume that it is because that would be a bad security mistake.
Yes it does sanitize. Since you are on Rails 3, check it in the console. It will show you the generated SQL statement and by looking at it you can determine whether the sanitization took place or not.
| common-pile/stackexchange_filtered |
how to change alphabetic order to descending order in drupal 7
I have a accordion menu in left side and the menu list come as alphabet order but i want newest come first. how can i change the sorting of that list.
How you've added accordion to menu?
i have create the menu first named Event and then create the content under this menu like Abc, New Event and all. In the accordion menu configuration change the menu source to event and choose the position left sidebar
Drupal menu items are manually ordered. You can drag and drop into the correct order here: /admin/structure/menu/manage/navigation
i am not talking about admin menu, i need to sort the accordion menu list according to the descending order
| common-pile/stackexchange_filtered |
How to randomly remove block side in a grid?
Following on from How to control square size in a grid from square area?, I would like to randomly remove block side in a grid. Here my idea:
%% In a first time, I randomly select a white patch in the grid (figure below):
let random-patch one-of patches with [pcolor = white]
%% Then, I draw red patches to identify intersections between white roads (figure below):
ask patches with [ (pxcor mod (side + 1) = 0 ) and (pycor mod (side + 1) = 0 ) ] [set pcolor red]
%% Finally, I color in brown all white patches that are situated between two red patches and on the same side than the random patch. To identify these white patches, have I to calculate distance between the random patch and the nearest red patches and to color all white patches situated along these distances ?
Thanks in advance for your help.
An alternative way to think about your problem is in terms of finding clusters of white patches: you're picking a white patch at random, and you want to turn all the contiguous white patches to brown.
You can look at the "Patch Clusters Example" in the Code Examples section of NetLogo's model library to see one way to do this.
Here is how I would do it. Let's start by defining a grow-cluster reporter:
to-report grow-cluster [ current-cluster new-patch ]
let patches-to-add [
neighbors4 with [
pcolor = [ pcolor ] of myself and
not member? self current-cluster
]
] of new-patch
let new-cluster (patch-set current-cluster new-patch)
report ifelse-value any? patches-to-add
[ reduce grow-cluster fput new-cluster sort patches-to-add ]
[ new-cluster ]
end
The code may be hard to understand if you're not used to functional programming because it uses recursion within a call to reduce. Still, in a nutshell, it:
takes an existing patch cluster and a new patch to add to this cluster
looks for neighbors of that new patch that should also be added to the cluster, i.e., those that are the same color but not already part of the cluster
calls itself for these new patches to add so that their neighbors can be added to the cluster (and those neighbors' neighbors, etc.) until no new patches are found.
Once you have grow-cluster, you can use it to accomplish exactly what you want by seeding it with an empty cluster and the random patch that you selected:
to remove-random-side
let random-patch one-of patches with [pcolor = white]
let side grow-cluster no-patches random-patch
ask side [ set pcolor brown ]
end
Caveat: for this to work, world wrapping has to be disabled in your model settings.
Since you're making a uniform grid, you might consider just doing math on pxcor and pycor instead of taking the Patch Clusters Example approach. That approach is best suited to dealing with irregular shapes.
To set up your grid, you can just do:
ask patches [
set pcolor brown
let horizontal-street? pycor mod (side + 1) = 0
let vertical-street? pxcor mod (side + 1) = 0
if horizontal-street? or vertical-street?
[ set pcolor white ]
if horizontal-street? and vertical-street?
[ set pcolor red ]
]
| common-pile/stackexchange_filtered |
Regex that matches all week day's name in a string
I want to match every week day in a string where all words are comma separated.
Examples:
"mon, thu, fry" should be matched
"mon, tue, sat" should be matched
"" should not be matched
"mon, tue, wed, thu, fri, sat, sun" should be matched
"foo, bar" should not be matched
I came up with this regex but it matches only the string containing ALL week days:
^(mon|tue|wed|thu|fri|sat|sun)$
How can I match them "indipendently"?
I am using python3
You can use: ^(?:mon|tue|wed|thu|fri|sat|sun)(?:\s*,\s*(?:mon|tue|wed|thu|fri|sat|sun))*$
What happens if a string has days mixed with non day words, e.g. mon, foo ?
Perhaps, ^(mon|tue|wed|thu|fri|sat|sun)(,\s*(mon|tue|wed|thu|fri|sat|sun))*$
@TimBiegeleisen I should then handle that as an invalid string in my code. So the regex should not match anything... in an ideal world
@refex - Check anubhava's comment. It handles the scenario which Tim is describing as well.
If you have the ability to use the newer regex module, you could use a recursive approach:
^((?:mon|tue|wed|thu|fri|sat|sun)(?:, )?)(?1)*$'
In Python this would be:
import regex as re
string = """
mon, tue, fri
mon, tue, sat
mon, tue, wed, thu, fri, sat, sun
foo, bar
mon
tue
wed
mon, wed
"""
rx = re.compile(r'^((?:mon|tue|wed|thu|fri|sat|sun)(?:, )?)(?1)*$')
days = list(filter(lambda x: rx.match(x), string.split("\n")))
print(days)
Rather than give you the direct answer, I'll try the teach you to fish approach.
Use an interactive regular expression facility (such as http://pythex.org), enter your tests strings first, then iterate on your regular expression string until all of the test strings match to your specification.
I'll give you a hint that you'll need to use a capture group and possibly a quantifier.
The interactive facility usually has a "regular expression cheatsheet" you can consult to give you ideas.
Good luck with your homework!
| common-pile/stackexchange_filtered |
Are All Heading Levels Required in HTML Emails?
I'm working on sending a mass email. The content I was given and the template I have really don't lend themselves to an <h1>. There are a bunch of headings, however, that should be <h2>.
Is this acceptable in an email? If not, what is a method of hiding an <h1> that works across most email clients?
Yes, both <h1> and <h2> are not only acceptable in email, they're recommended from an accessibility POV. <h> tags in email have the same meaning as in a web page, so you can choose whatever you think makes sense.
You may want to CSS-Reset their default visual display (also as you would in a web page). Eg:
h1, h2, h3 {margin: 0; padding: 0; [more reset styles...] }
Worth noting that common practice is to use no headings, or any block styles (such as p) in emails, since rendering of them can vary so widely across platforms. At the very least, you have to remember to in-line the styles of whatever you use, since some very big names in email platforms will strip out style blocks. That's generally done on the surrounding td tag.
Also one could use a span directly in the textblock to crate a headline
| common-pile/stackexchange_filtered |
how to use d3.data().enter().call()
I'm trying to link a d3 project with an open layers project. What I'm trying to do is to use d3 to find out if a given node exists in my DOM.
If it exists, i use transitions.
If it does not exist, I need to insert the node via the openlayers API. This is required as the nodes are registered with openlayers. My initial thought was to perform a call on d3.data( ).enter( ).call( myInsertFunction() )
But this does not seem to be working.
I hope someone out there can help me or point me in the right direction. I'm fairly new to the d3 lib.
function insertNewFeature(d) {
var word = d;
var pixel = new OpenLayers.Pixel(word.x,word.y);
var lonlat = map.getLonLatFromPixel(pixel);
var point = new OpenLayers.Geometry.Point(lonlat.lon,lonlat.lat);
var feature = new OpenLayers.Feature.Vector(point);
feature.id = word.city+'_'+word.text,
feature.attributes = {
text: word.text,
sentiment: word.sentiment,
count: word.count
};
feature.style = {
label: word.text,
labelAlign: 'mm',
fontColor: word.color,
fontFamily: word.font,
fontSize: word.size,
rotation: word.rotate,
strokeColor: '#FFFFFF',
strokeWidth: 1,
strokeOpacity: 0.5
}
svgLayer.addFeatures([feature]);
}
function update(data)
{
var text = d3.select("OpenLayers.Layer.Vector_4_troot").selectAll("text").data(data, function(d) { return d.cityCode + "_" + d.text.toLowerCase() });
text.transition()
.duration(1000)
.attr("transform", function(d) { return "translate(" + [ d.x , d.y ] + ")rotate(" + d.rotate + ")"; });
//text.style("font-size", function(d) { return d.size + "px"; });
text.enter().call(insertNewFeature());
}
Try this jsfiddle: http://jsfiddle.net/Q8b2z/
I'm not positive why, but you can't call call on the result of text.enter(). Instead it should work to call the similar insertNewFeature(text.enter()).
| common-pile/stackexchange_filtered |
New tokens to existing language
I am using Monaco editor in our project and I have issue I am not able to overcome.
At our scenario , user can add new words to the editor once he clicks on a button, for example, user has editor with language javascript and he now wants to add new word 'workTest', it should be highlighted in custom color.
How do I add new tokens to the editor with highlighted colors?
I already have my 'newTheme' with rules {token: 'asToken', foreground: 'FFA500', fontStyle: 'bold'}
How do I add the tokens to an existing language? I tried everything and nothing works.
The tokenization is done using a dynamic tokenizer (see the Monarch declarative syntax highlighter documentation). All keywords are specified in JS code, via a Regex rule.
You could create your own tokenizer and update that with each new keyword.
| common-pile/stackexchange_filtered |
How to render the function inside addEventListener load in reactjs or nextjs?
const Test = () =>
{
const [ reload , setReload ] = useState('')
useEffect(() => {
console.log("useEffect Reloded");
document.getElementById( "img" )!.addEventListener('load' , () => {
console.log("img loaded")
});
},[reload])
useEffect(() => {
document.getElementById( "btn" )!.addEventListener('click' , function() {
console.log("btn loaded");
setReload(v4())
});
}, [])
return (
<div>
<img src={picTest.src} width={400} id="img" />
<button id={"btn"}>reload</button>
</div>
);
};
export default Test;
I want "img loaded" to be printed twice:
1- Once when the photo is loaded
2- Second, when the user clicks on the btn button.
But it is not printed in any of these two cases
Does anyone know the solution?
That is not how things are handled in React. Below is an example of how things are handled in React. I suggest you react the docs first.
const Test = () =>
{
const [ reload , setReload ] = useState('')
const imageLoad = () => {
console.log("image loaded")
// whatever you want to do here
}
const handleClick = () => {
console.log("button clicked")
// whatever you want to do here
}
return (
<div>
<img onLoad={imageLoad} src={picTest.src} width={400} id="img" />
<button onClick={handleClick} id={"btn"}>reload</button>
</div>
);
};
export default Test;
What to do if the "img" tag is not on the page?
it does not matter if the img is on the page or not for the above code
| common-pile/stackexchange_filtered |
Concatenate const char to char
I'm trying to generate passwords and copy them to a string. Here is what I want to do:
char generatePassword(int npasswords) {
int i, z;
char c, fullPw[300];
for(z = 0; z < npasswords; z++) {
for (i = 0; i < 3; ++i) {
c = rand() % 23 + 'a';
strcpy(fullPw, c); // ERROR HERE
printf("%c", c);
}
for (i = 0; i < 3; ++i) {
c = rand() % 23 + 'A';
printf("%c", c);
strcat(fullPw, c);
}
for (i = 0; i < 3; ++i) {
c = rand() % 9 + '1';
printf("%c", c);
strcat(fullPw, c);
}
for (i = 0; i < 4; ++i) {
c = rand() % 10 + '!';
printf("%c", c);
strcat(fullPw, c);
strcat(fullPw, "\n");
}
}
return fullPw;
}
I'm getting an error
Invalid conversion from 'char' to 'const char*'
Anyone can help how to fix it?
Possible duplicate of Append Char To String in C?
There are plenty of good solutions on the duplicate. Just go through the answers and you will find something that fits your needs.
@MaxVollmer: "plenty [...] solutions": Mine is missing ... ;)
@alk Wouldn't the correct process be to add your answer to the other question and still vote to close this as duplicate? Unless of course you disagree that this is a duplicate at all.
@MaxVollmer: Probably, still I wasn't aware of the dupe, when writing my answer here.
strcpy() and strcat() are functions which operate on "strings". A single char is not a string (in C).
strcpy() as well as strcat() take pointers to the 1st element of a 0-terminated char-array (which in fact is what C is using as what other languages call a "string").
The code you show does not pass this for the functions' 2nd argument, but passes as single char only.
So far to what the error-message tells you.
To fix this there are several approaches.
To stay with using functions operating on strings you need to somehow make the char to append a string. This can be done by using a compound literal like so:
strcpy(fullPw, (char[2]){c});
This (char)[2] defines an unnamed variable of type char[2], initialises its 1st element to c and implicitly initialises the 2nd element to '\0'. Which all in all is a 1-char size "string". Passing it to strcpy() makes it decay to the address of the 1st element, to a char*.
Same for strcat().
BTW, this strcat(fullPw, "\n"); is correctly used as "\n" is a string literal, which defines a 2-char array, with the 1st element being set to '\n' and the 2nd to '\0'. Following the above approach this can as well be written as strcat(fullPw, (char[2]){'\n'});
Also please note that the life time of such "unnamed" variables is the current scope. So if you want to make sure they were deallocated right after there usage, that is inside the functions called, then enclose those calls into there own scope each, like so:
{
strcpy(fullPw, (char[2]){c});
}
This idea is so ugly, it becomes beautiful. Thank you!
@anatolyg: "ugly"? Well, I love compound literals! So am I a pervert? ;)
Still giving error
[Error] expected primary-expression before 'char'
[Error] expected ')' before 'char'
[Error] invalid conversion from 'char' to 'const char*' [-fpermissive]
I had three typos. Just fixed them. Please excuse. It should be (char[2]){c}.
first, when compiling, always enable the warnings, then fix them.
For gcc, at a minimum use: -Wall -Wextra -Wconversion -pedantic -std=gnu11
Note: other compilers use different options to produce the same result.
Compiling with the warnings enabled results in:
gcc -ggdb -Wall -Wextra -Wconversion -pedantic -std=gnu11 -c "untitled.c" (in directory: /home/richard/Documents/forum)
untitled.c: In function ‘generatePassword’:
untitled.c:12:17: warning: conversion to ‘char’ from ‘int’ may alter its value [-Wconversion]
c = rand() % 23 + 'a';
^~~~
untitled.c:13:28: warning: passing argument 2 of ‘strcpy’ makes pointer from integer without a cast [-Wint-conversion]
strcpy(fullPw, c); // ERROR HERE
^
In file included from untitled.c:2:0:
/usr/include/string.h:121:14: note: expected ‘const char * restrict’ but argument is of type ‘char’
extern char *strcpy (char *__restrict __dest, const char *__restrict __src)
^~~~~~
untitled.c:17:17: warning: conversion to ‘char’ from ‘int’ may alter its value [-Wconversion]
c = rand() % 23 + 'A';
^~~~
untitled.c:19:28: warning: passing argument 2 of ‘strcat’ makes pointer from integer without a cast [-Wint-conversion]
strcat(fullPw, c);
^
In file included from untitled.c:2:0:
/usr/include/string.h:129:14: note: expected ‘const char * restrict’ but argument is of type ‘char’
extern char *strcat (char *__restrict __dest, const char *__restrict __src)
^~~~~~
untitled.c:22:17: warning: conversion to ‘char’ from ‘int’ may alter its value [-Wconversion]
c = rand() % 9 + '1';
^~~~
untitled.c:24:28: warning: passing argument 2 of ‘strcat’ makes pointer from integer without a cast [-Wint-conversion]
strcat(fullPw, c);
^
In file included from untitled.c:2:0:
/usr/include/string.h:129:14: note: expected ‘const char * restrict’ but argument is of type ‘char’
extern char *strcat (char *__restrict __dest, const char *__restrict __src)
^~~~~~
untitled.c:27:17: warning: conversion to ‘char’ from ‘int’ may alter its value [-Wconversion]
c = rand() % 10 + '!';
^~~~
untitled.c:29:28: warning: passing argument 2 of ‘strcat’ makes pointer from integer without a cast [-Wint-conversion]
strcat(fullPw, c);
^
In file included from untitled.c:2:0:
/usr/include/string.h:129:14: note: expected ‘const char * restrict’ but argument is of type ‘char’
extern char *strcat (char *__restrict __dest, const char *__restrict __src)
^~~~~~
untitled.c:33:12: warning: return makes integer from pointer without a cast [-Wint-conversion]
return fullPw;
^~~~~~
untitled.c:33:12: warning: function returns address of local variable [-Wreturn-local-addr]
Compilation finished successfully.
also, the posted code, even after the above problems are fixed will not compile because it is missing the statements:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
Note: just because the list of compiler warnings ends with:
Compilation finished successfully.
Does NOT mean the code is correct. It just means the compiler was able to incorporate some kind of workaround for each of the problems in the code. Usually the result is NOT what you intended
Also, the function: rand() should be preceded, usually at the top of the main() function via a call to: srand() similar to:
#include <time.h>
...
int main( void )
{
...
srand( (unsigned)time( void ) );
to initialize the random number sequence with a random value
strongly suggest reading/understanding the MAN pages for the functions that your program is calling
| common-pile/stackexchange_filtered |
If already using the contains selector, why use the starts-with selector
Looking at other SO questions, I've learnt that *= means "contains" and ^= means "starts with". I noticed [class^="icon-"], [class*=" icon-"] {/* CSS Here */} in some third-party CSS code. This strikes me as redundant; I am unclear why [class*=" icon-"] {/* CSS Here */} would not have been sufficient.
Does the redundant use of the ^= selector serve any purpose (e.g., readability, older browser support, etc.)?
Question reference:
What is caret symbol ^ used for in css when selecting elements?
What does an asterisk before an equal sign mean (*=) ? What about the exclamation mark?
Where is that construct used? Looks redundand and should probably be [class*="icon-"] (No space, just one selector)
Harry's answer is correct. A similar explanation is also given here: http://stackoverflow.com/questions/3338680/is-there-a-css-selector-by-class-prefix/8588532#8588532
@Harry: Learnt and Learned are both correct. Learned is more common in the U.S.
@Brian: Oh sorry I didn't know that. Thanks for the comment :) My main intent was to correct the typo in the title and add the tag.
It is not a redundant selector. It is possibly used to select the elements with icon- class even if it is second one in the class list like in the below snippet.
[class^="icon-"] will only select the elements whose value for class attribute starts with icon-.
[class*=" icon-"] will select all elements that contain a class with icon- in its list of classes. Note how they have specifically used a space before.
Quoting CodingWithSpike's comment
[class*="icon-"] without a space would also match undesired classes like not-icon-1 or lexicon-name which is likely why the leading space is included.
In essence the selector group is used to select all elements who have at least one class which begins with icon- as part of their class list.
[class^="icon-"] {
color: green;
}
[class*=" icon-"] {
color: red;
}
[class^="icon-"],
[class*=" icon-"] {
background: beige;
}
[class*="icon-"]{
border: 1px solid brown;
}
<div class="icon-1">Only Icon class</div>
<div class="a icon-1">Some other class before</div>
<div class="a not-icon-1">Some other class before</div>
[class*="icon-"] without a space would also match undesired classes like not-icon-1 or lexicon-name which is likely why the leading space is included.
@CodingWithSpike: Absolutely spot on. I didn't think of that :)
| common-pile/stackexchange_filtered |
Regular expression for integer with or without commas
I want to create a regular expression for all sorts of numbers i.e whole numbers (+ve and -ve) and decimal numbers (+ve and -ve) with or without commas.
For e.g the regular expression should cover following number formats.
111 1.11 1,111 1,111.01 1,111,111.01
+111 +1.11 +1,111 +1,111.01 +1,111,111.01
-111 -1.11 -1,111 -1,111.01 -1,111,111.01
I have created two regular expressions for handling my scenario.
"^(\\+|-)?[0-9]\\d*(\\.\\d+)?$" // handles whole numbers with decimals
"^(\\+|-)?[0-9]\\d*(\\,\\d+)*?$" // handles whole numbers with commas
Now, I want to merge these two regular expressions in order to address my requirements.
Can anyone help me?
Thanks in advance.
Possible duplicate of Decimal number regular expression, where digit after decimal is optional Specifically the answer here
@ClasG: That one does not help.
You may merge these 2 patterns of yours like
^[+-]?[0-9]+(?:,[0-9]+)*(?:[.][0-9]+)?$
See the regex demo
Details:
^ - start of a string
[+-]? - an optional + or -
[0-9]+ - 1 or more digits
(?:,[0-9]+)* - zero or more sequences of:
, - a comma
[0-9]+ - 1 or more digits
(?:[.][0-9]+)? - an optional sequence of:
[.] - a dot
[0-9]+ - 1+ digits
$ - end of string
A more restrictive regex to only allow 3-digits in groupings will look like
^[+-]?[0-9]{1,3}(?:,[0-9]{3})*(?:[.][0-9]+)?$
^^^^^ ^^^
And if you want to also match whole parts with no thousand separators:
^[+-]?(?:[0-9]{1,3}(?:,[0-9]{3})*|[0-9]+)(?:[.][0-9]+)?$
Here is my solution that allows only 3 digits between comma:
^[+-]?\d{1,3}(?:,\d{3}|\d+)*(?:\.\d+)?$
Explanation:
^ : start of string
[+-]? : optional + or -
\d{1,3} : 1 to 3 digits (before the first optional comma)
(?: : non capturing group
,\d{3} : a comma followed by 3 digit
| : OR
\d+ : 1 or more digits
)* : group present 0 or more times
(?: : non capturing group
\.\d+ : decimal dot followed by 1 or more digits
)? : optional
$ : end of string
Not working for more than one comma. Thanks for your idea with nice description.
What about this one:
^[+-]?\d+(,\d+)?(\.\d+)?$
You can see it working here.
Not working for more than one comma. But thanks for the idea.
@Suniel, you understand you didn't ask for that in the requirements or in the tests, right? Anyway just change (,\d+)? with (,\d+)* and it will work as expected.
Actually i added * but in a wrong place. My mistake. Many thanks to you.
| common-pile/stackexchange_filtered |
Converting internal blu ray drive to external drive
So I have a LG Slim Blu-Ray Combo Drive - SATA CT40N that I'm trying to make work with usb. I have a SATA to usb 3 converter that I plugged into my surface pro 3. Drive seems to get sufficient power as I can open it, put a disk in, and I can hear the disk spinning. Problem is windows won't detect it. Any Ideas?
It is, in fact, insufficient power. Classic symptoms.
However, you may want to disable "USB selective suspend setting" - known to be a pain in situations like this. If it doesn't work get an external USB case for DVD that comes with extra usb-to-pin cable delivering extra power to the drive.
Like this:
http://www.amazon.co.uk/StarTech-Slimline-Optical-Drive-Enclosure/dp/B003GSCS2G
thanks for the advice, I'll look into this. Just out of curiosity, do you know the power required for this kind of drive?
It should say so on the label on the drive. usually it's 1.2 - 1.5 A.
| common-pile/stackexchange_filtered |
i want to compress the file by the deflater but it seems doesn't work
i have to do some precompress before the file upload, and i want to use the deflaterOutputStream to compress the file but it doesn't work, if i have a file about 10MB when i compress it on the outputstream it still 10MB, and i don't know why, and i also want to know that how to exchange the outputstream to a file with this method that compare the OutputStream size with the fileSize to judge the whether it compress or not. Thanks a lot.
public class test {
public static int m_lvl;
public static void main(String[] args) {
try {
Path file = new File("a.jpg").toPath();
ByteArrayOutputStream bos = new ByteArrayOutputStream((int) new File("a.png").toPath().toFile().length());
OutputStream bo = new DeflaterOutputStream( bos, new Deflater( m_lvl, true), 512 );
Files.copy(file, bos);
System.out.println((int) new File("a.zip").toPath().toFile().length());
System.out.println(bos.size());
bo.close();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I'm pretty sure DeflaterOutputStream is just a zip format. You can't zip a zip file any further.
@JohnGiotta is there any way to compress the file ?
Zip files are already compressed with the same algorithm Deflater uses.
thank you .but i already compress the img or mp3 but it still doesn't work in such method
From the question it looks like you are trying to compress any file.
There are a few concepts which you should try to understand and have nothing to do with Java itself, but with data compression and reconstruction.
There are at two types (as my limited knowledge knows :)) of algorithms for data compression/decompression:
Lossless algorithms, for example: ZIP
Lossy algorithms, for example JPEG
Without entering into much detail, what you want to do is pick some Raw Data, compress it (so it occupies less space) and send it over to someone.
From the list of algorithms above, you may pick one or the other depending on your needs. For example, you will perhaps pick a Lossless algorithm if you require that no information is lost when the data is compress (imagine a .docx file or any other document such as the binary information of a computer program).
Otherwise, you might pick a lossy algorithm if, for example, you're displaying an image to another human user and don't mind some information being lost because the human eye can't see it all.
Now, the problem resides in the fact that what you're now trying to do is compress an already compressed file.
Imagine the following:
You have a text file filled with 64kb of the letter "a" or "a" repeated 64kb times (using 64kb of disk space).
When you want to compress it using a lossless algorithm you might get a compressed file with something "65536a" in a single line using perhaps 6bytes of disk space, meaning a repeated 64kb times in the original file.
Imagine that for some reason you don't need to know how many times a is repeated - lossy compression, and you use a lossy algorithm to do that and get a single file with a line which reads "a" using perhaps 1 byte of disk space, meaning a appears in the original file.
Now, if for some reason you want a lossless compressed file of the lossy compressed file, using my reasoning, you might get something like "1a" which now occupies 2 bytes of disk space, ence it is a bigger file.
That is basically what you're trying to do. Compress an already compressed file, and, depending on the algorithm in question, you might get a smaller file or not. Most probably, when compressing from lossy to lossless you might get a bigger file as in my example.
As I have tried to resume. Compression depends when whether or not you have redundant information to be expressed in shorter ways.
EDIT 2: Refactoring the response in order to clarify a little bit more.
EDIT 3: Found out a type on my listing of algorithms
but when i compress a *.mp3 or *.jpg it still doesn't work.I'm really confused!
@JasonLong you should use MP3 or JPG in your question as example. A zip files is bad example.
@JasonLong MP3s and JPGs are also compressed formats and also won't compress much further.
@JasonLong A zip file uses a lossless compression algorithm... In short words, when you try to compress an already compressed file (with the same algorithm), while you won't be able to compress it any further, you might even get a bigger file. That is why I linked you to the wikipedia page. You might also want to try and zip out a .jpg file and see what happens.
@JoãoRebelo when i compress a jpg , it get a bigger one really .And on other word , the deflater just compress the string ? Or it just incident that i meet a file that already compressed? thanks for your patient!
@JoãoRebelo i know what your purpose ! Whether a file can be compress depends on whether the file has extra data can compress or not. If there nothing more it file after compress without any variety! it that right?
@Jason Long I will update my answer, but short answer is that compression works on repeated information that can be described/written in shorter means. When you have that requisite you will effectively compress something. Otherwise, you will not! Tell me if I made that clear.
@JasonLong see my updated answer... I hope it helps. If not, please let me know so I can make it better :)
@JoãoRebelo It is really explict! Thanks for your help!
| common-pile/stackexchange_filtered |
typescript: why is a string implicitly having an 'any' type?
const directoryToBeZipped = `${LOCAL_FILE_PATH}/${attachment.Key}`;
const zipFilePath = `${LOCAL_FILE_PATH}/${zippedFileKey}`;
zipTime = await streamZipLocalDirectory(directoryToBeZipped, zipFilePath);
and
/**
* Compress a local directory with all contents into a local zip file;
* @param {string} directoryToBeZipped path of local directory that is to be compressed
* @param {string} zippedFilePath path of the resultant zip file
* @returns {Promise<number>} total execution time in seconds
*/
export const streamZipLocalDirectory = async (
directoryToBeZipped,
zippedFilePath
) => {
I get this error:
error TS7006: Parameter 'directoryToBeZipped' implicitly has an 'any' type.
error TS7006: Parameter 'zippedFilePath' implicitly has an 'any' type.
I understand what this means.
My question is, how is it possible to get this error?
I have this
const zipFilePath = `${A}/${B}`
Why is it not a string? why is it implicitly having an 'any' type?
The error is about the parameters, not your variables.
Does this answer your question? Set type for function parameters?, specifically this answer
| common-pile/stackexchange_filtered |
How to Attach Events to Table Checkboxes in Material Design Lite
When you create a MDL table, one of the options is to apply the class 'mdl-data-table--selectable'. When MDL renders the table an extra column is inserted to the left of your specified columns which contains checkboxes which allow you to select specific rows for actions. For my application, I need to be able to process some JavaScript when a person checks or unchecks a box. So far I have been unable to do this.
The problem is that you don't directly specify the checkbox controls, they are inserted when MDL upgrades the entire table. With other MDL components, for instance a button, I can put an onclick event on the button itself as I'm specifying it with an HTML button tag.
Attempts to put the onclick on the various container objects and spans created to render the checkboxes has been unsuccessful. The events I attach don't seem to fire. The closest I've come is attaching events to the TR and then iterating through the checkboxes to assess their state.
Here's the markup generated by MDL for a single checkbox cell:
<td>
<label class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect mdl-data-table__select mdl-js-ripple-effect--ignore-events is-upgraded" data-upgraded=",MaterialCheckbox">
<input type="checkbox" class="mdl-checkbox__input">
<span class="mdl-checkbox__focus-helper"></span>
<span class="mdl-checkbox__box-outline">
<span class="mdl-checkbox__tick-outline"></span>
</span>
<span class="mdl-checkbox__ripple-container mdl-js-ripple-effect mdl-ripple--center">
<span class="mdl-ripple"></span>
</span>
</label>
</td>
None of this markup was specified by me, thus I can't simply add an onclick attribute to a tag.
If there an event chain I can hook into? I want to do it the way the coders intended.
We currently don't have a way directly to figure this out. We are looking into adding events with V1.1 which can be subscribed to at Issue 1210. Remember, just subscribe to the issue using the button on the right hand column. We don't need a bunch of +1's and other unproductive comments flying around.
One way to hack it is to bind an event to the table itself listening to any "change" events. Then you can go up the chain from the event's target to get the table row and then grab the data you need from there.
It's not the nicest piece of code, but then again, MDL is not the nicest library out there. Actually, it's pretty ugly.
That aside, about my code now: the code will bind on a click event on document root that originated from an element with class mdl-checkbox.
The first problem: the event triggers twice. For that I used a piece of code from Underscore.js / David Walsh that will debounce the function call on click (if the function executes more than once in a 250ms interval, it will only be called once).
The second problem: the click events happens before the MDL updates the is-checked class of the select box, but we can asume the click changed the state of the checkbox since last time, so negating the hasClass on click is a pretty safe bet in determining the checked state in most cases.
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
$(document).on("click", ".mdl-checkbox", debounce(function (e) {
var isChecked = !$(this).hasClass("is-checked");
console.log(isChecked);
}, 250, true));
Hope it helps ;)
this should be marked as the correct answer. great code
I think 50ms is a good guess, when clicking faster than 250ms (that is doable) it will not register the latest status.
With 50 it seemed to work better.
You could delegate the change event from the containing form.
For example
var form = document.querySelector('form');
form.addEventListener('change', function(e) {
if (!e.target.tagName === 'input' ||
e.target.getAttribute('type') !== 'checkbox') {
return;
}
console.log("checked?" + e.target.checked);
});
| common-pile/stackexchange_filtered |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.