query_id stringlengths 4 64 | query_authorID stringlengths 6 40 | query_text stringlengths 66 72.1k | candidate_id stringlengths 5 64 | candidate_authorID stringlengths 6 40 | candidate_text stringlengths 9 101k |
|---|---|---|---|---|---|
6a92afd839ca2c0be42c26ad0fbf658b4672e5bda8878206af78e69f0258592b | ['35b575382ee94ee6acf985be37f9ee75'] | You can store all of your result into one list and iterate over to that list and write into the file using "with statement"
as shown below
temp='AWS_ACCESS_KEY="{}"\n'.format(accesskey)
a.append(temp)
temp='AWS_SECRET_KEY="{}"\n'.format(secretkey)
a.append(temp)
with open(file_name,'w') as stream:
for i in a:
stream.write(i)
| 9e36b012952bf6e8245ceb1a402ddf20781a0f3e02aa288105fbf748c526356f | ['35b575382ee94ee6acf985be37f9ee75'] | Why this code is not going to the second "if part" but when I comment out the remove statements then it is going to the second "if part"
i need to take out 'abc' and 'abcd' and 'defg' from d['a']
below is my code.
d={'a': ['abc','def','ghi','abcd','ghij'], 'b': [6, 7, 8]}
for i in d['a']:
if i.startswith("a"):
d['a'].remove(i)
#print('1st print '+i)
if i.startswith("d"):
d['a'].remove(i)
#print('2nd print '+i)
print(d)
|
c4ec81cdccf27a3fcb83962a58af4ebbdc142cb836f2abd5858720bcada08e57 | ['35c7daba46e04926853c66ba23ffcea6'] | I assume you mean the Expand Selection to Tag command in Sublime?
In VS Code the built-in command Emmet: Balance (outward) does basically the same thing. It selects content of a tag and then progressively includes the tag and works outward with each repetition.
You can create a custom keybinding for it as well in the preferences, for example
[
{
"key": "ctrl+shift+a",
"command": "editor.emmet.action.balanceOut"
}
]
| 9f2b3308b24b6d606404a3d9dd3593026a3241bfd1606debfa634287c3470177 | ['35c7daba46e04926853c66ba23ffcea6'] | I had exactly the same issue and playing with the box-sizing didn't help at all. The only solution that worked for me in the end was to use row-fluid.
The difference with row-fluid is that they are based on percentages, not fixed pixels. Then the child spans in a row always add up to 12, instead of adding up to their parent span width in the normal pixel width rows.
So for example yours would now be
<div class="container">
<div class="row-fluid">
<div class="span4">a</div>
<div class="span8">b</div>
</div>
<div class="row-fluid">
<div class="span12">c</div>
</div>
</div>
Now you don't get any issues with changing margins, paddings, or borders.
|
5378af4205825face1efef5a9ddf8f8e14cc7333176c434e1e829a92651f590e | ['35cc3160de41474d9f9d77e8ba8355e9'] | Thanks to a YouTube video(sorry i forgot the title of the video and the owner of the video), i have finally found a solution using a windows command-line tools called DISKPART. The steps are actually quite simple. These are the steps as explained in the video:
Run cmd.
Type DISKPART. Then press enter. This will run diskpart tool
Type LIST VOLUME. Then press enter. This will list all volumes available on your PC. Example of my screenshot here
Type SELECT VOLUME #VOLUME NUMBER#. Then press enter. As you can see from my screenshot, VOLUME 4 is my pendrive. So i typed in SELECT VOLUME 4
Lastly, type SHRINK DESIRED=#amount to decrease in MB#. then press enter. In my case, i need to shrink it from 64GB to 16GB (48GB different). so i typed in SHRINK DESIRED=48000
Done
| eebd601238d798c2d75fe74b0a7d9165a4f48cc5744e398750b4e176034b6d29 | ['35cc3160de41474d9f9d77e8ba8355e9'] | This is my data
How do i calculate the total of all 'w add' that have non-blank 'g minus' value. For example, in the image i would add 5.61 and 160.11 and store it in a single value. i have no idea how to do this with SUMIF
|
632687b44c43bcb4d86bb65a42c7cf03719d4e0f3cd88a1e5f959d74d7c9a7e4 | ['35ceaa3003634053a2464012723f8ff6'] | I am trying to detect USB insert regardless of the device it is. Eg: A phone, a battery pack, a biometric system etc.. which may or may not be recognized by Linux (no drivers or nothing to "Drive/run")
Linux will, detect the USB insert, and then proceed to register and act on Recognized devices. For instance it will list USB device details in /dev/bus/usb/ etc... I would like to trap/process everything that is inserted into USB. This means, no dependence on stuff like udevadm. Also means I will need to trap the insert event early on the curve.
How do I do this? | 2a26525cab1b1d85bab4b88cd1f0d1114cb68fe4901af9c232bcf930d05eb91f | ['35ceaa3003634053a2464012723f8ff6'] | I am trying to create a simple Excel sheet to track customer debt. I have created a sheet called Customers and in there I have a list of customers.
Then for each month of the year, I have another sheet, e.g. April, May ...etc. April looks like this right now:
Inside the Remaining Debt cell for each customer, let's pick the first cell, so D2, I would like a formula that looks at the customer name A2, and if the customer name matches what's in April!B2 then the amount should be added.
The formula needs to work for all entries in the April sheet. To be honest, I am not sure if that is the best way to go about this, but I know this is one way.
If the formula is correct, the Remaining Debt cell will have -£1100. In terms of math formula, I think this will work:
debt amount + (all customer A activity in April and all other months)
I'm not sure how that translates to Excel.
|
f2fcf8864ea30361025423bd69cb2c2fd2382ebc31c469154f4d4d4e3882c990 | ['35e9dfb11d664cb1ade19e67c8a9d264'] | Yes. I too mentioned it. <PERSON> says "Indeed beautiful it is. Worthy to be in the possession of a king and the beautiful <PERSON>". But he had a better reason to go after it. It was establishing the dharma. Even if it were not for <PERSON>, he would go after <PERSON>, when he encountered him in any other form. I would not equate <PERSON> with <PERSON>. I would consider <PERSON> a far greater personality, only equitable to personalities like <PERSON>, <PERSON> in deeds and charector, who had far lesser measure of weaknesses. | fea762aab02468b73f83a9a5c54bcda2e7841102c3e09fc56193b706876e4d06 | ['35e9dfb11d664cb1ade19e67c8a9d264'] | Thank you for your answer! It might be fun to compile my own kernel but I fear that it is really time consuming and the backdraw you mentioned (that you have to compile again and again) could really be annoying. As it seems like aes-ni is in the standard-kernel I would go with this one. Thank you! |
11bfc6a902d33173c221b7bbe7350d6c8936158d97abdc0d078076fe1481e91b | ['35f454acc3ec49b6a6793ff108b00e2f'] | <PERSON>, estou com um problema nesse trecho do código que não consigo resolver de nenhuma maneira. No caso, os dois primeiros input recebem valores que são somados e essa soma aparece no ultimo input com o id dinheiroDivergência, até ai tudo certo.
<td><b>Dinheiro</b></td>
<!-- <PERSON> -->
<td><input type="number" class="form-control" id="dve" min="1" value="0" onkeyup="Calcular()" onmouseout="Calcular()" onkeydown="Calcular()"/></td>
<!-- <PERSON> -->
<td><input type="number" class="form-control" id="ds" min="1" value="0" onkeyup="Calcular()" onmouseout="Calcular()" onkeydown="Calcular()"/></td>
<!-- <PERSON> - Divergência -->
<td><input type="text" value="0" class="form-control" id="dinheiroDivergencia" disabled></td>
O meu problema está na formatação dos input, eu gostaria que ao usuário digitar os números formatassem automaticamente, por exemplo, ao digitar 333,333,333, as virgulas fossem adicionadas automaticamente a cada três números. Eu consegui fazer isso utilizando o Cleaver.js e o Autonumeric.js, mas eles bugam tudo na hora da soma.
| 807763213fa0d0e06d6290fa0e9501d5a1f1fd6dc2dc9e97c3b42325d3ce5de9 | ['35f454acc3ec49b6a6793ff108b00e2f'] | So I'm not good with excel (computers in general) and can do some things but this one is out of my league.
This is the problem:
The cost of a used car is highly correlated with the following variables:
t= age of car 1 ≤ t ≤ 5 (years)
V= volume of engine 1000 ≤ V ≤ 2500 (cubic centimeters)
D= number of doors D= 2,3,4,5
A= accessories and style A= 1,2,3,4,5,6 (qualitative)
Using regression analysis, the following relationship between the cost and four independent variables was found:
purchase cost= (1+1/t)*V*(D/2+A)
Plot the purchase price of the car as a function of the four variables.
I know how to input the function into excel and only use one number from each variable:
Function:
=(1+(1/B2))*C2*((D2/2)+E2
Where: B2=1, C2=1000, D2=2, E2=1
Which: A1=4000 (for the purchase cost)
What I don't know is how to make the function use multiple number combinations within those variables (i.e. how to change one variable and not the others). I've looked up "youtube" videos and numerous websites to figure this out and none of them showed me what I needed to know (or at least understood). Also, if you could make it in simple terms, that would be great. Took calculus in high school 10 years ago.. apparently it didn't stick with me too well.
Any help would be greatly appreciated.
|
37971d0ab6313710b45810697f7c2932dc8fe26ba89e9358cf3ffa91570fef52 | ['360c8c20e495402ea1892fec81bfef56'] | I uploaded several files to folder "/sdcard/Books/LadySusan" on my android emulator. When I check if file in folder exist, expression
new File("/sdcard/Books/LadySusan/ladysusan_1_austen_64kb.mp3").exists()
returns true, file exists in folder, but when I use
new File("/sdcard/Books/LadySusan").listFiles()
it returns empty array, not null but File[0]. I have permissions to read files from SD card
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
and code to request them. Any idea what can be wrong?
| b3224450831023b97fd707fa23b9473f00533f997c3cd3028d4875babdb00229 | ['360c8c20e495402ea1892fec81bfef56'] | I am trying to implement deferred binding using generators. When I an testing deferred binding in dev mode it works as expected, when I am switching to production deferred binding is not working for some reason.
I have following classes
public class GeneratorTest implements EntryPoint {
//should be modified by generator
public static class GeneratorTestPrefs extends PreferencesImpl {
...
}
...
}
public class PreferencesImpl implements Preferences {
...
}
public interface Preferences {
public void load(String key, Storage storage);
public void store(String key, Storage storage);
}
And following definition in gwt module.xml
<generate-with class="com.xxx.xxx.gwt.generator.server.PreferencesGenerator">
<when-type-assignable class="com.xxx.xxx.gwt.generator.client.Preferences"/>
</generate-with>
I added log for classes created by
GeneratorTestPrefs prefs = GWT.create(GeneratorTestPrefs.class)
In case of dev mode, in log file, I see GWT is using class created by generator (GeneratorTestPrefs_PreferencesAdapter)
[java] INFO: deferred binding: com.xxx.xxx.gwt.generator.client.GeneratorTestPrefs_PreferencesAdapter
In case of production mode, in log file, I see GWT is not using class created by generator (GeneratorTest$GeneratorTestPrefs)
Wed Apr 01 15:48:06 GMT+300 2015 com.xxx.xxx.gwt.generator.client.GeneratorTest INFO: deferred binding: com.xxx.xxx.gwt.generator.client.GeneratorTest$GeneratorTestPrefs
I have no idea what is wrong. Am I missing something? Am I doing something wrong?
Thank you in advance!
|
15bae1d92a92153a02bcec3365be278424c96782d31bf26e045cf28cafec2732 | ['361032e018e34bf78c36864c9a944e4d'] | Since you need to unit test the given class, mock its dependencies only, like solicitationService not solicitationRepository.
When mocking the behaviour of the methods of mocked objects method you can use thenReturn or thenAnswer method . In thenAnswer you can get the arg values passed to method and assert the values
@Test
void doesSendToClient() {
when(solicitationRepository.getAllCnpjWithoutIntegration()).thenReturn(Arrays.asList(solicitationEntity));
when(clientRestService.findClient(any())).thenReturn(true);
when(solicitationService.create(any())).thenAnswer((invocation) -> {
SolicitationDto solicitationDto = invocation.getArgument(0, SolicitationDto.class);
//assert data in dto and return require response
return solicitationEntity;
}
);
assertDoesNotThrow(() -> integrationService.sendToClient());
}
| f565a98bdd1bf56f420a8df96d8ad444d9909c7065bc87350b83879e1f00c0e1 | ['361032e018e34bf78c36864c9a944e4d'] | I think the main problem here is that you are not able to parse it properly . Refer this Parse XML TO JAVA POJO in efficient way
and you can use http://pojo.sodhanalibrary.com/ to get the correct POJO classes required for your task.
After you get the POJO you can compare the extensions
|
c482a8b06857c19308d0d2f303b790921ebff5e6f7d6c326912aa3aa4f8db308 | ['36156320b001421dad77b375c1b14e11'] | I have encountered the same issue while trying to restore some dumps, in -Fc custom format. I'm not sure the problem will or can occur with any of the other dump formats.
However, I found that the "out of memory" error that pg_restore laconically drops on exit, is program-internal and not actually an OOM. It also occured without any DB interaction, when 'restoring' the dump into another dump using the pg_restore -f output.sql input.dump form.
Unlike in your instance, it didn't help to use an older pg_restore or an older database and I found that the (very big, 200-400+GB uncompressed) dumps were simply corrupt in some places, due to a badly aging disk I used for the storage.
Since I didn't use the -Fc internal compression, but bzip2 on the whole dump, I could recover pretty much everything but the few records inside broken bz2 segments (something not possible with xz or other container formats, thanks bzip).
Recovery requires some knowledge about pg_dump's custom dump format. In my instance the errors all occured in the data segment of the dump which was a COPY statement. Without internal compression this looks just like the plain-sql COPY format, including newline-delimiters after each row. Though the custom format additionally prepends each line by a 4-byte integer (little-endian here) containing the line-length in bytes and a 0x00, then ends it with another 0x00.
I expect the "out of memory" error occurs when the line-length indicated by the int doesn't fit the broken row's length, and pg_restore doesn't find the terminating NULL it expects but reads into the next row.
But due to the newline from COPY preceding the NULL on every line, I could actually open the dumps in a pager like less, and use head and tail to exclude the broken rows and stitch the rest back together for a restore.
Using the earlier mentioned pg_restore -f output.sql input.dump form, I dumped the backup until the error, then would tail this output to get the last good / first broken row, using that row's data as a regex to csplit the original dump, drop the last row from the first segment, the first row from the second segment, and stitch the rest together again.
That final command then looked something like:
cat <(head -n -1 dump.xx00) <(tail -n +2 dump.xx01) | pg_restore -C -d postgres.
I hope this might help someone else with broken dumps. I conclude that using -Fc custom format isn't in some cases the best thing to use (recovery using plain SQL format would have been much simpler), and that pg_restore could really use some better error reporting.
| b80d196b520c90153137f64907bfa0ca7013367344d1c3f6663fac5f89a0834c | ['36156320b001421dad77b375c1b14e11'] | Same thing happens on any website I go to from amazon to target even over powered my banks website, happens on 2 different phones a note 5 and a galaxy s7 edge. Started on the note first now it's doing it on the s7 edge. I can never recreate when it happens I just know it will... the notes stock att bloat ware running the newest android version, the s7 is the same but has never had any apps installed on it other then what my company put on it when they gave it to me can't even go to certain websites with the phone but this same code pops up at random. It always happens on the stock Samsung Web browser haven't seen it happen on chrome yet
data:text/html;base64,PCFET0NUWVBFIGh0bWw+PGh0bWw+PGhlYWQ+PG1ldGEgbmFtZT0idmlld3BvcnQiIGNvbnRlbnQ9IndpZHRoPWRldmljZS13aWR0aCwgdXNlci1zY2FsYWJsZT1mYWxzZSwgaW5pdGlhbC1zY2FsZT0xLjAsIG1heGltdW0tc2NhbGU9MS4wIj48L2hlYWQ+PGJvZHk+PGRpdiBpZD0iaWZybSIgc3R5bGU9InBhZGRpbmc6MDsgbWFyZ2luOjA7Ij48aWZyYW1lIHNyYz0iaHR0cHM6Ly9zMy5hbWF6b25hd3MuY29tL25vdGlmaWNhdGlvbmNlbnRlci91cy9pbnN0YW50d2lubmVyL2c5WFdOb01Kam5NSEN4bW54UHFqWWtORDd6US5odG1sIiBzdHlsZT0idG9wOjA7IGxlZnQ6MDsgd2lkdGg6MTAwJTsgaGVpZ2h0OjEwMCU7IHBvc2l0aW9uOiBhYnNvbHV0ZTsgYm9yZGVyOjAiIHNjcm9sbGluZz0ieWVzIiBhbGxvd0Z1bGxTY3JlZW49InllcyI+PC9pZnJhbWU+PC9kaXY+PC9ib2R5PjwvaHRtbD4=
|
1ba4eb7afba8d91d71d9d00cbc33b0ad45fbf18347e97b6334e657bc9b0a93c0 | ['3628a3a2325e4b5db7e1dfd9670052bd'] | Make sure all libraries are loaded:
openmpi (which you have done already)
gcc
You can try with parameters that will allow you to identify if the problem is your machine in terms of resources. if the machine does not support such number of processes see how many processes (MPI or not MPI) it supports by looking at the architecture topology. This will allow you to identify what is the correct amount of jobs/processes you can launch into the system.
Very quick run:
mpirun -np 1 ./lulesh2.0 -s 1 -p -i 1
Running problem size 1^3 per domain until completion
Num processors: 1
Num threads: 2
Total number of elements: 1
To run other sizes, use -s <integer>.
To run a fixed number of iterations, use -i <integer>.
To run a more or less balanced region set, use -b <integer>.
To change the relative costs of regions, use -c <integer>.
To print out progress, use -p
To write an output file for VisIt, use -v
See help (-h) for more options
cycle = 1, time = 1.000000e-02, dt=1.000000e-02
Run completed:
Problem size = 1
MPI tasks = 1
Iteration count = 1
Final Origin Energy = 4.333329e+02
Testing Plane 0 of Energy Array on rank 0:
MaxAbsDiff = 0.000000e+00
TotalAbsDiff = 0.000000e+00
MaxRelDiff = 0.000000e+00
Elapsed time = 0.00 (s)
Grind time (us/z/c) = 518 (per dom) ( 518 overall)
FOM = 1.9305019 (z/s)
| de0c2d2b37154ebb2d7ba9ab3d5908efc40e2d4eb8c7e7ba6286c59b02956725 | ['3628a3a2325e4b5db7e1dfd9670052bd'] | First, you have to create an __init __.py (two = "_", before and after, no spaces) file inside the directory where you have your actual package.
Second, you want to simply call your package from the python script where you are import to.
e.g.:
my_script.py #your script where you want to include/import your package
my_clustering_dir # directory containing files for package
my_clustering.py # file should be inside my_clustering_dir
"__init __".py # make sure this file is inside my_clustering_dir only (it can be empty)
Now, you can go to my_script.py. Then, you can add the following:
from my_clustering_dir import my_clustering #no extension (.py) needed
|
9ccdb3bc77afda3df0bee1624f1ead0d353d4f0844ab621face4b11f4a65725e | ['362afeea4a8a40f9a4c0961c068220fc'] | I'm trying to create a layout with 6 different ImageButtons and even after reading many layout tutorials and docs I'm getting nowhere.
I am trying to create this:
Always portrait, images' indvidual height & width must stay same scale, anchored to screen bottom with system navigation buttons showing:
----------------------------
| |
| |
| |
| |
| BACKGROUND |
| |
| |
| |
| |
| |
|--------------------------|
| SM | MD | LG |
|--------------------------|
| FirstNight |
|--------------------------|
| NightWith |NightWithout|
----------------------------
Below is the latest version of the code I have for ImageButtons Night, NightWithConstable and NightWithoutConstable. The result of the code is nothing like what is expected:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="@drawable/appsalempicsmaller"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:layout_alignParentBottom="true" >
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/nightWithConstableButton"
android:src="@drawable/buttonnightwithconstable"
android:clickable="true"
android:scaleType="fitStart"
android:background="#00ffffff"
android:adjustViewBounds="true"
android:layout_gravity="bottom"
android:onClick="nightButtonOnClick"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="false"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/nightWithoutConstableButton"
android:src="@drawable/buttonnightwithoutconstable"
android:scaleType="fitStart"
android:background="#74ffffff"
android:clickable="true"
android:adjustViewBounds="true"
android:layout_alignParentBottom="true"
android:layout_gravity="bottom"
android:layout_alignParentRight="true"
android:layout_toRightOf="@+id/nightWithConstableButton" />
</LinearLayout>
<ImageButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/firstNightButton"
android:src="@drawable/buttonfirstnight"
android:scaleType="fitStart"
android:background="#7cffffff"
android:clickable="true"
android:adjustViewBounds="true"
android:baselineAlignBottom="false"
android:onClick="firstNightButtonOnClick"
android:layout_above="@+id/nightWithConstableButton" />
</RelativeLayout>
I haven't even bothered with the layout for the SM, ND, and LG buttons because I'm obviously missing something fundamental already.
Input and sage advice for creating the desired layout are appreciated.
| 7e0208e01fcf94577fd9baa78f3aaeea46b8bb1339c9ecd10d603d93345ac908 | ['362afeea4a8a40f9a4c0961c068220fc'] | I'm sure this has been answered but apparently I don't know what to search for.
I am working on my first non-trivial Haskell program -- a simulation of a card game I enjoy. I have the program working but there is a situation that I am certain can be handled better.
If I have a series of binds which are Either String TypeChangesBasedOnTheFunction.
playerInput <- getLine
case playerInput of
{- CASE STUFF NOT IMPORTANT TO THIS QUESTION -}
_ -> do let handValue = inputHasAllValidChars playerInput >>= makeDeckFromString >>= deckSubset (getCurrentPlayersDeck gameState) >>= whatHandRepresents >>= handBeatsCurrentTopTrick
Very soon after this part of the code runs, I need the value for whatHandRepresents. I can just run the same chain of binds again but I am certain there must be a better way by storing the value when it is determined in the code above.
My question is, is it possible to store this value. If so, how?
|
b6e29c90b91802029485c1df8f33c7a1dbb4f40c7b24f730ceeff4d1e6e9ce16 | ['362d2f21fb0e49baa4b3594b3b749445'] | I have documents that are structured like below, where each array element contains "n" and "v" as the key and value for different types of data. (collection name is doc)
{
"_id" : 1,
"logs" : [
{ "n" : "facility", "v" : 26 },
{ "n" : "num", "v" : 6 },
{ "n" : "ip", "v" : "<IP_ADDRESS>" },
{ "n" : "protocol", "v" : "55902/udp" },
{ "n" : "port", "v" : "53" }
]
},
{
"_id" : 2,
"logs" : [
{ "n" : "facility", "v" : 26 },
{ "n" : "num", "v" : 6 },
{ "n" : "ip", "v" : "<IP_ADDRESS>" },
{ "n" : "protocol", "v" : "13438/tcp" },
{ "n" : "port", "v" : "13438" }
]
},
{
"_id" : 3,
"logs" : [
{ "n" : "facility", "v" : 26 },
{ "n" : "num", "v" : 6 },
{ "n" : "ip", "v" : "<IP_ADDRESS>" },
{ "n" : "protocol", "v" : "13434/tcp" },
{ "n" : "port", "v" : "53" }
]
},
{
"_id" : 4,
"logs" : [
{ "n" : "facility", "v" : 26 },
{ "n" : "num", "v" : 6 },
{ "n" : "ip", "v" : "<IP_ADDRESS>" },
{ "n" : "protocol", "v" : "61662/udp" },
{ "n" : "port", "v" : "53" }
]
},
{
"_id" : 5,
"logs" : [
{ "n" : "facility", "v" : 26 },
{ "n" : "num", "v" : 6 },
{ "n" : "ip", "v" : "<IP_ADDRESS>" },
{ "n" : "protocol", "v" : "13435/tcp" },
{ "n" : "port", "v" : "13435" }
]
},
{
"_id" : 6,
"logs" : [
{ "n" : "facility", "v" : 26 },
{ "n" : "num", "v" : 6 },
{ "n" : "ip", "v" : "<IP_ADDRESS>" },
{ "n" : "protocol", "v" : "61662/udp" },
{ "n" : "port", "v" : "53" }
]
}
...
and Indexing is like below.
>db.doc.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "db_test.doc"
},
{
"v" : 1,
"key" : {
"logs.n" : 1,
"logs.v" : 1
},
"name" : "logs.n_1_logs.v_1",
"ns" : "db_test.doc"
}
]
I want to query this condition.
"ip" is "<IP_ADDRESS>" and "port" is "53"
so, I query like this.
db.doc.find ( {"$and" : [ {"logs" : { "$elemMatch" : { "n" : "ip", "v" : "<IP_ADDRESS>" } } }, {"logs" : { "$elemMatch" : { "n" : "port", "v" : "53" } } } ]})
but, query is very slow. (over 30seconds)
("ip" == "<IP_ADDRESS><PHONE_NUMBER>" },
{ "n" : "protocol", "v" : "13438/tcp" },
{ "n" : "port", "v" : "13438" }
]
},
{
"_id" : 3,
"logs" : [
{ "n" : "facility", "v" : 26 },
{ "n" : "num", "v" : 6 },
{ "n" : "ip", "v" : "<PHONE_NUMBER>" },
{ "n" : "protocol", "v" : "13434/tcp" },
{ "n" : "port", "v" : "53" }
]
},
{
"_id" : 4,
"logs" : [
{ "n" : "facility", "v" : 26 },
{ "n" : "num", "v" : 6 },
{ "n" : "ip", "v" : "137.68.160.184" },
{ "n" : "protocol", "v" : "61662/udp" },
{ "n" : "port", "v" : "53" }
]
},
{
"_id" : 5,
"logs" : [
{ "n" : "facility", "v" : 26 },
{ "n" : "num", "v" : 6 },
{ "n" : "ip", "v" : "<PHONE_NUMBER>" },
{ "n" : "protocol", "v" : "13435/tcp" },
{ "n" : "port", "v" : "13435" }
]
},
{
"_id" : 6,
"logs" : [
{ "n" : "facility", "v" : 26 },
{ "n" : "num", "v" : 6 },
{ "n" : "ip", "v" : "<PHONE_NUMBER>" },
{ "n" : "protocol", "v" : "61662/udp" },
{ "n" : "port", "v" : "53" }
]
}
...
and Indexing is like below.
>db.doc.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "db_test.doc"
},
{
"v" : 1,
"key" : {
"logs.n" : 1,
"logs.v" : 1
},
"name" : "logs.n_1_logs.v_1",
"ns" : "db_test.doc"
}
]
I want to query this condition.
"ip" is "<PHONE_NUMBER>" and "port" is "53"
so, I query like this.
db.doc.find ( {"$and" : [ {"logs" : { "$elemMatch" : { "n" : "ip", "v" : "<PHONE_NUMBER>" } } }, {"logs" : { "$elemMatch" : { "n" : "port", "v" : "53" } } } ]})
but, query is very slow. (over 30seconds)
("ip" == "<PHONE_NUMBER>" document count is 10,000,000 . and result document count is nothing.)
I think, MongoDB cannot using index when second query using $and operator.
If A query, B query and C query using $and operator,
$and : [ {A}, {B}, {C} ] . B and C query cannot using index. Right?
| 36c4191d518fbb82ae29a5659a09bac7ed274df9e963c8bef9e07481df63074a | ['362d2f21fb0e49baa4b3594b3b749445'] | I have syslog that like below.
date=2015-10-08 time=16:03:26 devname=D1_FIG device_id=ID300B3908601UID log_id=0021000002 type=traffic subtype=allowed pri=notice vd=root src=157.56.15.15 src_port=3584 src_int="port4" dst=211.16.12.55 dst_port=80 dst_int="WLN_200" SN=2775431942 status=accept policyid=430 dst_country="United Kingdom, Great Britain" src_country="United Kingdom, Great Britain" dir_disp=org tran_disp=dnat tran_ip=<IP_ADDRESS> tran_port=80 service=HTTP proto=6 duration=120 sent=132 rcvd=92 sent_pkt=3 rcvd_pkt=2
I want to parse this log using pyparsing like this.
{"date", "2015-10-08"}
{"time", "16:03:26"}
{"devname", "D1_FIG"}
{"device_id", "ID300B3908601UID"}
....
{"src", "157.56.15.15"}
....
{"dst_country", "United Kingdom, Great Britain"}
....
source code is like this.
from pyparsing import *
origin_str = "date=2015-10-08 time=16:03:26 devname=D1_FIG device_id=ID300B3908601UID log_id=0021000002 type=traffic subtype=allowed pri=notice vd=root src=157.56.15.15 src_port=3584 src_int=\"port4\" dst=211.16.12.55 dst_port=80 dst_int=\"WLN_200\" SN=2775431942 status=accept policyid=430 dst_country=\"United Kingdom, Great Britain\" src_country=\"United Kingdom, Great Britain\" dir_disp=org tran_disp=dnat tran_ip=<IP_ADDRESS><IP_ADDRESS> src_port=3584 src_int="port4" dst=<IP_ADDRESS> dst_port=80 dst_int="WLN_200" SN=2775431942 status=accept policyid=430 dst_country="United Kingdom, Great Britain" src_country="United Kingdom, Great Britain" dir_disp=org tran_disp=dnat tran_ip=12.15.7.17 tran_port=80 service=HTTP proto=6 duration=120 sent=132 rcvd=92 sent_pkt=3 rcvd_pkt=2
I want to parse this log using pyparsing like this.
{"date", "2015-10-08"}
{"time", "16:03:26"}
{"devname", "D1_FIG"}
{"device_id", "ID300B3908601UID"}
....
{"src", "<IP_ADDRESS>"}
....
{"dst_country", "United Kingdom, Great Britain"}
....
source code is like this.
from pyparsing import *
origin_str = "date=2015-10-08 time=16:03:26 devname=D1_FIG device_id=ID300B3908601UID log_id=0021000002 type=traffic subtype=allowed pri=notice vd=root src=<IP_ADDRESS> src_port=3584 src_int=\"port4\" dst=<IP_ADDRESS><PHONE_NUMBER> status=accept policyid=430 dst_country="United Kingdom, Great Britain" src_country="United Kingdom, Great Britain" dir_disp=org tran_disp=dnat tran_ip=12.15.7.17 tran_port=80 service=HTTP proto=6 duration=120 sent=132 rcvd=92 sent_pkt=3 rcvd_pkt=2
I want to parse this log using pyparsing like this.
{"date", "2015-10-08"}
{"time", "16:03:26"}
{"devname", "D1_FIG"}
{"device_id", "ID300B3908601UID"}
....
{"src", "157.56.15.15"}
....
{"dst_country", "United Kingdom, Great Britain"}
....
source code is like this.
from pyparsing import *
origin_str = "date=2015-10-08 time=16:03:26 devname=D1_FIG device_id=ID300B3908601UID log_id=0021000002 type=traffic subtype=allowed pri=notice vd=root src=157.56.15.15 src_port=3584 src_int=\"port4\" dst=211.16.12.55 dst_port=80 dst_int=\"WLN_200\" SN=<PHONE_NUMBER> status=accept policyid=430 dst_country=\"United Kingdom, Great Britain\" src_country=\"United Kingdom, Great Britain\" dir_disp=org tran_disp=dnat tran_ip=12.15.7.17 tran_port=80 service=HTTP proto=6 duration=120 sent=132 rcvd=92 sent_pkt=3 rcvd_pkt=2"
date_s = Word(nums, nums+'-')
time_s = Word(nums, nums+':')
identifier = Word(alphas, alphanums+'_') | date_s | time_s
equal = Literal("=").suppress()
KeyNValue = identifier.setResultsName("lhs") + equal + identifier.setResultsName("rhs")
for srvrtokens,startloc,endloc in KeyNValue.scanString(origin_str):
print srvrtokens
This is what I have so far:
['date', '2015-10-08']
['time', '16']
['devname', 'FW_IDC1']
['device_id', 'FG300B3908601477']
['log_id', '0021000002']
['type', 'traffic']
['subtype', 'allowed']
['pri', 'notice']
['vd', 'root']
['src', '147']
['src_port', '58979']
['dst', '210']
['dst_port', '80']
['SN', '<PHONE_NUMBER>']
['status', 'accept']
['policyid', '430']
['dir_disp', 'org']
['tran_disp', 'dnat']
['tran_ip', '172']
['tran_port', '80']
['service', 'HTTP']
['proto', '6']
['duration', '120']
['sent', '132']
['rcvd', '92']
['sent_pkt', '3']
['rcvd_pkt', '2']
But I don't know how to parse "time" and "dst_country" string.
|
3f11dcc2dc76ef502eb1cdb6700764b3d25a55d251888828d923a2de540c3f9d | ['363c06fcd55d4f9a84744c411ef351e1'] | It started appearing after I played a videogame using Dosbox.
I didn't update any driver but Windows did indeed do a number of updates recently. None seemed to have caused problems.
It's a laptop so the only cable is the one of the second monitor. I did try to remove the cable and re-insert it, to no avail. I also tried to change resolution to no avail.
It's just the background that is blurred. Everything else is perfectly fine, so it's definitely not an issue with the monitor (it also happens on both the built-in display and the external one). | 0bb342057b1672223aab02e7436ec0d2af2b6775d7d44836c527e09120784364 | ['363c06fcd55d4f9a84744c411ef351e1'] | The issue apparently was related to an application called Stardock Fences.
I used it for a very long time as I find it useful. Sometimes it did have minor glitches, but nothing major.
This time something must have happened that triggered this strange blur effect.
The solution was to uninstall the application. It is unclear at the moment whether by re-installing it the problem would re-appear or not. Eventually I'll try, but for now I'm happy ennough that the problem is solved.
|
f70c73a52cfbd685f0ceb19da778b4244aa1504d48309c1014400ab966dc0b59 | ['36552a70f4a94c34a79fbe713596b8d5'] | I have some EC2 instances running an express application listening on port 3000. I then have an elastic load balancer forwarding request from it's port 80 to these EC2 instances. Every time I bring down one of the express servers running on an EC2 instance and try to bring it back up I get the address in use error for port 3000. I can not find any actual process using this port (lsof, netstat, etc) is ELB still connected on port 3000 ? If so what is the workflow to restart applications behind ELB ?
| d1ecb2064763dacd57fee2e8bec952239551ec2422d331c0bb57531af1677e2d | ['36552a70f4a94c34a79fbe713596b8d5'] | I am trying to console.log myobject but I keep getting undefined. I tried using $scope.watch and $attrs.$observe. Can someone tell me what I'm doing wrong.
here is the html
<my-component some-data="$ctrl.data"></my-component>
here is the component and controller
module.component('myComponent', {
bindings: {
needThisStuff: '<someData'
},
controller: Ctrl,
templateUrl:
requirejs.toUrl('path/to/templ.html')
});
function Ctrl(){
var self = this;
console.log(self.needThisStuff);
}
how can I access needThisStuff using $watch or $observe or anything else, I am using angular 1.5
|
2e410db7d7d7894519b5391058c215b93fc6a72fd9fb6c30b9ef7967538fa846 | ['365a5642080c45d398e4028b87b2b93e'] | import UIKit
protocol SSGastureDelegate:NSObjectProtocol {
func callBack()
}
class SSUnderLineLabel: UILabel {
var tapGesture: UITapGestureRecognizer?
//Make weak refernece for SSGastureDelegate
weak var delegate:SSGastureDelegate?
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.initialization()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.initialization()
}
func initialization(){
let newsString: NSMutableAttributedString = NSMutableAttributedString(string: self.text!)
let textRange = NSString(string: self.text!)
let substringRange = textRange.range(of: "Terms and Conditions") // You can add here for own specific under line substring
newsString.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.styleSingle.rawValue, range: substringRange)
// self.attributedText = newsString.copy() as? NSAttributedString
self.attributedText = newsString
self.tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapResponse))
self.isUserInteractionEnabled = true
self.addGestureRecognizer(tapGesture!)
}
func tapResponse(recognizer: UITapGestureRecognizer) {
let text = (self.text)!
let termsRange = (text as NSString).range(of: "Terms and Conditions")
if (tapGesture?.didTapAttributedTextInLabel(label: self, inRange: termsRange))! {
print("Tapped terms conditions")
self.delegate?.callBack()
}
else {
print("Tapped none ")
}
}
}
//MARK:UITapGestureRecognizer Extension
//MARK:
extension UITapGestureRecognizer {
func didTapAttributedTextInLabel(label: UILabel, inRange targetRange: NSRange) -> Bool {
// Create instances of NSLayoutManager, NSTextContainer and NSTextStorage
let layoutManager = NSLayoutManager()
let textContainer = NSTextContainer(size: CGSize.zero)
let textStorage = NSTextStorage(attributedString: label.attributedText!)
// Configure layoutManager and textStorage
layoutManager.addTextContainer(textContainer)
textStorage.addLayoutManager(layoutManager)
// Configure textContainer
textContainer.lineFragmentPadding = 0.0
textContainer.lineBreakMode = label.lineBreakMode
textContainer.maximumNumberOfLines = label.numberOfLines
let labelSize = label.bounds.size
textContainer.size = labelSize
// Find the tapped character location and compare it to the specified range
let locationOfTouchInLabel = self.location(in: label)
let textBoundingBox = layoutManager.usedRect(for: textContainer)
let textContainerOffset = CGPoint(x: (labelSize.width - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x,y:(labelSize.height - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y)
let locationOfTouchInTextContainer = CGPoint(x:locationOfTouchInLabel.x - textContainerOffset.x,
y:locationOfTouchInLabel.y - textContainerOffset.y);
let indexOfCharacter = layoutManager.characterIndex(for: locationOfTouchInTextContainer, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
return NSLocationInRange(indexOfCharacter, targetRange)
}
}*`enter code here`
**How to use it:**
Assign this class for your label and follow these steps:
Demo for use class:
ViewController.swift
//===============
class ViewController: UIViewController,SSGastureDelegate {
@IBOutlet var underlineLbl: SSUnderLineLabel!
override func viewDidLoad() {
super.viewDidLoad()
self.underlineLbl.delegate = self
}
//Implement Delegate Method
func callBack()
{
//Open a specific vc for underline tap are`enter code here`a.
let termsconditionsVC = storyboard?.instantiateViewController(withIdentifier: "TermsConditionsVC") as! TermsConditionsVC
self.present(termsconditions, animated: true, completion: nil)
}
}*
| 859052c2a5c5b84c2f50fdea165aab19a189f23607846c7aca4949a12a65d6c9 | ['365a5642080c45d398e4028b87b2b93e'] |
func setPlaceholder(){
var placeholderLabel = UILabel()
placeholderLabel.text = "Describe your need..."
placeholderLabel.font = UIFont.init(name: "Lato-Regular", size: 15.0) ?? UIFont.boldSystemFont(ofSize: 14.0)
placeholderLabel.sizeToFit()
descriptionTextView.addSubview(placeholderLabel)
placeholderLabel.frame.origin = CGPoint(x: 5, y: (descriptionTextView.font?.pointSize)! / 2)
placeholderLabel.textColor = UIColor.lightGray
placeholderLabel.isHidden = !descriptionTextView.text.isEmpty
}
//Delegate Method.
func textViewDidChange(_ textView: UITextView) {
placeholderLabel.isHidden = !textView.text.isEmpty
}
|
99ebfc4c05d029009f91281a7bd3cd9970c07090f76350cf9c7bb41135abb93c | ['366356e0250940af86ab518e5c314747'] | I have a spring MVC application with servlet-context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd
">
<annotation-driven validator="validator"/>
<resources mapping="/resources/**" location="/resources/" />
<default-servlet-handler/>
<!-- Apache Tails configuration -->
<beans:bean class="org.springframework.web.servlet.view.UrlBasedViewResolver" id="tilesViewResolver">
<beans:property name="viewClass" value="org.springframework.web.servlet.view.tiles3.TilesView"/>
</beans:bean>
<beans:bean class="org.springframework.web.servlet.view.tiles3.TilesConfigurer" id="tilesConfigurer">
<beans:property name="definitions">
<beans:list>
<beans:value>/WEB-INF/layouts/layouts.xml</beans:value>
<beans:value>/WEB-INF/views/**/views.xml</beans:value>
</beans:list>
</beans:property>
</beans:bean>
<interceptors>
<beans:bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" p:paramName="lang"/>
</interceptors>
<beans:bean class="org.springframework.context.support.ReloadableResourceBundleMessageSource"
id="messageSource"
p:basenames="WEB-INF/i18n/application, WEB-INF/i18n/validation_messages"
/>
<beans:bean class="org.springframework.web.servlet.i18n.CookieLocaleResolver"
id="localeResolver"
p:cookieName="locale"/>
<beans:bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<beans:property name="validationMessageSource" ref="messageSource"/>
</beans:bean>
<context:component-scan base-package="com.myapp.mvc" />
I have only two .properties files in WEB-INF/i18n/ folder:
WEB-INF/i18n/application.properties
WEB-INF/i18n/validation_messages.properties
messageSource works fine in JSP pages:
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<fmt:message key="validation.User.NULL_FIRST_NAME"/>
and in Hibernate validator:
@Entity
@Table(name="users")
public class User {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Long id;
@Column(name="first_name")
@NotNull(message = "{validation.User.NULL_FIRST_NAME}")
@Size(max = 255, message = "{validation.User.TOO_LONG_FIRST_NAME}")
private String firstName;
//... getters and setters
}
But it doesn't work in jUnit test-class:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {JPATestConfig.class})
public class AbstractJpaTest {
@Inject
private MessageSource messageSource;
public void fillValidationMessages() {
Locale locale = null;
User_NULL_FIRST_NAME = messageSource.getMessage("validation.User.NULL_FIRST_NAME", null, locale);
}
}
I've try to use MessageSourceAware and different locales but every time I have the same error:
org.springframework.context.NoSuchMessageException: No message found under code 'validation.User.NULL_FIRST_NAME' for locale 'null'.
at org.springframework.context.support.DelegatingMessageSource.getMessage(DelegatingMessageSource.java:65)
at org.springframework.context.support.AbstractApplicationContext.getMessage(AbstractApplicationContext.java:1234)
at com.dominform.mvc.AbstractJpaTest.fillValidationMessages(AbstractJpaTest.java:198)
at com.dominform.mvc.jpa_tests.UserUtilTest.init(UserUtilTest.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Any ideas?
| 8e83b0378cdcc624ac76538f7d2e2e28dcf11af1d1cb622d72af62899f246f62 | ['366356e0250940af86ab518e5c314747'] | I have an object
object Foo {
fun doSomething(param: String) {
throw Exception()
}
}
I want it to become a stub (relaxed mock in mockk terminology) in my test.
Other words, I want this test to pass without exception:
@Test
fun shouldAskFooWithCorrectParams() {
mockkObject(Foo) // How to change it to make Foo a stub
Foo.doSomething("hey!")
verify(exactly = 1) { Foo.doSomething("hey!") }
}
|
2a69dd5f7257e41493cbe89b6bd42a1afd23a8eca1e29af9ace46fb488433258 | ['366b3a2ca3db492b8f8c5e19b80edeb8'] | Did the NLP library install correctly?
Check in the logs to verify there are no errors. Most of the times this issue comes when there the stanford nltk library does not install correctly.
A quick way to check is by running the GUI to try out the parser if that runs successfully then the library installed correctly otherwise if that throws errors then you know your installation was poor.
The Stanford website also mentions this take a look:
If you're new to parsing, you can start by running the GUI to try out the parser. Scripts are included for linux (lexparser-gui.sh) and Windows (lexparser-gui.bat).
Take a look at the Javadoc lexparser package documentation and LexicalizedParser class documentation. (Point your web browser at the index.html file in the included javadoc directory and navigate to those items.)
Look at the parser FAQ for answers to common questions.
If none of that helps, please see our email guidelines for instructions on how to reach us for further assistance.
| 330b2ba8e59bef9169daafe7c2e94f048e168ac1cd0e4ed2a883d2323527e6d9 | ['366b3a2ca3db492b8f8c5e19b80edeb8'] | This is the way to catch File Not Found Exception in Visual Basic 2015:
Try
path = "c:\winpython\codes\output.TXT"
Dim sr2 As System.IO.StreamReader = New System.IO.StreamReader(path)
Catch ex As FileNotFoundException
MessageBox.Show(ex.Message)
Catch ex As Exception
MsgBox(ex.Message)
End Try
Please remember apart from the File Not Found Exception you could also get any other exception while opening a file. So the last exception Catch is for that.
You can replace ex.Message with your own String message that you want to display to users like so:
Catch ex As Exception
MsgBox("There is an error while opening the File")
Hope this helps.
|
e2ae7bceee5dc8745576826e1752fd11fbedd380c686d25c92b6d3732a9ba6c0 | ['3670d3be412a41bba981976db337d370'] | You forgot to check your answers for extraneous roots. If you do that you will find that your second answer is extraneous: the two sides of the original equation are negatives of each other. There are other roots of the original equation but they are outside the domain $0\le x\le 180°$. | e851dba5b3ca0e3175a91ecb95e82b209612b0899040fe9bfb8bf2d88db92908 | ['3670d3be412a41bba981976db337d370'] | If the density function method is required, you should state that in your main question. The bounds on $x$ are clearly $0\le x\le \frac 12$, but the "slice" of $yz$ for a given $x$ is a ring or "washer". Putting that into a double integral would require multiple pieces: above and below the inner hole, and to the left and right of it. Is that really what you want? Cylindrical coordinates would work well, with $r$ having the bounds $y_1$ and $y_2$ as in my answer, and $0\le\theta<2\pi$. Can you use cylindrical coordinates? |
e1d17512e99d6a103883e448383c8d366ed05384b53f4d0368f9ef0f4e90d795 | ['3671e02bea6c42ba8ad772130ac90473'] | Suppose I have variable length string as below:
Write <Address> <Data0> <Data1> <Data2>
Read <Address>
Write <Address> <Data0>
Write <Address> <Data0> <Data1> <Data2> <Data3>
How do I read in SystemVerilog or Verilog using file operations. I know to read when there is fixed length of text
integer file = $fopen(file_name,"r");
code = $fgets(line, file);
code = $sscanf(line, "%s %h %h %h", txn_type, Address, Data[i]);
| 6330286a357cac2981780bcc7cc3b40621daaa36ee2973a0b03e098da143c44f | ['3671e02bea6c42ba8ad772130ac90473'] | initial begin
#100
a=0;
b=0;
#10
a=1;
b=1;
#100
forever
#10 a = ~a;
end
initial begin
#500
$finish;
end
always @(a) begin
$display("%f edge on a %d", $realtime, a);
b=1;
b=0;
end
always @(b) begin
$display("%f edge on b %d", $realtime, b);
a=0;
a=1;
end
|
207bba3198a41f227a8adcb518ce1e831ae4d89e3ccdec822d72476531201f05 | ['367d499602514bdda472cba102d47b91'] | No need to have the value of the zero.
If x* is a zero of g(x) then
g(x*)=0, that means xlog(x+1)+x*-1=0.
Bring terms on the right side of =. You then have x* = 1 - xlog(x+1) = G2(x*).
So x* is a fixed point for G2(x).
The same way, if x* is a zero of g(x),
xlog(x+1)+x*-1=0, so xlog(x+1)+x*=1.
From the definition of g(x), we see that 0 cannot be its zero. We can then divide both sides of the equation by x* as x*≠0.
We have log(x*+1)+1=1/x*.
Reversing both sides of the equations gives you 1/(log(x*+1)+1) = x*, meaning G1(x*)=x*.
Then x* is a fixed point for G1(x).
Good luck.
| cd3367ff13d34c6fad47f572ab44e64b921635283932a5304b2e1f426105233f | ['367d499602514bdda472cba102d47b91'] | So, how can i obtain a normal JPEG image from a PDF ? I don't need for particoular configurations. I need something like a simple (for example) `split mypdf.pdf --> myimg.jpeg` . I'm not interested about how the tool does the conversion. I'm interested only about the result. |
38290ba7c18d1e53d9e61de52f690b60944b68cf2b690b31d7bab3ca7d8c6148 | ['3682348528634ddfae9e75a580ad2c2d'] | I personally use the animate.css library
Simply link the css file to your page:
<link href= "https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" rel="stylesheet">
You can also download the file and serve it locally.
Then just add the classes "animated slideInLeft" to your element.
$('#content').show().addClass('animated slideInLeft');
You can check the documentation here: https://animate.style/
| b86e0c3df261848ba36d77617723e93e292a02a8b11e0fee94883678144e04f5 | ['3682348528634ddfae9e75a580ad2c2d'] | Finally got it working.
I was using https://heroku-default-domain.com/.well-know/asset-links.json (which was working fine)
and https://my-custom-domain/.well-know/asset-links.json (which was not working)
the folder became accessible when I added www as in https://www.my-custom-domain/.well-know/asset-links.json
Other URLs are served well without the www.
|
a13a4ee2e6b12b37769c27c5c06156d1aa2109e29c3a744633e5332e8420b931 | ['368af755880949efa5a31d8a9cc3d0a6'] | Ok.. Your Web Service Return JSON Data in Responce, so that you have Parse the Json Data in your Code, i Have Give Some Basic Logic How to Parse JSon Web Service,
//================================================
private ArrayList<HashMap<String, String>> MyArray = new ArrayList<HashMap<String,String>>();
private HashMap<String, String> MyTempHas;
private JSONObject JSONObj;
Private SoapObject responce = (SoapObject) envelope.getResponse();
/* gets our result in JSON String */
private String ResultObject = responce.getProperty(0).toString();
if (ResultObject.startsWith("{")) { // if JSON string is an object
JSONObj = new JSONObject(ResultObject);
Iterator<String> itr = JSONObj.keys();
MyTempHas = new HashMap<String, String>();
while (itr.hasNext()) {
String Key = (String) itr.next();
String Value = JSONObj.getString(Key);
MyTempHas.put(Key, Value);
// System.out.println(bundleResult.getString(Key));
}
MyArray.add(MyTempHas);
} else if (ResultObject.startsWith("[")) { // if JSON string is an array
JSONArr = new JSONArray(ResultObject);
System.out.println("length" + JSONArr.length());
for (int i = 0; i < JSONArr.length(); i++) {
JSONObj = (JSONObject) JSONArr.get(i);
Iterator<String> itr = JSONObj.keys();
MyTempHas = new HashMap<String, String>();
while (itr.hasNext()) {
String Key = (String) itr.next();
String Value = JSONObj.getString(Key);
MyTempHas.put(Key, Value);
// System.out.println(bundleResult.getString(Key));
}
MyArray.add(MyTempHas);
}
}
//========================================
In This Example if you have return only One Object then it Start with "{" and save all the atribute in Hasmap and then add into ArrayList.
If your Responce send Multiple Object then it Start with "[" array , then parse one by one object as per above logic.
then simle you get all the value from Hasmap which is store in ArrayList.
If you not able to get Value from the ArrayList then Tell me I will Help you.
I Hope this will Help you.
| c5974e0413ff3715635fb1439cc325921bb2c1f79ba8f8679d39fef5845e86f3 | ['368af755880949efa5a31d8a9cc3d0a6'] | ParseQuery query = new ParseQuery("login");
query.whereEqualTo("username", user);
query.whereEqualTo("password", pass);
query.findInBackground(new FindCallback() {
@Override
public void done(List<ParseObject> obj, ParseException e) {
if (e == null) {
if(obj.size() == 1){
prog.dismiss();
Toast.makeText(con, "Login Success..", Toast.LENGTH_SHORT).show();
Intent in = new Intent(con, home.class);
con.startActivity(in);
con.finish();
}else {
Toast.makeText(con, "Password Wrong....", Toast.LENGTH_SHORT).show();
}
} else {
System.out.println("Fail..................... ");
Toast.makeText(con, "Login Fail..", Toast.LENGTH_SHORT).show();
System.exit(0);
}
}
});
|
bdd600d68eacf667b4f48b41b00ccf9916cfab0a53c1156a92fb3f7b64413014 | ['368f3825da8345469531ff96494c4f72'] | Three things to remember while accessing an element in an index array:
1. Normal expression - hardcoded index
arr=(one two three)
element_0="${arr[0]}"
2. Normal expression - index stored in a variable
arr=(it is cool to write readable code)
for ((i=0; i < ${#arr[@]}; i++)); do
current_element=${arr[i]} # note, no '$' necessary before i
done
3. Arithmetic expression involving array elements
arr=(100 150 350)
((sum_of_first_two = arr[0] + arr[1])) # no need for '{ }'
| a30fa04d04aa1fae4120f9c2a954a530f7ac5d8c3b3f8e344b89aa375419287d | ['368f3825da8345469531ff96494c4f72'] | Timing function based on SECONDS, limited to second-level granularity only, doesn't use any external commands:
time_it() {
local start=$SECONDS ts ec
printf -v ts '%(%Y-%m-%d_%H:%M:%S)T' -1
printf '%s\n' "$ts Starting $*"
"$@"; ec=$?
printf -v ts '%(%Y-%m-%d_%H:%M:%S)T' -1
printf '%s\n' "$ts Finished $*; elapsed = $((SECONDS-start)) seconds"
# make sure to return the exit code of the command so that the caller can use it
return "$ec"
}
For example:
time_it sleep 5
gives
2019-03-30_17:24:37 Starting sleep 5 2019-03-30_17:24:42 Finished
sleep 5; elapsed = 5 seconds
|
18a10a8cf04cbc528e98e87922c3ad24f68bf44b84192dde2df0e414b5f554f8 | ['36ac0cea150f4b7eabddadd4dc32db1a'] | I would say that change the commented information on top in database.yml to
#
# Install the MYSQL driver
# gem install mysql2
#
# Ensure the MySQL gem is defined in your Gemfile
# gem 'mysql2'
#
# And be sure to use new-style password hashing:
# http://dev.mysql.com/doc/refman/5.0/en/old-client.html
second: add " gem 'mysql2' " (what ever is inside the double quotation marks) to gemfile .
save everything, do bundle install. Hope that helps.
or it just could be a typo.
| 40e4967344388e7e36c217368bef515e08c65d30eaf5fe270a87b94d2fea35e4 | ['36ac0cea150f4b7eabddadd4dc32db1a'] | Go to \RailsInstaller\Git\cmd then open the git (command prompt file) with a text editor or word pad (by right clicking the file and selecting edit) now there would be two lines which would look like
@chcp %cp_ansi% > <PERSON> < nul
and
@chcp %cp_oem% > nul < nul
delete both of them, and save the file . This should resolve the problem
|
f617ff3bf8fbd2b8f78226d0d3a33a80fc676b49f7656c81a35adfd7090762b1 | ['36afceb307fb4c61aa986fc67eb59475'] | We have a Rails app deployed in Heroku using Rails Geocoding with a Redis cache. I assume entries are cached to fill some percent of the memory and I recall it running around 90%, but the Redis usage has grown recently.
We have a 1 GB plan and stats show 1,023.65 MB memory used and we are getting an error in Redis now:
OOM command not allowed when used memory > 'maxmemory
We are using Redis for Sidekiq so it's possible that has been using more space, but how do I fix this issue? Can I limit the size of the Geocoder cache?
| de98196a4c997e0ca8822e1a9d364c2b2d853de93f83f0bedb18db8c0316f99c | ['36afceb307fb4c61aa986fc67eb59475'] | In my local rails console passing 9/31/2011 returns 10/1/2011
[1] pry(main)> Date.strptime("09/31/2011", '%m/%d/%Y')
=> Sat, 01 Oct 2011
In heroku console it throws an ArgumentError:
irb(main):002:0> Date.strptime("09/31/2011", '%m/%d/%Y')
ArgumentError: invalid date
from (irb):2:in `strptime'
|
7dd89979b1a8c2e6f3cead6c1c54d8a7e474e1f8638e296a0581155654c4847c | ['36b7d5fd52ef47f1b254e2b22031ba62'] | The problem with your data is the unequal time step.
import pandas as pd
# Create your dataset
index = pd.date_range('2000/01/01 00:00:00', periods=4, freq='min').to_list()
index[1] = pd.Timestamp('2000/01/01 00:00:10')
values = [0., 100., 100., 200.]
data = pd.Series(values, index)
data
[Out]:
2000-01-01 00:00:00 0.0
2000-01-01 00:00:10 100.0
2000-01-01 00:02:00 100.0
2000-01-01 00:03:00 200.0
When you call .resample() this is what's happening:
data.asfreq('T')
[Out]:
2000-01-01 00:00:00 0.0
2000-01-01 00:01:00 NaN
2000-01-01 00:02:00 100.0
2000-01-01 00:03:00 200.0
Values are placed into their corresponding minutes, as there is no data between 1min and 2min the value is filled with NaN. .mean() doesn't do anything useful (it turns the generator object into a df/series).
You could resample to 10 seconds, forward fill and then resample to 1 minute.
print(data.resample('10s').ffill())
[Out]:
2000-01-01 00:00:00 0.0
2000-01-01 00:00:10 100.0
2000-01-01 00:00:20 100.0
2000-01-01 00:00:30 100.0
2000-01-01 00:00:40 100.0
2000-01-01 00:00:50 100.0
2000-01-01 00:01:00 100.0
2000-01-01 00:01:10 100.0
2000-01-01 00:01:20 100.0
2000-01-01 00:01:30 100.0
2000-01-01 00:01:40 100.0
2000-01-01 00:01:50 100.0
2000-01-01 00:02:00 100.0
2000-01-01 00:02:10 100.0
2000-01-01 00:02:20 100.0
2000-01-01 00:02:30 100.0
2000-01-01 00:02:40 100.0
2000-01-01 00:02:50 100.0
2000-01-01 00:03:00 200.0
print(data.resample('10s').ffill().resample('1t').mean())
[Out]:
2000-01-01 00:00:00 83.<PHONE_NUMBER>
2000-01-01 00:01:00 100.000000
2000-01-01 00:02:00 100.000000
2000-01-01 00:03:00 200.000000
In your question you expect the result between 2min and 3min to be 150, but this will not be the case as you have value of 100 for the entirety of that minute.
Perhaps you'll find the .interpolate(method='time') useful. Here's a link to the docs.
| 2cb8c58a7cc5c836d287cd565c7ff8888ca18f8e63b02ec2ddb0509ab104ef83 | ['36b7d5fd52ef47f1b254e2b22031ba62'] | I'm trying to use Google Maps Engine API Client Library for Python to create table object using the following code:
service = build('mapsengine', 'v1', developerKey=api_key, http=http)
table = service.tables()
request = table.create(body = body)
response = request.execute()
Where body is the following:
{
"projectId": "deletedProjectID",
"name": "turf zones of Uppsala ",
"description": "Table to contain zones to plot",
"tags": [
"turf", "turfing", "uppsala"
],
"schema": {
"columns": [
{
"name": "dateCreated",
"type": "points"
},
{
"name": "latitude",
"type": "points"
},
{
"name": "longitude",
"type": "points"
},
{
"name": "name",
"type": "points"
}
]
}
}
However, I get the error:
---------------------------------------------------------------------------
HttpError Traceback (most recent call last)
<ipython-input-76-698f94a34d91> in <module>()
----> 1 response = request.execute()
C:\Users\User\AppData\Local\Enthought\Canopy32\User\lib\site-packages\oauth2client\util.pyc in positional_wrapper(*args, **kwargs)
130 else: # IGNORE
131 pass
--> 132 return wrapped(*args, **kwargs)
133 return positional_wrapper
134
C:\Users\User\AppData\Local\Enthought\Canopy32\User\lib\site-packages\apiclient\http.pyc in execute(self, http, num_retries)
721 callback(resp)
722 if resp.status >= 300:
--> 723 raise HttpError(resp, content, uri=self.uri)
724 return self.postproc(resp, content)
725
HttpError: <HttpError 400 when requesting https://www.googleapis.com/mapsengine/v1/tables?alt=json&key=[deleted] returned "A value is required.">
I've tried using body = json.dumps(body) but I still get the same error. The only argument which .create() takes in a body (docs) and I based the content of the body from this Google Maps Engine tutorial. On the Google Developers Console I can see that I've making requests to my project (although they've all resulted in errors). Could somebody explain what I've done wrong?
|
ab4fc4acaa0ac8cadcf74675a0652225e63ca91f8626870bfe51277b2ca767ae | ['36c6673c9e7b4e71b89c5c9d21261bd1'] | I'm trying to obtain the sha-1 of 1559 files stored in an array.
For that purpose I've implemented the following routine using the library jsSHA:
for (var i=0; i<_files.length; i++){
(function(file, i) {
var reader = new FileReader();
reader.onload = function () {
try {
var raw_content = reader.result;
var actual_contents = raw_content.slice(raw_content.indexOf(',') + 1);
var shaObj = new jsSHA("SHA-1", "B64");
shaObj.update(actual_contents);
var file_hash = shaObj.getHash("HEX");
console.log("File " + i + " hashed.");
file.file_hash = file_hash;
}
catch (e){
console.log("File " + i + "failed");
console.log(e);
console.log(file);
}
};
reader.readAsDataURL(file);
})(_files[i], i);
}
My problem is that the loop only works well with the first 995 elements. Since element 996 it starts to fail returning me this error "Error: Invalid character in base-64 string"
I know that this issue it's possibly more related to the way that I'm trying to read the files than to the jsSHA library, but it someone could shed some light into my mind it will be very helpful to me.
| 16c001d5f1603ea9cfa2de32cd634b266dcc4f0f5a44f354635319a06aa7bb49 | ['36c6673c9e7b4e71b89c5c9d21261bd1'] | I have a similar problem. At my first installation apparently everything went well, but after rebooting the machine the Orion service doesn't start.
MongoDB is running.
[rober@localhost ~]$ systemctl status contextBroker.service
● contextBroker.service - LSB: run contextBroker
Loaded: loaded (/etc/rc.d/init.d/contextBroker; bad; vendor preset: disabled)
Active: failed (Result: exit-code) since vie 2018-08-03 11:53:20 CEST; 23s ago
Docs: man:systemd-sysv-generator(8)
Process: 1712 ExecStart=/etc/rc.d/init.d/contextBroker start (code=exited, status=1/FAILURE)
<PERSON> 03 11:53:18 localhost.localdomain systemd[1]: Starting LSB: run contextBroker...
<PERSON> 03 11:53:18 localhost.localdomain contextBroker[1712]: contextBroker <PERSON>
<PERSON> 03 11:53:18 localhost.localdomain contextBroker[1712]: Starting...
<PERSON> 03 11:53:18 localhost.localdomain su[1718]: (to orion) root on none
<PERSON> 03 11:53:20 localhost.localdomain contextBroker[1712]: Starting contextBroker... cat: /var/run/contextBroker/contextBroker.pid: No existe el fichero o el directorio
<PERSON> 03 11:53:20 localhost.localdomain contextBroker[1712]: pidfile not found[FALLÓ]
<PERSON> 03 11:53:20 localhost.localdomain systemd[1]: contextBroker.service: control process exited, code=exited status=1
<PERSON> 03 11:53:20 localhost.localdomain systemd[1]: Failed to start LSB: run contextBroker.
<PERSON> 03 11:53:20 localhost.localdomain systemd[1]: Unit contextBroker.service entered failed state.
<PERSON> 03 11:53:20 localhost.localdomain systemd[1]: contextBroker.service failed.
This is the content of the log file /var/log/contextBroker/contextBroker.log
time=2018-08-03T09:31:10.021Z | lvl=ERROR | corr=N/A | trans=N/A | from=N/A | srv=N/A | subsrv=N/A | comp=Orion | op=contextBroker.cpp[399]:pidFile | msg=PID File (open '/var/run/contextBroker/contextBroker.pid': No such file or directory)
time=2018-08-03T09:32:30.401Z | lvl=ERROR | corr=N/A | trans=N/A | from=N/A | srv=N/A | subsrv=N/A | comp=Orion | op=contextBroker.cpp[399]:pidFile | msg=PID File (open '/var/run/contextBroker/contextBroker.pid': No such file or directory)
time=2018-08-03T09:33:46.508Z | lvl=ERROR | corr=N/A | trans=N/A | from=N/A | srv=N/A | subsrv=N/A | comp=Orion | op=contextBroker.cpp[399]:pidFile | msg=PID File (open '/var/run/contextBroker/contextBroker.pid': No such file or directory)
time=2018-08-03T09:36:13.636Z | lvl=ERROR | corr=N/A | trans=N/A | from=N/A | srv=N/A | subsrv=N/A | comp=Orion | op=contextBroker.cpp[399]:pidFile | msg=PID File (open '/var/run/contextBroker/contextBroker.pid': No such file or directory)
time=2018-08-03T09:36:31.675Z | lvl=ERROR | corr=N/A | trans=N/A | from=N/A | srv=N/A | subsrv=N/A | comp=Orion | op=contextBroker.cpp[399]:pidFile | msg=PID File (open '/var/run/contextBroker/contextBroker.pid': No such file or directory)
time=2018-08-03T09:37:54.942Z | lvl=ERROR | corr=N/A | trans=N/A | from=N/A | srv=N/A | subsrv=N/A | comp=Orion | op=contextBroker.cpp[399]:pidFile | msg=PID File (open '/var/run/contextBroker/contextBroker.pid': No such file or directory)
time=2018-08-03T09:39:01.179Z | lvl=ERROR | corr=N/A | trans=N/A | from=N/A | srv=N/A | subsrv=N/A | comp=Orion | op=contextBroker.cpp[399]:pidFile | msg=PID File (open '/var/run/contextBroker/contextBroker.pid': No such file or directory)
time=2018-08-03T09:40:11.421Z | lvl=ERROR | corr=N/A | trans=N/A | from=N/A | srv=N/A | subsrv=N/A | comp=Orion | op=contextBroker.cpp[399]:pidFile | msg=PID File (open '/var/run/contextBroker/contextBroker.pid': No such file or directory)
time=2018-08-03T09:47:36.258Z | lvl=ERROR | corr=N/A | trans=N/A | from=N/A | srv=N/A | subsrv=N/A | comp=Orion | op=contextBroker.cpp[399]:pidFile | msg=PID File (open '/var/run/contextBroker/contextBroker.pid': No such file or directory)
time=2018-08-03T09:53:18.581Z | lvl=ERROR | corr=N/A | trans=N/A | from=N/A | srv=N/A | subsrv=N/A | comp=Orion | op=contextBroker.cpp[399]:pidFile | msg=PID File (open '/var/run/contextBroker/contextBroker.pid': No such file or directory)
|
c8151e36472cf6081a9d6e697fe49b405c80d87e6b1b100457e8ead35a77265a | ['36f70929d2ab4e968082de405543c67a'] | I was doing the same tutorial.
Seems to me a bit weird that it had to be broken up in subexpressions, but it did the trick, and as I read here:
http://swiftlang.eu/community/34-xcode-6-beta-6-swift-can-t-handle-long-expressions/0
it might be due to a problem of Xcode.
Here's the rewritten function:
func checkForWin() {
var whoWon = ["I": 0, "You": 1]
for (key, value) in whoWon {
var wonA = (plays[1] == value && plays[2] == value && plays[3] == value)
var wonB = (plays[4] == value && plays[5] == value && plays[6] == value)
var wonC = (plays[7] == value && plays[8] == value && plays[9] == value)
var wonD = (plays[1] == value && plays[4] == value && plays[7] == value)
var wonE = (plays[2] == value && plays[5] == value && plays[8] == value)
var wonF = (plays[3] == value && plays[6] == value && plays[9] == value)
var wonG = (plays[1] == value && plays[5] == value && plays[9] == value)
var wonH = (plays[3] == value && plays[5] == value && plays[7] == value)
if(wonA || wonB || wonC || wonD || wonE || wonF || wonG || wonH) {
userMessage.hidden = false
userMessage.text = "Looks like \(key) won!"
resetBtn.hidden = false
done = true
}
}
}
| 7964963a1e7f65b1c459468e95ee1374ceca292658afbf4be10211925b99723c | ['36f70929d2ab4e968082de405543c67a'] | Thanks for the fast replies, I made it a bit more robust for my own usecase, where both 'mac' and options where unsure.
Note the == instead of === because most of the time integers were compared to strings.
export function getLabelByValue(value, options) {
if(value !== '' && value !== null && options.length > 0) {
return options.filter(el => el.value == value)[0].label
}
return ''
}
let label = getLabelByValue('mac', options)
|
de3a22ba6330f83cdedcd32e490228fd4c9c7efdbdbc81a927fe276d21fd4351 | ['36fa30d91c424126a74ce01fc6b8f902'] | Let $x = a + b$ where $a$ is the length to the left of $h$ and $b$ is the length to the right of $h$
From similarity on the left triangle, we have
$$
\frac{b}{h} = \frac{a+b}{y}
$$
and for the triangle on the right we have
$$
\frac{a}{h} = \frac{a+b}{z}
$$
Dividing these two equalities, you get
$$
\frac{a}{b} = \frac{y}{z}
$$
From the first equality, you have
$$
h = y\times \frac{b}{a+b}
$$
Notice that
$$
\frac{b}{a+b} = \frac{z}{y+z}
$$
which should help you conclude that
$$
h = \frac{yz}{y+z}.
$$
| 24dff99753614ca514ef023e3c24b7b08e2b799120f5946d09aaab274e4575e2 | ['36fa30d91c424126a74ce01fc6b8f902'] | Hello everybody ~ I am fresh off the newbie tree and waving good bye to Windows through the rear view mirror.
I just started up an old machine that has a fresh install of 8.10 on it and has never been used since.
As far as I can tell there is no gui desktop on it. I would like to update it to the latest, 14.x?
How do I update? Do I just over write the 8.10 with the latest? do I wipe the 8.10 first then install?
Can anyone please advise on this?
Many thanks.
|
547090e7ae0b4f0cde2f21324b70021504e1478e2e47fb7aa9d339dc5a9dda18 | ['3701aa3923e749e3bae2a0b3bf95b420'] | I am making grouped bar chart based on <PERSON> tutorial.
I can't figure out how to put circles on top of my bars to act as tooltip when hovering, just like in this tutorial except it's on bars and not on a line.
I tried appending the circles like this :
svg.selectAll("dot")
.data(data)
.enter().append("circle")
.attr("r", 5)
.attr("cx", function(d) { return x1(d.name); })
.attr("cy", function(d) { return y(d.value); })
});
But I get NaN values. I am very confused about which variable I should use to get the right cx and cy.
Here is my code.
Any ideas ?
Thank you
| e17d7d4d18b2cdcd592e92d6bc6a047b89d8b47743db2000665dcb9fbc3422c3 | ['3701aa3923e749e3bae2a0b3bf95b420'] | I solved my problem by adding a / before 'locales/locale-'
$translateProvider.useStaticFilesLoader {
prefix: '/locales/locale-'
suffix: '.json'
}
What happened is that it tried to load locales/local-xx.json from the current url.
For example if I was on the route
localhost:8080/users
the request was
localhost:8080/users/locales/locale-xx.json
instead of
localhost:8080/locales/locale-xx.json
|
7bd2b1071970d8845a210ca4120c12ca1609cd9a14bfc781a3a25984ae6e047e | ['3705c452e83c4b3daf2163312d9363e9'] | You are asking 2 different things.
First one:
but what if you have a form which edits something, but according to user-level you cant edit.
You can achieve this but not showing the fields in the form nor updating the database if the user doesn't have permissions.
if ($user_has_permissions)
{
echo form_input('field_name');
echo form_input('field_name');
}
and when updating the row
if ($user_has_permissions)
{
$this->db->set('db_field_name', $field_name);
}
If you want to show an error message in form validation, use callbacks (callbaks in CodeIgniter).
Check if the user has permissions and show the message if hasn't.
Second one
Using die() is not an option, I just dont wanna crash my whole app
If you wan't to stop the execution without using die(), you have some other "friendlier" forms to do it:
show_404();
show_error();
show_error('Description of your error');
This will stop the execution and will show a fancy screen with the error description.
| 1bbd9629d5084400a0745e3b7abcf299f57816d2b5f65ccf0b53e3f259b3b84e | ['3705c452e83c4b3daf2163312d9363e9'] | Try creating a .htaccess file in that folder, with the following line:
Deny from all
If you need to download the file, create a controller and use the download helper (force_download function). This will disable all kinds of access (so you cannot use this files in the website, if they are images you cannot use them with ).
|
218350378f1c04203b7921a53546766ae95b0d4f789c871aad52bfd2996565a5 | ['3713ffed73374806bb9f20548c98a202'] | I'm working on an angular 4 project. The code below helps me to get the real time value from slider when user slides between 0 and 1. Each time user slides, applycontrol function triggers because of ngModelChange.
<input [(ngModel)]="Brightness" type="range"
(ngModelChange)="applyControl($event)" min="0"
max="1" [step]="0.01" class="slider">
All i want to run another function inside applycontrol function only when user release the mouse after slide.
applyControl(value) {
console.log('Brightness:', value);
}
| d6646c49f671192c8f89e3d5f3b0090c11f9a9f9686a6351d741000926d3a360 | ['3713ffed73374806bb9f20548c98a202'] | I could select the background image from inside rectangle, but not able to move.
To move the image, i should go outside of the rectangle.
I know that the rectangle is created over the image, I'm looking for any option to move the image as it is selectable from inside rectangle.
My canvas screenshot
This is how i set the image and rectangle.
changeImage(innercanvasHeight, innercanvasWidth) {
const base_image = new Image();
base_image.crossOrigin = 'Anonymous';
base_image.src = 'assets/images/1wal.jpg';
fabric.Image.fromURL(base_image.src, (myImg) => {
const img1 = myImg.set({left: 160, top: 80, width: 600, height:
400, id: 'wallpaper'});
this.FabriCanvas.add(img1).setActiveObject(img1);
const hiddenImg = document.createElement('img');
hiddenImg.src = this.FabriCanvas.getActiveObject().toDataURL();
hiddenImg.id = 'target';
hiddenImg.style.display = 'none';
document.body.appendChild(hiddenImg);
this.innerCanvas(innercanvasHeight, innercanvasWidth);
});
innerCanvas(height, width) {
this.innercanvas = this.FabriCanvas.add(new fabric.Rect({
left: 160,
top: 80,
id: 'innerCan',
fill: 'transparent',
stroke: '#fff',
strokeWidth: 1,
width: width,
height: height,
selectable: false
}));
this.FabriCanvas.renderAll();
}
|
b0d3fe7cf6081d0dddd8902575383d3af2de30d9f91859d5054d253b70207964 | ['3718a6885045489dbc2d541706b61b84'] | Of course you can! Simply add height: <insert value that's above 100px here> to your CSS under .large and find the correct values to reach the expected result.
Example:
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
padding: 5em;
}
.grid {
display: grid;
grid-template-columns: 25% 25% 25% 25%;
grid-gap: 1em 1em;
grid-auto-flow: row dense;
}
.item {
background: rgba(0, 0, 0, 0.1);
border-radius: 0.25em;
padding: 2em;
}
.large {
background: rgba(255, 0, 0, 0.25);
grid-column: auto / span 2;
grid-row: auto / span 2;
height: 200px;
}
<div class="grid">
<div class="item">Small 1</div>
<div class="item">Small 2</div>
<div class="item large">Large 1</div>
<div class="item large">Large 2</div>
<div class="item">Small 3</div>
<div class="item">Small 4</div>
<div class="item">Small 5</div>
<div class="item">Small 6</div>
<div class="item">Small 7</div>
<div class="item">Small 8</div>
<div class="item">Small 9</div>
<div class="item">Small 10</div>
<div class="item">Small 11</div>
<div class="item">Small 12</div>
<div class="item">Small 13</div>
</div>
| 8d971a179ed05504e8c97a3e3d312fecefabfbe051c58f9f95a40720d09042ab | ['3718a6885045489dbc2d541706b61b84'] | To run programs in admin using a batch-file you must have admin permissions on your script first, if it's the same as C++. Here's something I've been using that I found somewhere on this website. Put it at the begining of your script and tell me if it worked!
rem Checking permissions
if "%PROCESSOR_ARCHITECTURE%" == "amd64" (
>nul 2>&1 "%SYSTEMROOT%\SysWOW64\cacls.exe" "%SYSTEMROOT%\SysWOW64\config\system"
) else (
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
)
rem If error then no admin permissions
if %errorlevel% NEQ 0 (
echo Catching admin permissions
timeout /t 2 /nobreak >nul
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
set params = %*:"=""
echo UAC.ShellExecute "cmd.exe", "/c ""%~s0"" %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
exit /B
) else (
pushd "%CD%"
CD /D "%~dp0"
)
|
2332649f0780238499eed4b1c5b6237a7ecbf06ba9be14fa773a0fe7aadf1cc6 | ['371c40ef819c4b32825b4f65b7202f33'] | Think of it has as opening up a whole bunch of doors until you find what you're looking for, then you have to go back and close/check the other ones.
public void preOrder(BinaryTree root) {
if(root != null) {
System.out.println(root);
preOrder(root.leftChild); <-- this gets called and will start from the top of the function
preOrder(root.rightChild); <-- how can this get called if the top one will always calls itself?
}
}
We can replace the preOrder calls with the matching code to look like:
public void preOrder(BinaryTree root) {
if(root != null) { <-- note the if check
System.out.println(root);
if(root.leftChild!= null) { <-- note the if check
System.out.println(root.leftChild.leftChild);
preOrder(root.leftChild.leftChild); <- this expands into another if block
preOrder(root.leftChild.rightChild); <- this also expands
}
if(root.rightChild!= null) { <-- note the if check
System.out.println(root.rightChild.leftChild);
preOrder(root.rightChild.leftChild);
preOrder(root.rightChild.rightChild);
}
}
}
It keeps expanding outwards... until you hit the special "base" if conditional that stops the recursion. In this case it is when you've found a leaf node of the tree, i.e. node == null, it stops the expansion because the if conditional is no longer true and everything begins to collapse in on itself, or in other words it can continue executing normally down the block of code.
| b5478c5ecc25eaf8fc6cccb6eee5044e52505ff22c3939ab5a0d6983f499921d | ['371c40ef819c4b32825b4f65b7202f33'] | I currently have a simple table in my database that stores sets and values. I want to be able to delete all entries in the database and return the number of distinct sets that were deleted.
create table sets(
SetId varchar(50)
Value int
)
If I have two sets each with two values, then the table will be loaded for four entries.
Set1, 0
Set1, 1
Set2, 0
Set2, 1
If I delete everything I want to be able to count how many unique SetIds were deleted, so in the example above it should return 2.
Right now I can accomplish this by creating a tempTable that contains the deleted SetIds and then I count distinct
CREATE TABLE #temp
(
SetId varchar(50)
);
delete from Sets
OUTPUT DELETED.SetId INTO #temp
select count(distinct SetId) from #temp;
Is there a better way to accomplish this without having to use a temp table?
|
86574289c6e34ed2fc90c7d1f958fbd9130f7dd1463986752e0a41a2f6428df8 | ['3729cb9bcb944150a286d73d807a5150'] | Another way is simply to not allow values that are not integers.
The following implementation is a little bit sucky, and I would like to abstract it later on in order for it to be more reusable, but here is what I did:
in the code behind in my view (I know this is might hurt if you are a hardcore mvvm ;o) )
I defined the following functions :
private void NumericOnly(System.Object sender, System.Windows.Input.TextCompositionEventArgs e)
{
e.Handled = IsTextNumeric(e.Text);
}
private static bool IsTextNumeric(string str)
{
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[^0-9]");
return reg.IsMatch(str);
}
And in the XAML view, every textbox that was only supposed to accept integers
was defined like this:
<TextBox Padding="2" TextAlignment="Right" PreviewTextInput="NumericOnly" Text="{Binding xxx.yyyy}" MaxLength="1" />
The key attribute being PreviewTextInput
| 9e0a0ec63b449fd49b32cf6cdc872b1994dc271336a4a4835365096183244ff6 | ['3729cb9bcb944150a286d73d807a5150'] | I added this as an issue on ng-grids github site. It turned out that others had had the same problem, and that there is a solution:
(you need to get your hands dirty though and alter the ng-grid code.)
https://github.com/angular-ui/ng-grid/issues/632
Im guessing it will make it into version 3.0
|
402b5be037db08c6d2244b091785bbd006477cbad6320558d0c5bddf493f0fb4 | ['372b94c3fcf04a54be5f2f154f91d93d'] | When using group by you need to use aggregate queries to access the object properties. It also creates an object called key with the values used to group by.
Select="new (max(staffID) as staffID, key.Forename, key.Surname, max(City) as City, max(Country) as Country, max(LastUpdatedDate) as LastUpdatedDate, max(tblStaffStatus) as tblStaffStatus, max(Score) as Score)"
If you are grouping by a single value then use
GroupBy="Surname"
Select="new (key as Surname)"
| 39a0e247b44af168f34a3b68966091877c64a35243b47922fba2551039d692bb | ['372b94c3fcf04a54be5f2f154f91d93d'] | You could move the script tag for the file upload so it is before requirejs is loaded. However since it relies on jquery then that might not be possible if you want jquery to run after requirejs.
The easiest option would be to edit the code snippet you've shown so that the call to factory() is outside the else block and will always run.
|
7e80be15b131410c62d2c7f39a61014d00a7a3fde86079300e7d9dc7b2ec7fe4 | ['37478a56034a425d99b84b1c338fabcb'] | First, use SoapUI to create your soap project from the wsdl. Try to send a request to play with the wsdl's operations. Observe how the xml request composes your data fields.
And then, if you are having problem getting SoapClient acts as you want, here is how I debug it. Set the option trace so that the function __getLastRequest() is available for use.
$soapClient = new SoapClient('http://yourwdsdlurl.com?wsdl', ['trace' => true]);
$params = ['user' => 'Hey', 'account' => '12345'];
$response = $soapClient->__soapCall('<operation>', $params);
$xml = $soapClient->__getLastRequest();
Then the $xml variable contains the xml that SoapClient compose for your request. Compare this xml with the one generated in the SoapUI.
For me, SoapClient seems to ignore the keys of the associative array $params and interpret it as indexed array, causing wrong parameter data in the xml. That is, if I reorder the data in $params, the $response is completely different:
$params = ['account' => '12345', 'user' => 'Hey'];
$response = $soapClient->__soapCall('<operation>', $params);
| 26ae2937d27ceb4000bc31b573a08e0ee6140fe639833369454423e2061688dd | ['37478a56034a425d99b84b1c338fabcb'] | I want to add 2 points that I learned:
Cron config files put in /etc/cron.d/ should not contain a dot (.). Otherwise, it won't be read by cron.
If the user running your command is not in /etc/shadow. It won't be allowed to schedule cron.
Refs:
http://manpages.ubuntu.com/manpages/xenial/en/man8/cron.8.html
https://help.ubuntu.com/community/CronHowto
|
9649a8b840015047c9261344b3b54b4fe5842aa2c2dcdfc774b2f464353f02d1 | ['37486f17003a43338ad0ee8c8f188c56'] | I'm working on python projects and generate coverage.xml for unit tests using the pytest-cov module. However I don't have any good tools to parse the coverage.xml and highlight which lines of code are missed. This seems to be a common use case but I can't find anything via google.
Are there any tools out there (preferably via command line since I work mostly over ssh) that does this?
I'm thinking of writing my own pygments filter if I can't find anything.
| f7c472281b09dc9ecfcc7b539411f9aedf18abafae4d82dbc994ca820de4a4cb | ['37486f17003a43338ad0ee8c8f188c56'] | We are integrating the Okta Sign-in Widget into our React-based webapp.
The example snippet:
var oktaSignIn = new OktaSignIn({baseUrl: baseUrl});
oktaSignIn.renderEl(...)
Works fine for us when rendering the widget for the first time, but after the user logs in and logs out again, the webapp renders the login component a second time and would attempt to execute the renderEl again to render the widget. This causes the following exception to be thrown:
Backbone.history has already been started
I have created this jsfiddle to demonstrate the problem. It just instantiates a signin widget twice (the second time after a wait). You can see that the second invocation causes the exception to be thrown.
https://jsfiddle.net/nudwcroo/6/
At the moment my workaround is to reload the entire webapp when going to the login component but that is undesirable for a single page app.
Is this a known issue? Is there any way to initialise the sign-in widget twice in a single javascript session?
|
bd8166d56f3ef458841f0ee60c9cc036cb571902094cc9ab581cef0fed4a0c86 | ['37487b8c27eb43c99138728e35f0b2f6'] | Sim, mas tem algo estranho quando <PERSON> import dash ele importa mas quando <PERSON> import dash_core_components ele da erro e fala "Dash was not successfully imported. Make sure you don't have a file named
'dash.py' in your current directory.
An exception has occurred, use %tb to see the full traceback." | 89fdae684c76818988c35ebe5d10877da8955c64bc88cb332105d60bc358051e | ['37487b8c27eb43c99138728e35f0b2f6'] | Just some context: $R\underbrace{(3,3,3, \ldots,3)}_\text{$k$ times}\leq n$, means that any colouring of a complete graph, $k_n$, on $n$ vertices or more with $k$ colours must contain a monochromatic triangle.
Claim: $R\underbrace{(3,3,3, \ldots,3)}_\text{$k$ times} \leq 3k!$
Proof:
Consider the minimum number of monochromatic edges connected to an arbitrary vertex, $V$. At least $\big\lceil{\frac{3k!-1}{k}}\big\rceil$ edges will be monochromatic. $\big\lceil{\frac{3k!-1}{k}}\big\rceil$ =$\frac{3k!}{k}$ when $k>1$. Therefore, vertex $V$ must be connected to $3(k-1)!$ monochromatic edges.
By trying to avoid a monochromatic triangle of color $k_1$, we will be forced into creating a monochromatic triangle of color {$k_2$, $k_3$, $\ldots$, or $k_i$}. If we connected any of the vertices $\{1,2,3, \ldots, 3(k-1)!\}$ with a blue edge, a blue monochromatic triangle would be formed, to avoid this, the remaining $3(k-1)!$ vertices must be colour with the remaining $k-1$ colours.
We can then consider a subgraph of the remaining vertices $\{1,2,3,\ldots,3(k-1)!\}$ and colour it with the remaining $k-1$ colours. We can focus on a new vertex, $V'$, within the subgraph.
Vertex $V'$ will be connected to at least $\displaystyle{\frac{3(k-1)!}{k-1}}$ monochromatic edges. Which equals $3(k-2)!$ edges.
We can continue this process until we consider the subgraph of remaining vertices $3(k-(k-1))!$ and colour it with the remaining $k-(k-1)$ colours. This means that this final subgraph has 3 vertices and has to be coloured with 1 colour. Therefore, a monochromatic triangle is unavoidable. Therefore, $R\underbrace{(3,3,3, \ldots,3)}_\text{$k$ times} \leq 3k!$.
I managed to get it down to $3k!$, I was wondering if anyone had better approximations?
|
582f9ebb7b7ce6e40cafeaa20257cac0e8b69e15cabac0aae67049e6b1dcf373 | ['3755a688eb2141e2b28adbd1b939781d'] | As far as I'm concerned, there is no question like this. I'm working on a NLP and sentiment analysis project in Kaggle and first of all I'm preparing my data.
The dataframe is a text column followed by a number from 0 to 9 which categorizes which cluster does the row (the document) belongs.
I'm using TF-IDF Vectorizer in sklearn. I want to get rid of anything that's not an english language word, so I'm using the following:
class LemmaTokenizer(object):
def __init__(self):
self.wnl = WordNetLemmatizer()
def __call__(self, doc):
return [self.wnl.lemmatize(t) for t in word_tokenize(doc)]
s_words = list(nltk.corpus.stopwords.words("english"))
c = TfidfVectorizer(sublinear_tf=False,
stop_words=s_words,
token_pattern =r"(?ui)\\b\\w*[a-z]+\\w*\\b",
tokenizer = LemmaTokenizer(),
analyzer = "word",
strip_accents = "unicode")
#a_df is the original dataframe
X = a_df['Text']
X_text = c.fit_transform(X)
which as far as I know, when calling c.get_feature_names() should return only the tokens which are proper words, without numbers or punctuation symbols.
I found the regex in a post in StackOverflow, but using a simpler one like [a-zA-Z]+ will do exactly the same (this is, nothing).
When I call the feature names, I get stuff like
["''abalone",
"#",
"?",
"$",
"'",
"'0",
"'01",
"'accidentally",
...]
Those are just examples, but it's representative of the output I get, instead of just the words.
I've been stuck with this for days trying different regular expressions or methods to call. Even hardcoded some of the outputs for the features on the stop words.
I'm asking this because later I'm using LDA to get the topics of each cluster and get punctuation symbols as the "topics".
I hope I'm not duplicating another post. Anymore information I need to provide will do gladly. Thank you in advance!
| 11221465a07d217421f77f9f97bf1190f3ba564de805c94cabf347509991251a | ['3755a688eb2141e2b28adbd1b939781d'] | This is my first time using bash in college and it's being pretty hard now.
The exercise is:
Make a shell script which receives by parameter one word and a file list and adds the word in the beggining and ending of each file
So far what I've done is this:
#!bin/bash
word=$1;
i=2;
j=2;
for [ i -le $# ] in ls
do
for [ j -le $# ] in ls
do
if [ $i = $j ] then
$j=`word+$j+word`;
fi
done
done
and of course it doesn't work, but I really don't know why.
If anybody could help, it'd be great.
Sorry by any language mistake or convention in SO, I just arrived here. Thank you very much!
|
7ddc9008bf14e6b1267071a545830d4c672d8811ea098121acbb95ff0dfab29c | ['3758b41596f84b4a87f7f73b13cf23fb'] | I'm having trouble within an IOS swift application trying to get bluetooth RSSI signal strength from the peripheral. I've been trying to use readRSSI() (see code below) which returns a Future, but I've so far been unable to map that Future into another usable variable such as an Int or String. I'm new to Swift, so not sure if I'm missing an async step or other. I'm used to working in R, python, JS and having some challenges wrapping my head around the syntax. Any help is greatly appreciated.
I've tried switching multiple ways of extracting the content from within extensions to the ViewController without luck. I get errors on type-mismatches no matter how I try to pass the Future type value.
let strengthCharacteristic = self.peripheral.readRSSI()
let thisRet = self.strengthChar.map({ avar in
return avar
})
self.strengthLabel.text = String(thisRet ?? 0)
| 05425ac92ef7a7358beac4706eb2246b40e6f3bc31f90d5960916763fb08b3a8 | ['3758b41596f84b4a87f7f73b13cf23fb'] | I have been able to use the getSymbols function to draw financial data from the default source (yahoo) successfully from within RStudio. When I tried to run this in a script from the command line, this fails and returns no data. The same when I manually enter the command from the command line.
Code:
library(quantmod)
args <- commandArgs(FALSE)
options("getSymbols.warning4.0"=FALSE)
getSymbols("APL")
chartSeries(APL, subset='last 1 months')
saveChart('png')
Error:
Error in download.file(paste(yahoo.URL, "s=", Symbols.name, "&a=", from.m, :
unable to connect to 'chart.yahoo.com' on port 80.
I'm executing this from a VM running Windows Server 2008. Any ideas? I want to be able to call this code from PHP to update a figure when the user visits a page
|
dec7a4922d1b66e8b468de3a967b2f1764aeac119f18955748d7f2043c5c47eb | ['37591e2125fd443da32bfda811c5f3b4'] | I am building a set of chart displays, one of which is for a month display of daily trading - that is, one point of data per day (closing).
Since there is no trade during weekends and holidays, I need to discard these data points. Not only that, but data points should still appear adjacent to each other, regardless of any gaps in time. This can be seen in any such chart e.g. in the 3 month graph for Nasdaq on Yahoo Finance - see how weekends are skipped.
My question is: how should one correctly implement this in JFreeChart?
Thanks in advance!
| 627095aa4af003317f8b81db15da43bd2d68c8a1b4c9ce7d5ac553c550d078e0 | ['37591e2125fd443da32bfda811c5f3b4'] | OK, so no one answered my question... Here is what I found out that works. Create a security group, add your users. On the Exchange server you want them to have access right click it while using the Exchange system manager and give this groups permissions in the security taps. I gave them everything but full control.
Hope this helps anyone having the same issues.
|
b7cdaa95f2ff4863b27fae62a71b45617b11e6eda3f6adac57505010696945bc | ['376ad9ad2b4843ba818754d1f8c41b76'] | So your program must be something like this.
public class BooleanBug {
public static String bool(Boolean param) {
if ((null != param) && param.booleanValue() == true) {
return "a";
} else if ((null != param) && param.booleanValue() == false) {
return "b";
}
return "c";
}
public static void main(String[] args) {
System.out.println(bool(true));
System.out.println(bool(null));
System.out.println(bool(false));
}
}
| 3fa7c944f3e7557a6fec1b2f7156985e5ab8e8ec8babd2ecd0a7c0d178f745c0 | ['376ad9ad2b4843ba818754d1f8c41b76'] | I am using web socket for push notifications. In my android application (client side) I use Autobahn web socket client. It works fine, but if you want reliable solution then I think you can go for Azure Push Notification Service. But I think you can only send/receive few push notifications using their free service. To scale further you need to pay.
But using web socket you can send as many number of notifications as you want. Further, you can keep the connection always on, so that you don't need to reconnect the socket connection every time. But to ensure the active web socket connection you need implement PingPong. And that PingPong might use some the bandwidth.
|
87598305c655d83a989777f66c0948fd353c2e15e311aca4db4e73be087d6149 | ['376cae989bf5449ea21f5e1cc70f5c67'] | In case anyone comes across this - I figured out I just put the DispatchQueue blog into the wrong spot. Below you will find the adjusted code which works as intended.
func loadCategories() {
if let currentUserEmail = Auth.auth().currentUser?.email {
let docRef = db.collection(currentUserEmail).order(by: "Name")
docRef.getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents> \(err)")
} else {
for document in querySnapshot!.documents {
print(document.data())
self.categories.append(document.documentID)
self.db.collection(currentUserEmail).document(document.documentID)
.collection(document.documentID).whereField("Category", isEqualTo: document.documentID)
.getDocuments { (querySnapshot, error) in
if let error = error {
print("\(error)")
} else {
if let docCount = querySnapshot?.count {
self.categoryQuestionCountSub[document.documentID] = docCount
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
}
}
}
}
}
}
| ef986824107f3012ac8ce3dc57f268aca61dd84bfc489125adc15f0bd502c102 | ['376cae989bf5449ea21f5e1cc70f5c67'] | I've read now multiple threads on data retrieval from Firestore but I still haven't been able to find an answer and make this work -> making me open a new thread.
I'm trying to get the count of documents in a subcollection of a collection of Categories to display onto a detailTextlabel in Tableview. The data retrieval for the categories (Documents in a higher collection) works fine, getting the data asynchronously and displaying them at cellForRow level.
However, I'm trying to get it's subcollection querySnapshot?.count, which also then loads into a Dictionary as wished, but I can't get it do load the data outside of the closure (I can't get it to work with DispatchQueue.main.asynch). The second to last print statement (categories) works fine, the one below it, shows an empty dict.
I'd greatly appreciate any kind of input.
Thanks
<PERSON>
Please find the code here:
func loadCategories() {
if let currentUserEmail = Auth.auth().currentUser?.email {
let docRef = db.collection(currentUserEmail).order(by: "Name")
docRef.getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents> \(err)")
} else {
for document in querySnapshot!.documents {
print(document.data())
self.categories.append(document.documentID)
self.db.collection(currentUserEmail).document(document.documentID)
.collection(document.documentID).whereField("Category", isEqualTo: document.documentID)
.getDocuments { (querySnapshot, error) in
if let error = error {
print("\(error)")
} else {
if let docCount = querySnapshot?.count {
self.categoryQuestionCountSub[document.documentID] = docCount
}
print("\(self.categoryQuestionCountSub) outside if let")
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
print("\(self.categories) outside of Loop")
print("\(self.categoryQuestionCountSub) outside of Loop")
}
}
}
}
|
0a2865ada56d3496466156fd84afe691e8dcd9df071cd84422254b80d9c2575d | ['377096242a83494380caaccc755bfdc6'] | I'm making a quiz app in Django. It is a MCQ type of quiz app where users have to select the answer from a list of multiple answers.
Now, in my models.py there are three models:
Quiz
Question
Answer
Where Quiz model defines the type of quiz (For example Basic, Intermediate, Advance), Question model has a ForeignKey of Quiz to specify the type of question and a CharField to mention the text of the question. The Answer model is similar to Question model but with ForeignKey of Question to specify the question that answer is related to, CharField for the text of the answer and a BooleanField to specify if that answer is correct or not.
models.py
from django.db import models
# Create your models here.
class Quiz(models.Model):
q_name = models.CharField(max_length=30)
desc = models.CharField(max_length=100)
def __str__(self):
return self.q_name
class Question(models.Model):
quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE)
label = models.CharField(max_length=1000)
def __str__(self):
return self.label
class Answer(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
text = models.CharField(max_length=1000)
is_correct = models.BooleanField(default=False)
def __str__(self):
return self.text
views.py
from django.shortcuts import render, redirect, reverse
from django.contrib import messages
from .models import Quiz, Question, Answer
def basic_quest(request, quiz_name, ques_no):
if request.method == "POST":
guess = request.POST.get('answer')
ans = Answer.objects.get(text = guess)
if ans.is_correct == True:
messages.success(request,("Correct"))
return redirect('basic_quest')
else:
messages.error(request,("Wrong"))
else:
question = Question.objects.get(id = ques_no)
answers = Answer.objects.filter(question = ques_no)
return render(request, 'quest.html', {'question' : question, 'answers' : answers})
quest.html
{% extends 'base.html' %}
{% block title %}
Question - Quiz Python
{% endblock title %}
{% block content %}
<div class="container">
{% if messages %}
{% for message in messages %}
<div class="alert alert-primary alert-dismissible fade show" role="alert">
{{ message }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% endfor %}
{% endif %}
<p><h1>{{ question.label }}</h1></p>
<form method="POST">
{% csrf_token %}
{% for answer in answers %}
<label><input type="radio" name="answer" value={{ answer.text }}> {{ answer.text }}</label>
</br>
{% endfor %}
<input type="submit">
</form>
</div>
{% endblock content %}
After selecting the answer using the radio button and clicking on submit I want it to display a message on the same page as correct or incorrect by checking the value of the radio button selected with the answer available in the Answer model.
But I'm getting the following error:
NoReverseMatch at /quiz/Basic/1
Reverse for 'basic_quest' with no arguments not found. 1 pattern(s) tried: ['quiz/(?P<quiz_name>[^/]+)/(?P<ques_no>[^/]+)$']
Request Method: POST
Request URL: http://localhost:8000/quiz/Basic/1
Django Version: 2.2.7
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'basic_quest' with no arguments not found. 1 pattern(s) tried: ['quiz/(?P<quiz_name>[^/]+)/(?P<ques_no>[^/]+)$']
Exception Location: /Users/apple/Desktop/myvenv/quiz/lib/python3.7/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 673
Python Executable: /Users/apple/Desktop/myvenv/quiz/bin/python
Python Version: 3.7.4
Python Path:
['/Users/apple/Desktop/quiz',
'/Library/Frameworks/Python.framework/Versions/3.7/lib/python37.zip',
'/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7',
'/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload',
'/Users/apple/Desktop/myvenv/quiz/lib/python3.7/site-packages']
| 3c5fbe6e892756b42ff263427bfa34d3e62abf4bfc63fc86de149e6d87c58184 | ['377096242a83494380caaccc755bfdc6'] | I have added a screenshot of how my html template looks in the browser. I'm not getting a dropdown in my form for Name label. I am getting the desired output(dropdown) in my model. I have already gone through the official documentation of Django, but was not able to find a solution. I am new to Django.what should I do?
models.py
from django.db import models
class Record(models.Model):
CHOICES = (
('<PERSON>', '<PERSON>'),
('<PERSON>', '<PERSON>'),
('<PERSON>', '<PERSON>')
)
date = models.DateTimeField(auto_now_add = True)
emp_name = models.CharField(max_length=10, choices=CHOICES)
amount = models.PositiveIntegerField(default=0)
views.py
from django.http import HttpResponse
from django.views.generic import FormView
from .models import Record
from .forms import RecordForm
class home(FormView):
template_name = 'myapp/home.html'
form_class = RecordForm
def form_valid(self, form):
return HttpResponse("Sweeeeeet.")
forms.py
from django import forms
from .models import Record
CHOICES = [
('<PERSON>', '<PERSON>'),
('<PERSON>', '<PERSON>'),
('<PERSON>', '<PERSON>')
]
class RecordForm(forms.ModelForm):
name = forms.CharField(label='Name', widget=forms.Select(choices=CHOICES))
amount = forms.IntegerField()
class Meta:
model = Record
fields = '__all__'
urls.py
from django.urls import path
from django.contrib.auth import views as auth_views
from .views import EmployeeListView, home
from . import views
urlpatterns = [
path('', home.as_view(),name='home'),
path('logout/', auth_views.LogoutView.as_view(template_name = 'myapp/logout.html'), name='home-logout'),
path('profile/', views.profile, name='home-profile'),
path('employee/', EmployeeListView.as_view(), name='home-employee'),
]
home.html
<style type="text/css">
.form-container {
border-radius: 10px;
padding: 10px;
box-shadow: 0px 0px 10px 0px;
}
.row {
padding: 80px;
}
</style>
<div class="row">
<div class="col s12 m12">
<div class="card teal lighten-1">
<div class="card-content white-text">
<form method="POST" class="form-container">
{% csrf_token %}
<div class="fieldWrapper">
<label for="id_name">Name</label>
{{ form.name }}
</div>
<div class="fieldWrapper">
<label for="id_amount">Amount</label>
{{ form.amount }}
</div>
<button class="waves-effect waves-light btn" type="submit">Post</button>
</form>
</div>
</div>
</div>
</div>
output
Not getting a dropdown for Name label
|
9d730a2f65533feb4f4925efc6eee2acb6216f77913659ba6f9d632e462cd0b9 | ['37718eaef3b04e39aa425e1613015dea'] | I am working on a feature in which I am proving the excel dump to the user. When user downloads the excel sheet it works fine. the moment user tries open with Microsoft Excel it gives me an error "Excel cant open the file because the file format or the extension is not valid" This is happening only in firefox browser, and in file name .xlsx extension is added automatically.
Code I am using to create the excel dump is
header('Pragma: public');
header("Expires: Mon, 12 Jul 2012 05:00:00 GMT"); // Date in the past
header('Content-Disposition: attachment; filename="excel.xls"');
header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate'); // HTTP/1.1
header('Cache-Control: pre-check=0, post-check=0, max-age=0');
$header = "Date\t";
$header .= "Other Details Details\t";
echo $header . "\n";
echo "Date1\t";
echo "Detail1\t\n";
echo "Date2\t";
echo "Detail2\t\n";
| 0e28dfbc8f84b27465e195d41d4ea698880cb3681b82fed650297b3c9d7118d8 | ['37718eaef3b04e39aa425e1613015dea'] | I have removed the code deploy agent from one of the ec2 instance in region: us-west-2 using the command:
sudo dpkg -r codedeploy-agent
as mentioned in the doc http://docs.aws.amazon.com/codedeploy/latest/userguide/how-to-run-agent.html#how-to-verify-agent-version-ubuntu
To reinstall I copied the install from the s3 bucket adn when I do
sudo ./install auto
I am getting this message:
I, [2016-05-13T14:20:<PHONE_NUMBER>] INFO -- : Starting Ruby version check.
I, [2016-05-13T14:20:<PHONE_NUMBER>] INFO -- : The current Ruby version is not 2.0.x! Restarting the installer with /usr/bin/ruby2.0
I, [2016-05-13T14:20:<PHONE_NUMBER>] INFO -- : Starting Ruby version check.
I, [2016-05-13T14:20:<PHONE_NUMBER>] INFO -- : Starting update check.
I, [2016-05-13T14:20:<PHONE_NUMBER>] INFO -- : Attempting to automatically detect supported package manager type for system...
I, [2016-05-13T14:20:<PHONE_NUMBER>] INFO -- : Checking AWS_REGION environment variable for region information...
I, [2016-05-13T14:20:<PHONE_NUMBER>] INFO -- : Checking EC2 metadata service for region information...
I, [2016-05-13T14:20:<PHONE_NUMBER>] INFO -- : Running version 1.0-1.950
I, [2016-05-13T14:20:<PHONE_NUMBER>] INFO -- : Downloading version file from bucket aws-codedeploy-us-west-2 and key latest/VERSION...
I, [2016-05-13T14:20:<PHONE_NUMBER>] INFO -- : Running version matches target version, skipping install
I, [2016-05-13T14:20:<PHONE_NUMBER>] INFO -- : Update check complete.
I, [2016-05-13T14:20:<PHONE_NUMBER>] INFO -- : Stopping updater.
|
35a805b81b912e2ff8e13ed6e78a1cc4c1a2bd08b65627434f62240bf1dde898 | ['377f3d7604cb47f19b6bf0249c4a9e8e'] | I have a standard HTML form that submits login data to a server, but I would also like to submit the users geolocation from javascript.I use the geolocation code from another stackoverflow question:
window.onload = function(){
if(navigator.geolocation)
navigator.geolocation.getCurrentPosition(handlesucces, onError);
}
function handlesucces(location) {
location.coords.latitude;
location.coords.longitude;
}
function onError() {
document.write("Error");
}
But am unsure how to add this data to the POST from the HTML form
| f8b5e5ae8ebe88991df8a0cdd55bdda082d9a277f034dd18c1f2e4de30b165c0 | ['377f3d7604cb47f19b6bf0249c4a9e8e'] | I have an array that I want to loop through. Using:
echo count($places);
I get a value of 2. Similar print_r the array gives 2 items.
However, when i run a for loop it seems to go through 4 iterations. This can be seen by adding echo $i to the loop, which produces an output of 0,1,2,3.
This is my code:
function enrichfromDB($places) {
$con = mysqli_connect("localhost","user","password","db1");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo count($places);
print_r($places);
for ($i=0 ; $i<count($places) ; $i++) {
echo $i;
$name = $places[$i]['name'];
$gettag = "SELECT Tag FROM PlaceTags WHERE Name = '$name'";
$data = mysqli_query($con,$gettag);
while($row = mysqli_fetch_assoc($data)) {
$tags[] = $row['Tag'];
}
$places[$i]['category_labels'][0][] = $tags[$i];
}
return $places;
}
|
0f1cf8aaadf3e5c2d61ae391950325a357dfdade96b0ee752d4c9ee30394b42a | ['37865194ba514fe691ea17ad1eb1b827'] | SampleClient.java - does all the client stuff
package sampleclient;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SampleClient extends JFrame{
private JTextField userText;
private JTextArea chatWindow;
private ObjectOutputStream user;
private ObjectOutputStream output;
private ObjectInputStream input; //from the server
private String message = "";
private String serverIP;
private Socket connection;
private String name;
private JTextArea contacts;
private PrintWriter toS;
//constructor
public SampleClient(String host, String username){
super("Client");
serverIP = host;
name = username;
userText = new JTextField();
userText.setEditable(false); //not allowed to type while no one is connected
userText.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
sendMessage(event.getActionCommand());
userText.setText("");
}
}
);
add(userText, BorderLayout.SOUTH);
contacts = new JTextArea();
chatWindow = new JTextArea();
add(new JScrollPane(contacts), BorderLayout.EAST); //scroll
contacts.append(" ONLINE CONTACTS \n");
add(new JScrollPane(chatWindow), BorderLayout.CENTER); //scroll
setSize(300, 150);
setVisible(true);
}
//connect to server
public void startRunning(){
try {
connectServer();
setupStreams();
whileChatting();
}catch(EOFException eofException){
showMessage("\n Client terminated connection");
}catch (IOException ioException){
ioException.printStackTrace();
}finally{
closeAll();
}
}
//connectServer
private void connectServer() throws IOException{
showMessage("Attempting connection... \n");
connection = new Socket(InetAddress.getByName(serverIP), 6789); //passes to an IP Adrdress and Port Number
showMessage("Connected to:" + connection.getInetAddress().getHostName()); //prompt
toS = new PrintWriter(connection.getOutputStream(), true);
toS.println(name);
}
//set up streams for sending and receive the messages
private void setupStreams()throws IOException{
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream()); //receive messages
showMessage("\n Streams are connected");
}
//actual chat
private void whileChatting()throws IOException{
ableToType(true);
do{
try{
message = (String) input.readObject();
showMessage("\n" +message);
}catch(ClassNotFoundException classNotFoundException){
showMessage("\n ERROR!");
}
}while(!message.equals("SERVER - END"));
}
//close sockets and streams
private void closeAll(){
showMessage("\n Closing connections..");
ableToType(false);
try{
output.close();
input.close();
connection.close();
}catch(IOException ioException){
ioException.printStackTrace();
}
}
//send messages to server
private void sendMessage(String message){
try{
System.out.println(name);
output.writeObject( "\n" + name + ": " + message);
output.flush(); //push bytes
showMessage("\n" + name + ": " + message);
}catch(IOException ioException){
chatWindow.append("ERROR!");
}
}
//Update chatWindow
private void showMessage(final String m){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
chatWindow.append(m); //appear at the end of the conversation
}
}
);
}
//permission to type to for user
private void ableToType(final boolean tof){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
userText.setEditable(tof);
}
}
);
}
}
clientTest.java
package sampleclient;
import javax.swing.*;
public class ClientTest {
public String userName;
private static JFrame frame = new JFrame("Messenger");
private static String getUsername() {
return JOptionPane.showInputDialog(
frame,
"Enter Username:",
"Instant Messenger",
JOptionPane.QUESTION_MESSAGE);
}
public static void main(String[] args){
String username = getUsername();//getting username
SampleClient client;
client = new SampleClient("<IP_ADDRESS>", username); //localhost
client.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
client.startRunning();
}
}
SampleServer.java - does all the server stuff
package sampleserver;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.lang.Object.*;
public class SampleServer extends JFrame{
private JTextField userText; //message variable area
private JTextArea chatWindow; //display the conversation
private ObjectOutputStream output; //output stream->flows from my computer to the other computer
private ObjectInputStream input; //input stream->receive stuff
private ObjectInputStream name; //input stream->receive stuff
private ServerSocket server; //server variable
private Socket connection; //socket variable
private Vector<String> users;
private Vector<String> ips;
private JTextArea conList;
private PrintWriter p;
private BufferedReader fromC;
//constructor
public SampleServer(){
super("Instant Messenger");
userText = new JTextField(); //text field
userText.setEditable(false); //not allowed to type anything if there are no online
userText.addActionListener(
new ActionListener(){
public void actionPerformed (ActionEvent event){
sendMessage(event.getActionCommand()); //sends the message
userText.setText("");
}
}
);
add(userText, BorderLayout.SOUTH);
users = new Vector();
ips = new Vector();
chatWindow = new JTextArea();
conList = new JTextArea();
conList.setEditable(false);
add(new JScrollPane(chatWindow));
add(new JScrollPane(conList), BorderLayout.EAST);
conList.append(" ONLINE USERS \n");
setSize(300, 150);
setVisible(true);
}
//set up and run the server
public void startRunning(){
try {
server = new ServerSocket(6789, 100); //port number and only 100 can connect to the server
while(true){
try{
//connect and have conversation to other client
waitForConnection(); //waiting method
setupStreams(); //set up output and input stream
whileChatting(); //actual chat
}catch(EOFException eofException){
showMessage("\n Server ended the connection!");
}finally {
closeAll();
}
}
}catch(IOException ioException){
ioException.printStackTrace();
}
}
//wait for connection, then display connection information
private void waitForConnection() throws IOException{
showMessage("Waiting for someone to connect...\n");
connection = server.accept(); //once someone asked for connection, accepts this
//showMessage("Now connected to "+connection.getInetAddress().getHostName()); //converts the ip address to string
ips.add(connection.getInetAddress().getHostName()); // adds ip address of client to ips vector
fromC = new BufferedReader(new InputStreamReader(connection.getInputStream())); // gets what client sent through printwriter - username
String s = new String(fromC.readLine()); // saves as string
users.add(s); // saves username of client to users vector
String con = (connection.getInetAddress().getHostName());
showMessage(s + " / " + con + " has connected.");
Iterator c = users.iterator(); // username iterator
Iterator b = ips.iterator(); // ip address iterator
while(c.hasNext()) {
String d = (c.next()).toString(); // gets next element in users vector
String e = (b.next().toString()); // gets next element in ips vector
conList.append(d + "\n"); // displays username in online users list
conList.append("(" + e + ")\n\n"); // displays ip in online users list
}
}
//get stream to send and receive data
private void setupStreams()throws IOException{
output = new ObjectOutputStream(connection.getOutputStream()); //computer who we communicate to
output.flush(); //bytes of information that is send to other person (leftover)
input = new ObjectInputStream(connection.getInputStream()); //receive messages
showMessage("\n Streams are now setup! \n");
}
//actual chat conversation
private void whileChatting() throws IOException{
String message = "You are now connected!";
sendMessage(message);
ableToType(true);
do{
try{
message = (String) input.readObject(); //views it as an object and make sure it's a string
showMessage("\n" + message);
}catch(ClassNotFoundException classNotFoundException){
showMessage("\nError!");
}
}while(!message.equals("CLIENT - END"));
}
//close streams and sockets
private void closeAll(){
showMessage("\n Closing connection... \n");
ableToType(false);
try{
output.close();
input.close();
connection.close();
}catch(IOException ioException){
ioException.printStackTrace();
}
}
//send message to other computer
private void sendMessage(String message){
try{
output.writeObject("SERVER - " +message); //sends the mesage to the output stream
output.flush(); //push extra bytes to user
showMessage("\n SERVER - " + message);
}catch(IOException ioException){
chatWindow.append("\n ERROR!"); //put in the chat area
}
}
//updates chatWindow
private void showMessage(final String text){
SwingUtilities.invokeLater( //updats GUI or threads
new Runnable(){
public void run(){
chatWindow.append(text); //add string at the end of the chatWindow
}
}
);
}
//allow user to type
private void ableToType(final boolean tof){
SwingUtilities.invokeLater( //updats GUI or threads
new Runnable(){
public void run(){
userText.setEditable(tof); //updates the GUI
}
}
);
}
}
serverTest.java
package sampleserver;
import javax.swing.JFrame;
public class serverTest {
public static void main(String[] args){
SampleServer server = new SampleServer();
server.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
server.startRunning();
}
}
The problem is that we have to do a client-client program and what we did was there are 2 laptops, one for opening the client and server and one for only the client. the 2 laptops successfully connected (client-server) but the client of the laptop with the server can't connect to the chat. Though, if the client of the 2nd laptop is closed, the 1st laptop can connect to its server. Help please?
| 997a22ee3de43108c1584302edb2bb58f6ebca05884e885521f2183605e0ce29 | ['37865194ba514fe691ea17ad1eb1b827'] | What our code does right now is there are clients and one server, and the clients can send their messages through the server. The problem is, we need to do client-client, so the client's message must go directly to the other client's chat box. We can only see what they are talking about in the server chatbox not in the clients' chatboxes. Apparently it can only do client-server. Please help? Thanks!
SampleServer.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Kim
*/
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.lang.Object.*;
public class SampleServer{
private ObjectOutputStream output; //output stream->flows from my computer to the other computer
private ObjectInputStream input; //input stream->receive stuff
private ObjectInputStream name; //input stream->receive stuff
private Socket connection; //socket variable
private String user;
private String ip;
private PrintWriter p;
private BufferedReader fromC;
private serverTest server; //Saves the server test to append messages.
//constructor
public SampleServer(Socket c, String username, String userip, serverTest t){ //EDITED!!
connection = c;
server = t;
ip= userip;
user= username;
//setupStreams(); //set up output and input stream
try{
output = new ObjectOutputStream(connection.getOutputStream()); //computer who we communicate to
output.flush(); //bytes of information that is send to other person (leftover)
input = new ObjectInputStream(connection.getInputStream()); //receive messages
showMessage("\n Streams are now setup! \n");
}catch(IOException ioException){
ioException.printStackTrace();
}
}
public void run() //This method gets called when Thread starts running
{
whileChatting();
closeAll();
}
//get stream to send and receive data
private void setupStreams(){
try{
output = new ObjectOutputStream(connection.getOutputStream()); //computer who we communicate to
output.flush(); //bytes of information that is send to other person (leftover)
input = new ObjectInputStream(connection.getInputStream()); //receive messages
showMessage("\n Streams are now setup! \n");
}catch(IOException ioException){
ioException.printStackTrace();
}
}
//actual chat conversation
private void whileChatting(){
String message = "You are now connected!";
sendMessage(message);
do{
try{
message = (String) input.readObject(); //views it as an object and make sure it's a string
showMessage("\n" + message);
}catch(Exception e){
//showMessage("\nError!");
}
}while(!message.equals("CLIENT - END"));
}
//close streams and sockets
public void closeAll(){
showMessage("\n Closing connection... \n");
try{
output.close();
input.close();
connection.close();
}catch(IOException ioException){
ioException.printStackTrace();
}
}
//send message to other computer
public void sendMessage(String message){
try{
output.writeObject("SERVER - " +message); //sends the mesage to the output stream
output.flush(); //push extra bytes to user
}catch(IOException ioException){
showMessage("\n ERROR!"); //put in the chat area
}
}
//updates chatWindow
private void showMessage(String text){
server.showMessage(text);
}
}
ServerTest.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Kim
*/
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.lang.Object.*;
public class serverTest extends JFrame {
private JTextField userText; //message variable area
private JTextArea chatWindow; //display the conversation
private ServerSocket server; //server variable
private Vector<String> users;
private Vector<String> ips;
private JTextArea conList;
private ArrayList<SampleServer> connections = new ArrayList<SampleServer>();
public static void main(String[] args){
new serverTest();
}
public serverTest()
{
super("Instant Messenger");
userText = new JTextField(); //text field
userText.addActionListener(
new ActionListener(){
public void actionPerformed (ActionEvent event){
sendMessage(event.getActionCommand()); //sends the message
userText.setText("");
}
}
);
add(userText, BorderLayout.SOUTH);
users = new Vector();
ips = new Vector();
chatWindow = new JTextArea();
conList = new JTextArea();
conList.setEditable(false);
add(new JScrollPane(chatWindow));
add(new JScrollPane(conList), BorderLayout.EAST);
conList.append(" ONLINE USERS \n");
setSize(300, 150);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
try {
server = new ServerSocket(6789, 100); //port number and only 100 can connect to the server
while(true){
try{
showMessage("Waiting for someone to connect...\n");
Socket connection = server.accept(); //once someone asked for connection, accepts this
//showMessage("Now connected to "+connection.getInetAddress().getHostName()); //converts the ip address to string
ips.add(connection.getInetAddress().getHostName()); // adds ip address of client to ips vector
BufferedReader fromC = new BufferedReader(new InputStreamReader(connection.getInputStream())); // gets what client sent through printwriter - username
String s = new String(fromC.readLine()); // saves as string
users.add(s); // saves username of client to users vector
String con = (connection.getInetAddress().getHostName());
showMessage(s + " / " + con + " has connected.");
Iterator c = users.iterator(); // username iterator
Iterator b = ips.iterator(); // ip address iterator
conList.setText("");
while(c.hasNext()) {
String d = (c.next()).toString(); // gets next element in users vector
String e = (b.next().toString()); // gets next element in ips vector
conList.append(d + "\n"); // displays username in online users list
conList.append("(" + e + ")\n\n"); // displays ip in online users list
}
final SampleServer se = new SampleServer(connection, s, con, this);
Thread t = new Thread(new Runnable(){
public void run()
{
se.run();
}
});
t.start();
connections.add(se);
}catch(EOFException eofException){
showMessage("\n Server ended the connection!");
}
}
}catch(IOException ioException){
ioException.printStackTrace();
}
}
public void closeAll()
{
while (!connections.isEmpty())
{
connections.get(0).closeAll();
connections.remove(0);
}
}
public void sendMessage(String text)
{
showMessage("\n SERVER - " + text);
for (SampleServer s : connections)
{
s.sendMessage(text);
}
}
public void showMessage(final String text)
{
SwingUtilities.invokeLater( //updats GUI or threads
new Runnable(){
public void run(){
chatWindow.append(text); //add string at the end of the chatWindow
}
}
);
}
}
clientTest.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Kim
*/
import javax.swing.*;
public class clientTest {
public String userName;
private static JFrame frame = new JFrame("Messenger");
private static String getUsername() {
return JOptionPane.showInputDialog(
frame,
"Enter Username:",
"Instant Messenger",
JOptionPane.QUESTION_MESSAGE);
}
public static void main(String[] args){
String username = getUsername();//getting username
SampleClient client;
client = new SampleClient("localhost", username); //localhost
client.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
client.startRunning();
}
}
sampleClient.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Kim
*/
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SampleClient extends JFrame{
private JTextField userText;
private JTextArea chatWindow;
private ObjectOutputStream user;
private ObjectOutputStream output;
private ObjectInputStream input; //from the server
private String message = "";
private String serverIP;
private Socket connection;
private String name;
private JTextArea contacts;
private PrintWriter toS;
//constructor
public SampleClient(String host, String username){
super("Client");
serverIP = host;
name = username;
userText = new JTextField();
userText.setEditable(false); //not allowed to type while no one is connected
userText.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
sendMessage(event.getActionCommand());
userText.setText("");
}
}
);
add(userText, BorderLayout.SOUTH);
contacts = new JTextArea();
chatWindow = new JTextArea();
add(new JScrollPane(contacts), BorderLayout.EAST); //scroll
contacts.append(" ONLINE CONTACTS \n");
add(new JScrollPane(chatWindow), BorderLayout.CENTER); //scroll
setSize(300, 150);
setVisible(true);
}
//connect to server
public void startRunning(){
try {
connectServer();
setupStreams();
whileChatting();
}catch(EOFException eofException){
showMessage("\n Client terminated connection");
}catch (IOException ioException){
ioException.printStackTrace();
}finally{
closeAll();
}
}
//connectServer
private void connectServer() throws IOException{
showMessage("Attempting connection... \n");
connection = new Socket(InetAddress.getByName(serverIP), 6789); //passes to an IP Adrdress and Port Number
showMessage("Connected to:" + connection.getInetAddress().getHostName()); //prompt
toS = new PrintWriter(connection.getOutputStream(), true);
toS.println(name);
}
//set up streams for sending and receive the messages
private void setupStreams()throws IOException{
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream()); //receive messages
showMessage("\n Streams are connected");
}
//actual chat
private void whileChatting()throws IOException{
ableToType(true);
do{
try{
message = (String) input.readObject();
showMessage("\n" +message);
}catch(ClassNotFoundException classNotFoundException){
showMessage("\n ERROR!");
}
}while(!message.equals("SERVER - END"));
}
//close sockets and streams
private void closeAll(){
showMessage("\n Closing connections..");
ableToType(false);
try{
output.close();
input.close();
connection.close();
}catch(IOException ioException){
ioException.printStackTrace();
}
}
//send messages to server
private void sendMessage(String message){
try{
output.writeObject( "\n" + name + ": " + message);
output.flush(); //push bytes
showMessage("\n" + name + ": " + message);
}catch(IOException ioException){
chatWindow.append("ERROR!");
}
}
//Update chatWindow
private void showMessage(final String m){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
chatWindow.append(m); //appear at the end of the conversation
}
}
);
}
//permission to type to for user
private void ableToType(final boolean tof){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
userText.setEditable(tof);
}
}
);
}
}
|
7c13908504b7e55591c6c39bb02aee8ee9cbfbb95982c86e959640876977fb8e | ['379148df0e2544709c3ed34ff9ccea01'] | Service Proxy does not handle the Actor references like Actor Proxy does. Services stack is independent of the actor and does not have knowledge of the actor references. Instead of passing the actor interface, you can pass the actor reference (https://msdn.microsoft.com/en-us/library/azure/microsoft.servicefabric.actors.actorreference.get.aspx) and then bind (https://msdn.microsoft.com/en-us/library/azure/microsoft.servicefabric.actors.actorreference.bind.aspx) the actor reference to the actor interface type on the receiving side. You can cast the output of the binding method to the actor interface.
| e97b8930f322d48da02602504225401c043a582a3b7cac6a765544e0653ceb57 | ['379148df0e2544709c3ed34ff9ccea01'] | ActorProxy and ServiceProxy today works best for connecting to actors and services within the cluster. You can expose a stateless service with -1 instance count that can accept the user requests and then use Actor and Service remoting to connect to the actor service within the cluster. In the future release we may offer out of the box application gateway that supports remoting.
|
f62329b850db27b618af65a7a2208d7c286567d42ee61e4b1cbf953b89511872 | ['37b00aaa733c4f5aaef6fffa93c27e35'] | I am stumbling over exact same situation, usung KUbuntu 11.04.
(And me once was used emacs, not vim. So looking at those 3split console was surprising for me, too.)
Now I did hg rollback and installed me merger gui tool KDiff3 .
Then looking into "howto get this gui merger tool activated within the hg merge?"
hg help merge
Tells me what to do...
which kdiff3
/usr/bin/kdiff3
So I added to ~/.profile
export HGMERGE="/usr/bin/kdiff3"
Then all was done.
In a new shell hg merge popped me up with the gui merger tool KDiff3, see handbook-pdf http://kdiff3.sourceforge.net/doc/kdiff3_de.pdf
| a67a102cee68c3bc660058d2ba1006fca9e3a7bc404494f56552b86e3b0c2132 | ['37b00aaa733c4f5aaef6fffa93c27e35'] | I think it's worth mentioning you are using python2.
#!/usr/bin/env python2
j = {'a': 1.0}
k = {'c': 3.0}
p = {'e': j, 'f': k}
for v in p.itervalues():
print "v before inplace updates:", v
for k, v_inside in v.items():
print "v[k] before inplace change", v[k]
v[k] = {key: value / 3.0 for key, value in v.items()}
print "v[k] after inplace change", v[k]
print "p after inplace edits:\n", p
Produces this output:
v before inplace updates: {'a': 1.0}
v[k] before inplace change 1.0
v[k] after inplace change {'a': 0.3333333333333333}
v before inplace updates: {'c': 3.0}
v[k] before inplace change 3.0
v[k] after inplace change {'c': 1.0}
p after inplace edits:
{'e': {'a': {'a': 0.3333333333333333}}, 'f': {'c': {'c': 1.0}}}
|
7dc60f16bebea10a3446af78ce9e268c195ad94bfc27429bc4422ebf5b54f512 | ['37b24abe6d2149a5832249b6a64d4d3b'] | I need to build an application which will have an admin area where admin can create forms and assign validation rules. I can use either laravel or cakephp for this application.
What is the best way to do this? Should I create tables and models separately for each admin created form or should I use a master table to store admin created form fields?
| e2c850ab6543078075881ca7999ed20e6e1fb54dcf46b4bef4a5218d4d696e30 | ['37b24abe6d2149a5832249b6a64d4d3b'] | I had faced a similar problem. It's possible to save the flann index to disk in OpenCV, but EmguCV doesn't wrap all the functions of OpenCV. The save() and load() functions of Index class are missing in EmguCV.
The solution is to download the EmguCV source code from GIT repository, add the missing functions to it and then recompile the binaries.
You can find the Index wrapper files in cvextern project which is available in the EmguCV repository.
|
99bc07d702cca3d12a4ad35dfb1d147dc23dc03d200ff13b88e08976b9704995 | ['37be8cbeff0c4ac4bbbc26f71189c81f'] | I have three verbs that describe your friend's feeling or attitude:
disparage: (vt) regard or represent as being of little worth.
Disparage is most commonly used to refer to how someone speaks or writes of something, but it does include the thought or feeling as well.
undervalue: (vt) rate (something) insufficiently highly; fail to appreciate.
Included in the use of this word is the belief that the thing someone undervalues does indeed have value.
vilipend: (vt) regard as worthless or of little value; despise.
Not as common as the other two, but apt, and somewhat sinister.
If you are looking for an adjective, then you might try:
disdainful: (adj) showing contempt or lack of respect.
Or there's also:
contemptuous: (adj) showing contempt; scornful.
| 75f2f2becfdbfc3efe67b5abd33a1a5e6ec7864dbdb7c217875e4dbc0b8dddea | ['37be8cbeff0c4ac4bbbc26f71189c81f'] | You've indicated three general meanings that might apply to some, but not all, of the more specific meanings I listed in the initial question (how to account for "possibly," "quite or very," and "directly"?). Also, I find it interesting that two of the general ideas you've indicated contradict each other: "neither more nor less" and "a little more or less." That's worth a question in and of itself. So, yeah, a little disappointed. :) |
fbdd46e980e2005dab451a96c95643fe5e1a3165e30475a401c6bdbd387a0d76 | ['37d1a5cfaf7943d7927b025fee984bed'] | Im using page with RadAjaxManager and RadComboBox on it.
<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server"
DefaultLoadingPanelID="RadAjaxLoadingPanel1" EnablePageHeadUpdate="False">
<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="_Partners" >
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="_SubPartners" />
<telerik:AjaxUpdatedControl ControlID="_Clients" />
<telerik:AjaxUpdatedControl ControlID="_Positions" />
<telerik:AjaxUpdatedControl ControlID="_Candidates" />
</UpdatedControls>
</telerik:AjaxSetting>
<telerik:AjaxSetting AjaxControlID="_Candidates">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="rpCandidateApplications" />
</UpdatedControls>
</telerik:AjaxSetting>
<telerik:AjaxSetting AjaxControlID="_SubPartners">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="_Clients" />
<telerik:AjaxUpdatedControl ControlID="_Candidates" />
<telerik:AjaxUpdatedControl ControlID="_Positions" />
</UpdatedControls>
</telerik:AjaxSetting>
I have large data binding , but it loads data very slow and my client is complnaing about performance.Any help would be appreciated!
| 7b157636a6bbb9d7ed5b32b81b47fcd8ab3d188ef83cfd420c20ed1fe69ae20b | ['37d1a5cfaf7943d7927b025fee984bed'] | I'm developing add-in for Outlook 2013,I'm struggling with PR_INTERNET_MESSAGE_ID , I could easily get PR_INTERNET_MESSAGE_ID on archiving incoming mails, but it returns nothing on sending mail.
Any help would be appreciated!
Thank you!
here is my code
string PR_INTERNET_MESSAGE_ID = "http://schemas.microsoft.com/mapi/proptag/0x1035001F";
Microsoft.Office.Interop.Outlook.PropertyAccessor pal = mailItem.PropertyAccessor;
string Internet_Message_Id = pal.GetProperty(PR_INTERNET_MESSAGE_ID).ToString();
|
afd45ce76e053d2c5049fbe04c3269588528fd0aa158cd92410737ccde906adf | ['37d528f1ec554220b9364f8e056f910d'] | Yes.
Sencha touch can be used to develop on all three platforms.
The same application can be built into multiple platforms using cordova/phonegap. Using sencha touch, we can maintain a single code base and multiple apps .
And yes, you can package and publish it to windows store to run it as a windows application.
Abhi.
| c840e96ac2698888467a224d57753507284bd6b95b7415d0a3a84dcf8b9b768c | ['37d528f1ec554220b9364f8e056f910d'] | I want to check form the javascript if a browser's auto-update is enabled.
The reason I want this is that our software supports only a set of Browser versions and we want to alert them if auto-update is on.
Is there any way we can do this?
<PERSON>
|
98b5716e4a8e33e93ca5029216f2be24a88a9f5a4a8eb891c899fa9ad207351f | ['37e1a4092c724272938b979186cbbf3c'] | This is boolean that check service is running or not.
I can't use this in onCreate.
CODE:
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (ser.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
How to check boolean in onCreate?
| 3a0bac0c273d212c8da75141c7b63b91b4655cab7bb066f3124ae2450004a989 | ['37e1a4092c724272938b979186cbbf3c'] | I am working on a download project.I want to pass a string value in activity to anywhere in same Activity
My request: when I click the button,String str pass to DownloadFromURL class and get the string
Please help me
code:
public class FirstActivity extends Activity {
Button btnShow;
Intent i;
public static final int progress_bar_type = 0;
private static String file_url = "http://api.androidhive.info/progressdialog/hive.jpg";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnShow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String str = "file";//Value that I want to pass to DownloadFromURL class
new DownloadFileFromURL().execute(file_url);
}
});
}
class DownloadFileFromURL extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(), 8192);
String res = "";//This should String that I want to get from FirstClass
OutputStream output = new FileOutputStream("/sdcard/"+res+".jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
}
|
d7d7198e985cfe5afd7378cefabb4b47a523a086092fa3f990263f1f9f250cd5 | ['37e9a476c2294a0da63c714796c0648b'] | I have a standalone application in Eclipse 4 RCP.
When exporting it as a product, as shown below:
The following structure is generated:
How to change the icon of the executable aplicacao.exe?
I already tried to put images in the Launching tab of the .product file, but without success.
| 634f6922ce5272bd1fd1452599ad70e905ea806d97cbb2c314a4e65849e5c410 | ['37e9a476c2294a0da63c714796c0648b'] | The indicatorStyle exists only in TopTabNavigator. See docs below:
Top tabBarOptions:
https://reactnavigation.org/docs/material-top-tab-navigator#tabbaroptions
Bottom tabBarOptions:
https://reactnavigation.org/docs/bottom-tab-navigator/#tabbaroptions
In the TopTabNavigator, the indicator line is displayed for default. Currently has a bug in React Navigation... When set the tabStyle backgroundColor, the indicator line disappears. See issue below:
https://github.com/react-navigation/react-navigation/issues/8012
|
7e85400b954f9feaa4c94162cd86942f42be3852cd7bb6389b0ce5256883899d | ['37f4503d3d064d5b96dfa18e85260442'] | I see how you get -7 + j17 by distribution. Why don't we get the same result when we pass through polar form though? When two polar form phasors are multiplied, we multiply their magnitude and add their angles. Why isn't this working here? I feel like I'm missing something very basic here. | fee406a615f07a4cdf5250409c302338ee989b2cf7cf3648b0f021b7e6f58b14 | ['37f4503d3d064d5b96dfa18e85260442'] | What I can add after some more reading and thinking, is that "image, providing maximum activations for a neiron" implies that the net (by means of backpropagation) will try to go through most efficient way and even through several ways in parallel if possible.
Convolution of previous layer's neirons recognizing eye, body and fin will be maximum when they are at right positions relatively to each other. So the net is limited with minimum size of a pattern.
Convolution coefficients are something like -0.5, 1, 0.5 (I simplify 3*3 convolution to 1D). This means like "not here", "ideally here", "ok if here". So if previous layer's neiron has > 0 at both places 1 and 2, so the image will contain maybe 2 fins, this will give even higher activations. So generally the net will try to push maximum patterns into a given space (e.g. 224*224 pixels).
Maybe on infinite input image we would see identical repeating patterns, but in real life paddings at corners and so on limit them and make different.
So now I think positions on the generated images don't mean that they were such on source images, maybe a bit, indirectly, as a side effect of adjusting to corner effects. But the colors and pattern sizes has to reflect source images.
It's interesting why they are so noisy... First layers' convolutions are usually quite smooth...
|
acf9c1712b97fee4c2d8379ecef41e324e724e5e76e2e6619e4ec2e4f4d8aabf | ['37f61a2e8bd643bd82172d518f331449'] | I want to make a dropdown menu with the following options. I want be able to select a select multiple value for option A, B, and C, but disable multiple selection if option D is selected. How can I do that? Thanks.
<label>Choose an option:</label>
<select required multiple>
<option>Please select</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">C</option>
</select>
| adf96a4da66100d3841bd89663d26703a6c1a4677578903e8b237bed3c69229a | ['37f61a2e8bd643bd82172d518f331449'] | I have a dropdownlist with data loaded from MySQL database. The data.list was the list of data produced by a SQL query in node.js. Each record has a ID and a name. I want to set a default selection where the selected name is "<PERSON>". The code below generates a dropdown where all options are selected instead of the option with name "<PERSON>". Is there any way that I can achieve this by javascript? Thanks.
HTML Code with javascript:
<select id="mySelect" name="mySel" size =20 multiple>
<% if(data.list) { %>
<% data.list.forEach(function (row) { %>
<option value="<%= row.ID %>" <% row.name %> === "<PERSON>" ? selected = true : false><%= row.name %></option>
<% }) %>
<% } %>
</select>
|
38e9a1e40d5e281512383eadcaf4a5401b594de5ff2311aa75765ecde6ef35b6 | ['38075be0b70a444bacce2ab452d989df'] | I am working on a basic code - my aim is to use gender_guesser.detector to find the gender for rows in a dataframe where the imported file (from CSV) would be missing those values. For simplicity, I just created a dummy dataframe in the code below.
I am pretty new to Python and very much in the learning phase so I assume that there are definitely more elegant solutions to what I am trying to do. My idea was to add a new column, find the values for each row using the above mentioned function and then fill out the NaN values while keeping the original gender values where applicable (dropping the temp column once it's done).
The d.get_gender part works if I manually apply it to a specific row and Jupyter accepts the function as well.
df = pd.DataFrame([['Adam','Smith',''],['Lindsay','Jackson','M'],['Laura','Jones','F'],['Arthur','Jackson','']] ,columns=['first_name','last_name','gender'])
import gender_guesser.detector as gender
df['newgender']=""
def findgender(dataframe):
for row in dataframe:
d = gender.Detector()
df.loc[row, 'newgender'] = d.get_gender(df.loc[row,'first_name'])
return df
df.apply(findgender, axis=1)
When I then try to apply this to my dataframe, I get a lengthy error message, the last line being
KeyError: ('<PERSON>', 'occurred at index 0')
I tried to look up similar posts here but for most, adding axis=1 solved the issue - as I already have it, I am clueless why the code is not working.
Any help or explanation on why the issue is occurring would be extremely helpful.
| 915ff49cac49f553f31c06eeb92f1d1d4f508cafc1437decc9162eabefd37e0e | ['38075be0b70a444bacce2ab452d989df'] | I am trying to create a summary table from a dataframe that looks like below example. The columns have a set list of unique values.
tdf = pd.DataFrame({"A": ["ind1", "ind2", "ind1", "ind3", "ind3", "ind1", "ind1"],
"B": ["ind3", "ind1", "ind3", "ind1", "ind1","ind3", "ind2"],
"C": ["ind1","ind1","ind2","ind2","ind3","ind3","ind3"],
"D": ["ind3","ind1","ind2","ind3","ind2","ind1","ind3"],
"E": ["ind1","ind3","ind1","ind1","ind2","ind2","ind2"]})
I'd then need to create a new table-like object that has a header that correspond to the columns and 3 rows with frequency counts of the set index values.
setvalues = ['ind1','ind2','ind3']
result = pd.DataFrame({"A": [4,1,2],
"B": [3,1,3],
"C": [2,2,3],
"D": [2,2,3],
"E": [3,3,1]})
I tried pivot tables but it wasn't returning the required format. In Excel I could just set the index values and do a simple COUNTIF on the columns but I am struggling to implement it in Python.
|
e84722c383e35a014a5f7b0615273d6bda88de38e411cdad3fbb19a8cf4b4725 | ['3819857a923641108ad4feb98f35e478'] | strtok() stores the pointer in static variable where did you last time left off , so on its 2nd call , when we pass the null , strtok() gets the pointer from the static variable .
If you provide the same string name , it again starts from beginning.
Moreover strtok() is destructive i.e. it make changes to the orignal string. so make sure you always have a copy of orignal one.
One more problem of using strtok() is that as it stores the address in static variables , in multithreaded programming calling strtok() more than once will cause an error. For this use strtok_r().
| 2146748ead4656689e4e77167c5feab45445b40f62c3e4b0fe617b85e2022862 | ['3819857a923641108ad4feb98f35e478'] | strtok() stores the pointer in static variable where did you last time left off , so on its 2nd call , when we pass the null , strtok() gets the pointer from the static variable .
If you provide the same string name , it again starts from beginning.
Moreover strtok() is destructive i.e. it make changes to the orignal string.
so make sure you always have a copy of orignal one.
One more problem of using strtok() is that as it stores the address in static variables , in multithreaded programming calling strtok() more than once will cause an error.
For this use strtok_r().
|
8b3cc3812dbac3e12c09b7386a903a5c6eb6fbcd2109253f9d3ede4f037ef834 | ['38302f2de5344027a103778b6b8ef925'] | try {
String[] tab = null;
String line = null;
tab = line.split("-");
int countLoss = Integer.parseInt(tab[3]+plusLoss);
int countWin = Integer.parseInt(tab[2]+plusWin);
int countTie = Integer.parseInt(tab[4]+plusTie);
BufferedReader br = new BufferedReader(new FileReader("users.txt"));
StringBuilder sb = new StringBuilder();
String zlepek = "";
while ((line = br.readLine()) != null) {
if(tab[0].equals(loginUser.user)) {
String newScore = (tab[0] + "-" + tab[1] + "-" + countWin + "-" + countLoss + "-" + countTie + "\n");
zlepek = zlepek+newScore;
} else {
String oldScore = (tab[0] + "-" + tab[1] + "-" + tab[2] + "-" + tab[3] + "-" + tab[4] + "\n");
zlepek = zlepek+oldScore;
}
sb.append(zlepek).append("\n");
}
br.close();
PrintWriter pw = new PrintWriter(new FileWriter("users.txt")); // pass true to append
pw.print(sb);
pw.close();
plusWin = 0;
plusLoss = 0;
plusTie = 0;
} catch(IOException e) {}
}
| e27feddb851b3f4c0c50e917b86a5af136b8f261d5c4ea681702ffcf4ac36cb1 | ['38302f2de5344027a103778b6b8ef925'] | #NoEnv
#SingleInstance force
#Persistent
SetTimer, CheckIdle, 5000
CheckIdle:
If ( A_TimeIdle > 15000 ) {
ControlSend,, {space}, WindowTitle
}
Return
This is my code and I'm sure I got everything correct, but it seems to send the keystrokes every 5 seconds, which is the interval set in the timer.
It's behaving like the if statement is always true and it doesn't reset A_TimeIdle.
Can someone help?
|
fdb104dfae10593769473cf9aac89614888c9f7e11125c53cfb14aeb3f02ea4c | ['3834d8d6401c4a4b8c8511ffbfbaed75'] | The NewSeries command returns the new series. Even though Add states that it returns a series that it adds to the collection it does not. The documentation may be what is causing your confusion here. Check out this MSDN article on the subject: http://msdn.microsoft.com/en-us/library/ff194065.aspx
| 53412273f2f0cced6158c8e63cc2027380cf91147072c340e56ea471a7d788aa | ['3834d8d6401c4a4b8c8511ffbfbaed75'] | The easiest way that I've seen to do encryption is through RSA
Check out the MSDN on it: http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsacryptoserviceprovider.aspx
It does involve using bytes, but when it comes down to it you kind of do want encryption and decryption to be tough to figure out otherwise it will be easy to hack.
|
f2ca6cbc4c866eb46d263729a3363b17d5ce96a6636291e86d375e2e67b95eb2 | ['383c52f2c4664d759548c1b76301b9b5'] | I have a form my drivers complete where part of the form is related to fueling. There is a possibility of 6 separate fuel stops. Each fuel stop line has input where gallons and cost are also included. By default the Cost and Gallons purchased cost is set to $0.00.
My reason for asking assistance:
Occasionally the drivers will inadvertently clicks into one of the date fields on a fueling line and the date will auto populate with the then current date (which can be changed). Then the rest of that line remains all zeros.
I am trying to figure out a validation script that will put the date field back to NULL preferably (or blank) if the Fuel Purchase Cost is at $0.00 as well as the DEF Purchase Cost is also $0.00. BOTH of these items need to be true. Additionally I am not sure how to keep the user inputted DATE if FUEL_PURCH_STOP_1 is >0 AND DEF_PURCH_STOP_1 >0.
NOTE: Fueling will always span 2-3 days.
My end goal is... If a driver clicks in the date field inadvertently, the current date is auto populated. Then if there is a "0" in the both the FUEL_PURCH_STOP_1 AND DEF_PURCH_STOP_1 fields then remove the date from that line. If either one or both of the two fields have a value >0 then I want to keep the user inputted date in the field.
I tried:
var v1 = +getField("FUEL_PURCH_STOP_1").value;
var v2 = +getField("DEF_PURCH_STOP_1").value;
// Set this field's value
if v1 >0 andalso v2 >0) {
event.valueAsString === "WHAT GOES HERE??";
} else {
event.valueAsString === "";
}
| 0a14fa4ccbe20a7706f3876f4c91f515a05078d51348b79bf9e7b57bf7fbfb2b | ['383c52f2c4664d759548c1b76301b9b5'] | I have a group of radio buttons (3) that populates the correct one for each record based on the input of the Database.
The Data column it reads will have only one of three values: 'SLSC', 'SLDC', 'DLDC'.
Based on that, one radio button of the three options will be checked on the record. This worked fine until I changed the style of radio buttons being used. I changed from the default vb radio button to the SkinRadioButton class however I kept the original naming convention for each radio button.
During debug; I receive the proper response from the database, say for example the DB returns 'SLSC' as the value. In my SELECT CASE section it shows DvrResp = SLSC yet fails to see the true statement and no radio button is set to true (or ticked). It simple looks at the 3 cases and then executes the CASE ELSE and moves on. Would changing to SkinRadioButton seriously cause this piece of code to now not function as it once did? Is anyone able to advise why that would be and what I need to do to correct this please?
CODE:
Private Sub LoadResp()
Dim cmd As New SqlCommand
Dim reader As SqlDataReader
Try
cmd.Parameters.Clear()
cmd.CommandText = "SELECT DRIVER_COUNT
FROM LOAD_INFO_TABLE
WHERE PETS_LOAD_NUMBER = @dc"
cmd.Parameters.AddWithValue("@dc", tbPetsLoadNumber.Text)
cmd.CommandType = CommandType.Text
cmd.Connection = New SqlConnection With {
.ConnectionString = My.MySettings.Default.MY_DatabaseConnectionString
}
cmd.Connection.Open()
Try
reader = cmd.ExecuteReader()
Dim DvrResp As String
With reader
.Read()
DvrResp = .GetString(0)
Select Case True
Case DvrResp = "SLSC"
rbSLSC.Checked = True
rbSLSC.BackColor = Color.Yellow
rbSLDC.BackColor = Color.Transparent
rbDLDC.BackColor = Color.Transparent
Case DvrResp = "SLDC"
rbSLDC.Checked = True
rbSLSC.BackColor = Color.Transparent
rbSLDC.BackColor = Color.Yellow
rbDLDC.BackColor = Color.Transparent
Case DvrResp = "DLDC"
rbDLDC.Checked = True
rbSLSC.BackColor = Color.Transparent
rbSLDC.BackColor = Color.Transparent
rbDLDC.BackColor = Color.Yellow
Case Else
Exit Select
End Select
Return
End With
reader.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
cmd.Connection.Close()
End Sub
|
e2055bd803d8dbed9dfe6495b5993b368234bcf3dabf60a71a9e6521f5f661a1 | ['383fdb2a2abd4f579d84bc55802dd7f3'] | I have a WordPress Website that currently uses its own authentication.
I am building a new web app on React which would be on its sub-domain.
I will be using AWS Cognito for authentication.
Now I want to enable a single sign-on between the Wordpress site and the React App via Cognito.
i.e user logs in to the Wordpress site and when he navigates to the react app, he does not have to login again.
Please suggest how to achieve this.
| 7c6812bc913e8df869ea078de7512a41f330bd1c2e979ad73af2a3627f59a1da | ['383fdb2a2abd4f579d84bc55802dd7f3'] | When the node server is running locally, this seems to work fine.
But when then code is deployed on ec2 instance, I get:
"User: arn:aws:sts<IP_ADDRESS>XXXX:assumed-role/aws-elasticbeanstalk-ec2-role/i-XXX is not authorized to perform: cognito-idp:AdminDeleteUser on resource: arn:aws:cognito-idp:ap-south-1:XXXX:userpool/XXXX"
Any help will be appreciated
|
9fd801774aae6530679588c48a4c5a896e2917fdf05d4bd0789be91660aaf2ea | ['38480790716f48ed8f572c0363ca2f25'] | I would like to read an image and then change its format but without saving it.
For example I can read the image like this
BufferedImage img=ImageIO.read(new File(fileName));
Then I want to change the format of img, for example from jpeg to png.
The only way I found is to use ImageIO.read to write and then read the new image, but it does seem to be an efficient way to do it.
| 38cfd66b839ec484a6ff7f034447420f88d947cf8875b6eb3518cce4f2393e5d | ['38480790716f48ed8f572c0363ca2f25'] | All implementation of <PERSON>'s algorithms I have seen do not have a recursive function, but I have also read that by definition dynamic programming is an algorithm with a recursive function and "memory" of things already calculated.
So is <PERSON>'s algorithm with a loop qualified as dynamic programming?Or in order to qualify as dynamic algorithm I have to change a loop into a recursive function.
|
3417a0146e52b9b21d5de83dacdabbdc404b13cba8fc67dee31a9a397ac48c44 | ['385fe459e7304829ae100fe7398344cc'] | The question is to find the general solution in integers $x,y,z$ to $$2x+3y+5z=7$$ where none of $x,y$ or $z$ are divisible by $7$.
Without the divisible by $7$ condition I found that the general solution is $$(x,y,z)=(3t+5z-7,7-5z-2t,z)$$ where $t,z$ are arbitrary integers. I have no idea how to deal with the condition though?
| 7dbb336d00d64116dd50e11397075a1eab4c5d0e4177916f4c62523cee0a2679 | ['385fe459e7304829ae100fe7398344cc'] | DON'T "READ THIS" by Robert. READ THIS: Maybe it's because above answers are 5 years old, but with most new wireless routers, the correct setup is very different and much easier! I tried the above solutions but they did not work correctly. What worked was an expanded version of this: http://www.linksys.com/us/support-article?articleNum=143751
Disconnect LANs between SMC modem and DLinks.
On SMC modem: setup its IP as <IP_ADDRESS>, Subnet Mask as <IP_ADDRESS>, turn on DHCP server, make sure IP range is starting from 2 or more. If you can setup "DHCP Reservation", do it - reserve 192.168.0.2 for the first DLink, and 192.168.0.3 for the second DLink.
On both DLinks: change "Type of Internet Connection" to "Bridge Mode", select manual IP settings for Bridge Mode. Set Gateway to 192.168.0.1, set Subnet Mask to 255.255.255.0, and IP address accordingly: on first DLink to <IP_ADDRESS><PERSON>. READ THIS: Maybe it's because above answers are 5 years old, but with most new wireless routers, the correct setup is very different and much easier! I tried the above solutions but they did not work correctly. What worked was an expanded version of this: http://www.linksys.com/us/support-article?articleNum=143751
Disconnect LANs between SMC modem and DLinks.
On SMC modem: setup its IP as 192.168.0.1, Subnet Mask as 255.255.255.0, turn on DHCP server, make sure IP range is starting from 2 or more. If you can setup "DHCP Reservation", do it - reserve <IP_ADDRESS> for the first DLink, and <IP_ADDRESS> for the second DLink.
On both DLinks: change "Type of Internet Connection" to "Bridge Mode", select manual IP settings for Bridge Mode. Set Gateway to <IP_ADDRESS>, set Subnet Mask to <IP_ADDRESS>, and IP address accordingly: on first DLink to 192.168.0.2, on second DLink to <IP_ADDRESS><PHONE_NUMBER>, turn on DHCP server, make sure IP range is starting from 2 or more. If you can setup "DHCP Reservation", do it - reserve 192.168.0.2 for the first DLink, and 192.168.0.3 for the second DLink.
On both DLinks: change "Type of Internet Connection" to "Bridge Mode", select manual IP settings for Bridge Mode. Set Gateway to 192.168.0.1, set Subnet Mask to <PHONE_NUMBER>, and IP address accordingly: on first DLink to 192.168.0.2, on second DLink to 192.168.0.3
On both DLinks: set identical WiFi settings - the same SSID, password etc. However, set channel manually - first DLink ch1, second DLink ch11.
Turn off DLinks.
Cables: Connect LAN slot #1 on SMC modem to WAN slot on first DLink. Connect LAN slot #2 on SMC modem to WAN slot on second DLink.
Power up DLinks.
Enjoy.
|
111517bf5c75e80b98111087e2e2d9874107ea7c2eafbf8aeb818781c9e5e0fa | ['386f20f204404e369bdac25ead750995'] | There are many adaptations of Pranayama. @ Uday it is wrong to say there is only one form of Pranayama. The basics are the same - inhale deeply, hold for a while and exhale. The most common forms are inhaling and exhaling through alternate nostrils. Brammari Pranyama is another common form wherein the exercise is done while making a sound like humming of bees. There are still other variations. | 6e25f7b19e2caea15c1eafc072725ebe713fa41c594ecc2ebec6d311eb682cca | ['386f20f204404e369bdac25ead750995'] | An interesting aside - in Zorastrianism - Good and God is Asura and the evil Deivas. Their Gor is <PERSON> - Parsee (Farsi) does not have the alphabet 'sa' instead they use 'ha' - so is God then an Asura? and now the query about how deities called 'Asuras' in rig Veda became Demons!!!! Interesting! |
9b0aae0f1a9d11927f039da71af8422c58872d9eae12f43bfa7cfacfb98c9728 | ['386f68078ed541e78c41282ba90ba749'] | I have a Company model and I want to update the Company record and save a list of phone numbers all at once. There is a 1-* relationship.
My ViewModel looks like:
public class CompanyRegisterViewModel
{
public int CompanyId { get; set; }
public int CompanyTypeId { get; set; }
public IEnumerable<SelectListItem> CompanyTypes { get; set; }
[Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(ValidationStringResource))]
[MaxLength(250, ErrorMessageResourceName = "MaximumLength", ErrorMessageResourceType = typeof(ValidationStringResource))]
public string LicensedCompanyName { get; set; }
public List<Phone> Phones { get; set; }
}
In my Save(Company company) method, if I call:
_context.Companies.Add(company);
_context.SaveChanges();
Will this save a new company record and save the List<Phone> Phones or do I need a transaction and call SaveChanges() again to save the Phones. I also need to set CreatedBy and DateCreated for each Phone record. Should I loop through the Phone records prior to saving and update each record in a foreach loop? I want this set automatically in the backend, not in the UI.
| 9505ab9630ad7af4d554032f76fa6c79326e55682011f57b27178c274d4b6686 | ['386f68078ed541e78c41282ba90ba749'] | I figured it out. I was setting the defaultPageSize in the wrong constructor, so the variable was never getting set, causing the page size to be 0.
int defaultPageSize;
private IInventoryRepository inventoryRepository;
public InventoryController()
{
this.inventoryRepository = new InventoryRepository(new MovieContext());
this.defaultPageSize = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["defaultPageSize"]);
}
public InventoryController(IInventoryRepository inventoryRepository)
{
this.inventoryRepository = inventoryRepository;
this.defaultPageSize = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["defaultPageSize"]);
}
|
e54cc5fad48431ef14847811f1fbda9ed6ea6a31fc0fd6bc116f4783c65b6410 | ['3873bb16ed4145b9a01bcb374557c44b'] | Lets say I malloc some struct inside a kernel where I performed some calculation upon. I then want to return these variable, however they were not sent in as pointers when I initialized the kernel,So If I want to return these value. How would I go about doing so? Sample codes below.
I am only asking this as a general question not to solve the code below. I have other issues where I run into this and I don't know what's the best way to go about it. I understand that you can just throw in a pointer and copy the results onto it. However if the size of the result isn't predetermined it would be very hard to do so efficiently. So I am asking if there is a better way.
__global__ void addKernel()
{
int* c = (int*)malloc(sizeof(int) * 32);
#pragma unroll
for (int i = 0; i < 32; i++){
c[i] += 1;
}
}
| 318b9f232330b0721e6442456f849c6c2c57c1d6308277ec71b0df4a77036baa | ['3873bb16ed4145b9a01bcb374557c44b'] | Basically I'm working on this beat detection algorithm, the strange thing i am encountering right now is that when i split the work load on to another thread. So now i have one main thread and another worker thread. My worker thread somehow is always working faster than the main thread. It seems strange because what i have learned is that the main thread should theoretically always be faster because it is not taking time to initialise the thread. However what i get is even i pass a extra 1024 samples to the worker thread( they are both working with around 30 million samples currently) it is still faster than the main thread. Is it because i have applications running on my main thread? I'm really confused right now. here is the code
UnityEngine.Debug.Log ("T800 Start");
Step3 s1= new Step3();
Step3WOMT s2= new Step3WOMT();
System.Object tempObj= samples2 as System.Object;
float[] tempArray = new float[eS.Length/ 2];
System.Threading.ParameterizedThreadStart parameterizedts = new System.Threading.ParameterizedThreadStart(s1.DoStep3);
System.Threading.Thread T1 = new System.Threading.Thread(parameterizedts);
T1.Start (tempObj);
s2.DoStep3(samples1);
UnityEngine.Debug.Log ("s2");
//UnityEngine.Debug.Log (stopwatch.ElapsedMilliseconds);
T1.Join();
Don't worry I'm only using c# features in the multithread so I believe it should be fine. What i am really confused about is that if i comment out the T1.join(); line the whole thing somehow go even slower. Im genuinely confused right now as there seems no reasonable answer to this question.
|
7c988699cbb813cb99618b60d3e16e20250861e2ed78ae32b79a12c0420b93ea | ['387cb357399242d2aa0269f5a3320863'] | I have a function (written in Swift) and I would like to get the LLVM IR for the function PLUS any dependencies so that I can run the resulting LLVM IR in a fully self-contained environment.
As an example, consider the following function:
func plus(a: Int, b: Int) ->Int {
return a + b
}
plus(5, 7)
I can pass the emit-ir option to swiftc, however, the resulting LLVM IR contains external calls and the resulting IR cannot be run using lli (the error is shown below).
LLVM ERROR: Program used external function '__TFSsa6C_ARGVGVSs20UnsafeMutablePointerGS_VSs4Int8__' which could not be resolved!
Is there any way of grabbing the IR for these external functions so that I can use lli to run the program?
| d0a1b887c349d8c540166f5ed29da1e2341d8ed976d1340df04a094c0a27994f | ['387cb357399242d2aa0269f5a3320863'] | I'm trying to compile a function ("fun") to LLVM IR and create a Module using the ParseIR function. The program segfaults at the call to ParseIR. I'm using LLVM 3.5 and the code is below.
#include <cstdio>
#include <iostream>
#include <sstream>
#include <string>
#include "llvm/ADT/StringRef.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/ExecutionEngine/MCJIT.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/raw_os_ostream.h"
using std<IP_ADDRESS>cout;
using std<IP_ADDRESS>endl;
using std<IP_ADDRESS>ostringstream;
using std<IP_ADDRESS>string;
using llvm<IP_ADDRESS>getGlobalContext;
using llvm<IP_ADDRESS>LLVMContext;
using llvm<IP_ADDRESS>MemoryBuffer;
using llvm<IP_ADDRESS>Module;
using llvm<IP_ADDRESS>ParseIR;
using llvm<IP_ADDRESS>SMDiagnostic;
using llvm<IP_ADDRESS>StringRef;
int main() {
string fun = "int fun(int x) {return x;}\n";
string cmd = "echo '" + fun + "' |"
+ " clang++ -cc1 -xc++ -O0 -std=c++1y -fno-use-cxa-atexit"
+ " -I/usr/local/lib/clang/3.5.0/include/"
+ " -I/usr/include/c++/4.9/"
+ " -I/usr/include/x86_64-linux-gnu/c++/4.9/bits/"
+ " -I/usr/include/x86_64-linux-gnu -I/usr/include/"
+ " -I/usr/include/x86_64-linux-gnu/c++/4.9/"
+ " -I/usr/lib/gcc/x86_64-linux-gnu/4.9/include/"
+ " -I/usr/include/c++/4.9/backward/"
+ " -I/usr/lib/gcc/x86_64-linux-gnu/4.9/include-fixed/"
+ " -stdlib=libstdc++ -S -emit-llvm"
+ " -o /dev/stdout 2> /dev/stdout";
FILE *file = popen(cmd.c_str(), "r");
ostringstream llvm;
char line[1024];
while (fgets(line, 1024, file))
llvm << line;
pclose(file);
LLVMInitializeNativeTarget();
LLVMInitializeNativeAsmPrinter();
LLVMContext &ctx = getGlobalContext();
SMDiagnostic *err;
StringRef ref = StringRef(llvm.str().c_str());
MemoryBuffer *buff = MemoryBuffer<IP_ADDRESS>getMemBuffer(ref);
cout << "***** C++ *****\n" << fun << "\n"
<< "***** LLVM *****\n" << llvm.str() << endl;
//segfault
Module *mod = ParseIR(buff, *err, ctx);
return 0;
}
I compiled and ran the above code using the following command:
g++ -std=c++14 fun.cpp -o fun `llvm-config --cxxflags --ldflags --libs --system-libs`
./fun
***** C++ *****
int fun(int x) {return x;}
***** LLVM *****
; ModuleID = '-'
target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"
target triple = "x86_64-unknown-linux-gnu"
; Function Attrs: nounwind
define i32 @_Z3funi(i32 %x) #0 {
%1 = alloca i32, align 4
store i32 %x, i32* %1, align 4
%2 = load i32* %1, align 4
ret i32 %2
}
attributes #0 = { nounwind "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "no-realign-stack" "stack-protector-buffer-size"="8" "unsafe-fp-math"="false" "use-soft-float"="false" }
!llvm.ident = !{!0}
!0 = metadata !{metadata !"clang version 3.5.1 (branches/release_35 225591)"}
Segmentation fault (core dumped)
|
0abbd0707510a079dbe121d1b9b25ddd2e11b46374d121546ee35fdd9888f064 | ['38828663f37440529f3d60885f47c0b8'] | So I did some further digging, and was able to come to the conclusion that the problem IS NOT with Ghostscript. It was that the PictureBox in my application was still holding the .jpg file in memory. Oddly enough, I assumed setting the PictureBox.src to "Nothing" would release the file, but that didn't work. After doing some various google searches, I was able to uncover a workaround here: https://support.microsoft.com/en-us/kb/309482
When you load a PictureBox control with a picture file, the Microsoft Visual Studio .NET or Microsoft Visual Studio 2005 Integrated Development Environment (IDE) maintains a lock on the file. This occurs when you set the Image property of a PictureBox control to a file manually at design time, or when you use the FromFile method at run time.
RESOLUTION (for my application anyways):
Dim fs As System.IO.FileStream
' Specify a valid picture file path on your computer.
fs = New System.IO.FileStream(JpgFilePath,
IO.FileMode.Open, IO.FileAccess.Read)
frmFigureViewer.picMyJPEG.Image = System.Drawing.Image.FromStream(fs)
fs.Close()
| 6a0eef7efc0c514ecdaf1aeedbed731ff44ca595f7970534bc9ca81ebb7662fb | ['38828663f37440529f3d60885f47c0b8'] | I had accidentally left my DestinationPath blank for the 2nd and 3rd lines of the excel sheet. That was what was giving me just the "\" as the destination path. Seems to be working properly now.
As someone mentioned below in one of the comments, stepping through my code in the debugger was extremely helpful to solving this problem. My final code has some structural changes, in that I no longer have columns for SourcePath and DestPath, and instead use a folder dialog box to have the user select both of those.
The code for selecting my Source and Destination Folders:
Sub SourceFolder()
Dim lCount As Long
Dim rCount As Long
SourcePath = vbNullString
DestPath = vbNullString
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = OpenAt
.Title = "Source Path"
.Show
For lCount = 1 To .SelectedItems.Count
SourcePath = .SelectedItems(lCount)
MsgBox (SourcePath)
Next lCount
End With
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = OpenAt
.Title = "Destination Path"
.Show
For rCount = 1 To .SelectedItems.Count
DestPath = .SelectedItems(rCount)
MsgBox (DestPath)
Next rCount
End With
End Sub
The code for actually going out to the SourcePath, searching for the filename located in Column A (including with wildcards before and after), copying it to the DestinationPath, and renaming it with ColumnB's Value, followed by an underscore, and then ColumnA's Value is as follows:
Option Explicit
Public SourcePath As String
Public DestPath As String
Dim PartNum As String
Dim PLISN As String
Sub MoveFiles()
Dim LastRow As Long
Dim i As Long
Dim filename As String
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
For i = 3 To LastRow
PLISN = Cells(i, "B").Value
PartNum = Cells(i, "A").Value
If Right(SourcePath, 1) <> Application.PathSeparator Then
SourcePath = SourcePath & Application.PathSeparator
Else
SourcePath = SourcePath
End If
If Right(DestPath, 1) <> Application.PathSeparator Then
DestPath = DestPath & Application.PathSeparator
Else
DestPath = DestPath
End If
If Dir$(SourcePath & "*" & "*" & PartNum & "*") = "" Then
Cells(i, "C").Value = "Source file does not exist."
ElseIf Dir$(DestPath & PLISN & "_" & "*" & PartNum & "*" & ".pdf") <> "" Then
Cells(i, "C").Value = "File already exists."
Else
filename = Dir$(SourcePath & "*" & PartNum & "*" & ".pdf")
'Copy the file
FileCopy SourcePath & filename, DestPath & PLISN & "_" & filename
Cells(i, "C").Value = "File Copied to new location"
End If
Next i
End Sub
|
da534304c5975a3f5e6f1a1210e0e4beaf41f237f91b5922b666e80ff314e14b | ['388878e79daa4eb1b22fa04a5f6e461f'] | I'm trying to "variance-normalize" an image. In order to do so, I subtract the mean from the pixel value (to have a $0$ mean), and divide by the standard deviation (to have a unit variance) right? But I've also seen division by the standard deviation, since it's obviously not the same, what does it do?
I'm also a bit confused about the values I get after normalization: some values still more than $1.0$ or less than $-1.0$. I thought a unit variance means a variance from $-1.0$ to $1.0$.
| 8f67922168ba4c695f4aaace139e0242ee3f8fb4b5674dcf1c953a33ec2b76cb | ['388878e79daa4eb1b22fa04a5f6e461f'] | @TheLearner: Also important is how to deal with bottlenecks. I personally never blame slowdown on individuals. Instead I assign more resource to the bottleneck - maybe they need someone else to help them, maybe they can't reproduce a problem if all else fail I personally go and pair with the person working on the bottleneck until we solve it together - that servers 2 purposes, first two heads are better than one and second this is the perfect time to mentor a junior employee |
66424f7217979c994bda09eb04af0c89ccd80860b943828754d22704134a76ca | ['388cb168bf6344c594422d297587f1b5'] | meanwhile there are quite a few libraries that support Pdf generation. You'll find a good overview in <PERSON> Blog.
However, I ran into issues when I was trying to annotate existing Pdfs. The existing libraries capable of (transparent) annotations are quite pricy. Therefore, I ended up annotating the Pdf on the server side.
Feel free to read more about my experience at <PERSON>'s blog.
| 63f2bd672203798a383e7d8e264ed10f2520d3107ab61ec13fcdc4eda8d56696 | ['388cb168bf6344c594422d297587f1b5'] | While Deskmetrix seems quite nice, I ended up using Tapstream because it's free and Deskmetrix is pretty expensive.
Since Tapstream's main focus is evaluating advertisement campaigns its analytics feature is rather poor (compared to Flurry for instance). However, they allow custom event tracking.
When developing Mils, it was of great help that Tapstream supports both Mac OS X and Windows 8.
|
746764a6e9898755c23a5345b762134bf41287e64c8a711c169f8fbc660f94c2 | ['389118924ff34ef4a1145fc45d39275a'] | how to show start date and end date in date picker and select them to perform some event in iPhone
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
// Get the current date
NSDate *pickerDate = [self.datePicker date];
NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit )
fromDate:pickerDate];
NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit )
fromDate:pickerDate];
// Set up the fire time
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setDay:[dateComponents day]];
[dateComps setMonth:[dateComponents month]];
[dateComps setYear:[dateComponents year]];
[dateComps setHour:[timeComponents hour]];
// Notification will fire in one minute
[dateComps setMinute:[timeComponents minute]];
[dateComps setSecond:[timeComponents second]];
NSDate *itemDate = [calendar dateFromComponents:dateComps];
[dateComps release];
| 8f0cd9a8f9ae65057861c43333bed588a52c90fc7da876df1a785e9613f2a624 | ['389118924ff34ef4a1145fc45d39275a'] | I am fetching data form JSON and storing that data in 10 differnet NSMutable Arrays .I want to show that data in 10 sections of the tableview so how to do this
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
//return categories.count ;
if(section == 0)
{
return [appDelegate.books1 count];
}
else if(section == 1)
{
return [appDelegate.books2 count];
}
else if(section == 2)
{
return [appDelegate.books3 count];
}
else if(section == 3)
{
return [appDelegate.books4 count];
}
else if(section == 4)
{
return [appDelegate.books5 count];
}
else if(section == 5)
{
return [appDelegate.books6 count];
}
else if(section == 6)
{
return [appDelegate.books7 count];
}
else if(section == 7)
{
return [appDelegate.books8 count];
}
else if(section == 8)
{
return [appDelegate.books9 count];
}
else if(section == 9)
{
return [appDelegate.books10 count];
}
}
if i am doing below it shows only first section
Book1*aBook=[appDelegate.books1 objectAtIndex:indexPath.row];
int count=[appDelegate.books1 count];
cell.text = aBook.municipality;
cell.detailTextLabel.text=aBook.title;
cell.textLabel.backgroundColor=[UIColor clearColor];
cell.backgroundColor=[UIColor clearColor];
self.tableView.backgroundColor=[UIColor clearColor];
return cell;
|
034982adc92e87d2aba506022f7dc3a9c993298422ec4db23ad08fd9331a726f | ['38b1a640f5a44397967119f01f331330'] | Yes, I have no direct access to the server console. I'm waiting for physical access, but that might take a week or more. The $TARGET_MAC is indeed the expected MAC. I'll add this info to the question. I'm not entirely sure about the L3 layer though. In terms of arping it looks like there is none and other admins told me that it's the same L2 segment, but that mail thing suggests otherwise. Are there any other ways I could check for L3 components? | 807e358bb6c6fdf450f256361e6a6ffd1b2f96d57e81298e787c5ca01aed6189 | ['38b1a640f5a44397967119f01f331330'] | 1) Yes, assuming the drives have compatible sizes (see 3) )
2) none of the drives is the "main" drive, they mirror each other
3) Even if your system automatically rebuilds an array if possible, beware that "1 TB" disk is actually a vendor-dependent term. Depending on your setup, the initial process may have claimed all blocks in those disks. If you get a replacement "1 TB" drive later, even from the same vendor, it may have less blocks. In that case, you won't be able to use it as a replacement. You'll have to get a disk with the same or larger number of blocks being used in the array. Therefore, it is often advisable to limit the array to a number of blocks which most "1 TB" disks should fulfill. Usually 1 TB - a few blocks ~ (10^12 - 100 )B is quite safe. And of course it also depends on the drive partitioning alignment.
4) Depends on the SW used.
|
5890c61e039c37f56d4da7b944425fdfeb4015b16e1df53152c7a47e8cc5d5ed | ['38b6935f37b945f5ad23f22697135792'] | I'm trying to produce a report using r markdown that I can toggle between color and black and white. I've created a set of graphs using ggplot and saved them to objects, with a color and black and white version of each. To toggle the report I've created separate variables.
color <- 1
bw <- 0
In the code chunks for my report sections, I'm using if statements to check the values of the variables above and print the graphs.
if(color > 0) graph1_color
if(color > 0) graph2_color
if(bw > 0) graph1_bw
if(bw > 0) graph2_bw
When I knit my report, all of my intended graphs show up. If i set color and bw <- 1, all graphs. If just color <- 1, both color graphs, and if just bw <- 1, both bw graphs.
My issue is when I have 6 or seven graphs and I dont want to write if(color > 0) graph1_color for each of the graphs. Instead I used the following:
if(color > 0) {
graph1_color
graph2_color
}
if(bw > 0) {
graph1_bw
graph2_bw
}
But when I do this, only the last graph prints, eg graph2 prints but not graph1. What do I need to change in my if statement to get all of the graphs within the squiggle brackets to show?
| 17991b94d3ae257c4f7b1da3e6c4027953f6a2fd9a6920c6688eee6dea7dad34 | ['38b6935f37b945f5ad23f22697135792'] | I'm creating a bunch of graphs that I want to share a theme, for consistency because who doesnt love consistency.
All of my theme() elements are holding except for legend.position, and I'm all out of ideas.
The gist is as follows:
I want a theme that I can add to all of my graphs to give them the same formatting. There are two graphs that I'm creating, so I'm creating two similar themes.
I'm also splitting up my graphs in a possibly? nontraditional way. E.g. creating a graph template that includes the basic ggplot layers, but leaves out geom_point or geom_line, so that I can reuse those templates. Currently, I'm adding the theme that I've created in there.
Here's an example of one theme. The last parameter I set is for the legend to appear at the bottom.
mytheme <- theme(strip.background = element_rect(colour = "black", fill = "white"),
axis.text.x = element_text(angle = 50, hjust = 1, size = 9),
axis.text.y = element_text(size = 9),
legend.position = "bottom") +
theme_bw()
Lets test it out!
plot_template <- ggplot(mtcars) +
facet_grid(~cyl) +
mytheme
testplot <- plot_template +
geom_point(aes(x=mpg, y=disp, color = drat)) +
scale_color_continuous()
testplot
... and the legend appears on the right.
When I look at mytheme in the environment, it shows as a list of 65, and upon opening I see legend.position. It is listed as a type of charater[1] with a value of 'right'. This doesnt seem right, and I cannot for the life of me figure out what is going on.
Everything works just fine if I add legend.position separately, but this defeats the entire purpose of creating the unifying theme so I dont have to add each element to every graph.
mytheme <- theme(strip.background = element_rect(colour = "black", fill = "white"),
axis.text.x = element_text(angle = 50, hjust = 1, size = 9),
axis.text.y = element_text(size = 9)) +
theme_bw()
plot_template <- ggplot(mtcars) +
facet_grid(~cyl) +
mytheme +
theme(legend.position = "bottom")
testplot <- plot_template +
geom_point(aes(x=mpg, y=disp, color = drat)) +
scale_color_continuous()
Has anyone encountered this before or can see something that I'm doing wrong?
My guess is that I'm not fully understanding how setting a theme mytheme <- ... works, and I'm using it inappropriately, but nothing in the documentation is leading me to believe that I'm doing something funky.
|
af8e2f5cd498711dab4d8024490e2d4e76075d602c8d47e6419d1d2d1e10aa39 | ['38bb1c60dcec4d48ace4bbeb715c474e'] | I have strange issue with my animation - when
I shoot the enemy It should explode. And the animation is beeing done properly just one time.
Each next one has less frames. I have no idea why. Could someone help ?
Thanks in advance
I set the framespeed on 1 to make problem more visible.
http://jsfiddle.net/pza6eeos/
| 8f914905e3227114080c798023c8378c51a593906d79ce99bc76e331149c49b5 | ['38bb1c60dcec4d48ace4bbeb715c474e'] | I would like to put my JSON data (which I succesfully get) into events in FullCalendar Plugin, but unfortunetly It doesnt work for me...
$('#calendar').fullCalendar({
events: function (start, end, timezone, callback) {
$.getJSON("http://localhost:3000/test/2014-09-09", function (data, stat) {
alert(data[0].dates[0].dateStart)
start:data[0].dates[0].dateStart
});
}
});
|
09af6360f130f27d938aa28c00d8e0d6948c4b39099127c6391bb924ad05c154 | ['38bc0c79422c4abdba7190fddac49dbd'] | I have a stack implementation that uses an array and i am trying to convert it to an array list. The array is top and arrayList is on bottom. Do these 2 segments of code do the same thing? I also have two segments of a pop method one array and one array list. But for this one i get an error that temp has not been initialized and cannot find symbol temp. Any help is appreciated thanks.
USING ARRAY
public void push(T value)
{
if(size==values.length)
expandCapacity();
values[size] = value;
size++;
}
USING ARRAYLIST
public void push(T value)
{
values.add(value);
size++;
}
USING ARRAY
public T pop()
{
if(isEmpty())
throw new RuntimeException("Attempt to pop from empty stack");
size--;
T temp = values[size];
values[size] = null;
return temp;
}
USING ARRAYLIST
public T pop()
{
T temp;
if(isEmpty())
throw new RuntimeException("Attempt to pop from empty stack");
size--;
values.add(temp);
values.temp = null;
//values[size] = null;
return temp;
}
| 09812d7abff7b7ee2812df62dd1405d76e5b1aa523c82f76a72e25a89556cdc9 | ['38bc0c79422c4abdba7190fddac49dbd'] | This is the top portion of my ArrayListStack class. I am trying to make values become an array list of T of 10. I am getting an error "incompatible types required: ArrayListStack found:java.util.ArrayList". In the line values = new ArrayList(10)". How would i properly set this value thanks
import java.util.ArrayList;
public class ArrayListStack<T> implements StackInterface<T>
{
private ArrayListStack<Integer> values= new ArrayListStack<Integer>();
private int size;
public ArrayListStack()
{
size = 0;
values = new ArrayList<T>(10);
}
|
0590bcb045304600942e5ed76166cfc06620d8260085d5afcddc4869c1e97569 | ['38ccc96403be4778991a1503918cdea2'] | Прямо в конфигурации можно задать по умолачнию, так как у вас в примере
'authTimeout' => '30', //секунды
Если вы хотите брать это значение из базы, единственный способ делать это после создания приложения, например в методе login
public function login()
{
if ($this->validate()) {
// Устанавливаем значение authTimeout с базы данных
Yii<IP_ADDRESS>$app->user->authTimeout = 'Запрос в базу на получения authTimeout';
return Yii<IP_ADDRESS>$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
}
return false;
}
| ace48ea8cff453b2b85d4566dc5602732e37329b05be12b342401a37857cc183 | ['38ccc96403be4778991a1503918cdea2'] | I'm pretty much a newbie when it comes to any kind of complex networking, so basically yes? What I want is routing table's last line to look like this: ``<IP_ADDRESS> <IP_ADDRESS> <IP_ADDRESS><PHONE_NUMBER> <PHONE_NUMBER> 255.255.255.252``, am I just not understanding how this works? |
34be34c7dc685ff82f6942dd7815f96bc270c6a9df14e7e7e1f3cc8d2a729693 | ['38edb466421f4bb69bf30bb9da8ca6e4'] | Like <PERSON> said my model configuration is wrong.
if you have more than 1 column as key you should set them on contexts OnModelCreating method like modelBuilder.Entity<KullaniciYetkiView>().HasKey(ky => new { ky.KullaniciId, ky.LokasyonId, ky.YetkiId });
Here is the HasKey method explanation. http://msdn.microsoft.com/en-us/library/gg671266(v=vs.103).aspx
| 5e9a21960949b8c068a7b422393ef9eb51b7043f5296ee03ebf28b8ed99d4f5c | ['38edb466421f4bb69bf30bb9da8ca6e4'] | I think the date format in string is not proper. the reason of works in SQL Server Management Studio and not works in .Net can be the connections languge.
first select works but secend gives same exeption
SET LANGUAGE us_english
select CAST('12.18.2012' as datetime)
SET LANGUAGE turkish
select CAST('12.18.2012' as datetime)
|
6c41a836bf4dabf264911ec971a4e8117d7aad7473f5ea48f74f1d5b35accc8b | ['38f25be558884ebc943c0ba1f26d8ae1'] | Suppose you have fa0 as WAN
ip access-list extended WAN_ACL_IN
remark --- These are outgoing DNS queries.
permit udp any eq domain any gt 1023
remark --- Permit legitimate business traffic.
permit tcp any any established
permit udp any range 1 1023 any gt 1023
remark --- Deny all other DNS traffic.
deny udp any any eq domain
deny tcp any any eq domain
remark --- Explicitly deny all other traffic.
deny ip any any
and you need to apply the acl to your WAN interface
interface fa0
ip access-group WAN_ACL_IN in
| 55b4148f80a29a86a7700aa290a53f99ae8f1dff8a1432c9ecee5f3baf58309d | ['38f25be558884ebc943c0ba1f26d8ae1'] | Note: I have zero technical knowledge about Android or custom roms or root etc.
Am using Moto G5 plus (4bg) and I play games like PES 2019 and pubgm a lot.
Now my device runs these games with some lags but playable,but in order to get competitive edge I need to get more fps,that's why am considering ways to improve performance,even at the cost of short term heating and more power consumption.Any advice?
|
54d9b2ed25b6c42dfb4c0eec60acc3b65a6d75b5a9202a2cb0bba2d472ab194b | ['38f3d4bdc687468081ddf5864003d054'] | Yes, but it is not a documented feature. You can use Games.Leaderboards.loadTopScores to get top scores. When you have a LeaderboardScore object you can use score.getScoreHolder().getPlayerId() to get his Google+ id. Then open https://plus.google.com/PUT_ID_HERE/posts and you can contact that player via Hangouts.
| a94b6fbf8b21b267a3f08e6631cc98bdf88df68269aca1b5c64e7377f106790d | ['38f3d4bdc687468081ddf5864003d054'] | It is an old question, but I met the same problem, so probably it is worth posting my answer. You tried to add your certificate to KeyStore.getInstance("AndroidCAStore"), but got an exception. Actually you should have done the opposite - add entries from that keystore to the one you created.
My code is a bit different from yours, I just post it for the sake of complete answer even though only middle part matters.
KeyStore keyStore=KeyStore.getInstance("BKS");
InputStream in=activity.getResources().openRawResource(R.raw.my_ca);
try
{
keyStore.load(in,"PASSWORD_HERE".toCharArray());
}
finally
{
in.close();
}
KeyStore defaultCAs=KeyStore.getInstance("AndroidCAStore");
if(defaultCAs!=null)
{
defaultCAs.load(null,null);
Enumeration<String> keyAliases=defaultCAs.aliases();
while(keyAliases.hasMoreElements())
{
String alias=keyAliases.nextElement();
Certificate cert=defaultCAs.getCertificate(alias);
try
{
if(!keyStore.containsAlias(alias))
keyStore.setCertificateEntry(alias,cert);
}
catch(Exception e)
{
System.out.println("Error adding "+e);
}
}
}
TrustManagerFactory tmf=TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keyStore);
// Get a new SSL context
SSLContext ctx = SSLContext.getInstance("SSL");
ctx.init(null,tmf.getTrustManagers(),new java.security.SecureRandom());
return ctx.getSocketFactory();
|
46b9da8553c32fd5311c0796c152930dde2cae767896f93ca63611b6f1224495 | ['38f54c2264ec4fcaa907ffb088ee3e4a'] | I'm trying to register a chrome app to get a registration id so I test but the chrome javascript console is showing:
Uncaught TypeError: Cannot read property 'register' of undefined
I don't know what's wrong. I got the example from: https://github.com/GoogleChrome/chrome-app-samples#push-messaging
| 53df029332ed8ed77a3049d9f37b13fa2ed185bd21def5b82490ccb942e3ba87 | ['38f54c2264ec4fcaa907ffb088ee3e4a'] | I'm using Android Studio 2.2 Beta and trying to pull down the latest firebase libraries for cloud messinging but keeps running into errors.
failed to resolve:
com.google.firebase:firebase-core:9.4.0
Any ideas what I need to do? I have Android SDK 6 and 7, Tools (Preview Channel), and Tools (Rev. 23, 24, 25) installed. I'm stuck hard.
|
5d617cc0f3a2d1b8ea7768340c9beac6f34ae5ed30f1fc87b092e694daf31cdf | ['38f63f7ba97b4f47ae4830ff2d7a933d'] | Установил и запускаю apache на windows10, уже полностью его настроил. Но, он не хочет запускаться и не выдаёт никаких ошибок.
Всё что происходит после запуска - ничего:
c:\Server\bin\Apache24\bin>tasklist | find "8000"
c:\Server\bin\Apache24\bin>httpd.exe -k start
c:\Server\bin\Apache24\bin>
Пробовал на портах 80, 8080, но они заняты.
Может кто-нибудь подсказать что делать?
| fe9b28ba462c52338b312094c4e26a425a551513360282144e76b7de7bea4aa3 | ['38f63f7ba97b4f47ae4830ff2d7a933d'] | Мой вопрос заключался несколько в другом. При нажатии на кнопку отправки формы, данные из форм должны отправляться письмом на мою электронную почту. Но этого не происходит и пытаясь выяснить эту проблему я немного запутался. Сейчас я не понимаю почему при нажатии на кнопку считывается отправка метода POST, но данные не отправляются... |
71c982f9e45848722bfbeb0f6e7421f1b310c3b4b8d91542a8c9408a03f937e3 | ['39030ffdc32d4358a9558ab22628400c'] | i have a question. Is it possible to make my friend and other people access to a database in PostgreSQL to write in tables? If yes, how can i do that?
I'm connecting to my database through this string:
db = psycopg2.connect(
host = "192.168.1.xxx",
user = "Ripetra",
password = "MyPassword",
database = "Ripetra",
)
etc...
any answer will be appreciated <3
| fda09cc60769b4e06cdaa1d51f4de9b5eb435a1b4eba9e47979c4ca4d97ff4d7 | ['39030ffdc32d4358a9558ab22628400c'] | By far NONE answered my question, so i'm stuck here...
Basically i made a program (it's connected to my PostgreSQL database) which, depending on the user input, it will change tables contents in the database. It's a sort of Register/Login sistem. (click here if you want to see the script). When i run it on my pc (Windows 10 x64) it works like a charm. But when a friend of mine (Windows 10 x64) tries to run it (on a different network) it gives him this error:
Could not connect to server: Connection refused
Is the server running on host “<IP_ADDRESS><PHONE_NUMBER>” and accepting TCP/IP connections on port 5432?
(if it can help you, i tried MySQL too, but i got the same result... my friend cannot access to my database!)
So, I was asking my self "Is it even possible allow other devices to access my database from other networks? If yes, how can I do it?"
|
ff88103b0cb893db41fb138fb59466c926c7529625e44180eba45518645e485c | ['39054f49bbd047808e167f9f0365f393'] | No clue how to deal with this situation.
Recently start unit test with django.
In my project, i have a custom change_list.html to add a button on the admin page.
I'm looking for a unit test which can verify this custom button.
Here is my code in admin.py :
class LocationAdmin(OSMGeoAdmin):
def get_urls(self):
urls = patterns('', url(
r'^import/$',
self.admin_site.admin_view(self.import_process)
))
super_urls = super(LocationAdmin, self).get_urls()
return urls + super_urls
def import_process(self, request):
pass
admin.site.register(Location, LocationAdmin)
This code automaticaly load the template in app/admin/app/app/change_list.html
Which is :
{% extends "admin/change_list.html" %}
{% load staticfiles %}
{% block extrahead %}
<link rel="stylesheet" href="{% static "css/custom_upload.css" %}">
{% endblock %}
{% block object-tools-items %}
{{ block.super }}
<li><a role="button" href="import/" class="btn btn-primary btn-margin-left">Import</a></li>
{% endblock %}
But how about when you want to proove that work's with a unit test?
I'm able to test template when i can use a view and the function render_to_string
Like this :
response = my_view(HttpRequest())
expected_html = render_to_string(
'template.html',
{'arg_key': arg}
)
self.assertEqual(response.content.decode(), expected_html)
But here, i don't figure it out how to call the admin view with the associate template part.
Here a start of what i found to add unit test on admin page.
class MockRequest(object):
pass
class MockSuperUser(object):
def has_perm(self, perm):
return True
request = MockRequest()
request.user = MockSuperUser()
class ModelAdminTests(TestCase):
def setUp(self):
self.site = AdminSite()
def test_admin_import_button_on_location_admin_page(self):
ma = ModelAdmin(Location, self.site)
#Here the correct assert ?
Thank you all.
| 6624019d75e25b59de018c5db6b69e29b118519ba258c888e8cf4591bb03b5ef | ['39054f49bbd047808e167f9f0365f393'] | Here is what i get from my router:debug :
listeAbo-page ANY ANY ANY /abonnements
Seems OK for me.
From @ar34z, i've tested to put the URL directly on my login form (/abonnements) and it works. It's the only link in the whole site which have a problem. I still doesn't understand why.
Thank you all of you to brought me your help.
|
c4d8e0106a8cb380444a5c30421b97b0449320f77fe753f006e913df488d8383 | ['3924428e2f5e41ddb6a6f042032b7322'] | As <PERSON> writes, there isn't any cross-platform tool to managed work items similar to witadmin or tfpt. Also, the TEE CLC uses the TFS SDK for Java but the CLC is packaged up in the download for convenience. There should not be a dependency between the plugin and the CLC.
| a7862dbbe2194cf4b11f691d693873c3cbc05d4e7c3fda335246a24762782f16 | ['3924428e2f5e41ddb6a6f042032b7322'] | I ran into this issue today and was pulling my hair out trying to figure out what the problem was. It worked during debugging but didn't after packaging and installing. To be a bit clearer, if I packaged on my dev box, installing would work as expected but if my CI machine (VSTS) built it, it wouldn't.
It turns out that the size of the created VSIX file was an order of magnitude different. This was due to the fact that the number of node_modules in the VSIX varied greatly! After investigating, it turns out that the difference between npm2 and npm3 caused the issue. npm2 (which is what VSTS does today) packages up the npm modules differently than npm3 (and apparently it's incompatible with VS Code).
|
7186ca87ecf6c1f0a82b43efb4b7565a5449989d2904f051e24b05b106a7e8f2 | ['394cc88fd715456bbbbce2e8a65d8399'] | @Ramhound: I tried the Google DNS and Open DNS as well and tried to chanegt the preferred DNS Server. But when I reconnect after changin the settings, it defaults to 'Obtain DNS Server Automatically' and I am not able to check with the changed settings. I'll try on MacOS and let you know | bea905b5ca6b2fc2ca8b74727561500612ec3befb88d7b65f6e1d59a4b3389f0 | ['394cc88fd715456bbbbce2e8a65d8399'] | You won't be able to do that with only the current pagination widget: page 5 out of 10 may or may not be the middle.
But if you are sure page 5 is the middle then just select page 5 when initializing instantsearch.js, using searchParameters option.
If you cannot do that, what I would do is create a custom pagination widget that would:
filter entries to select only "todays" entries first: using a numeric filter with the options.helper
show a previous button that would change the numeric filter to select past entries
show a next button that would change the numberic filter to select future entries
|
b9370016568cba68a7a848f1a88050f3015ab40c89a1b7142c06bdb29983aed0 | ['3962880ed5f940fcb523d1be43411cf0'] | I coded program when i press "back", finish application and stop all service.
But after finish, Android studio says application is not closed, and profiler still say app is not closed and using memory.
How can I release all memory and close application without System.exit(0) and android.os.Process.killProcess(android.os.Process.myPid())?
Here's code when I used at test.
@Override
public void onBackPressed(){
finishAndRemoveTask();
}
@Override
protected void onDestroy(){
// Stopping notification listener service
stopService(serv);
// Removing notification
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICES)).cancel(0);
System.out.println("Goodbye, Cruel world.");
}
| 9852a9b8cd77c97ee26d014b23abf21c6ff00742f5212cecc68a275864bb0340 | ['3962880ed5f940fcb523d1be43411cf0'] | Use String#split(String).
Split slice string to string array with parameter.
As example, "test test2 test3".split(" ") returns {"test","test2","test3"}.
See code below.
Java 7
public String search(String target){
for(String n : list){
String[] split = n.split(" ");
if(split[3].equals(target)){
return split[3]; // Return n if you want to return all string
}
// Cannot find target
return null;
}
Java 8
public String search(String str){
List<String> lst = list.filter(s -> s.split(" ")[3].equals(str)).collect(Collectors.toList());
return lst.size() == 0 ? null : lst.get(0).split(" ")[3]; // Do not split if you want to return all string
}
|
36ebc5e11d58f64871485e14d2fd6588a4c83cf11f58205e86aaf6fa7189bc36 | ['3969b89b18d14688bfa3ba715b0929fd'] | I recommend to use one of two commonly methods. I describe how to make it with fetch object, on client and express framework on server.
1. Setting the token in the HttpOnly cookie
In server controller
module.exports.checkUser = (request, response) => {
const { token = null } = (/token=(?<token>[^;]*)/.exec(request.headers.cookie) || {}).groups || {} // Or better use cookie-parser
crudModel.verifyUser((result) => {
if (Array.isArray(result) && result.length > 0) {
if(result[0].email == request.body.email && result[0].password == request.body.password){
let jwtToken = jwt.sign({
email: result[0].email,
user_id: result[0].uid
}, "mohit_pandey_1996", {
expiresIn: 300000
});
response.cookie('token', jwtToken, {
httpOnly: true,
// secure: true // - for secure, https only cookie
});
response.render('dashboardView'); // - now we don't need to appear token to the view, because it automatically appears in cookies in each request
}
} else {
console.log('Invalid Username or Password');
response.render('errorView');
}
}, token); // <- pass token
}
On the client side (on page), if you are use fetch for requests, you need to add the credentials parameter
function makeRequest(url) {
return fetch(url, {
credentials: 'include'
})
}
More about pros and cons of this method you can read this
https://stackoverflow.com/a/39833955/9051045
2. Using token in request header with saving it into localStorage
Example (client script) in html > head
function makeRequest(url, method) {
var jwtToken = localStorage.getItem('token')
var headers = {}
if(jwtToken) {
headers['Authorization'] = 'Bearer ' + jwtToken
}
return fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors',
headers: headers
})
}
This function make request with token, when it was setup in localStorage
Your Controller function: (server)
module.exports.checkUser = (request, response) => {
var {token = ''} = (/Bearer\s+(?<token>.*)/.exec(request.get('Authorization') || '') || {}).groups || {}
crudModel.verifyUser( (result) => {
if (Array.isArray(result) && result.length > 0) {
if(result[0].email == request.body.email && result[0].password == request.body.password){
let jwtToken = jwt.sign({
email: result[0].email,
user_id: result[0].uid
}, "mohit_pandey_1996", {
expiresIn: 300000
});
response.render('dashboardView', { token : jwtToken});
}
}else{
console.log('Invalid Username or Password');
response.render('errorView');
}
}, token); // <-pass token
}
View(ejs) :
<script>
localStorage.setItem('token', "<%= JSON.stringify(token) %>"); // <- setup token into localStorage, (but i think it's not good place for that, and would be better get token with another authorization request)
</script>
<!-- Your code below -->
<li class="nav-item active">
<a href="/user/home?authorization=Bearer "+data>Home
<span class="sr-only">(current)</span>
</a>
</li>
| 747dc46842c089bfb38ba5fe2b990bb382f9d4d534722fbc6fd4ace847da2725 | ['3969b89b18d14688bfa3ba715b0929fd'] | I think error happened because variable allStudents is not a React object.
constructor() {
this.state = {
filterValue: ''
}
}
render() {
const students = [
{city: '', company: '', email: '', firstName: '', grades: '', id: '', lastName: '', pic: '', skill: ''}
] // <-- this is your array of students
const allStudents = students.filter(student => {
return student.firstName.includes(this.state.filterValue) ||
student.lastName.includes(this.state.filterValue)
}) // <-- Apply filter
.map(student => {
return (
<div key={student.key}>
<p>Name: {student.firstName} {student.lastName}</p>
<p>Email: {email}</p>
</div>)
}); // <-- Wrap each element into React Component
return (<div className="container">
<input
id="search"
name="search"
onChange={this.handleInput}
placeholder="Search by name"
style={{width: '100%', border: '0', padding: '15px 0 7px 10px'}}
value={this.state.filterValue}
/>
<hr />
{allStudents}
</div>)
}
|
9bb5c6081f5e243feff36849c0b786b7360c266253cd1950113bc5478b040781 | ['3987d7aa64dd4bcdafa50d0e73809578'] | I was wondering if anyone was able to explain why All of my JSON is returning as Undefined.. The json is question is this
{"273746":[{"name":"Darius's Wizards","tier":"GOLD","queue":"RANKED_SOLO_5x5","entries":[{"playerOrTeamId":"273746","playerOrTeamName":"Magnanimous","division":"V","leaguePoints":0,"wins":19,"losses":15,"isHotStreak":false,"isVeteran":false,"isFreshBlood":false,"isInactive":false}]}]}
and the Javascript i've got to run through this is:
Note: in the code provided i /sumID is 273746 and s is 'oce' due to Riot API guidelines i can't give you a direct link to the API so i had to paste it in above.
function statsLookUp(i,s) {
$.ajax({
url: 'https://oce.api.pvp.net/api/lol/' + s + '/v2.5/league/by-summoner/' + i + '/entry?api_key=',
type: 'GET',
dataType: 'json',
data: {
},
success: function (json) {
//all json goes here
var sumID = i;
leagueName = json[sumID].name;
leagueTier = json[sumID].tier;
leagueDiv = json[sumID].entries.division;
leagueLoss = json[sumID].entries.losses;
leagueWin = json[sumID].entries.wins;
document.getElementById("sLeague").innerHTML = leagueName;
document.getElementById("sTier").innerHTML = leagueTier;
document.getElementById("sDivision").innerHTML = leagueDiv;
document.getElementById("sWins").innerHTML = leagueWin;
document.getElementById("sLosses").innerHTML = leagueLoss;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error getting Summoner data!");
}
});
}
everything continues to return as undefined, but i can't seem to find the issue at hand :/
| 2535fe941cf0633754e439ef1302ad906dc7e70d60091a9f092bb5a26dcf86c6 | ['3987d7aa64dd4bcdafa50d0e73809578'] | JSFIDDLE for testing http://jsfiddle.net/8dw09y59/
Hey guys, I've tried everything.. Could someone please explain why i continue to get the "uncaught referenceerror: summonerLookUp is undefined"
I've tried switching the function to windows.summonerLookUp = function() { , but thats hasn't changed anything either. I've tried loading them within , within I've tried loading it at the end of the document, but i get the error "In XHTML 1.0 Transitional the tag cannot contain a tag ." is anyone able to explain whats going on here?
This is my index.js
function SummonerLookUp() {
var SumName
SumName = $("#SumInput").val();
if(SumName !== "") {
$.ajax({
url: 'https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/' + SumName + '?api_key=',
type: 'GET',
dataType: 'json',
data: {
},
success: function (json) {
var SUMMONER_NAME_NOSPACES = SumName.replace(" ", "");
SUMMONER_NAME_NOSPACES = SUMMONER_NAME_NOSPACES.toLowerCase().trim();
summonerLevel = json[SUMMONER_NAME_NOSPACES].summonerLevel;
summonerID = json[SUMMONER_NAME_NOSPACES].id;
document.getElementById("sLevel").innerHTML = summonerLevel;
document.getElementById("sID").innerHTML = summonerID;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error getting Summoner data!");
}
});
} else {}
}
and my index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>LoLStats.GG</title>
<script language="javascript" type="text/javascript" src="../Javascript/index.js"></script>
</head>
<body>
Summoner Name
<br />
<input id="SumInput" />
<button onclick="summonerLookUp()">Click me</button>
<br />
<br />Summoner Level: <span id="sLevel"></span>
<br />Summoner ID: <span id="sID"></span>
</body>
</html>
|
73756dc2877310b7624ed5f8d1505175473cff531a6f4944ff705a745bfd4ea3 | ['39a4ea407ed141b282869968636ffbf8'] | So if I take the function f(x) = |x| + 1 and I reflect f(x) given its definition, it is not -f(x)? Sorry, I am a little confused as I was taught that vertical reflections are always symmetric about the x-axis. In this case, if f(x) = |x| + 1 and the reflected function is g(x) = -|x| + 1 then wouldn't that be a reflection about the line y = 1 and not the x-axis? | ed4fc74f97826a502676a800b71e61015338b61447071fd9bdde4f6fe560afc5 | ['39a4ea407ed141b282869968636ffbf8'] | Ok so basically when looking at a function such as f(x) = |x| + 1 and when I am told that there is a vertical reflection, the reflection is based on the base function, g(x) = |x| and not the whole function f(x) = |x| + 1 because then that would be looking at vertical symmetry in the x-axis and not reflection, correct? I have graphed both f(x) = |x|, g(x) = -|x| - 1 and h(x) = -|x| + 1 and I understand what you are talking about. Basically the reflection occurs based on the base function first and then the translation of one unit up to obtain g(x) = -|x| + 1. |
b10c6276e441ffcea9e09939a5a6b71d38676df731327269887d318707a21715 | ['39a75e3b8ecb4f179e6c89719d92e7c7'] | I've integrated this nice Facebook-Button to my WordPress site via iframe. Although I care for cross-browser-compatibility plus the fact I could not influence the iframe content in regular ways I'm wondering why this quirks when viewed in IE6.
Could I've done something wrong anyway or is it conceivable stuff quirks by default and Facebook doesn't care about that?
| ebd744c947887498eb9ccb9c22745bca1803843adb7377f03e24573fe703a7d5 | ['39a75e3b8ecb4f179e6c89719d92e7c7'] | In my HTML-template I have placed a logo surrounded by an <a>-tag. My purpose with this is to refer to the homepage by using just as much TypoScript as realy necessary. I searched in TSref and official forums on that but just came across a solution already creating this link by using stdWrap which is exactly what I not want. Is it possible to keep it that simple that I only need to place a marker within the <a>-tag inside my HTML-template?
I thought of something like this: <a href="###HOMELINK###">logo image here</a> and then using ...marks.HOMELINK = TEXT in the TS template record.
I simply don't want to get things parsed twice which already can be achieved by simple markup in my HTML-template.
|
086e5a52d6e7e50f3c6f83cc426b4c0c07001c28076410e0c87b3bde154e514d | ['39ab126ce98a49479ed76a6c76fce102'] | So I have found a solution to the problem. It works very well but It seems a bit overkill for something as simple as clearing a field.
Maybe a javascript snippet is a cleaner solution?
Well enough with the ranting here is the solution:
Clear the form field in the "command" object (the form backing object) when there are no error in the field.
When there is validation errors Spring picks up the values "rejectedValuse" from the BindingResult object so
make a "proxy" of the BindingResult and return "" when the getFieldValue(String s) function is called..
Make a "what did you say"? ... a proxy. Like this:
public class BindingResultProxy implements BindingResult {
final private BindingResult proxied;
final private Set<String> fieldsToClearValueFor;
public BindingResultProxy(BindingResult proxied) {
this.proxied = proxied;
fieldsToClearValueFor = new TreeSet<String>();
}
public void clearFieldValueFor(String fieldname) {
fieldsToClearValueFor.add(fieldname);
}
@Override
public Object getTarget() {
return proxied.getTarget();
}
@Override
public Map<String, Object> getModel() {
return proxied.getModel();
}
.... And it goes on to override all the methods in BindingResults using proxied like the above method
.. then in getFieldValue() return "" when decided by some mechanism.. (list) you get the point? :-)
@Override
public Object getFieldValue(String s) {
if (fieldsToClearValueFor.contains(s)) return "";
return proxied.getFieldValue(s);
}
Then in the controller use:
if(result.hasErrors()){
//If there are errors, clear the fields
ArrayList<String> fieldsToClear = new ArrayList<String>(3);
for(FieldError fieldError: result.getFieldErrors()) {
fieldsToClear.add(fieldError.getField());
}
if(result.hasGlobalErrors()){
//there is only one global error here in case the new password does not match the confirm password
//so clear the confirmPassword as well
fieldsToClear.add("confirmPassword");
}
clearFormFieldValues(result, model, fieldsToClear.toArray(new String[fieldsToClear.size()]));
return "/account/changePassword";
.....
private void clearFormFieldValues(BindingResult result, Model model, String... fieldsToClear) {
final BindingResultProxy configuredBindingResult = new BindingResultProxy(result);
for (String fieldToClear : fieldsToClear) {
configuredBindingResult.clearFieldValueFor(fieldToClear);
}
model.addAttribute("org.springframework.validation.BindingResult.changePasswordForm",
configuredBindingResult);
}
Very simple indeed?!??!?
| 3b4d10056fa24c34b598c570ffe9ff8bf6df4ae2a134d54f87fe7e3fbaf20403 | ['39ab126ce98a49479ed76a6c76fce102'] | As the title implies I want to change the http status after an exception occured.
The short background is that to be able to show an error page I need to send a status code of 200 to the client. (On error status codes it dumps the data and shows a generic error popup)
To test this I have:
@RequestMapping(value= "/err")
public String throwError()
{
throw new IllegalStateException();
}
In web-xml:
<error-page>
<error-code>500</error-code>
<location>/errorPage</location>
</error-page>
And the errorPage controller (gets called)
@RequestMapping(value = "/errorPage", method = RequestMethod.GET)
public String errorPage(HttpServletResponse response, Model model, Locale locale ) {
int errorStatus = response.getStatus();
response.reset();
model.addAttribute("errorStatus", errorStatus);
response.setStatus(HttpServletResponse.SC_ACCEPTED);
LOGGER.debug("---------->" + response.getStatus());
return "errorPage";
}
The catalina log output is 200 BUT the response in the client is:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Somewhere Spring encodes the exception as a statuscode 500 (I suppose it is in the HandlerExceptionResolver chain?) and then my errorPage controller is called.
Spring seems to remember that an exception was thrown and ignores (or recodes?) the status code to 500 after the controller returns.
The confusing (or maybe not?) thing is that if I return a Response Entity from the errorPage controller and set the status code this will be honored. Eg:
return new ResponseEntity(HttpStatus.ACCEPTED);
I suppose that this is not a bug but a feature and that Spring knows better than me and I should really change my way of implementing this whole thing. (!!?)
I cannot return just a ResponseEntity since I need to render the error page. I suppose I could if I streched myself render the page in the controller and put it into the ResponseEntity to achieve what I want but it just seems ... wrong.
There must be a way of controlling what status code is returned other than returning a ResponseEntity (and bypassing whatever mechanism is resetting it to 500). Or just telling the framework not to re encode the thrown exception as a status code 500.
To be complete I have tried setting the statuscode in a HandlerExceptionResolver and returning a ModelAndView with the same disappointing result. (500)
I have also tried @ControllerAdvice @ExceptionHandler .. same result..
Any clues to what happens after returning from the controller (or HandlerExceptionResolver) that sets the status code and how I can disable it?
Maybe it is some unknown setting in my configuration that causes this?
|
6496a227c843833fe303b8b6bd2edadfc0280d04ebea969ae6e20fef1dc20f80 | ['39ad1cf14c2a477ba659a91ee334aec2'] | It looks like the site is doing something with the User-Agent. If I change that property to match what my version of Firefox sends, I get the full response body. When I left the property as 'ruby', the response was incomplete. Not sure what the root cause is, but this seemed to alleviate the symptoms.
require 'rubygems'
require 'hpricot'
require 'open-uri'
doc = open("http://yellowpages.com.mt/Malta-Search/Radio-In-Malta-Gozo.aspx", 'User-Agent'=>'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:<IP_ADDRESS>) Gecko/20090729 Firefox/3.5.2') { |f| Hpricot(f) }
puts doc.search('h6')
Hope this helps!
| d58af0880329f3384b6c3b05cbefa435077051652995c90b598ace467cb4c189 | ['39ad1cf14c2a477ba659a91ee334aec2'] | I'm not sure how you're loading the xml data, but in the past, I've gotten around the issue by appending a random number to the path of the xml file:
xml.load("data.xml?"+Math.random());
Basically, Flash will always think the file is a different URL. It won't be able to find a match in your cache.
Again, I'm not sure how you're loading the XML data, so I'm not sure if this applies to your situation.
Hope it helps, though.
|
8c44af23c2ef401be7f905d18529f96a47ad35a342bd16cb396184f4fb1f9491 | ['39b073767b9b4b37b9a1e587d092b39c'] | could you please use next setting in your .xib file (416 = 480 - 20 (width for status bar) - 44(width for nav bar)
if you want icon in the top on iPhone 5 use next setting for icons:
if you want icon in the bottom on iPhone 5 use next setting for icons:
| 7114092176618607410d5526630fe6116a85ac8f11b498f6b435ebd50300dad7 | ['39b073767b9b4b37b9a1e587d092b39c'] | I thin these code will help you:
NSArray *query = @"https://oauth.vk.com/blank.html#access_token=b1b33dfaa3&expires_in=86400&user_id=311515 ";
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
for (NSString *param in [query componentsSeparatedByString:@"&"]) {
NSArray *parts = [param componentsSeparatedByString:@"="];
if([parts count] < 2) continue;
[params setObject:[parts objectAtIndex:1] forKey:[parts objectAtIndex:0]];
}
|
94c7b8f451841700cf623dc5f68c526dd92b1c2ef8481fc1b860aeadc0f3bedc | ['39b9b570fe754ce5a8c5c8ab6f264fb7'] | Is there a library or cli program which is capable of dropping/extracting frames from a SWF movie? Let's say I have a SWF movieclip with 451 frames, of which I will like to make a new movie clip out of with only the first 450 frames. No wrappers or containers though.
| 8e9f51bcb935508d5ae5d29c7f02544c539d2ff28ec370c985eba5aa3fb49728 | ['39b9b570fe754ce5a8c5c8ab6f264fb7'] | What is going to happen to HHA?
Will restarting my town cause the houses in HHA to disappear? I thought they might stay because these gamers are connected to your streetpass right? Or will that be wiped out too? It would be nice if I could get my furniture back once I deleted my save file. (after I unlock the HHA of course.)
Sorry for the bad English!
|
e0478f858d435fc5bf1dcad467573b9028143bf6837ebdfc945e0dd89aecee47 | ['39bd723520a140a4aff36f0814420393'] | This is an exercise I came up with, but can't solve myself.... Here goes:
Say you receive as input a list of N nodes. Each node n is connected to one or more nodes. The input could look something like:
Node A is linked to node B and C
Node B is linked to node A and C
Node C is linked to node A and B
The goal is to find a function that maps each node to a coordinate in a plane in such a way that the straight lines connecting each node do not intersect each other.
The example above is trivial: As long as the nodes are not all on the same axis it will work, but it gets lot harder with more nodes and more links between them. I'm assuming some inputs do not have any valid answer, but I don't see how you can prove it.
| 5eed450752243c2f52d76e6d7d4525c627b83a7749391424c3d949b07fba91ce | ['39bd723520a140a4aff36f0814420393'] | I'm trying to find the general way of optimizing a summation function and I'm a bit lost. I would like to find the maxium (and the minimum, ideally) of:
$$ \sum_{n=1}^{x} f(n)$$
For example, let's say:
$$ f(n) = -(n-4)^2 + 16 $$
In this scenario, the answer is easy to find without doing any work: f(n) is positive for $n \in [0, 8]$, and then becomes negative for infinity, we can maximize the sum by adding all positive numbers ($x = 8$).
Is there a way to find this mathematically, in a general way for all functions? Usually when looking to optimize a function I would take the derivative, but the derivative of a summation doesn't make much sense, does it?
Thanks.
|
4f01057e47ca948867ea5066384b7365a4466aa563ecefc2931798011c3def3f | ['39c2fa5e84a043b1abe646b299ee5303'] | Нашел ответ в английском стеке, вот ссылки:
https://stackoverflow.com/questions/36464592/psycopg2-cursor-execute-is-not-working-properly
https://stackoverflow.com/q/13715743/9374673
Мой класс в итоге получился таким:
class ConnectDB:
def __init__(self):
self.info_db = {"dbname": "my_data_base",
"host":"localhost"}
self.conn = psycopg2.connect(** self.info_db)
self.cursor = self.conn.cursor()
def query(self, request):
self.cur.execute(request)
self.conn.commit()
def toyal(self):
return self.cur.fetchall()
def status(self):
return self.cur.statusmessage
def close(self):
self.cur.close()
self.conn.close()
Класс для использования:
class Use:
def __init__(self):
self.cursor = ConnectDB()
def save_board_in_db(self):
request = f"""INSERT INTO Users (user_name)
VALUES ('Bob')"""
self.cursor.query(request)
return self.cursor.status()
def __del__(self):
self.cursor.close()
Для записи в БД:
data = Use()
data.save_board_in_db()
status = data.status()
| 459844dfb20145188ae96be09266336b1797299ed6812dc0fe8c24ad632535c1 | ['39c2fa5e84a043b1abe646b299ee5303'] | Supose we have $\{K_i\}_i a colection of compact sets. This means that for every $i$ there exists some $R_i>0$ such that $K_i$ is bounded: $K_i\subseteq B(0,R_i)$. Now let $K$ be the intersection of the $K_i$. By property of intersections $K\subseteq K_i$ for all $i$, this implies, $K\subseteq B(0, R_i)$ for all $i$, i.e. $K$ is bounded. |
12f67b9add7ce69f03bdacf283ed18cba3d7bd41ffe5e6e2a8114a98e1e3e8f8 | ['39c458323b3a4e33981723396057cc64'] | I have some large files which I want to run on Google Colaboratory from my terminal by specifying the file name or by sending a request to the Google colab server. How can I do that ?
PS: The files are run one by one using a javascript file on which I have no control. Their running process is all handled by that js file and I can't modify it. Is there any way to send these files on the colaboratory and run it there ?
I would appreciate if the solution you give also has a documentation URL so that I can refer to it future if similar need arises.
| 8b3814efed0a66f4280b77773578439f0b1da88ccdb7f6fe9d34a1e51c56578e | ['39c458323b3a4e33981723396057cc64'] | This code has ambiguous behaviour as per ob.fn() call which is quite clear as per the function definition. But when changed the function definition from 'boolean' to 'double' the behaviour was quite unexpected to me.
public class Varargs {
public void fn(boolean ...a){
System.out.println("calling double fn");
for(boolean i:a){
System.out.print(i+" ");
}
System.out.println("\n");
}
public void fn(int ...a){
for(int i:a){
System.out.print(i+" ");
}
System.out.println("\n");
}
public static void main(String[] args) {
System.out.println("Entering 5 numbers.");
Varargs ob = new Varargs();
ob.fn();
ob.fn(2,5,5,3,2,2,3,4,3,3);
}
}
But why isn't the ambiguity being shown in this ?
public class Varargs {
public void fn(double ...a){
System.out.println("calling double fn");
for(double i:a){
System.out.print(i+" ");
}
System.out.println("\n");
}
public void fn(int ...a){
for(int i:a){
System.out.print(i+" ");
}
System.out.println("\n");
}
public static void main(String[] args) {
System.out.println("Entering 5 numbers.");
Varargs ob = new Varargs();
ob.fn();
ob.fn(2,5,5,3,2,2,3,4,3,3);
}
}
After changing 'boolean' to 'double' , what led to disappearance of ambuigity?
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.