_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d4701 | train | for (; i < grades.length; i++); <--- See the semi-colon at the end, basically this is executing all the code between the ) and the ;, which isn't much, meaning you could actually remove the loop with only a minor side effect to the code.
Instead, you should be doing something more like...
for (int i = 0; i < grades.length; i++) {
System.out.println(i);
System.out.printf("%d\t%s\t%d\n", i, Students[i], grades[i]);
sum += grades[i];
}
Note, now I can include i in the definition of the loop without issue
This is not a uncommon issue and one you will likely repeat a few more times in the future
A: for(;i<grades.length;i++);
The semicolon is the troublemaker here.
This leads to your variable i being more than the last index of the array. Hence the out of bounds exception!!
A: As Elliot said, remove the semicolon from the end of your for-loop and your code should work fine. It's also common practice to initialize your counter variable inside the for-loop. The for-loop header should look like
for(int i = 0;i<grades.length;i++) | unknown | |
d4702 | train | Inner template:
<form #myForm="ngForm">
<input ngModel name="name" type="text" required />
<input ngModel name="email" type="email" required />
<input ngModel name="phone-number" type="text" required />
<button (click)="onSubmit(myForm)">Submit</button>
</form>
Innner .ts:
onSubmit(form: NgForm) {
console.log(form.invalid);
}
Be sure that you have imported FormsModule into your module:
import { FormsModule } from '@angular/forms';
@NgModule({
// ...
imports: [..., FormsModule, ...],
// ...
})
A: Important: import { FormsModule } from '@angular/forms'; into your app-module and add it to the imports array.
@NgModule({
imports: [FormsModule],
})
Create a template variable in form element like myForm given below and on button tag make use of property binding [disabled]="!myForm.form.valid". Now Submit button will only work when each form element is filled.
Template file:
<form #myForm="ngForm" method="POST" (ngSubmit)="submitForm(myForm)">
<div>
<label>Name</label>
<input name="name" type="text" required ngModel/>
</div>
<div>
<label>Email</label>
<input name="email" type="email" required ngModel/>
</div>
<div>
<label>Phone no</label>
<input name="phone" type="number" required ngModel/>
</div>
<button type="submit" [disabled]="!myForm.form.valid">Submit</button>
<pre>{{myForm.value | json}}</pre>
</form>
You can find my code snippet on StackBlitz | unknown | |
d4703 | train | Are the dates in varchar2 type? Then, you can first convert it into timestamp format. Since it has timezone also, use the to_timestamp_tz function.
SQL> select to_timestamp_tz('Sun Dec 29 11:55:29 EST 2013','Dy Mon dd hh24:mi:ss TZR yyyy') from dual;
TO_TIMESTAMP_TZ('SUNDEC2911:55:29EST2013','DYMONDDHH24:MI:SSTZRYYYY')
---------------------------------------------------------------------------
29-DEC-13 11.55.29.000000000 AM EST
Once the dates are in timestamp type, subtracting them will give you the difference in interval day to second type.
SQL> select to_timestamp_tz ('Mon Dec 30 20:21:34 EST 2013','Dy Mon dd hh24:mi:ss TZR yyyy')
2 - to_timestamp_tz ('Sun Dec 29 11:55:29 EST 2013','Dy Mon dd hh24:mi:ss TZR yyyy') from dual;
TO_TIMESTAMP_TZ('MONDEC3020:21:34EST2013','DYMONDDHH24:MI:SSTZRYYYY')-TO_TI
---------------------------------------------------------------------------
+000000001 08:26:05.000000000
Then use extract to get the individual components from the interval.
SQL> select extract(day from intrvl) as dd,
2 extract(hour from intrvl) as hh24,
3 extract(minute from intrvl) as mi,
4 extract(second from intrvl) as ss
5 from (
6 select to_timestamp_tz ('Mon Dec 30 20:21:34 EST 2013','Dy Mon dd hh24:mi:ss TZR yyyy')
7 - to_timestamp_tz ('Sun Dec 29 11:55:29 EST 2013','Dy Mon dd hh24:mi:ss TZR yyyy') as intrvl
8 from dual
9 );
DD HH24 MI SS
---------- ---------- ---------- ----------
1 8 26 5
A: I figured out one solution but it will work only for same time zone dates.
with tab as (
select to_date(replace(substr('Sun Dec 28 23:59:59 EST 2013', 4), 'EST '), 'Mon DD HH24:MI:SS RRRR') start_date,
to_date(replace(substr('Tue Dec 30 20:21:34 EST 2013', 4), 'EST '), 'Mon DD HH24:MI:SS RRRR') end_date
from dual),
tab_sec as
(select ((end_date - start_date) * 24 * 60 * 60) sec from tab)
select lpad(trunc(sec / (60*60)), 2, '0')||':'||
lpad(trunc((sec - (trunc(sec / (60*60)) * 60 * 60))/60), 2, '0')||':'||
lpad(mod(sec, 60), 2, '0') diff
from tab_sec;
A: You can use NUMTODSINTERVAL
For example
with x as (
select to_date('01/01/2014 10:00:00','dd/mm/yyyy hh24:mi:ss') d1 ,
to_date('01/01/2014 12:00:00','dd/mm/yyyy hh24:mi:ss') d2
from dual
union all
select to_date('02/01/2014 10:00:00','dd/mm/yyyy hh24:mi:ss') d1 ,
to_date('01/01/2014 12:00:00','dd/mm/yyyy hh24:mi:ss') d2
from dual
union all
select to_date('01/01/2014 10:30:00','dd/mm/yyyy hh24:mi:ss') d1 ,
to_date('01/01/2014 12:00:00','dd/mm/yyyy hh24:mi:ss') d2
from dual
union all
select to_date('01/01/2014 10:00:30','dd/mm/yyyy hh24:mi:ss') d1 ,
to_date('01/01/2014 12:00:00','dd/mm/yyyy hh24:mi:ss') d2
from dual
union all
select to_date('01/01/2014 10:00:30','dd/mm/yyyy hh24:mi:ss') d1 ,
to_date('02/01/2014 12:20:10','dd/mm/yyyy hh24:mi:ss') d2
from dual
)
select d1 , d2 , numtodsinterval(d2 - d1, 'day') as interval_diff
from x
D1 D2 INTERVAL_DIFF
------------------- ------------------- ---------------------------------
01/01/2014 10:00:00 01/01/2014 12:00:00 +000000000 02:00:00.000000000
02/01/2014 10:00:00 01/01/2014 12:00:00 -000000000 22:00:00.000000000
01/01/2014 10:30:00 01/01/2014 12:00:00 +000000000 01:30:00.000000000
01/01/2014 10:00:30 01/01/2014 12:00:00 +000000000 01:59:30.000000000
01/01/2014 10:00:30 02/01/2014 12:20:10 +000000001 02:19:39.999999999 | unknown | |
d4704 | train | As you have discovered you cannot overlay reference types on top of value types. So to implement your union, you need to use either one or the other. Your structures must contain value types and so we conclude that you must use value types exclusively.
So, how do you implement your character arrays as value types? By using a fixed size buffer.
unsafe public struct S1
{
fixed byte MsgId[Const.FieldSizeTime + 1];
....
} | unknown | |
d4705 | train | Why are your modules not stored in directories? For example:
/
app.js
lib
--/logger
----/index.js
then in app.js you can just require(./lib/logger) | unknown | |
d4706 | train | Everyone has provided comments telling you what the problem is but if you are a beginner you probably don't understand why it's happening, so i'll explain that.
Basicly, when opening a file with python, each new line (when you press the Enter Key) is represented by a "\n".
As you read the file, it reads line by line, but unless you remove the "\n", it your line variable will read
thethingsonthatline\n
This can be useful to see if a file contains multiple lines, but you'll want to get rid of it. Edchum and alvits has given a good way of doing this !
Your corrected code would be :
infile1 = open("D:/p/non_rte_header_path.txt","r")
infile2 = open("D:/p/fnsinrte.txt","r")
for line in infile1:
for item in infile2:
eachfile = open(line.rstrip('\n'), "r") | unknown | |
d4707 | train | Don't use relative paths for your URLs in the page. Start them all with a /. Change this:
<img src="images/image1.jpg" class="card-img" alt="...">
to this:
<img src="/images/image1.jpg" class="card-img" alt="...">
When the path does not start with a /, then the browser adds the path of the containing page URL to the URL before requesting it from the server because ALL requests to the server must be absolute URLs. That makes things break as soon as you are no longer on a top level page. But, if your URLS always start with /, then the browser doesn't have to mess with the path of the URL before requesting it. | unknown | |
d4708 | train | You just have to replace the argument to an input function to take input from the user. So the code will be changed from
obj = Circle(3)
to
obj = Circle(int(input("Please Enter Radius:")))
The int() before the input function is to convert the input from string to an integer.
To know more about taking input from user, please check out here.
A: class Circle:
def __init__(self, r):
self.radius = r
def area(self):
return 3.14 * (self.radius ** 2)
def perimeter(self):
return 2*3.14*self.radius
obj = Circle(int(input("Enter Radius:")))
#obj = Circle()
print("Area of circle:",obj.area())
print("Perimeter of circle:",obj.perimeter()) | unknown | |
d4709 | train | Please check data in column podate and validity. Any of this column is having string value. That is the reason why you are getting this error.
A: Try to use MSSQL server ISDATE() function it returns 0 if a string isn't date and 1 if it is date and can be converted. Try to run following select and check incorrect strings:
select 'incorrect podate', podate from dbo.tbl_POR_PO_MAIN where ISDATE(podate)=0
union all
select 'incorrect validity', validity from dbo.tbl_POR_PO_MAIN where ISDATE(validity)=0
A: Found this thread:
SQL Server expects dates in the format mm/dd/yyyy so you will need to
convert your date into this format before submitting.
The problem with this error is that if the day value of a date is
<=12, it will automagically be converted to mm/dd/yyyy giving you the
false impression that your code is working. it's not until the day
hits 13> that the problem raises it's ugly head.
Sounds like this could be the issue,maby you should take a looka the podate structure. | unknown | |
d4710 | train | Try something like this to do a force reload of the image. So every time the image is requested a new one will appear. Change your header like this.
header("Location:../profile_images/".$image."?".rand(1,3000)); | unknown | |
d4711 | train | Create .jshintrc file in your home directory and set es5 to FALSE.
{
"es5" : false, // true: Allow ES5 syntax (ex: getters and setters)
} | unknown | |
d4712 | train | If your ethernet shield is a cheap clone, they are known to be faulty.
You will be able to get a DHCP address by plugging it directly into your DHCP server, but you will not get an address if the shield is connected to a switch.
You can fix this by soldering 2 x 100 Ohm resistors to the correct pins of the network socket on the bottom of the shield.
Alternatively, use a static ip address, or buy a different ethernet shield. | unknown | |
d4713 | train | According to the line in the file you're getting the error, PHP is failing to parse this line:
protected $headersKeys = [];
The only issue that is possible here is that your PHP version is too old and does not work with the [] array definer.
You should update your PHP version to at least 5.4. | unknown | |
d4714 | train | There are two ways of doing it.
*
*Create context variable and use this variable in file mask.
*Directly use TalendDate.getDate() or any other date function in file mask.
See both of them in component
1st approach,
*
*Create context variable named with dateFilter as string type.
*Assign value to context.dateFilter=TalendDate.getDate("yyyy-MM-dd");
*Suppose you have file name as "ABC_2015-06-19.txt" then
*In tFileList file mask use this variable as follows.
"ABC_"+context.dateFilter+".*"
2nd approach
*
*In tFileList file mask use date function as follows.
"ABC_"+TalendDate.getDate("yyyy-MM-dd")+".*"
these are the two best way, you can make changes in file mask per your file names. | unknown | |
d4715 | train | extract 'location' from initial json, and then convert to DataFrame
with open('Location History.json', encoding='utf-8') as data_file:
data = json.loads(data_file.read())
pd.DataFrame(data['locations']) | unknown | |
d4716 | train | CAST('2016-07-14' AS DATETIME) -- the CAST is not needed; '2016-07-14' works fine. (Especially since you are comparing against a DATE.)
IN ( SELECT ... ) is inefficient. Change to a JOIN.
On eds_stock, instead of
INDEX(`Prime Item Nbr`)
have these two:
INDEX(`Prime Item Nbr`, `Date`)
INDEX(`Prime Item Nbr`, `Curr Traited Store/Item Comb.`, `Date`)
INT is always a 4-byte number, even if you say int(2). Consider switching to TINYINT UNSIGNED (and other sizes of INT).
float(4,2) -- Do not use (m,n); it causes an extra rounding and my cause undesired truncation. Either use DECIMAL(4,2) (for money), or plain FLOAT.
Bug?? Did you really want 8 days, not just a week in
AND `Date` BETWEEN CAST('2016-07-14' AS DATETIME) AND CAST('2016-07-21' AS DATETIME)
I like this pattern:
AND `Date` >= '2016-07-14'
AND `Date` < '2016-07-14' + INTERVAL 1 WEEK
Instead of two selects
SELECT count(*) AS rangedandselling
FROM ( SELECT DISTINCT `store_formats`.`Store Name` ...
One select will probably work (and be faster):
SELECT COUNT(DISTINCT `store_formats`.`Store Name`) AS rangedandselling ...
Once you have cleaned up most of that, we can get back to your question about 'wrong index', if there is still an issue. (Please start a new Question if you need further help.) | unknown | |
d4717 | train | This is pretty simple. Follow these steps
1) Go to your target build setting
2) Click on Add Build Phase (at buttom right corner) and choose Add Run Script
3) In the Edit Text Box copy paste this script
#!/bin/bash
echo "Copy Box database schema into bundle"
cp -fr ./Box.framework/Resources/BoxCoreDataStore.momd "${BUILT_PRODUCTS_DIR}/${CONTENTS_FOLDER_PATH}/BoxCoreDataStore.momd"
After Doing this click on build and you are done.
Happy coding
A: If someone faces the same problem than here is the fix:
You need to add files in Box.framework/Resources/BoxCoreDataStore.momd folder to your application package.
Add "Copy Files" phase and specify Destination = Executables, Subpath = ./BoxCoreDataStore.momd then add all files from above mentioned folder. | unknown | |
d4718 | train | Compress the theme into a zip file, and just upload it via the Wordpress Dashboard....
Appearance -> Themes -> then click on "Add New" -> then click on "Upload Theme" | unknown | |
d4719 | train | I figured out the answer. It works if I prepend the gem install command with CC='clang -fdeclspec'.
Like this:
CC='clang -fdeclspec' gem install sqlite3 | unknown | |
d4720 | train | There are two main issues.
*
*The call to minL in the addInput function doesn't have the right number of parameters.
*minL doesn't return a boolean value when addInput expects it to.
function minL(elem,event,nr){
var v = elem.value;
if(v.length < nr ){
elem.classList.add("invalid");
} else if (v.length > nr) {
elem.classList.add("invalid");
} else {
elem.classList.remove("invalid");
return true;
}
}
function addInput(elem,event){
event.preventDefault();
var container = document.querySelector("#containerNrTel");
if(minL(document.querySelector("[name=numarTelefon]"), event, 10)){
container.innerHTML += '<input type="text" placeholder="nr telefon" />';
}
} | unknown | |
d4721 | train | That's an Archimedean spiral curve. As the page says in polar coordinates the formula of the curve is r = aθ, usually the scalar a is 1 i.e. r = θ. Polar to cartesian conversion is
x = r cos θ, y = r sin θ
Hence
x = θ cos θ, y = θ sin θ
Varying θ from 0 to 6π would give the curve you've. When you vary the parameter θ and get x and y values what you get would be relative to the origin (0, 0). For your case, you've to translate i.e. move the points by the x and y offset to position it accordingly. If you want a bigger version of the same curve you've to scale (before translation) i.e. multiply both x and y values by a constant scalar.
A: (I think the spiral image is more confusing than helpful...)
for a point (x, y), you want to get back the angle theta in degrees, where (1,0) is at 0 degrees and (0, 1) is at 90 degrees.
So we want to find theta. Using trigonometry, we know that x is the adjacent side and y is the opposite side, and tan(theta) == y/x.
This is slightly confused by the fact that tan() repeats every 180 degrees - tan(y/x) == tan(-y/-x). Luckily, Python has a built-in function, atan2, that compensates for that. It returns theta in radians, and we convert that to degrees, like so:
from math import atan2, degrees
x, y = (2, 2)
theta = degrees(atan2(y, x)) # => theta == 45.0
however atan2 returns values in -2*pi < theta <= 2*pi (-179.9... to +180 degrees); you want it in (0.. 359.9...) degrees:
theta = (degrees(atan2(y, x)) + 360.0) % 360.0
A: You want a vector field where one of the trajectories is the Archimedean spiral.
If you take the spiral formula
x = θ cos θ, y = θ sin θ
from the answer of legends2k and compute its tangent, you get
vx = cos θ - θ sin θ, vy = sin θ + θ cos θ
Elimination of θ for x and y in the most straightforward way gives the general vector field
vx = x/r-y, vy = y/r + x, where r=sqrt(x^2+y^2).
The angle of the vector field is then obtained as atan2(vy,vx).
A: If someone could verify this I'd appreciate it.
This solution allows you to have a radius which grows at a different rate then the angle
radius:
r(t) = r_scalar * t
d(r(t))/dt = r_scaler
degrees:
a(t) = a0 + a_scalar * t
d(a(t))/dt = a_scaler
location:
x(t),y(t) = x0 + r(t)*cos(a(t)), y0 + r(t)*sin(a(t))
Now we can compute the direction of any t as:
d(x(t))/dt = r(t)*(-sin(a(t))*d(a(t))/dt) + d(r(t))/dt*cos(a(t))
d(y(t))/dt = r(t)*(cos(a(t))*d(a(t))/dt) + d(r(t))/dt*cos(a(t))
which simplifies:
d(x(t))/dt = r(t)*(-sin(a(t))*a_scaler) + r_scaler*cos(a(t))
d(y(t))/dt = r(t)*(cos(a(t))*a_scaler) + r_scaler*sin(a(t))
to get the a value of t for a,b such that it is closest to x(t),y(t). you can first approximate saying the distance x0,y0 to x1,y1 will satisfy r(t).
t0 = sqrt((x0 - x2)^2 + (y0 - y1)^2)/r_scalar
seeing that the closest point in the spiral will be at the same degree, adjust t minimally such that the angle is satisfied.. ie
t1 = t0-t2 where atan((y0 - y1)/(x0 - x2)) = (a0 + a_scalar * t0) % 2*pi - (a0 + a_scalar * t2)
thus
t2 = (((a0 + a_scalar * t0) % 2*pi) - atan((y0 - y1)/(x0 - x2)) + a0)/a_scalar
then the closest direction angle is atan((d(x(t0-t2))/dt / d(y(t0-t2))/dt))
A: import numpy as np
import matplotlib.pyplot as plt
import math
def fermat_spiral(dot):
data=[]
d=dot*0.1
for i in range(dot):
t = i / d * np.pi
x = (1 + t) * math.cos(t)
y = (1 + t) * math.sin(t)
data.append([x,y])
narr = np.array(data)
f_s = np.concatenate((narr,-narr))
return f_s
f_spiral = fermat_spiral(20000)
plt.scatter(f_spiral[len(f_spiral)//2:,0],f_spiral[len(f_spiral)//2:,1])
plt.scatter(f_spiral[:len(f_spiral)//2,0],f_spiral[:len(f_spiral)//2,1])
plt.show() | unknown | |
d4722 | train | As far as I know, Microsoft.Azure.Management.Resources.dll that implements the ARM API. We need to assign application to role, after that then we can use token in common. More information about how to assign application to role please refer to the article .This blog also has more detail steps to get AceessToken. | unknown | |
d4723 | train | spring-boot-starter-web already includes Jackson. You should not override the managed version, otherwise the versions can be different between different Jackson libraries, causing ClassNotFoundException.
Remove this from the pom:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.5</version>
</dependency>
and let the transitive dependency with the correct version be used.
Or when you add Jackson to your pom, just don't use any version number, since parent project dependency management already includes all jackson libraries with a consistent version.
A: Try 2 options :
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.8</version>
or
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.7.3</version>
A: If you are using SpringBoot you should know that Jackson is added by default. so remove to avoid conflicting versions and it should work. | unknown | |
d4724 | train | I am not familiar with Selenium, but getting the page source for a url is easy with HttpClient:
string url = "https://www.instagram.com/" + _theUsername;
using (var httpClient = new HttpClient()){
var response = await httpClient.GetStringAsync(url);
Debug.WriteLine(response);
}
and response will have your page source. And if you do not want to show the web page then there is no need for a WebView anyway. | unknown | |
d4725 | train | Move
$.ajaxSetup({
data: window.csrf
});
in document.ready().
And like other answers point out, if you want to send csrf-token, you have to use headers key in ajaxSetup.
A: Here is the method binding the csrf token if you are using laravel
In head of app.blade.php
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
In JS.
// CSRF Token
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
A: You are passing data in post method which is overriding the one in ajaxSetup
jQuery.post( url [, data ] [, success ] [, dataType ] )
$.post('/awesome/ajax/url', { foo: 'bar' }, function(data)
Instead, you should pass it in headers, Refer How can I add a custom HTTP header to ajax request with js or jQuery?.
HTH | unknown | |
d4726 | train | This is a bug that was introduced in pandas 0.24.0, and fixed in 0.24.1. See https://github.com/pandas-dev/pandas/issues/24940 | unknown | |
d4727 | train | having done some research into this I can inform you that there are currently two version of Microsoft's Application Request Routing one for 32-bit architecture and the other for 64-bit.
Although it does not say, I would presume that the Web Platform Installer version is only for 32-bit, in order to get a 64-bit specific version you are going to have to download from one these two locations:
http://blogs.iis.net/wonyoo/archive/2011/04/20/how-to-install-application-request-routing-arr-2-5-without-web-platform-installer-webpi.aspx
or
http://www.microsoft.com/en-us/download/details.aspx?id=7173
the blog (first URL) gives details on how to install into IIS once you have downloaded.
hope this proves useful.
A: What processor architecture are you using?
The error seems to suggest that only 64bit AMD processors are currently supported, perhaps it might be worth looking into a solution more specific to your processor.
I'm guessing your using an Intel CPU?
I'm aware that there are certain scenarios where running IIS in 32 bit mode on a 64 bit system is required.
A: it might be worth looking at these installation guidelines on the IIS site found at this address:
http://www.iis.net/learn/extensions/installing-application-request-routing-%28arr%29/install-application-request-routing
if these don't solve the issue it might well be worth either posting on the IIS forum:
http://forums.iis.net/
or posting on technet forum:
http://social.technet.microsoft.com/Forums/en-gb/categories/ | unknown | |
d4728 | train | It is because of your xml file path, be sure about that your path directory is true. I checked your code in my pc and worked well. Search your "haarcascade_frontalface_alt2.xml" file in your pc and copy it to your code.
The same problem was also mentioned here | unknown | |
d4729 | train | Ok, stupid mistake...
When launching the app, I init my AVCaptureSession, add inputs, outputs, etc. And I was just calling start_new_record a bit too soon, just before commitConfiguration was called on my capture session.
At least my code might be useful to some people.
A: SWIFT 4
SOLUTION #1:
I resolved this by calling file_writer?.startWriting() as soon as possible upon launching the app. Then when you want to start recording, do the file_writer?.startSession(atSourceTime:...).
When you are done recording and call finishRecording, when you get the callback that says that's complete, set up a new writing session again.
SOLUTION #2:
I resolved this by adding half a second to the starting time when calling AVAssetWriter.startSession, like this:
start_recording_time = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)
let startingTimeDelay = CMTimeMakeWithSeconds(0.5, 1000000000)
let startTimeToUse = CMTimeAdd(start_recording_time!, startingTimeDelay)
file_writer?.startSession(atSourceTime: startTimeToUse)
SOLUTION #3:
A better solution here is to record the timestamp of the first frame you receive and decide to write, and then start your session with that. Then you don't need any delay:
//Initialization, elsewhere:
var is_session_started = false
var videoStartingTimestamp = CMTime.invalid
// In code where you receive frames that you plan to write:
if (!is_session_started) {
// Start writing at the timestamp of our earliest sample
videoStartingTimestamp = currentTimestamp
print ("First video sample received: Starting avAssetWriter Session: \(videoStartingTimestamp)")
avAssetWriter?.startSession(atSourceTime: videoStartingTimestamp)
is_session_started = true
}
// add the current frame
pixelBufferAdapter?.append(myPixelBuffer, withPresentationTime: currentTimestamp)
A: This is for future users...
None of the above worked for me and then I tried changing the camera preset to medium which worked fine | unknown | |
d4730 | train | Because this:
let User = {
name,
email
};
is a shortform for:
let User = {
name: name,
email: email,
};
So it directly initializes both properties to the value that the variables name and email are holding. name is defined, it is the name of the page you are in, which you can easily check with:
console.log(name);
but email is not defined yet, and trying to get an undeclared variable results in an error:
console.log(email); // email is not defined
To solve that, explicitly declare both variables before:
let name = "test";
let email = "[email protected]";
let User = {
name,
email
};
Or initialize the properties not at all:
let User = {};
or directly set the properties to a value:
let User = {
name: "test",
email: "[email protected]",
};
A: Your code is ok,
Please check do you have any existing name,email variable which you are set in the User Object,
I think you do not have existing name and email variable. So that It can not create the User Object itself.
You can do like this..
let User = {};
User['name']='Praveen';
User['email']='[email protected]';
This link could help you, https://alligator.io/js/object-property-shorthand-es6/ | unknown | |
d4731 | train | Did you restage the app after un-binding? Changes to bindings don't take affect until after an app has been restaged. You can verify by running cf env app-name and seeing of the VCAP_SERVICES environment variable is still set. | unknown | |
d4732 | train | The question is not very clear, but for my understanding, this is what you are looking for
Firestore.instance.collection('save')
.where('fav', arrayContains: '[email protected]').snapshots()
A: The question is not very clear, but for my understanding, you want to find one e-mail in the array field. This array is contained on each document, and all the documents are "streamed" in a collection of snapshots.
Contains Method: https://api.dartlang.org/stable/2.0.0/dart-core/Iterable/contains.html
bool contains (
Object element
)
Returns true if the collection contains an element equal to element.
This operation will check each element in order for being equal to element, unless it has a more efficient way to find an element equal to element.
The equality used to determine whether element is equal to an element of the iterable defaults to the Object.== of the element.
Some types of iterable may have a different equality used for its elements. For example, a Set may have a custom equality (see Set.identity) that its contains uses. Likewise the Iterable returned by a Map.keys call should use the same equality that the Map uses for keys.
Implementation
bool contains(Object element) {
for (E e in this) {
if (e == element) return true;
}
return false;
} | unknown | |
d4733 | train | It is not possible to either delete a dataset or change its datatype. From section 5.3.2 of the HDF5 manual:
The datatype is set when the dataset is created and can never be changed.
This is due to how space is assigned in an HDF5 file. While it's not possible to delete a dataset (for the same reasons), it can be "unlinked" and be made inaccessible, but this does not reclaim the used space.
If you really need to change the datatype, you have two choices: the first is to unlink the old dataset and create a new one in its place. The new dataset can have the same name as the old one. However, if space is a concern, you may prefer to just create an entirely new HDF5 file, and copy the old data into the new one.
A: According to This post which is a similar problem there is no mechanism for deleting a dataset in an HDF5 file. It also indicates that it is possible to Modify in place. | unknown | |
d4734 | train | I think you are trying to do something like this.
List<Integer> filters=new ArrayList<>();
filters.add(Place.TYPE_ESTABLISHMENT);
AutocompleteFilter autocompleteFilter=AutocompleteFilter.create(filters);
PendingResult<AutocompletePredictionBuffer> pendingResult=Places
.GeoDataApi
.getAutocompletePredictions(sGoogleApiClient,"delhi", rectangleLyon, autocompleteFilter);
//rectangleLyon is LatLngBounds, to remove filters put autocompletefilter as null
// Second parameter(as String "delhi") is your search query
AutocompletePredictionBuffer autocompletePredictionBuffer=pendingResult.await(10, TimeUnit.SECONDS);
Status status=autocompletePredictionBuffer.getStatus();
Iterator<AutocompletePrediction> iterator=autocompletePredictionBuffer.iterator();
while (iterator.hasNext()){
AutocompletePrediction autocompletePrediction=iterator.next();
// do something
}
You can add more filters using
filters.add(Place.<MORE FILTERS>); //example TYPE_AIRPORT
Check here for more filter types
https://developers.google.com/places/supported_types | unknown | |
d4735 | train | You seem to be using the wrong API. The setContent() method and the options hash is part of the leaflet-sidebar library API, but not of sidebar-v2. | unknown | |
d4736 | train | Reading various articles about this on the wide web, there seems to be very few guides for specific images, but this
http://allyssabarnes.com/2013/07/22/how-to-block-your-images-from-being-pinned/
link shows:
<meta name="pinterest" content="nopin" description="Enter your new description here" />
and
<img src="your-image.png" nopin="nopin">
Which leads me to establish that due to Opengraph being a meta feature that you would need to do something like:
<meta property="og:image" content="jamesngart.com/img/OG-Harvester.jpg" nopin="nopin" />
I would also hope you'd be using https://developers.pinterest.com/docs/getting-started/introduction/ for reference as well.
See also https://stackoverflow.com/a/10421287/3536236
Which actually states that (as of 2012) Pinterest does not directly reference OG:images in its processing.
Overall it's a little questionable why you would want to share an image on OpenGraph, (ie for Facebook and Google searches) that would then not be available for Pinterest specifically.
A: Don't add the nopin attribute to the facebook open (og) graph metatag.
Instead create a new meta tag and add it below or above the opengraph tag.
In the following example - pinning is disabled for the whole page:
<meta property="og:image" content="jamesngart.com/img/OG-Harvester.jpg" />
<meta name="pinterest" content="nopin" />
If you want to disable pinning per image you have to add the nopin attribute to the image (IMG) tag:
<img src="jamesngart.com/img/OG-Harvester.jpg" nopin="nopin" />
Read more about pinterest data-attributes and metatags in this article at csstricks | unknown | |
d4737 | train | Try out this, Change your code as below :
scan_btn = findViewById(R.id.scan_btn);
A: It does not affect your code. This is a new feature of Android studio that directly maps the widget from your XML to Java code. Your app may crash for any other reason
A: Starting with API 26, findViewById uses inference for its return type, so you no longer have to cast.
Old definition:
Button btn = (Button) findViewById(R.id.btn)
New definition:
<T extends View> T findViewById(R.id.value)
So if your compile Sdk is at least 26, it means that you can make use of this. No need casting. | unknown | |
d4738 | train | I don't think the zip utility supports this sort of transformation. A workaround is to use a symbolic link:
ln -s directory new_directory
zip -r foo.zip new_directory
rm new_directory
If other archive formats are an option for you, then this would be a bit easier with a tar archive, since GNU tar has a --transform option taking a sed command that it applies to the file name before adding the file to the archive.
In that case, you could use (for example)
tar czf foo.tar.gz --transform 's:^directory/:new_directory/:' directory | unknown | |
d4739 | train | Apparently the dot is actually included in the key name, try:
myObject['screeningField.displayName'] | unknown | |
d4740 | train | There is one immediate problem with the design as you describe it if you intend to block the thread waiting for messages - which is the use variable sized messages and a CR as the delimiter.
I imagine that HalUARTReadDMA() is designed to block the calling thread until len bytes have been received so you clearly cannot reliably use it to block for a variable length message.
The code would look something like (making a few assumptions):
while (1)
{
static const size_t bufferSize = sizeof(Message_t);
uint8_t buffer[bufferSize];
// blocks until message received
unsigned len = HalUARTReadDMA(buffer, bufferSize);
if (len == bufferSize)
processMessage(buffer);
}
There's no particularly nice or reliable solution to the problem of using variable sized messages with DMA that doesn't involve polling - unless the DMA controller can detect end-of-message delimiters for you.
If you can't change the message format, you'd be better off with interrupt-driven IO in which you block on reception of individual message bytes - especially in the case of a UART, which has relatively low data rate.
A: Unless your DMA driver has the functinality to accept a queue of buffer pointers, can generate an interrupt when a CR is received and move on its own to the next buffer pointer, you are going to be stuck with iterating the rx data, looking for a CR.
If you have to iterate the data, you may as well do it in a 'classic' ISR, fetching the chars one-by-one from the rx FIFO and shoving them into a buffer until a CR is received.
You could then queue the buffer pointer into a suitable circular queue, fetch another buffer from another circular pool queue of 'empty' buffers for the next message, signal a semaphore so that the thread that is going to handle the message will be run and exit from your ISR via the OS so that an immediate reschedule is performed.
The rx thread could dequeue the message, process it and then requeue it to the pool queue for re-use by the ISR.
Continually searching a complete buffer for a CR with strchr() is not likely to be particularly efficient or easy - the CR may be in the middle of the DMA buffer and you involve yourself with data copying of the remining partial buffer.
. | unknown | |
d4741 | train | _M_AMD64 appears to be specific to Visual Studio compilers. The question is confusing because it suggests that CMake is doing the pre-processing. It doesn't. You are using gcc. gcc doesn't appear to implement the Visual Studio specific pre-processor macros.
You'll either have to alter the code to work with gcc or define the missing macros yourself using a CMake command like target_compile_definitions.
Be aware that the README file says to use Visual Studio 2015 for building on Windows. | unknown | |
d4742 | train | Here's what I ended up with. It works because onTouchStart is always calld before onClick if it's a touch event and if not's then the custom logic gets called anyway. It also fires before the hover has happened. This preserves the :hover event. e.preventDefault() did not.
let isVolumeBarVisible;
const onTouchStartMute = e => (
isVolumeBarVisible = e.currentTarget.nextElementSibling
.querySelector('.jp-volume-bar-container').clientHeight > 0
);
const onClickMute = () => () => {
if (isVolumeBarVisible !== false) {
// Do custom mute logic
}
isVolumeBarVisible = undefined;
};
<Mute
aria-haspopup onTouchStart={onTouchStartMute}
onClick={onClickMute}
>
<i className="fa">{/* Icon set in css*/}</i>
</Mute>
A: What you can do is use a flag to indicate you were in a touch event before being in your mouse event, as long as you are using bubble phase. So attach a listener to your container element like this:
let isTouch = false;
const handleContainerClick = () => isTouch = false;
const handleMuteClick = () => {
if (isTouch == false) {
console.log("mute toggled");
}
};
const volumeControlOnClick = () => {
isTouch = true;
};
class Volume extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<div className="jp-volume-container" onClick={handleContainerClick}>
<Mute onTouchStart={volumeControlOnClick} onClick={handleMuteClick}><i className="fa fa-volume-up" /></Mute>
<div className="jp-volume-controls">
<div className="jp-volume-bar-container">
<VolumeBar />
</div>
</div>
</div>
);
}
};
class Mute extends React.Component {
render() {
return (
<button className="jp-mute" onTouchStart={this.props.onTouchStart} onClick={this.props.onClick}>
{this.props.children}
</button>
);
}
};
class VolumeBar extends React.Component {
render() {
return (
<div className="jp-volume-bar" onClick={() => console.log("bar moved")}>
{this.props.children}
</div>
);
}
};
render(<Volume />, document.getElementById('container'));
If you are not using bubble phase so you can register a timeout of 100ms with the same logic above, where after 100ms you make your flag variable false again. Just add to your touchStart handler:
setTimeout(() => {isTouch = false}, 100);
EDIT: Even though touch events are supposed to be passive by default in Chrome 56, you call preventDefault() from a touchEnd event to prevent the click handler from firing. So, if you can't modify the click handler of your Mute class in any way, but you can add a touchEnd event, than you could do:
const handleTouchEnd = (e) => e.preventDefault();
const volumeControlOnClick = () => console.log("volumeControlOnClick");
class Volume extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<div className="jp-volume-container">
<Mute onTouchStart={volumeControlOnClick} onTouchEnd={handleTouchEnd}><i className="fa fa-volume-up" /></Mute>
<div className="jp-volume-controls">
<div className="jp-volume-bar-container">
<VolumeBar />
</div>
</div>
</div>
);
}
};
class Mute extends React.Component {
render() {
return (
<button className="jp-mute" onTouchStart={this.props.onTouchStart} onTouchEnd={this.props.onTouchEnd} onClick={() => console.log("mute toggled")}>
{this.props.children}
</button>
);
}
};
class VolumeBar extends React.Component {
render() {
return (
<div className="jp-volume-bar" onClick={() => console.log("bar moved")}>
{this.props.children}
</div>
);
}
};
render(<Volume />, document.getElementById('container'));
A: Try this
render() {
return (
<div className="jp-volume-container" onClick={handleContainerClick}>
<Mute onTouchStart={volumeControlOnClick} onClick={handleMuteClick}><i className="fa fa-volume-up" /></Mute>
<div className="jp-volume-controls">
<div className="jp-volume-bar-container">
<VolumeBar />
</div>
</div>
</div>
);
}
};
class Mute extends React.Component {
render() {
return (
<button className="jp-mute" onTouchStart={this.props.onTouchStart} onClick={this.props.onClick}>
{this.props.children}
</button>
);
}
};
class VolumeBar extends React.Component {
render() {
return (
<div className="jp-volume-bar" onClick={() => console.log("bar moved")}>
{this.props.children}
</div>
);
}
};
render(<Volume />, document.getElementById('container')); | unknown | |
d4743 | train | curl_setopt($ch, CURLOPT_POSTFIELDS, array('recipient'=>'123123', 'message'=>'assss'));
I just change the above code to this:
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
where $postData is:
$postData = 'recipient='.$recipient.'&message='.$message['message']
Alas! | unknown | |
d4744 | train | const player = {
currentChoice: null
}
const computer = {
currentChoice: null
}
const choices = ["Lapis", "Papyrus", "Scalpellus"];
document.querySelector('#Lapis').onclick = setLapis
document.querySelector('#Papyrus').onclick = setPapyrus
document.querySelector('#Scalpellus').onclick = setScalpellus;
function setLapis(){
player.currentChoice = choices[0];
console.log(player.currentChoice);
}
function setPapyrus(){
player.currentChoice = choices[1];
console.log(player.currentChoice);
}
function setScalpellus(){
player.currentChoice = choices[2];
console.log(player.currentChoice);
}
<button id="Lapis">Lapis</button>
<button id="Papyrus">Papyrus</button>
<button id="Scalpellus">Scalpellus</button> | unknown | |
d4745 | train | Figured it out - it's not a stacked graph I want, but a dodged graph with full overlap / no offset. position_dodge to the rescue!
ggplot(x, aes(x = reorder(species, -age), y = age, fill = lifestage)) +
geom_bar(stat="identity", position = position_dodge(width = 0), width = 2) +
coord_flip() | unknown | |
d4746 | train | Strictly speaking, this is a directed graph traversal not a directed tree.
A simple algorithm, that ignores the edges but based on position, and gives the expect output is:
>>> positions = [Node.objects.filter(position=i) for i in range(1,3+1)]
>>> import itertools
>>> list(itertools.product(positions))
[(<Node: A1>, <Node: B1>, <Node: C1>),
(<Node: A2>, <Node: B1>, <Node: C1>),
(<Node: A3>, <Node: B1>, <Node: C1>)] | unknown | |
d4747 | train | I guess you are looking for something like this :
## giving a vector x and a threshold .thresh
## returns the min index, where the cumulative sum of x > .thresh
get_min_threshold <-
function(x,.thresh)
max(which(cumsum(x[order(x)]) < .thresh))+1
## apply the function to each column of the data.frame
lapply(ndx,get_min_threshold,.thresh=.98) | unknown | |
d4748 | train | You're describing multitenancy - create one table for N 'tenants' instead of N identical (or nearly) tables, but partition it with a tenant_id column, and use that to filter results in SQL WHERE clauses.
For example the generated code for findByUsername would be something like select * from person where username='foo' and tenant_id=3' - the same code as a regular call but with the tenant_id column to restrict within that tenant's data.
Note that previously simple things like unique constraints are now harder because you would want to restrict uniqueness within a tenant, but allow a value to be reused across tenants. In this case changing the unique constraint to be on the combo of username and tenant_id works and does the heavy lifting in the database.
For a while there were several related plugins, but they relied on tweaking internal APIs and some features broke in newer Hibernate versions. But I believe that http://grails.org/plugin/multi-tenant-single-db is active; it was updated over a year ago, but it is being used. Contact the authors if it looks like it'll be what you need to be sure it's active. Note that this can only work with Hibernate 3.x.
Hibernate 4 added support for multitenancy, but I haven't heard much about its use in Grails (which is expected, since it's not that common a requirement). It's not well documented, but this bug report highlights some of the potential pitfalls and should still be a working example (the test app is still on GitHub): https://jira.grails.org/browse/GPHIB-6.
I'd like to ensure that this is working and continues to work, so please let me know via email if you have issues later. It's a great feature and having it in Hibernate core makes things a lot easier for us. But we need to make it easy to use and well-documented, and that will happen a lot faster when it's being used in a real project. | unknown | |
d4749 | train | Use query to find the current status of document with 'Id':x and the update the other document using UpdateExpression with "ADD"
import boto3
from boto3.dynamodb.conditions import Key, Attr
from datetime import datetime
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('your_table_name')
result = table.query(
KeyConditionExpression=Key('Id').eq('x')
)
if result is None or result['ExpiresAt'] < datetime.now():
table.update_item(
Key={
"Id": "y"
},
UpdateExpression='ADD counter :inc',
ExpressionAttributeValues={
':inc': {'N': '1'}
}
) | unknown | |
d4750 | train | The answer to my question turned out rather simple:
dynamic pObj = JObject.Parse(obj).ToObject<ExpandoObject>();
I had to cast it as ExpandoObject not just dynamic.
@Tsahi: this is not a design problem. My intention was to provide the server with parameters (filter) which is a quite common task for a client to reduce the dataset to be transferred. We could debate a standard way how to provide these parameters, however. In my special case the most practical way is the anonymous object. | unknown | |
d4751 | train | Disclaimer: I work for Spotify
Upon examination of the Android app's source code, it seems that launching the radio is done with an internal intent. In other words, via an unpublished URI scheme which is unpublished because it is subject to change between versions.
I'm not sure if this is a feature which is planned for the mobile clients, though I'll certainly ask around internally about it. I would encourage making a thread on the community forums (they do get read) pushing for it as well.
Update: Apparently the reason for using an internal URI scheme is that when the radio feature was developed for the Android app, the URI scheme was not completely finalized. The team seems interested in fixing this behavior, and I've filed a JIRA ticket as a reminder for them. | unknown | |
d4752 | train | Use JSONObject for simple JSON and JSONArray for array of JSON.
try {
JSONParser parser = new JSONParser();
JSONObject data = (JSONObject) parser.parse(
new FileReader("/config.json"));//path to the JSON file.
JSONObject jsonObject = data.getJSONObject("exclusion");
JSONArray array= jsonObject.getJSONArray("pid");
} catch (Exception e) {
e.printStackTrace();
}
Use google-simple library
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
A: Try this:
String jsonTxt = IOUtils.toString( is );
JSONObject json = (JSONObject) JSONSerializer.toJSON( jsonTxt );
JSONObject exclusion= json.getJSONObject("exclusion");
String serviceLevelList[]= pilot.getString("serviceLevelList");
String pid[]= pilot.getString("pid");
A: You Can Try methods Of Gson Object to convert JSON to Java Object and Vise Versa.
for That you Can Use Dependancy as follows
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6.2</version>
</dependency>
Gson object Provides several methods as follows :
Gson gson = new Gson();
// Convert Java object to JSON and assign to a String
String jsonInString = gson.toJson(obj);
//Convert JSON to Java object, read it from a JSON String.
String jsonInString = "{'name' : 'myname'}";
Staff staff = gson.fromJson(jsonInString, Student.class);
you can try this with your code :-)
A: We have been using XStream for years now. Although our main use has been for .XML files, it also supports reading and writing JSON as well, and we've used like that for a couple of times.
Include it in your maven project with this dependency snippet:
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.11</version>
</dependency>
You have all info you need in their web site. They even have a "Two minute tutorial" and a "JSON Tutorial" that might be of use (which, by the way, has a "Read from JSON" mention that might be directly applicable to your case). There are also several posts across the internet, as they documented in their references section, and even a XStream course in StudyTrails.
A: By using JSONObject and JSONArray classes you can perform different operation on json data.
Refer this link for know about handling the json data of different format, | unknown | |
d4753 | train | First, the user has to generate
String token = FirebaseInstanceId.getInstance().getToken(); and then store it in firebase database with userId as key or you can subscribe the user to any topic by FirebaseMessaging.getInstance().subscribeToTopic("topic");
To send notification you have to hit this api https://fcm.googleapis.com/fcm/send with headers "Authorization" your FCM key and Content-Type as "application/json" the request body should be
{
"to": "/topics or FCM id",
"priority": "high",
"notification": {
"title": "Your Title",
"text": "Your Text"
}
"data": {
"customId": "02",
"badge": 1,
"sound": "",
"alert": "Alert"
}
}
or you can Use okHttp which is not recommended method because your FCM key will be exposed and can be misused.
public class FcmNotifier {
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
public static void sendNotification(final String body, final String title) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
OkHttpClient client = new OkHttpClient();
JSONObject json = new JSONObject();
JSONObject dataJson = new JSONObject();
dataJson.put("text", body);
dataJson.put("title", title);
dataJson.put("priority", "high");
json.put("notification", dataJson);
json.put("to", "/topics/topic");
RequestBody body = RequestBody.create(JSON, json.toString());
Request request = new Request.Builder()
.header("Authorization", "key=your FCM key")
.url("https://fcm.googleapis.com/fcm/send")
.post(body)
.build();
Response response = client.newCall(request).execute();
String finalResponse = response.body().string();
Log.i("kunwar", finalResponse);
} catch (Exception e) {
Log.i("kunwar",e.getMessage());
}
return null;
}
}.execute();
}
}
A: This is the simplest way I can achieve notification with android and the help of firebase database.
add this to AndroidManifest.xml
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<service android:name="YourNotificationService"></service>
<application>
<receiver android:name=".BootListener">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
</application>
and then make a java class that extends BroadcastReceiver for boot listener
public class BootListener extends BroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
context.startService(new Intent(context, YourNotificationService.class));
}
}
and then make a java class that extends service to run your notification on background
public class YourNotificationService extends Service {
private DatabaseReference mDatabase;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent pIntent, int flags, int startId) {
mDatabase = /*your firebase*/
mDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
/* your code */
}
@Override
public void onCancelled(DatabaseError databaseError) {}
});
return super.onStartCommand(pIntent, flags, startId);
}
}
and you could combine this with SharedPreference or user information to listen to a specific firebase database. | unknown | |
d4754 | train | I tend to use png files rather than vector based graphics such as pdf or eps for this situation. The files are much smaller, although you lose resolution.
If it's a more conventional scatterplot, then using semi-transparent colours also helps, as well as solving the over-plotting problem. For example,
x <- rnorm(10000); y <- rnorm(10000)
qplot(x, y, colour=I(alpha("blue",1/25)))
A: Beyond Rob's suggestions, one plot function I like as it does the 'thinning' for you is hexbin; an example is at the R Graph Gallery.
A: Here is one possible solution for downsampling plot with respect to the x-axis, if it is log transformed. It log transforms the x-axis, rounds that quantity, and picks the median x value in that bin:
downsampled_qplot <- function(x,y,data,rounding=0, ...) {
# assumes we are doing log=xy or log=x
group = factor(round(log(data$x),rounding))
d <- do.call(rbind, by(data, group,
function(X) X[order(X$x)[floor(length(X)/2)],]))
qplot(x,count,data=d, ...)
}
Using the definition of ccdf() from above, we can then compare the original plot of the CCDF of the distribution with the downsampled version:
myccdf=ccdf(rlnorm(10000,3,2.4))
qplot(x,count,data=myccdf,log='xy',main='original')
downsampled_qplot(x,count,data=myccdf,log='xy',rounding=1,main='rounding = 1')
downsampled_qplot(x,count,data=myccdf,log='xy',rounding=0,main='rounding = 0')
In PDF format, the original plot takes up 640K, and the downsampled versions occupy 20K and 8K, respectively.
A: I'd either make image files (png or jpeg devices) as Rob already mentioned, or I'd make a 2D histogram. An alternative to the 2D histogram is a smoothed scatterplot, it makes a similar graphic but has a more smooth cutoff from dense to sparse regions of space.
If you've never seen addictedtor before, it's worth a look. It has some very nice graphics generated in R with images and sample code.
Here's the sample code from the addictedtor site:
2-d histogram:
require(gplots)
# example data, bivariate normal, no correlation
x <- rnorm(2000, sd=4)
y <- rnorm(2000, sd=1)
# separate scales for each axis, this looks circular
hist2d(x,y, nbins=50, col = c("white",heat.colors(16)))
rug(x,side=1)
rug(y,side=2)
box()
smoothscatter:
library("geneplotter") ## from BioConductor
require("RColorBrewer") ## from CRAN
x1 <- matrix(rnorm(1e4), ncol=2)
x2 <- matrix(rnorm(1e4, mean=3, sd=1.5), ncol=2)
x <- rbind(x1,x2)
layout(matrix(1:4, ncol=2, byrow=TRUE))
op <- par(mar=rep(2,4))
smoothScatter(x, nrpoints=0)
smoothScatter(x)
smoothScatter(x, nrpoints=Inf,
colramp=colorRampPalette(brewer.pal(9,"YlOrRd")),
bandwidth=40)
colors <- densCols(x)
plot(x, col=colors, pch=20)
par(op) | unknown | |
d4755 | train | So, by investigating about this question I got the following conclusions:
*
*QtWebView DOES support SVG elements in the HTML. I figure that this is true at least since Qt V4.7, since it is the one I'm presently using;
*Still don't know why d3.min.js works and the "regular" d3.js doesn't;
*D3.js doesn't have to be added to Qt's resources, calling it in the HTML file is enough.
Hope this helps anyone finding the topic. | unknown | |
d4756 | train | For the one's that are interested: here is the final solution.
(Big thanks to @Kintamasis )
*
*Install Gulp / Gulp BrowserSync
*Create a gulpfile.js in your themes' folder.
var gulp = require('gulp');
var browserSync = require('browser-sync').create();
gulp.task('browser-sync', function() {
browserSync.init({
proxy: "YOUR PROXY HERE"
});
gulp.watch("*").on('change', browserSync.reload);
});
*Run gulp browser-sync in your WP theme folder. | unknown | |
d4757 | train | I got the answer:
>>> re.findall(r'(?:abc.*\d+.tar.bz2|xyz\-ok.*.tar.bz2)', a)
['abc330b125.tar.bz2']
A: You can use this regex:
re.findall(r"[\w-]+\.tar.bz2",a)
result
# ['abc330b125.tar.bz2', 'my-libs.tar.bz2']
If you want all filenames, you can do it:
re.findall(r"[\w-]+\.tar.(bz2|gz)",a)
result
# ['abc330b125.tar.bz2', 'my-libs.tar.bz2', 'xyz-notok-0.tar.gz' ]
A: You're using "findall," so I assume you want to find all of the tar files. If that's the case, this will work:
re.findall('\S*\.tar\.bz2', a)
['abc330b125.tar.bz2', 'my-libs.tar.bz2']
If you only want to find the ones beginning with "abc," containing only letters and numbers, you could use this:
re.findall('abc\w*\.tar\.bz2', a)
['abc330b125.tar.bz2']
A: I tried to use regex101.com (awesome website for testing regular expressions) to make some tests and it seems that this regular expression :
[a-zA-Z0-9-_]*(.)(tar)(.)(bz2)
captures what you are asking for.
I'm sure you already know, but for anyone who might want a clarification: to capture the actual "." in the string, you need to enclose them in parentheses.
Hope this helps ! | unknown | |
d4758 | train | You are inflating your view inside onCreateView, but you don't pass it to the system. Instead you tell it to inflate its own (you return super). It doesn't make any sense.
You should return your v view like so:
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragmentmusiclist, container, false);
// ...
return v;
} | unknown | |
d4759 | train | Unity (or any IoC container framework) is basically a super-factory, creating objects and handing them to you. How is it supposed to create an instance of a static class?
Refactor your design to use a non-static class. If necessary create a class that wraps the static class and delegates to it.
EDIT: If you specifically want the container to call an existing static factory method, you can use StaticFactoryExtension.
EDIT: Unless you need to swap out implementations after deployment, I'd recommend avoiding XML configuration and writing fluent configuration code (calling container.RegisterType, etc.) in a single place in your application instead. You can still use separate configuration code in your unit tests. | unknown | |
d4760 | train | This one-liner must certainly be possible to further simplify, but I haven't managed to come up with one that's readable. I'm sure you can improve it.
def means = str.trim().split('\n')*.split(',').collect{it*.trim().collect{e -> new BigDecimal(e)}.withIndex()}.collect{e -> e.collect{ee->[(ee[1]): [ee[0]]].entrySet()}}.flatten().groupBy{it.key}.collectEntries{key, val -> [(key):val*.value.flatten().average()]}
With your test input, it produces
[0:0.6155980983990644, 1:0.20778834435382369, 2:0.7596710859407870,
3:0.32559653419534601, 4:0.8212399996214238, 5:0.43146512277478637,
6:0.5688295357050794, 7:0.16873360404239284]
Where the keys are the column indices and the values are the corresponding means. | unknown | |
d4761 | train | This does belong on ServerFault.
However.
Stopping a service with net.exe actually does two things:
*
*Sends the stop command to the service.
*Wait an amount of time (either 30s or 60s, IIRC) to see if the service has stopped. If it has, report success. Else, error.
My guess it that net.exe stop splunk is hitting whatever timeout that net.exe uses sometimes.
What you can do instead is:
sc.exe stop splunk
The sc.exe command will only do step 1. It sends the stop command and immediately returns. The PowerShell cmdlet Stop-Service will do the same thing, IIRC. Note that net.exe and sc.exe are not native PowerShell commands or cmdlets. They're standard programs.
You can also do this to wait, say, 5 seconds:
$svc = Get-Service splunk;
$svc.Stop();
$svc.WaitForStatus('Stopped','00:00:05');
And then you can look at $svc.Status to see what it's doing.
Or you can tell it to wait indefinitely:
$svc = Get-Service splunk;
$svc.Stop();
$svc.WaitForStatus('Stopped');
Get-Service returns an object of type System.ServiceProcess.ServiceController. You can take a look at $svc | Get-Member or $svc | Format-List to get more information about the object and what you can do with it.
If you want your script to be able to kill the process, you'll probably need to get the PID. That's somewhat more complex because the above class doesn't expose the PID for some stupid reason. The typical method is WMI:
$wmisvc_pid = (Get-WmiObject -Class Win32_Service -Filter "Name = 'splunk'").ProcessId;
Stop-Process $wmisvc_pid -Force;
WMI also exposes it's own Start() and Stop() methods, and is particularly useful because Start-Service and Stop-Service don't work remotely, but WMI does. | unknown | |
d4762 | train | What I think you need to do is:
if you are using the package https://github.com/fruitcake/laravel-cors you will have config/cors.php and there is where you should add
'exposed_headers' => ['_msg'],
and you have to create the middleware as it's explained in the issue https://github.com/fruitcake/laravel-cors/issues/308#issuecomment-490969761
$response->headers->set('Access-Control-Expose-Headers', '_msg');
I hope it works | unknown | |
d4763 | train | First, I would simplify the code a bit. The three var calculation in all three branches seem to be the same. So is the updating of #hours_left. You should be able to factor them out of the if. This will also reduce the number of if branches from 3 to 1 - if I am not missing something.
As for the problem, I would look at the_current_time. You are not zero padding the minutes, so 10:05 will become 105, or 1:05. I can't see how this would cause any dramas, as the calculations do not depend on this value, but it will change the if branch you will take.
Ah, I missed the time_hours calculation difference in the first branch of if. It uses opening_hours instead of target_hours. This explains why a bad the_current_time will make a difference on the reported value. | unknown | |
d4764 | train | Add this to your body
http://www.redips.net/javascript/adding-table-rows-and-columns/
<button onclick="addRow()">Add Row</button>
<button onclick="addCol()">Add Column</button>
<button onclick="removeRow()">Remove Row</button>
<button onclick="removeCol()">Remove Column</button>
<script>
var table = document.getElementById("po-table");
function addRow() {
var lastrow = table.rows.length;
var lastcol = table.rows[0].cells.length;
var row = table.insertRow(lastrow);
var cellcol0 = row.insertCell(0);
cellcol0.innerHTML = "<input type='text' name='course_code[]'></input>";
var cellcol1 = row.insertCell(1);
cellcol1.innerHTML = "<input type='text' name='course_name[]'></input>";
for(i=2; i<lastcol;i++)
{
var cell1 = row.insertCell(i);
cell1.innerHTML = "<input type='checkbox' name='pos[]'></input>";
}
}
function addCol() {
var lastrow = table.rows.length;
var lastcol = table.rows[0].cells.length;
var headertxt = table.rows[0].cells[lastcol-1].innerHTML;
var headernum = headertxt.slice(headertxt.indexOf("PO")+2);
headernum = headernum.trim();
//for each row add column
for(i=0; i<lastrow;i++)
{
var cell1 = table.rows[i].insertCell(lastcol);
if(i==0)
cell1.innerHTML = "PO " + (Number(headernum)+1);
else
cell1.innerHTML = "<input type='checkbox' name='pos[]'></input>";
}
}
function removeRow(){
var lastrow = table.rows.length;
if(lastrow<2){
alert("You have reached the minimal required rows.");
return;
}
table.deleteRow(lastrow-1);
}
function removeCol(){
var lastcol = (table.rows[0].cells.length)-1;
var lastrow = (table.rows.length);
//disallow first two column removal unless code is add to re-add text box columns vs checkbox columns
if(lastcol<3){
alert("You have reached the minimal required columns.");
return;
}
//for each row remove column
for(i=0; i<lastrow;i++)
{
table.rows[i].deleteCell(lastcol);
}
}
</script>
A: You can just clone the current row and append it to the table with the following jQuery:
$(".default-row").clone().insertAfter(".default-row:last-child");
An example of it working is here: http://jsfiddle.net/05Lo1sm6/
A: For Dynamic creation of tables with respect to entered row and column, you can use this code
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Dynamic Table</title>
<script>
function createTable()
{
rn = window.prompt("Input number of rows", 1);
cn = window.prompt("Input number of columns",1);
for(var r=0;r<parseInt(rn,10);r++)
{
var x=document.getElementById('myTable').insertRow(r);
for(var c=0;c<parseInt(cn,10);c++)
{
var y= x.insertCell(c);
y.innerHTML="Row-"+r+" Column-"+c;
}
}
}
</script>
<style type="text/css">
body {margin: 30px;}
</style>
</head><body>
<table id="myTable" border="1">
</table><form>
<input type="button" onclick="createTable()" value="Create the table">
</form></body></html> | unknown | |
d4765 | train | Well then just print the answer outside the loop. If I'm getting your doubt correctly.
list_A = []
list_B = []
num_sells = 0
num_buys = 0
num_holds = 0
for x in range(10000):
list_A.append(np.random.randint(0,10))
list_B.append(np.random.randint(0,10))
if list_A[x] > list_B[x]:
num_buys += 1
elif list_A[x] < list_B[x]:
num_sells += 1
else:
num_holds += 1
cprint("Buy!", 'green', attrs=['bold', 'reverse', 'blink'], file=sys.stderr)
cprint("Sell!", 'red', attrs=['bold', 'reverse', 'blink'], file=sys.stderr)
cprint("Hold!", attrs=['bold', 'reverse', 'blink', 'dark'], file=sys.stderr)
Like the above. | unknown | |
d4766 | train | I found that loopback which is based on express have these generators, for anyone interested in this | unknown | |
d4767 | train | The get() reads all documents from that collection. You need to use delete() to delete a document. Try refactoring the code as shown below:
const deleteChat = async () => {
const chatSnapShot = await db
.collection("chats")
.doc(router.query.id)
.collection("messages")
.get();
const deletePromises = chatSnapshot.docs.map(d => d.ref.delete());
await Promise.all(deletePromises)
console.log("Documents deleted")
};
Here chatSnapShot.docs is an array of QueryDocumentSnapshot and you can get DocumentReference for each doc using .ref property. Then the doc reference has .delete() method to delete the document. This method returns a promise so you can map an array of promises and run them at once using Promise.all()
You can also delete documents in batches of up to 500 documents using batched writes. | unknown | |
d4768 | train | You could escalate your permissions much the same way installers do it. It will require user interaction, as that's the way the OS is designed (and rightly so) - you can't go around it.
A: You cannot escalate permissions as such (at least I'd like to know about it, but doesn't seem possible as yet), but you need to run / start your app (embed into manifest) elevated.
Please take a look at these entries...
How do I force my .NET application to run as administrator?
Elevating process privilege programatically?
I'd suggest what comments said, running that from the setup. Or let your app run as admin from the start, or possibly jump start an elevated process from your app - when needed (e.g. running another exe of yours that has its manifest properly). | unknown | |
d4769 | train | You need to write a private validate function something like this.
class Auction < ActiveRecord::Base
validates :days,:presence => true, :numericality => { :greater_than_or_equal_to => 0, :only_integer => true }
validates :hours,:presence => true, :numericality => { :greater_than_or_equal_to => 0, :only_integer => true }
validate :days_and_hours
private
def days_and_hours
if !(days && hours)
errors.add_to_base("Days and hours can not be zero. Thank you.")
end
end
end
A: You can check for a value greater than 0 by using the numericality validator:
validates :auction_duration, :numericality => { :greater_than => 0 }
More info is at: http://guides.rubyonrails.org/active_record_validations_callbacks.html#numericality
A: So my final solution was an extension of @rharrison33:
validates :days,:presence => true, :numericality => { :greater_than_or_equal_to => 0, :only_integer => true }
validates :hours,:presence => true, :numericality => { :greater_than_or_equal_to => 0, :only_integer => true }
validate :days_and_hours
def days_and_hours
# It may not validate days and hours separately before validating days_and_hours,
# so I need to make sure that days and hours are both not NIL before trying to compute 'time'
# I also only want to compute end_time if it has not been computed yet
if (!self.days.nil? && !self.hours.nil?)
if (self.end_time.nil?) # if end_time has not yet been computed
if (self.days == 0 && self.hours == 0)
self.errors[:base] << "Days and hours can not be zero."
else
time = self.hours + self.days*24
self.end_time = time.minutes.from_now.utc
self.setStatus # validate status after end time is set
end
end
end
end | unknown | |
d4770 | train | The problem is in the call to input.close() - this causes the underlying input stream to be closed. When the input stream being closed is System.in, bad things happen (namely, you can't read from stdin any more). You should be OK just eliminating this line.
A: input.hasNextInt()
This line throws the exception if there is no Integer, so instead of it going to else block it forward to catch block. It will never go to else block if exception get caught. | unknown | |
d4771 | train | By default, you can't make XHR requests across different domains.
You'll need to dynamically generate script tags and use JSONP.
Here's an article that seems to cover how to do it: http://cjihrig.com/blog/remote-ajax-calls-using-jsonp/
Also, it's important to note that this can cause security issues.
A: I believe the issue here has a lot to do with the differences between your localhost file structure and root path location and your remote server file structure and root path location. First, your url, even for AJAX calls, shouldn't be pathed from root. Your public folder (www, public_html) should redirect traffic into your framework, so you maintain SEO-friendly urls and a more secure site, in the event that PHP should somehow fail. That being said, your AJAX url should still be www.merryflowers.com/students/get_parent_info, where students is your controller and get_parent_info is your function in your students controller. If it's working locally, then it should work remotely, but it needs the correct pathway to get where it needs to go. I'm guessing your local setup includes an htdocs folder, whereas your remote server, as you stated, includes www and public_html folders (possibly simlinked). Start by checking your code for pathway reference differences - pathways locally that don't exist remotely, differences in folder structure, etc... Then go through your config, bootstrap, and any other files that define pathways and alter them accordingly. I'd also retag your question with MVC, PHP, Apache (if you're using Apache, or ISAPI, or whatever), htaccess, and path.
A: Ok, the problem was with the code in MerryParent Model. There was nothing wrong in my jquery code.
In MerryParent model,
function getMerryParents($field_value){
if (is_int($field_value))
$conditions=array('merryParent.id'=>$field_value);
else
$conditions=array('merryParent.email'=>$field_value);
//debug($conditions);
$merryparent_info=$this->find('first',array(
'conditions'=>$conditions,
'recursive'=>-1 //fetches merry_parents table data only not the associated data
));
debug($merryparent_info);
return $merryparent_info;
}
I changed merryParent.id to MerryParent.id and merryParent.email to MerryParent.email and it works now on the remote server. :)
A: This worked for me.. i faced same problem but get it solved by following two steps
1). while referring jquery and other js files I changed to IP address instead relative path
2) in all http get requests i replaced localhost with correct IP address.
Thanks Lazerblade. You helped me a lot.
Mukharjee | unknown | |
d4772 | train | I think, unless you want to prefix all your paths in that template matching / with the variable I suggested to store the result of the marker insertion, one way to merge the existing code with my suggestion is to change the match from / to /* e.g. use
<xsl:template match="/*">
<!-- div for text -->
<div>
<!-- LATIN : always present -->
<h3>Latin</h3>
<xsl:apply-templates select="//tei:body//tei:p"/>
<!-- ENGLISH : always present -->
<h3>English</h3>
<xsl:apply-templates select="//tei:back//tei:p[@xml:lang='EN']"/>
<!-- FRENCH : sometimes present -->
<xsl:if test="//tei:back//tei:p[@xml:lang='FR']">
<h3>French</h3>
<xsl:apply-templates select="//tei:back//tei:p[@xml:lang='FR']"/>
</xsl:if>
<!-- FOOTER for notes -->
<div class="footer">
<!-- FOOTNOTES (uses mode="build_footnotes" to construct a block of footnotes in <div>) -->
<xsl:if test="$footnote-sources">
<div class="footnotes" id="footnotesdiv">
<xsl:apply-templates select="$footnote-sources" mode="build_footnotes"/>
</div>
</xsl:if>
</div>
</div>
</xsl:template>
that would then mean that my suggestion to use
<xsl:template match="/">
<xsl:apply-templates select="$fn-markers-added/node()"/>
</xsl:template>
can be kept and the XSLT processor would apply it.
There is however the use of that variable $footnote-sources at the end of the template, as far as I can see from the snippet its use on nodes from the original input document would not be affected by the introduction of a temporary result adding markers but somehow to me it would feel wrong to at that place keep processing the original input while the rest works on the temporary result so I would be inclined to change the variable declaration to
<xsl:variable name="footnote-sources" select="$fn-markers-added/tei:text//tei:seg//date[@type='deposition_date'] |
$fn-markers-added/tei:text//tei:seg//note[@type='public_note'] | $fn-markers-added/tei:text//tei:seg[@corresp]"/>
With those two changes I think my suggestion in the previous answer should then be applied. Although now looking again at the posted source with a tei root element I wonder how a global variable having paths starting with tei:text would select anything but perhaps that is an omission in the sample. | unknown | |
d4773 | train | For a Table, you can simply use the ShowAllData method of its Autofilter object:
activesheet.listobjects(1).autofilter.showalldata
Note this won't error even if there is no filter currently applied.
A: This expands on the answer from @Rory (the go-to-answer I look up every time I can't remember the syntax). It avoids errors that occur when the table doesn't contain an auto-filter.
The section If Not .AutoFilter Is Nothing checks for the AutoFilter object property of the ListObject (table). If it Is Nothing then that table had it's auto-filter removed.
With Activesheet.Listobjects(1)
If not .AutoFilter Is Nothing Then .AutoFilter.ShowAllData
End With
A: Hi Guys use this "Worksheets("Sheet1").ListObjects(1).Range.AutoFilter = False" and please note if already filter applied it will remove filter on the other hand if filter not applied before it will apply the filter.
A: I am finding that the "...ClearAllData" method fails.
Sneaky - not hugely elegant solution - that works by field (so cumbersome if you need to do the whole table), but easy if you just have one field (e.g. field 2 in my example) is to use the wildcard:
ActiveSheet.ListObjects(1).Range.AutoFilter Field:=2, Criteria1:="=*"
A: ActiveSheet.ShowAllData
Or
Cells.AutoFilter | unknown | |
d4774 | train | As suggested by @DaveNottage, an anonymous thread with standard Post was my best solution so far. This is the function I've been using quite succesfully so far.
I call it from the main program with the destination url, the params that will be sent as JSON and a Callback Procedure that will handle the HTTPResponse received.
procedure HTTPPostAsync(HTTPClient: TNetHTTPClient; url, params: string; CallBack: HTTPClientProc);
var
Thread: TThread;
begin
// define the thread
Thread := TThread.CreateAnonymousThread (
procedure
var
HTTPResponse: IHTTPResponse;
JSon : TStringStream;
begin
Json := TStringStream.Create(Params, TEncoding.UTF8);
Json.Position := 0;
HTTPClient.ContentType := 'application/json';
HTTPClient.Accept := 'application/json';
HTTPClient.ConnectionTimeout := 20000;
HTTPClient.ResponseTimeout := 20000;
try
HTTPResponse:= HTTPClient.Post(url,Json);
TThread.Synchronize (TThread.CurrentThread,
procedure
begin
Callback(HTTPResponse);
end
);
finally
Json.Free;
end;
end
);
// let it roll
Thread.start;
end;
A: Just copy files from {$BDS}/source/rtl/net from 10.2.3 into your project directory and cut non-exist function GetEncodingMIMEName into 'utf-8' everywhere.
This fix works fine, but it will better if Embarcadero will stop make stupid bugs with every release | unknown | |
d4775 | train | A custom type converter should work fine. Here's a quick example (thrown together -- not tested). Also, I added a "Length" property to the ICustomerAddresses so I knew how many to loop through:
public class AddressConverter : TypeConverter<ICustomerAddresses, IList<Address>>
{
protected override IList<Address> ConvertCore(ICustomerAddresses source)
{
var addresses = new List<Address>();
for (var i = 0; i < source.Length; i++)
{
var addr = source[i];
addresses.Add(new Address
{
Addr1 = addr.Addr1,
Zip = addr.Zip
});
}
return addresses;
}
}
And you could probably utilize Automapper inside the loop too to convert the ICustomerAddress to an Address instead of doing it manually like I did. | unknown | |
d4776 | train | Try below one
$fix_d_table = TableRegistry::get('fixed_departures'); $f_dates_march
= $fix_d_table ->find("all")
->where(['trek_id' => 3])
->andWhere(
function ($exp) {
return $exp->or_([
'date_from <=' => date('Y-m-d', strtotime("+10 days")),
'date_from >=' => date('Y-m-d')
]);
})
->order(['date_from'=>'asc'])
->select(['date_from', 'date_to', 'seats_available','id'])
->toArray();
A: should be
'date_from >=' => date("Y-m-d",strtotime("+10 days"))
if you can rely on mysql server date you can use NOW() inside your query
->where(function($exp, $q) {
return $exp->gte($q->func()->dateDiff([
'date_from ' => 'identifier',
$q->func()->now() ]), 10);
});
this will give you the following SQL condition
WHERE
(
DATEDIFF(date_from , NOW())
) >= 10 | unknown | |
d4777 | train | I had these SDK included in project:
*
*AppLovin
*Facebook
*LeadBolt
*MoPub
*RevMob
*Upsight
*Vungle
I have deleted all of them except Vungle. After that I received another message from Google. This time they warned me about Vungle version. I had to update Vungle SDK to version 3.3 or higher.
Now my app is published without any problems.
So If you have any of the above SDKs, try removing one by one and upload new version of APK. (I removed all, since I didn't need them) | unknown | |
d4778 | train | Here is my updated answer with code snippet. the problems are: 1) missing <html><head> at top, 2) missing jquery package, 3) fonteselect.js and fontselect.css need to be called with https://, not http://.
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<link rel="stylesheet" type="text/css" href="https://www.jqueryscript.net/demo/Easy-Google-Web-Font-Selector-With-jQuery-Fontselect/fontselect.css" />
<script src="https://www.jqueryscript.net/demo/Easy-Google-Web-Font-Selector-With-jQuery-Fontselect/jquery.fontselect.js"></script>
<style>
body { padding:50px; background-color:#333;}
p, h1 { color:#fff;}
</style>
</head>
<body>
<script>
$(function(){
$('#font').fontselect().change(function(){
// replace + signs with spaces for css
var font = $(this).val().replace(/\+/g, ' ');
// split font into family and weight
font = font.split(':');
// set family on paragraphs
$('p').css('font-family', font[0]);
});
});
</script>
<script>
$("#size").change(function() {
$('p').css("font-size", $(this).val() + "px");
});
</script>
<select id="size">
<option value="7">7</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
</select>
<p> </p>
<input id="font" type="text" />
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p>
</body>
</html>
A: Chrome is beginning to refuse to download links from non-encrypted sources in an effort to combat phishing fraud and you can read more about that here.
So, the issue is that your <script> links to download the JQuery and fontselect libraries are being done via http and not https and your browser is not downloading them because of that.
Change:
<script src="http://ajax.googleapis.com/ajax/l...
<script src="http://www.jqueryscript.net/demo/Easy-Google-Web-F...
To:
<script src="https://ajax.googleapis.com/ajax/l...
<script src="https://www.jqueryscript.net/demo/Easy-Google-Web-F...
$(function(){
$('#font').fontselect().change(function(){
// replace + signs with spaces for css
var font = $(this).val().replace(/\+/g, ' ');
// split font into family and weight
font = font.split(':');
// set family on paragraphs
$('p').css('font-family', font[0]);
});
});
$("#size").change(function() {
$('p').css("font-size", $(this).val() + "px");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.jqueryscript.net/demo/Easy-Google-Web-Font-Selector-With-jQuery-Fontselect/jquery.fontselect.js"></script>
<link rel="stylesheet" type="text/css" href="http://www.jqueryscript.net/demo/Easy-Google-Web-Font-Selector-With-jQuery-Fontselect/fontselect.css">
<style>
body { padding:50px; background-color:#333;}
p, h1 { color:#fff;}
</style>
<select id="size">
<option value="7">7</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
</select>
<p> </p>
<input id="font" type="text" />
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p>
With that said and done, this feature is incredibly easy to implement yourself, without any external libraries at all:
// First, get a reference to the drop down and the target element
var dd = document.getElementById("size");
var target = document.querySelector("p");
// Then, set up an event handling function for when the value of the select changes
dd.addEventListener("change", function(){
// Remove the previously applied class
target.className = "";
// Just apply the CSS class that corresponds to the size selected
target.classList.add(dd.value);
});
body { padding:50px; background-color:#333;}
p, h1 { color:#fff;}
/* CSS class names must start with a letter */
.seven { font-size:7px; }
.ten { font-size:10px; }
.twenty { font-size:20px; }
.thirty { font-size:30px; }
<select id="size">
<option value="">Choose a font size...</option>
<!-- The values here must match the names of the CSS classes -->
<option value="seven">7</option>
<option value="ten">10</option>
<option value="twenty">20</option>
<option value="thirty">30</option>
</select>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p>
A: First, make sure you have the jQuery library linked to in your document. Then, make sure that $(this).val() gives you a correct value. | unknown | |
d4779 | train | you need to do something like this:
Get-AzureRmRedisCache -Name "isi$i" -ResourceGroupName "iaas101" | where { $_.ProvisioningState -eq 'Succeeded' } |
Remove-AzureRmRedisCache -Force
You filter with Where-Object.
Alternatively you can do:
$cache = Get-AzureRmRedisCache -Name "isi$i" -ResourceGroupName "iaas101"
if ( $cache.ProvisioningState -eq 'Succeeded' ) { do stuff }
or this (UGLY):
if ( (Get-AzureRmRedisCache -Name "isi$i" -ResourceGroupName "iaas101").ProvisioningState -eq 'Succeeded' ) { do stuff } | unknown | |
d4780 | train | The trouble is that CMake resets the contents of CMAKE_FIND_LIBRARY_SUFFIXES during the PROJECT statement, see the file Modules/CMakeGenericSystem.cmake in the installation of CMake. For example, this CMakeLists.txt
cmake_minimum_required(VERSION 2.8.12)
message("CMAKE_FIND_LIBRARY_SUFFIXES = ${CMAKE_FIND_LIBRARY_SUFFIXES}")
project(st)
message("CMAKE_FIND_LIBRARY_SUFFIXES = ${CMAKE_FIND_LIBRARY_SUFFIXES}")
set(CMAKE_FIND_LIBRARY_SUFFIXES ".a") # <--- this is needed to replace the default
# Packages
find_package(GSL REQUIRED)
# Libraries
message("Libraries: ${GSL_LIBRARIES} ${GSLCBLAS_LIBRARIES}")
when executed as
cmake -D CMAKE_FIND_LIBRARY_SUFFIXES=".a" .
produces the output
CMAKE_FIND_LIBRARY_SUFFIXES = .a
-- The C compiler identification is GNU 9.2.1
-- The CXX compiler identification is GNU 9.2.1
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
CMAKE_FIND_LIBRARY_SUFFIXES = .so;.a
-- Found PkgConfig: /usr/bin/pkg-config (found version "1.6.3")
-- Found GSL: /opt/gsl-2.6/include (found version "2.6")
Libraries: /opt/gsl-2.6/lib64/libgsl.a;/opt/gsl-2.6/lib64/libgslcblas.a
-- Configuring done
-- Generating done
Apparently, a possible solution seems to be to redefine the variable (by manually modifying the script) right after the PROJECT statement, as done in the above sample code. | unknown | |
d4781 | train | Not sure how the fact the data is from cube makes much difference, inside of tableau you're looking at a integer and returning a string shouldn't matter.
If you want give this a try
create a calculated field like this:
ZN([Margin 1]) + ZN([Margin 2]) + ZN([Margin 3])
Then create your if statement based on the new calculated field returning string
If [NewCalculated field] <0 then
"Red"
If [NewCalculated field] 0 then
"Amber"
Else
"Green"
End
Have a go | unknown | |
d4782 | train | You should never need to manually specify the ID when creating new instances; Rails will automatically create the auto-incrementing column to handle generating unique IDs for you.
In this case, if you have tampered with the ID column and changed its type, the easiest way to reset this is to simply recreate the table. | unknown | |
d4783 | train | You need to rename the index with the year:
groups = df.groupby("year")
fig, axes = plt.subplots(1, len(groups), sharey=True, figsize=(14,8))
for ax, (year, group) in zip(axes, groups):
# The rename_axis function makes the difference
group.set_index("forecast").rename_axis(year)["percent increase when left out"].plot(kind="bar", ax=ax)
ax.tick_params(axis='both', which='both', length=0)
ax.legend()
fig.subplots_adjust(wspace=0)
Output: | unknown | |
d4784 | train | You need to tell android that your app should become part of the chooser
In the manifest you have to declare that you have an activity that can handle the relevant content
<manifest ... >
<application ... >
<activity android:name=".MyDownloadActivity" ...>
<intent-filter >
<action android:name="android.intent.action.VIEW" />
<action android:name="android.intent.action.SEND" />
<action android:name="android.intent.action.SENDTO" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:mimeType="*/*"
android:scheme="file" />
</intent-filter>
<intent-filter > <!-- mime only SEND(_TO) -->
<action android:name="android.intent.action.SEND" />
<action android:name="android.intent.action.SENDTO" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<category android:name="android.intent.category.CATEGORY_OPENABLE" />
<data android:mimeType="*/*" />
</intent-filter>
</activity>
</application> | unknown | |
d4785 | train | I suspect you're encountering output buffering, where it's waiting to get a certain number of bytes before it flushes. You can look at the unbuffer command if that is undesirable for you.
A: As it turns out, Python detects whether or not you are using a tty, and increases its buffering when you are not. Several options on how to disable this can be viewed at this question. | unknown | |
d4786 | train | Using security="none" means that security is not applied to the URLs, so the statement of adding a Content Security Policy with Spring Security to URLs mapped with security="none" is contradictory.
I'm guessing that you want to allow any user access to those URLs. If that is the case, you can easily use the permitAll expression.
Then, you can specify which URLs are have the Content Security Policy set using DelegatingRequestMatcherHeaderWriter. For example, using Spring Security 4+ you can use:
<http>
<intercept-url pattern="/*/yyy/**" access="permitAll" />
<intercept-url pattern="/*/zzz/**" access="permitAll"/>
<intercept-url method="GET" pattern="/*/api/products" access="xxxx" />
<headers>
<header ref="headerWriter"/>
</headers>
<csrf disabled="true" />
<http-basic entry-point-ref="customBasicAuthenticationEntryPoint" />
<!-- ... -->
</http>
<beans:bean id="headerWriter"
class="org.springframework.security.web.header.writers.DelegatingRequestMatcherHeaderWriter">
<beans:constructor-arg>
<beans:bean class="org.springframework.security.web.util.matcher.OrRequestMatcher">
<beans:constructor-arg>
<beans:bean class="org.springframework.security.web.util.matcher.AntPathRequestMatcher"
c:pattern="/*/yyy/**"/>
<beans:bean class="org.springframework.security.web.util.matcher.AntPathRequestMatcher"
c:pattern="/*/zzz/**"/>
</beans:constructor-arg>
</beans:bean>
</beans:constructor-arg>
<beans:constructor-arg>
<beans:bean
class="org.springframework.security.web.header.writers.StaticHeadersWriter"
c:headerName="Content-Security-Policy"
c:headerValues="default-src 'self'"
/>
</beans:constructor-arg>
</beans:bean>
Note that if you are using Spring Security 3, then you will need to explicitly list all the headers you want enabled (adding any explicit headers means only those headers are applied). For example:
<headers>
<cache-control />
<content-type-options />
<hsts />
<frame-options />
<xss-protection />
<header ref="headerWriter"/>
</headers>
You can find additional details on the differences in the migration guide. | unknown | |
d4787 | train | Try like below and confirm.
driver.get("https://www.phptravels.net/")
wait = WebDriverWait(driver,30)
checkin = wait.until(EC.element_to_be_clickable((By.ID,"checkin")))
checkin.click()
date = 15
select_date = wait.until(EC.element_to_be_clickable((By.XPATH,f"//div[@class='datepicker-days']//td[text()='{date}']")))
select_date.click()
Update: As per comments to select date from Flights section.
driver.get("https://www.phptravels.net/")
wait = WebDriverWait(driver,30)
flights = wait.until(EC.element_to_be_clickable((By.XPATH,"//button[@aria-controls='flights']")))
flights.click()
departure_date = wait.until(EC.element_to_be_clickable((By.XPATH,"//input[contains(@class,'depart')]")))
departure_date.click()
date = 15
select_date = wait.until(EC.element_to_be_clickable((By.XPATH,f"(//div[@class='datepicker-days'])[3]/table/tbody/tr[3]/td[text()='{date}']")))
select_date.click() | unknown | |
d4788 | train | The path refers to the name of the action you call from your HTML or jsp file.
For eg -
<html:form action="Name" name="nameForm" type="example.NameForm">
The corresponding action mapping will be something like -
<action path="/Name" type="example.NameAction" name="nameForm" input="/index.jsp">
<forward name="success" path="/displayname.jsp"/>
Check out this link for a complete example. | unknown | |
d4789 | train | Based upon what you are trying to do,
And what the other members advised you already,
It sounds like you did not correctly format your if...then and/or your select...case statements.
The code below should do what you are trying to do.
We use the SELECTINDEX property to find out which index element in the drop down is selected at present.
Additionally, The code below can be affected (affected so it does not work) by any code in the combobox/dropdown object's event procedures if you have any of them setup.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'
Select Case Combobox1.SelectedIndex
Case 1
Form2.Show()
Me.Hide()
Case 1, 4
Form3.Show()
Me.Hide()
Case 3
Form4.Show()
Me.Hide()
Case 5
Form5.Show()
Me.Hide()
Case 6
Form6.Show()
Me.Hide()
Case 7
Form7.Show()
Me.Hide()
Case 8
Form8.Show()
Me.Hide()
Case 9, 10
Form9.Show()
Me.Hide()
Case 11
Form10.Show()
Me.Hide()
Case 12
Form11.Show()
Me.Hide()
Case 13
Form12.Show()
Me.Hide()
End Select
'
End Sub
A: *
*Combo box to open Form
*Add & Name Combo Box SelectFormsEdit
*Go to Property Sheet, Data Tab, Edit Row Source, SQL:
SELECT MsysObjects.Name
FROM MsysObjects
WHERE (((MsysObjects.Type)=-32768));
*Event Tab, After Update, ... Code Builder:
Private Sub SelectFormsEdit_AfterUpdate()
DoCmd.OpenForm SelectFormsEdit, , , , acFormEdit
End Sub
*Save everything | unknown | |
d4790 | train | I'm a moron and left off parens on name in the model. | unknown | |
d4791 | train | As long as the script doesn't put part of itself into your code when you use it, you should be OK. IOW: If it is just some kind of tool you use to help build your real code (which is totally separate and entirely your own work), then you can liscense that stuff however you want.
What you can't do is relicense somebody else's work without their permission. If the script injects part of itself into your code, that would include that injected part. Also, if you link anything GPLed (object file, link library, etc), then your license needs to be GPL-compatible (and the linked part has to stay GPL).
A: My understanding of the GPL is that if your code relies on the script, then you have to release your code under the GPL as well. If your code interfaces with the script, but it isn't a neccessary component (i.e. the script is or is part of a module or plugin) then only the module/plugin needs to be released under the GPL. IANAL...
A: First, you need to determine to what extent your app depends on the GPL script. If your app doesn't work without the script, then I think it's safe to say that it depends on it on a fundamental way. If this is the case, then your code must also be released under the GPL license - please notice that this doesn't imply that you can not sell your app, you are free to do so, but now the code of your app must be available for any one to use, see, modify, and distribute the modifications.
If you're not OK with the last part, maybe you should look for other script alternatives, licensed under a more permisible model. For instance, any of the following licenses would be fine: Apache, MIT, even LGPL | unknown | |
d4792 | train | You can't on your side. The index must be added to a local object only. You can't use an indexed view either.
You can ask the other party to add an index for you to their table...
Edit:
Expanding John's answer... You could try:
SELECT * FROM OPENQUERY(LinkedServer, 'CREATE INDEX etc;SELECT 0 AS foobar')
A: I'm not certain however I suspect that this cannot be done.
OPENQUERY is intended to return a Result Set and so is unlikely to accept DDL statements.
See the Microsoft Books Online reference for examples of acceptable usage scenarios.
http://technet.microsoft.com/en-us/library/ms188427.aspx | unknown | |
d4793 | train | That's because the default String Comparator uses lexicographical order -- i.e. character by character, as in a dictionary. Since "1" comes before "2", any String starting with "1" will precede any other starting with "2".
You should use a custom comparator to implement Natural Sorting. A good example would be Alphanum, from Dave Koelle, which you would use like this:
Collections.sort(myarraylist, new AlphanumComparator());
A: I use this simple class to order my Strings:
public abstract class StringOrderer {
public static ArrayList<String> order(ArrayList<String> items, boolean ascending) {
Collections.sort(items, new StringComparator());
// reverse the order
if(!ascending) Collections.reverse(items);
return items;
}
class StringComparator implements Comparator<String> {
@Override
public int compare(String s1, String s2) {
// use the users default locale to sort the strings
Collator c = Collator.getInstance(Locale.getDefault());
return c.compare(s1, s2);
}
}
}
The basic idea is that i have a custom Comparator that uses the default Locale.
A: Since you are using String in the Array list it alway checks characters. Better you try using Integer. It may works for you.
A: As String can not be extended, it is better to change ArrayList<String> to ArrayList<ClassWithStringAttribute> then implement Comparable in ClassWithStringAttribute when you need custom comparison. For your particular case and illustration, the following class should work, though not a nice approach.
myarraylist= StringSorter.getSortedList(myarraylist);
Will give you a sorted list
public class StringSorter implements Comparable<StringSorter>{
String tempString;
public StringSorter(String data) {
this.tempString = data;
}
public static List<String> getSortedList(List<String> unsortedList){
List<StringSorter> tempList=new ArrayList<StringSorter>();
for (String current : unsortedList) {
tempList.add(new StringSorter(current));
}
Collections.sort(tempList);
List<String> sortedString=new ArrayList<String>();
for (StringSorter current : tempList) {
sortedString.add(current.tempString);
}
return sortedString;
}
@Override
public int compareTo(StringSorter other) {
Integer otherInt=Integer.parseInt(other.tempString.replaceFirst("Item ", ""));
Integer thisInt=Integer.parseInt(this.tempString.replaceFirst("Item ", ""));
if(otherInt>thisInt){
return -1;
}else if(otherInt<thisInt){
return 1;
}else{
return 0;
}
}
}
A: How about this custom Comparator,
public class StringNumSuffixComparator implements Comparator<String>{
@Override
public int compare(String o1, String o2) {
String str1 = o1;
String str2 = o2;
Integer num1 = Integer.parseInt(str1.replaceAll("\\D+",""));
Integer num2 = Integer.parseInt(str2.replaceAll("\\D+",""));
return num2.compareTo(num1);
}
}
To sort them with Collections.sort(),
Collections.sort(items, new StringNumSuffixComparator()); | unknown | |
d4794 | train | I think zoo::rollapplyr should work here. Here's a simple n=2 window,
MA <- function(X) {
if (!is.matrix(X)) X <- matrix(X, nrow = 1)
Hmisc::wtd.mean(X[,1], X[,2])
}
df %>%
group_by(product) %>%
mutate(n2 = zoo::rollapplyr(
cbind(price, weight), 2, MA,
by.column = FALSE, partial = TRUE)
) %>%
ungroup()
# # A tibble: 15 x 7
# id price product reference distance weight n2
# <int> <dbl> <chr> <dbl> <dbl> <dbl> <dbl>
# 1 1 40 B 45 0.889 0.111 40
# 2 2 50 B 45 1.11 1 49
# 3 3 34 A 45 0.756 0.244 34
# 4 4 56 B 45 1.24 1 53
# 5 5 78 B 45 1.73 1 67
# 6 6 35 B 45 0.778 0.222 70.2
# 7 7 23 B 45 0.511 0.489 26.8
# 8 8 40 B 45 0.889 0.111 26.1
# 9 9 50 A 45 1.11 1 46.9
# 10 10 34 B 45 0.756 0.244 35.9
# 11 11 56 B 45 1.24 1 51.7
# 12 12 78 A 45 1.73 1 64
# 13 13 35 B 45 0.778 0.222 52.2
# 14 14 23 B 45 0.511 0.489 26.8
# 15 15 12 A 45 0.267 0.733 50.1
And here's a method demonstrating multiple windows in one call:
df %>%
group_by(product) %>%
mutate(
data.frame(lapply(
setNames(2:4, paste0("n", 2:4)),
function(n) zoo::rollapplyr(
cbind(price, weight), n, MA,
by.column = FALSE, partial = TRUE)
))
) %>%
ungroup()
# # A tibble: 15 x 9
# id price product reference distance weight n2 n3 n4
# <int> <dbl> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
# 1 1 40 B 45 0.889 0.111 40 40 40
# 2 2 50 B 45 1.11 1 49 49 49
# 3 3 34 A 45 0.756 0.244 34 34 34
# 4 4 56 B 45 1.24 1 53 52.3 52.3
# 5 5 78 B 45 1.73 1 67 61.3 60.6
# 6 6 35 B 45 0.778 0.222 70.2 63.8 59.5
# 7 7 23 B 45 0.511 0.489 26.8 56.7 56.4
# 8 8 40 B 45 0.889 0.111 26.1 28.5 55.7
# 9 9 50 A 45 1.11 1 46.9 46.9 46.9
# 10 10 34 B 45 0.756 0.244 35.9 28.4 29.8
# 11 11 56 B 45 1.24 1 51.7 50.7 43.4
# 12 12 78 A 45 1.73 1 64 60.7 60.7
# 13 13 35 B 45 0.778 0.222 52.2 49.2 48.5
# 14 14 23 B 45 0.511 0.489 26.8 43.8 42.6
# 15 15 12 A 45 0.267 0.733 50.1 50.0 48.7
This method takes advantage of the not-well-known behavior of mutate with an unname argument that returns a data.frame. The use of setNames is so that the column names are meaningfully named, there are likely other ways one might approach that.
There's not a particular reason I'm using Hmisc::wtd.mean over a custom function other than I know it works well. The use of the MA function is because within zoo::rollapply*, the FUN= argument is passed a single matrix, so we need to handle it specially, even more so because due to partial=TRUE, the first time MA is called for each group, it is passed a vector instead of a matrix. | unknown | |
d4795 | train | I have fixed your script on http://jsfiddle.net/rwowf5j8/41/
Fixed and tested -- Issue was in the spelling in document.body.style.backround and there were some other tricks to do that easily so I fixed that..
<script>
function getColour(value) {
changeColour(value);
}
function changeColour(colour) {
if (colour == "Blue") {
document.body.style.background = "blue";
}
else if (colour == "Red") {
document.body.style.background = "Red";
}
}
</script>
<body>
<form name="Form2">Do you prefer the colour red or blue?
<input type="radio" name="ColourRad" onchange="getColour('Red')" value="Blue" />Red
<input type="radio" name="ColourRad" onchange="getColour('Blue')" value="Red" />Blue
</form>
</body>
A: A Very Simple Method to do this..
Hope this helps you.
document.onreadystatechange = function()
{
if(document.readyState == "complete")
{
var blue = document.getElementById("blue");
var red = document.getElementById("red") ;
blue.onclick = function()
{
document.body.style.background = "blue";
}
red.onclick = function()
{
document.body.style.background = "red";
}
}
}
<body>
<form name="Form2">Do you prefer the colour red or blue?
<input id="red" type="radio" name="color" value="Blue" />Red
<input id="blue" type="radio" name="" value="Red" />Blue
</form>
</body>
A: Using your function to change the background color:
function getColour() {
var rad = document.forms["Form2"]["ColourRad"];
var i, x;
for (i = 0; i < rad.length; i++) {
if (rad[i].checked) {
x = rad[i].value
}
}
changeColour(x);
}
function changeColour(colour) {
//if the value of the input is the color, you don't need
//to check if the color is blue or red to set it
document.body.style.background = colour
}
<form name="Form2">Do you prefer the colour red or blue?
<!--in your code, the Red input is with Blue color -->
<input type="radio" name="ColourRad" onchange="getColour()" value="Red" />Red
<!--the same with the Blue input, where the Blue is Red -->
<input type="radio" name="ColourRad" onchange="getColour()" value="Blue" />Blue
</form>
Also you can use this instead:
<form name="Form2">Do you prefer the colour red or blue?
<input type="radio" name="ColourRad" onchange="document.body.style.backgroundColor = this.value" value="red" />Red
<input type="radio" name="ColourRad" onchange="document.body.style.backgroundColor=this.value" value="blue" />Blue
</form>
A: Here's another method. First, I wait for the document to finish loading. Next, I get a list of all elements that have the name 'colorRad' - this allows me to collect a list of all the radio buttons involved in setting the background color.
Next, I attach an event listener that simply gets the value of the radio-button when its selected and finally, applies this to the background-color of the document body's inline style.
Adding a new colour option is as simple as duplicating one of the radio buttons and changing the text displayed in it's label and by setting it's value - this label also allows you to select a radio button with the text, as opposed to limiting the target area to the size of the radio-button's circle only.
Lastly, since the onRadBtnChanged function is attached to each radio-button's object, when the function is called, the this parameter refers to the radio-button object itself. This allows us to get info from the radio-button's value, and avoids having to handle each option specifically, as you have done in your changeColor function. Also, we save the wasted cpu cycles of iterating through the entire list each time, as you do in getColor - only one can be selected at a time - attaching the event-handler to the object itself means that we only need concern ourselves with the particular element that changed. (the change event only fires when the radio-button is selected. It does not fire when the selection of a different one causes one to be deselected - it only fires on selection, or 'checking')
Example:
<!doctype html>
<html>
<head>
<script>
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded(evt)
{
var colRadBtns = document.getElementsByName('colorRad');
var i, n = colRadBtns.length;
for (i=0; i<n; i++)
{
colRadBtns[i].addEventListener('change', onRadBtnChanged, false);
}
}
function onRadBtnChanged(evt)
{
document.body.style.backgroundColor = this.value;
}
</script>
</head>
<body>
<label><input name='colorRad' value='red' type='radio'/>Red</label>
<label><input name='colorRad' value='blue' type='radio'/>Blue</label>
<label><input name='colorRad' value='yellow' type='radio'/>Yellow</label>
<label><input name='colorRad' value='green' type='radio'/>Green</label>
<label><input name='colorRad' value='orange' type='radio'/>Orange</label>
</body>
</html>
A: The 2 things you needed to do were:
*
*Switch the values in the input tags because they didn't match up.
*In the changeColour() function, you didn't fully spell out background in document.body.style.backround you missed the g.
I also switched the script tags from the top to be at the bottom, right before the closing body tag just because I usually do it like that.
Fixing those two small issues makes it run perfectly.
A: Use this instead:
document.body.style.backgroundColor
A: basically the style property was wrong, it should be backgroundColor
but you can get the same effect much simpler, for example:
onchange="document.body.style.backgroundColor=this.value;" | unknown | |
d4796 | train | Your function do one, and only one, thing. So, in your case, it should find the smaller_root according to some variables.
The return value of your function should be the root. In your case, it is possible that it returns None, which would indicate that there is no root for the solution.
However, you are trying to make the function do more than one thing, that is, you are trying to make the function return a value (the root) AND print out a message if no root is found.
You should choose one functionality only for you function: It will EITHER print out the result (that is, print a root or a message) OR return the result.
Every other logic beyond that of the functionality would be out of the function's scope, e.g.:
def smaller_root(a,b,c):
"""
akes an input the numbers a,b and c returns the smaller solution to this
equation if one exists. If the equation has no real solution, print
the message, "Error: No Real Solution " and simply return.
"""
discriminant = b**2-4*a*c
if discriminant == 0:
return -b/(2*a)
elif discriminant > 0:
return (-b-discriminant**0.5)/(2*a) #just need smaller solution
else:
return None
result = smaller_root(some_a, some_b, some_c)
if (result is None):
print("Error: No Real Solution") | unknown | |
d4797 | train | for single line set
shareBtn.titleLabel?.adjustsFontSizeToFitWidth = YES;
instead of this
factLabel.adjustsFontSizeToFitWidth = true;
for multiple line us use
actLabel.numberOfLines = 0;
factLabel.lineBreakMode = NSLineBreakByWordWrapping;
CGSize maximumLabelSize = CGSizeMake(factLabel.frame.size.width, CGFLOAT_MAX);
CGSize expectSize = [factLabel sizeThatFits:maximumLabelSize];
factLabel.frame = CGRectMake(factLabel.frame.origin.x, factLabel.frame.origin.y, expectSize.width, expectSize.height); | unknown | |
d4798 | train | Transform your object to a string like this
let obj = {
"Jenny" : [
"Second number must be smaller than first",
"Signature must be filled !"
]
};
let str = "";
Object.keys(obj).forEach(k => {
str += k + ":\n";
str += obj[k].join(",\n");
});
console.log(str);
A: Extract the data from the JSON data that you have in errors instead of running JSON.stringify directly. You should be able to get the data like this: errors["Jenny"] to get a list of the errors. Then combine them into a string according to your liking.
A: I honestly don't think your question has absolutely anything to do with JSON. The only reason why some JSON even shows up is because you're generating it for the alert():
alert(JSON.stringify(errors, null, 2));
// ^^^^^^^^^^^^^^ This generates JSON
If you want to concatenate some array items you can use a combination of the concatenation operator (+) and Array.join():
alert(w_name + ":\n" + errors[w_name].join(",\n"));
Tweak format to your liking.
var w_name = "Jenny";
var errors = {};
errors[w_name] = [];
errors[w_name].push("Second number must be smaller than first");
errors[w_name].push("Signature must be filled!");
alert(w_name + ":\n" + errors[w_name].join(",\n")); | unknown | |
d4799 | train | You have a list with two dictionaries. To filter the dictionaries you can try
keep=[key1,key2] #keys you wanna keep
newList = []
for item in mylist:
d = dict((key,value) for key, value in item.iteritems() if key in keep)
newlist.append(d)
del mylist
Also using funcy you can do a
import funcy
mydict={1:1,2:2,3:3}
keep=[1,2]
funcy.project(mydict,keep)
=> {1: 1, 2: 2}
which is much prettier imho.
A: You could use the list comprehension https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions
[l for l in your_list if l['UserDiscount'] >= 1 ]
[{'UserDiscount': l['UserDiscount'],'CostTotalInvEOPAmount': l['CostTotalInvEOPAmount']} for l in your_list ]
Using this way you can filter the elements in your list and change the structure of your dicts in the list | unknown | |
d4800 | train | Try:
((TextBox)wsPlanInfo.FindControl("txtLearningPlanName")).Text
It will search the Wizard Step's Control list for a textbox with that ID name. It then casts it as a TextBox and so you can then use the Text property.
A: Removing disableSelection(document.body) in my javascript solved my problem. Note to self, post entire code when asking a question. | unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.