id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23535500
|
My code is simple:
<div style="text-align: center;">
<p>
Here you will tell..
</p>
<asp:CheckBoxList runat="server" ID="cbl" Width="300px"></asp:CheckBoxList>
<br />
<input type="button" id="next_3" value="Next Page" />
</div>
And here is a screen shot
A: You can have it contained within another <div> that does left-aligning like so:
<div style="text-align: center;">
<p>Here you will tell..</p>
<div style="text-align: left; width: 50%; margin: auto;">
<asp:CheckBoxList runat="server" ID="cbl" Width="300px"></asp:CheckBoxList>
</div>
<input type="button" id="next_3" value="Next Page" />
</div>
A: Just add the following to your checkboxlist
Style="text-align='left'";
<asp:CheckBoxList ID="CheckBoxList1" runat="server" TextAlign="Right" Style="text-align='left';"
RepeatColumns="10" RepeatDirection="Vertical" CellSpacing="20">
A: Without using DIV and other elements and fixed sizes.
We can "align checkboxlist text by Setting
"float:left" to the checkbox list input type
in Css
Please check the following example code:
========================================
.CheckboxList
{
font-size:14px;
color:#333333;
}
.CheckboxList input
{
float:left;
clear:both;
}
.Aspx Code:
===========
<asp:CheckBoxList runat="server" ID="chlCities" RepeatColumns="2" CssClass="CheckboxList"></asp:CheckBoxList>
A: Maybe I don't understand your question, but for me this works fine:
<table>
<tr>
<td><input type="checkbox" name="cb1" id="cb1"><label for="cb1">Checkbox 1</label></td>
</tr>
<tr>
<td><input type="checkbox" name="cb2" id="cb1"><label for="cb2">Checkbox 2</label></td>
</tr>
<tr>
<td><input type="checkbox" name="cb3" id="cb1"><label for="cb3">Checkbox 3</label></td>
</tr>
<tr>
<td><input type="checkbox" name="cb4" id="cb1"><label for="cb4">Checkbox 4</label></td>
</tr>
<tr>
<td><input type="checkbox" name="cb5" id="cb1"><label for="cb5">Checkbox 5</label></td>
</tr>
</table>
If you can link to or show your HTML, maybe we can give you more help.
| |
doc_23535501
|
@Timed("test")
@RestController
public class TempHandler{
@GetMapping(value="/path")
@Timed(value="ping")
public ResponseEntity ping(@RequestHeader Map<String,String> headers){
return applyHeaders(Response.status(200).entity("ok"));
}
}
I have created a @Configuration class as well to return a TimedAspect object.
@Configuration
public class TimedConfiguration {
@Bean
public TimedAspect timedAspect(MeterRegistry registry) {
return new TimedAspect(registry);
}
}
I have included the spring AOP dependancy in my build.gradle as well. Please help me to figure out what I am doing wrong. Thanks!
| |
doc_23535502
|
damage_grade
counts
age
0
Grade 1
1
0-10
1
Grade 2
4
0-10
2
Grade 3
2
0-10
3
Grade 1
5
0-10
4
Grade 2
2
0-10
5
Grade 3
5
0-10
6
Grade 1
1
11-20
7
Grade 2
6
11-20
8
Grade 3
2
11-20
9
Grade 1
6
11-20
I want to add up the counts having the same age and damage_grade to make the table look like this.
damage_grade
counts
age
0
Grade 1
6
0-10
1
Grade 2
6
0-10
2
Grade 3
7
0-10
3
Grade 1
7
11-20
4
Grade 2
6
11-20
5
Grade 3
2
11-20
| |
doc_23535503
|
I use this code for compress a file with GzipStream.
public static void Compress(FileInfo fileToCompress)
{
using (FileStream originalFileStream = fileToCompress.OpenRead())
{
if ((File.GetAttributes(fileToCompress.FullName) & FileAttributes.Hidden) != FileAttributes.Hidden & fileToCompress.Extension != ".gz")
{
using (FileStream compressedFileStream = File.Create(fileToCompress.FullName + ".gz"))
{
using (GZipStream compressionStream = new GZipStream(compressedFileStream, CompressionMode.Compress))
{
originalFileStream.CopyTo(compressionStream);
Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
fileToCompress.Name, fileToCompress.Length.ToString(), compressedFileStream.Length.ToString());
}
}
}
}
}
I use this link for compress directory. but don't work for me :(
A: From what I can tell, you can't compress an entire directory to a single gz file. You end up with multiple gz files.
A: You can package the directory up as a .Tar file and then use gZip on the tar file.
Which would require using a library such as SharpZipLib. You can install the library from the Manage NuGet Packages menu.
DirectoryInfo directoryOfFilesToBeTarred = new DirectoryInfo(@"c:\tar\start");
FileInfo[] filesInDirectory = directoryOfFilesToBeTarred.GetFiles();
String tarArchiveName = @"c:\tar\mytararchive.tar.gz";
using (Stream targetStream = new GZipOutputStream(File.Create(tarArchiveName)))
{
using (TarArchive tarArchive = TarArchive.CreateOutputTarArchive(targetStream, TarBuffer.DefaultBlockFactor))
{
foreach (FileInfo fileToBeTarred in filesInDirectory)
{
TarEntry entry = TarEntry.CreateEntryFromFile(fileToBeTarred.FullName);
tarArchive.WriteEntry(entry, true);
}
}
}
Source:
https://dotnetcodr.com/2015/02/04/packing-and-unpacking-files-using-tar-archives-in-net/
OR
You can zip the directory in pure .NET 3.0. Using SharpZipLib may not be desirable due to the modified GPL license.
First, you will need a reference to WindowsBase.dll.
This code will open or create a zip file, create a directory inside, and place the file in that directory. If you want to zip a folder, possibly containing sub-directories, you could loop through the files in the directory and call this method for each file. Then, you could depth-first search the sub-directories for files, call the method for each of those and pass in the path to create that hierarchy within the zip file.
public void AddFileToZip(string zipFilename, string fileToAdd, string destDir)
{
using (Package zip = System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate))
{
string destFilename = "." + destDir + "\\" + Path.GetFileName(fileToAdd);
Uri uri = PackUriHelper.CreatePartUri(new Uri(destFilename, UriKind.Relative));
if (zip.PartExists(uri))
{
zip.DeletePart(uri);
}
PackagePart part = zip.CreatePart(uri, "", CompressionOption.Normal);
using (FileStream fileStream = new FileStream(fileToAdd, FileMode.Open, FileAccess.Read))
{
using (Stream dest = part.GetStream())
{
CopyStream(fileStream, dest);
}
}
}
}
destDir could be an empty string, which would place the file directly in the zip.
Sources:
https://weblogs.asp.net/jongalloway/creating-zip-archives-in-net-without-an-external-library-like-sharpziplib
https://weblogs.asp.net/albertpascual/creating-a-folder-inside-the-zip-file-with-system-io-packaging
| |
doc_23535504
|
let regexSymbol = new Regex(@"\b\}|\.\b")
if (Regex.IsMatch(".", regexSymbol.ToString())) then
printfn "symbol0"
But it doesn't print anything..
I'd like the regex to represent only strings that are exactly "}" or "." , without any following or preceding characters on the same line.
Anyone knows how I should change it please?
Thanks.. :)
A: If you need to match strings that way, you'd use beginning-of-string and end-of-string anchors:
open System.Text.RegularExpressions
let regexSymbol = new Regex("^[}.]$") // in this case verbatim is not required
if (regexSymbol.IsMatch(".")) then printfn "Matched! :)" else printfn "Not matched... :("
if (regexSymbol.IsMatch("}.")) then printfn "Matched! :)" else printfn "Not matched... :("
This prints "Matched" at the first line, and "Not Matched" at the second.
But isn't it better just to check whether or not this string equal to "}" and '.'? Sorry, just starting exploring F#.
A: The problem is that what a "." isn't considered a word boundary. So \b" matches 'A"', but not '."'.
| |
doc_23535505
|
query FestivalList($size: Int = 2, $skip: Int = 0) {
model: festival(limit: $size, offset: $skip) {
data {
festivalId
name
artists {
name
}
}
}
}
As response I get following error: Cannot query field "name" on type "FestivalArtistItem".
So how should I query the related data through GraphQL? I'm using Directus 8.8.1
| |
doc_23535506
|
Currently I'm using InfoPath to receive data from SQL database.
Thank you
Detailed help will be highly appreciated.
A: Did you create a new form using the Database template or are you connecting to the DB after the fact from a list you wanted to add the SQL db connection to? The easiest route is just to Create a new IP form using the Database template under the Advanced templates as it creates the fields and controls to enter and edit the SQL data you want to work with. If not then you need to run a SQL CREATE statement.
A: I use infopath to create a Sharepoint list and then Visual Studio SSIS package to transfer the sharepoint list data to a SQL database table, using a schedule stored procedure.
| |
doc_23535507
|
Create a class named TestLease whose main() method declares four Lease objects. Call a getData() method three times. Within the method, prompt a user for values for each field for a Lease, and return a Lease object to the main() method where it is assigned to one of main()’s Lease objects. Do not prompt the user for values for the fourth Lease object, but let it continue to hold the default values.
Then, in main(), pass one of the Lease objects to the showValues() method that displays the data. Then call the addPetFee() method using the passed Lease object and confirm that the fee explanation statement is displayed. Next, call the showValues() method for the Lease object again and confirm that the pet fee has been added to the rent. Finally, call the showValues() method with each of the other three objects; confirm that two hold the values you supplied as input and one holds the constructor default values.
My results is correct as the homework requires. But my professor says that I have a logical error at getData() method. I tried to find the error but could not figure out.
class Lease {
private String name;
private int aptNumber;
private double rent;
private int term;
private static final int FEE = 10;
public Lease() {
name = "XXX";
aptNumber = 0;
rent = 1000.0;
term = 12;
}
public void setName(String tenant) {
name = tenant;
}
public void setAptNumber(int apt) {
aptNumber = apt;
}
public void setRent(double monthRent) {
rent = monthRent;
}
public void setTerm(int t) {
term = t;
}
public String getName() {
return name;
}
public int getAptNumber() {
return aptNumber;
}
public double getRent() {
return rent;
}
public int getTerm() {
return term;
}
public void addPetFee() {
rent = rent + FEE;
explainPetPolicy();
}
public static void explainPetPolicy() {
System.out.println("A pet fee of $10 is added to your monthly rent and: ");
}
}
import java.util.Scanner;
class TestLease
{
public static void main (String args[])
{
Lease lease1 = getData();
showValues(lease1);
Lease lease2 = getData();
showValues(lease2);
Lease lease3 = getData();
showValues(lease3);
lease3.addPetFee();
showValues(lease3);
Lease lease4 = new Lease();
showValues(lease4);
}
public static void showValues(Lease ls)
{
System.out.println("\n\nYour lease results:" +
"\nName : " + ls.getName() +
"\nApartment : " + ls.getAptNumber() +
"\nRent : " + ls.getRent() +
"\nTerm : " + ls.getTerm() + "\n");
}
public static Lease getData()
{
Lease sample = new Lease();
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter your name:");
String sampleName = userInput.nextLine();
sample.setName(sampleName);
System.out.println("Please enter your apartment number:");
int sampleAptNumber = userInput.nextInt();
sample.setAptNumber(sampleAptNumber);
System.out.println("Please enter your monthly rent amount:");
double sampleRent = userInput.nextDouble();
sample.setRent(sampleRent);
System.out.println("Please enter the term of your lease in months:");
int sampleTerm = userInput.nextInt();
sample.setTerm(sampleTerm);
userInput.nextLine();
return sample;
}
}
| |
doc_23535508
|
@Transactional
@PUT
@Path("/{servicePointNumber : \\d+}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response updateServicePoint( @PathParam("userId") Long userId,
@PathParam("servicePointNumber") Integer servicePointNumber,
ServicePoint servicePoint,
@BeanParam GenericBeanParam params) throws ForbiddenException, UnprocessableEntityException, InternalServerErrorException {
if(params.getAuthToken() == null) throw new ForbiddenException("Unauthorized access to web service.");
logger.log(Level.INFO, "updating existing Service Point by executing ProviderResource.ServicePointResource.updateServicePoint(servicePoint) method of REST API");
// set resource ID passed in path param on updated resource object
Provider foundProvider = providerFacade.find(userId);
servicePoint.setProvider(foundProvider);
servicePoint.setServicePointNumber(servicePointNumber);
ServicePoint updatedServicePoint = null;
try {
// reflect updated resource object in database
updatedServicePoint = servicePointFacade.update(servicePoint);
// populate created resource with hypermedia links
pl.salonea.jaxrs.ServicePointResource.populateWithHATEOASLinks(updatedServicePoint, params.getUriInfo());
} catch (EJBTransactionRolledbackException ex) {
ExceptionHandler.handleEJBTransactionRolledbackException(ex);
} catch (EJBException ex) {
ExceptionHandler.handleEJBException(ex);
} catch(Exception ex) {
throw new InternalServerErrorException(ExceptionHandler.ENTITY_UPDATE_ERROR_MESSAGE);
}
return Response.status(Status.OK).entity(updatedServicePoint).build();
}
And this method is defined inside ServicePointResource class of JAX-RS layer. This is inner class of ProviderResource class.
The problem here is that the code throws exception:
Transaction aimed at persisting entity instance has been rolled back: detached entity passed to persist: pl.salonea.entities.Provider
Provider is @ManyToOne association with ServicePoint and moreover Provider ID is part of ServicePoint composite Primary Key.
If I move this part:
// set resource ID passed in path param on updated resource object
Provider foundProvider = providerFacade.find(userId);
servicePoint.setProvider(foundProvider);
servicePoint.setServicePointNumber(servicePointNumber);
ServicePoint updatedServicePoint = null;
try {
// reflect updated resource object in database
updatedServicePoint = servicePointFacade.update(servicePoint);
to external EJB class that is @Stateless session bean and has default Transaction Management of type REQUIRED this will update correctly and error with detach method doesn't appear. So I suppose this @Transactional annotation demarcation on above method has no effect and doesn't work!
| |
doc_23535509
|
here are my codes
from tkinter import *
from PIL import Image,ImageTk
from tkinter import filedialog
from PIL import Image, ImageTk
import os
import cv2
import numpy as np
import time
class application(Tk):
def __init__(self,parent):
Tk.__init__(self,parent)
self.parent = parent
self.minsize(width=300,height=500)
self.initialize()
def initialize(self):
self.grid_columnconfigure(0,weight=1)
self.grid_columnconfigure(1,weight=1)
self.grid_columnconfigure(2,weight=1)
#Button widgets
###########################################################################################
#self.button1 = Button(self,text='Image Selector',bg= 'blue',width=15,height=2,command=self.browseFiles)
#self.button1.grid(column=0,row=1,sticky='W',pady=5)
self.button2 = Button(self,text='User control',bg= 'blue',width=15,height=2,command=self.Image_Classification)
self.button2.grid(column=0,row=1,sticky='W',pady=5,padx=150)
self.button3 = Button(self,text='Exit',bg= 'blue',width=10,height=2,command=self.destroy)
self.button3.grid(column=1,row=5,sticky='W',pady=5)
#self.button4 = Button(self,text='Method 2',width=10,height=2)
#self.button4.grid(column=0,row=2,sticky='W',pady=5)
#Text widget for inserting result
############################################################################################
self.text1 = Text(self,height=2,width=20,state=NORMAL)
self.text1.grid(column=2,row=1,sticky='E',padx=5)
#self.text1.configure(bg='cyan')
#self.canvas2 = Canvas(self,height=10,width=20,state=NORMAL)
#self.canvas2.grid(column=2,row=2,sticky='E',padx=5)
self.text3 = Text(self,height=2,width=20,state=NORMAL)
self.text3.grid(column=2,row=3,sticky='E',padx=5)
self.canvas = Canvas(self,width=230,height=180,state=NORMAL)
self.canvas.grid(column=0,row=4,sticky='W',padx=100,pady=10)
#self.canvas.configure(bg='green')
#Label widget
############################################################################################
self.label1 = Label(self,text="Mode", bg = 'red', width=10,height=2,anchor="center")
self.label1.grid(column=0,row=0,sticky='W',padx=120)
self.label2 = Label(self,text="Inspection",bg = 'red',width=20,height=2,anchor="center")
self.label2.grid(column=2,row=0,sticky='E',padx=50)
self.label3 = Label(self,text="Image",bg = 'red',width=10,height=2,anchor="center")
self.label3.grid(column=0,row=3,sticky='W',padx=120)
self.label4 = Label(self,text="Classification",bg = 'red',width=10,height=2,anchor="center")
self.label4.grid(column=1,row=1,sticky='E',pady=10)
#self.label5 = Label(self,text="Result 2(Black Spot)",width=30,height=2,anchor="e")
#self.label5.grid(column=1,row=2,sticky='E',pady=10)
self.label6 = Label(self,text="Time",bg = 'red',width=10,height=2,anchor="center")
self.label6.grid(column=1,row=3,sticky='E',pady=10)
'''def browseFiles(self):
self.filename = filedialog.askopenfilename(initialdir = '/',title = "Select a File",
filetypes = [("image",".jpeg"),("image",".png"),("image",".jpg")])
start=time.time()
self.imageFile = ImageTk.PhotoImage(file=self.filename)
self.canvas.create_image(50,10,image=self.imageFile,anchor=NW)
self.img = cv2.imread(self.filename)
self.hist = cv2.calcHist([self.img], [0], None, [256], [0,256])
self.mean_px = cv2.mean(self.img)
self.max_nums = max(self.hist); self.max_num = str(self.max_nums)
self.max_num_px= np.where(self.hist==self.max_nums)[0]+1; self.max_num_px = str(self.max_num_px)
self.min_nums = min(self.hist); self.min_num = str(self.min_nums)
self.min_num_px= np.where(self.hist==self.min_nums)[0]+1; self.min_num_px = str(self.min_num_px)
self.hist_2_num = round((self.max_nums*(2/5))[0])
self.hist_2_min_num = self.hist[self.hist>=self.hist_2_num][0]
self.hist_2_max_num = self.hist[self.hist>=self.hist_2_num][len(self.hist[self.hist>=self.hist_2_num])-1]
self.hist_2_min_val = np.where(self.hist==self.hist_2_min_num)[0][0]+1
self.hist_2_max_val = max(np.where(self.hist==self.hist[self.hist>=self.hist_2_num][len(self.hist[self.hist>=self.hist_2_num])-1])[0])
self.hist_2_diff = self.hist_2_max_val - self.hist_2_min_val
self.results = []
if self.hist_2_diff>50:
self.results.append('good')
else:
self.results.append('bad')
for choices in self.results:
self.text1 = Text(self,height=2,width=20,state=NORMAL)
self.text1.insert(END,str(choices))
self.text1.grid(column=2,row=1,sticky='E',padx=5)
end=time.time()
Time_elapsed='{:.3f}s'.format(end-start)
text3 = Text(self,height=2,width=20,state=NORMAL)
text3.insert(END,str(Time_elapsed))
text3.grid(column=2,row=3,sticky='E',padx=5)'''
def Image_Classification(self):
start=time.time()
for self.i in range(1,31):
for self.j in range(1,11):
self.filename = 'Path/Folder_'+str(self.i)+'/'+str(self.j)+'.jpg'
self.img = cv2.imread(self.filename)
self.hist = cv2.calcHist([self.img], [0], None, [256], [0,256])
self.mean_px = cv2.mean(self.img)
self.max_nums = max(self.hist); self.max_num = str(self.max_nums)
self.max_num_px= np.where(self.hist==self.max_nums)[0]+1; self.max_num_px = str(self.max_num_px)
self.min_nums = min(self.hist); self.min_num = str(self.min_nums)
self.min_num_px= np.where(self.hist==self.min_nums)[0]+1; self.min_num_px = str(self.min_num_px)
self.hist_2_num = round((self.max_nums*(2/5))[0])
self.hist_2_min_num = self.hist[self.hist>=self.hist_2_num][0]
self.hist_2_max_num = self.hist[self.hist>=self.hist_2_num][len(self.hist[self.hist>=self.hist_2_num])-1]
self.hist_2_min_val = np.where(self.hist==self.hist_2_min_num)[0][0]+1
self.hist_2_max_val = max(np.where(self.hist==self.hist[self.hist>=self.hist_2_num][len(self.hist[self.hist>=self.hist_2_num])-1])[0])
self.hist_2_diff = self.hist_2_max_val - self.hist_2_min_val
self.results = []
if self.hist_2_diff>50:
self.results.append('{}: good'.format(self.j))
print('{}: good'.format(self.j))
else:
self.results.append('{}: bad'.format(self.j))
print('{}: bad'.format(self.j))
for choices in self.results:
self.text1 = Text(self,height=2,width=20,state=NORMAL)
self.text1.insert(END,str(choices))
self.text1.grid(column=2,row=1,sticky='E',padx=5)
#self.text1.tag_config(background='blue')
self.j+=1
end=time.time()
Time_elapsed='{:.3f}s'.format(end-start)
text3 = Text(self,height=2,width=20,state=NORMAL)
text3.insert(END,str(Time_elapsed))
text3.grid(column=2,row=3,sticky='E',padx=5)
if __name__ == "__main__":
app = application(None)
#font.nametofont('TkDefaultFont').configure(size=10)
app['bg']='Cyan'
app.title("Trial")
app.mainloop()
My results
The expected results
Test images
A: You should not create new Text widgets to store the result in each iteration. As you have already created those Text widgets for showing results and time elapsed inside initialize(), you can just insert the results into those widgets after the for loop:
def Image_Classification(self):
self.results = []
start = time.time()
for self.i in range(1, 31):
for self.j in range(1, 11):
self.filename = 'Path/Folder_'+str(self.i)+'/'+str(self.j)+'.jpg'
self.img = cv2.imread(self.filename)
self.hist = cv2.calcHist([self.img], [0], None, [256], [0,256])
self.mean_px = cv2.mean(self.img)
self.max_nums = max(self.hist); self.max_num = str(self.max_nums)
self.max_num_px = np.where(self.hist==self.max_nums)[0]+1; self.max_num_px = str(self.max_num_px)
self.min_nums = min(self.hist); self.min_num = str(self.min_nums)
self.min_num_px = np.where(self.hist==self.min_nums)[0]+1; self.min_num_px = str(self.min_num_px)
self.hist_2_num = round((self.max_nums*(2/5))[0])
self.hist_2_min_num = self.hist[self.hist>=self.hist_2_num][0]
self.hist_2_max_num = self.hist[self.hist>=self.hist_2_num][len(self.hist[self.hist>=self.hist_2_num])-1]
self.hist_2_min_val = np.where(self.hist==self.hist_2_min_num)[0][0]+1
self.hist_2_max_val = max(np.where(self.hist==self.hist[self.hist>=self.hist_2_num][len(self.hist[self.hist>=self.hist_2_num])-1])[0])
self.hist_2_diff = self.hist_2_max_val - self.hist_2_min_val
result = 'good' if self.hist_2_diff > 50 else 'bad'
self.results.append(f'{self.i}.{self.j}: {result}')
end = time.time()
time_elapsed = f'{end-start:.3f}s'
self.text3.delete('1.0', END)
self.text3.insert(END, time_elapsed)
self.text1.delete('1.0', END)
for result in self.results:
self.text1.insert(END, f'{result}\n')
Update: added scrollbar for self.text1:
def initialize(self):
...
self.text1 = Text(self, height=2, width=20, state=NORMAL)
self.text1.grid(column=2, row=1, sticky='nse', padx=5)
self.scrollbar1 = Scrollbar(self, orient=VERTICAL, command=self.text1.yview)
self.scrollbar1.grid(column=3, row=1, sticky='ns')
self.text1.config(yscrollcommand=self.scrollbar1.set)
...
| |
doc_23535510
|
getData() {
const queryParam = "?callback=JSONP_CALLBACK";
return this.jsonp.get('http://localhost:3000/data/bar-chart-data' + queryParam)
.subscribe(data => console.log(data.json()),
err => console.log(err));
}
This is the url setting from express.js
app.get('/data/bar-chart-data', function (req, res) {
res.json({"foo": "bar"});
})
But it keeps throwing this error:
Response_body: "JSONP injected script did not invoke callback."
headers: Headersok: true status: 200' statusText: "Ok" type: 3url:
"http://localhost:3000/data/bar-chart-data
callback=ng_jsonp.__req0.finished"
| |
doc_23535511
|
But when my URL Opens instead of the URL it gives a port in the URL bar
and it gives internet Explorer cannot display the page.
My code is
System.setProperty("webdriver.ie.driver", "C:\\Program Files\\Internet Explorer\\iexplore.exe" );
WebDriver driver = new InternetExplorerDriver();
driver.get("https://google.com");
Can anyone please help me here?
A: You are using the IE directly in your code. You should not use the normal IE (iexplore.exe) file.
You should use the InternetExplorerDriver file which you can download from http://docs.seleniumhq.org/download/
32 Bit: http://selenium-release.storage.googleapis.com/2.42/IEDriverServer_Win32_2.42.0.zip
64 Bit: http://selenium-release.storage.googleapis.com/2.42/IEDriverServer_x64_2.42.0.zip
Once you download them provide them as below.
System.setProperty("webdriver.ie.driver", "PATH_OF_IEDriverServer.exe" );
| |
doc_23535512
|
Normally this is fixed with a @Mock (using Mockito) or mockDomain(), but I am not in a unit test so these items are not seen.
How can I test my service layer through an integration test if it cannot see my domain objects that I need to use? These domain objects are separated because of the need to use them across multiple projects.
A: If your GORM classes are not in the same package as your Application class then you need to add the ComponentScan annotation to the Application class to indicate where you GORM classes are. Example:
@ComponentScan(basePackages=['foo.bar', 'my.company'])
class Application {
....
A: If you are writing tests do not forget:
*
*Annotations in Spec. @IntegrationTest is important
@ContextConfiguration(loader = SpringApplicationContextLoader, classes = ConfigTest)
@EnableAutoConfiguration
@IntegrationTest
class PaymentServiceSpec extends Specification{
// Tests with GORM entities
}
*Class where hibernate is injected
@SpringBootApplication
@Import(HibernateGormAutoConfiguration)
class CoreConfigTest {
}
*Because of @IntegrationTest it is necessary to have an Application class for tests
@SpringBootApplication
class TestApplication {
static void main(String[] args) {
run TestApplication, args
}
}
I am using this dependencies:
runtime 'org.postgresql:postgresql:9.3-1102-jdbc41'
compile("org.grails:gorm-hibernate4-spring-boot:1.1.0.RELEASE") {
exclude module: 'spring-boot-cli'
exclude module: 'groovy-all'
}
compile("org.springframework.boot:spring-boot-starter-jdbc:1.2.2.RELEASE")
A: There is GORM for Spring Boot available. Examples in https://spring.io/guides/gs/accessing-data-gorm/
If you are writing tests, you can use the HibernateTestMixin or use HibernateDatastoreSpringInitializer to initialize GORM.
| |
doc_23535513
|
this is my last try but it's gives me OutOfMemoryError :
BufferedReader r = new BufferedReader(new FileReader(filePath));
StringBuilder total = new StringBuilder();
String line;
while((line = r.readLine()) != null) {
total.append(line);
}
txtView.setText(total.toString());
How bookReaders or editors handle this kinds of problems ?( they also display text instantly )
| |
doc_23535514
|
var def = viz.append("svg:defs")
.selectAll(".traffic")
.data(["green", "yellow", "red"]) ;// grey
def.enter().append("svg:marker")
.attr("id", String)
.attr("class","traffic")
.attr("viewBox", "0 0 8 10")
.append("svg:polyline")
.attr("points","0,0 8,5 0,10 1,5")
.attr("fill", String)
;
and my path will call the markers like
viz.selectAll("path").attr("marker-mid", "url(#red)");
Is is possible to use d3.svg.symbol() instead of marker or along with marker ?
A: The d3.svg.symbol() object is used to generate the string for the "d" attribute of a <path>. So you change your marker to contain a path instead of a polyline and replace the "points" attribute with a "d" attribute and use the symbol function to calculate the attribute value.
The only other complication is to make sure that the symbol fits neatly within your marker. The symbols are sized by area with a default size of 64 square units, I found I had to make the viewBox 14 units on each side to get them to fit without cropping. (If you find the symbols are too small, set the markerWidth and markerHeight attributes on the <marker> element; the default is 3, aka three times the line width.) The symbols are designed to be centered at (0,0) within their coordinate system, so the viewBox should also be centered around zero.
You also have to be careful with styling markers, since the graphics inherit styles from the line they are attached to, not from the <marker> element.
Fiddle: http://fiddle.jshell.net/5hgSa/1/
var symbolGenerator = d3.svg.symbol()
.type( function(d) {
//sample function, not sure if you wanted them all the same symbol or not!
var coloursToSymbols = {
red:"cross",
yellow:"square",
green:"diamond"
};
return coloursToSymbols[d];
});
var def = viz.append("svg:defs")
.selectAll(".traffic")
.data(["green", "yellow", "red"]) ;
def.enter().append("svg:marker")
.attr("id", String)
.attr("class","traffic")
.attr("viewBox", "-7 -7 14 14")
.append("svg:path")
.attr("d", symbolGenerator)
.style("fill", String) //use style, not attribute, to override the CSS on the path
;
| |
doc_23535515
|
Is there any way to squash all commits in a repository from a specific author into the first child from another author?
Of course, one possibility would be to run git rebase --interactive using the SHA of the root commit and manually go through the list of commits and apply the squash command to the appropriate commit manually. However, it would be useful to know whether there is a quicker option, bearing in mind there are a very large number of commits.
A: To squash all commits of the author with email foo@bar.com into the next child commit of another author, you can use the following. You can of course also check any other attribute like author name, commiter email, committer name, ...
git filter-branch --commit-filter '[ "$GIT_AUTHOR_EMAIL" = "foo@bar.com" ] && skip_commit "$@" || git commit-tree "$@"'
| |
doc_23535516
|
Have a lot of xml files that contains data that i wants to delete.
Im trying to use notepad ++ that have the replace function.
Can i somehowe use notepad ++ to select area that start with tag example:
<greetingCard:state generatedStep="THEME_SELECTION" to the area that ends with tag :
</greetingCard:greetingCard>
I have several xml with a lots of tags, but wants to delete the content from the
tag. Is this possible some how?
A: You can use Regex function, but i don't have use notepad++ currently... If you use SublimeText or regex function if exist in notepad++, create similar regex :
<greetingCard:state generatedStep="THEME_SELECTION"(.*)<\/greetingCard:greetingCard>
| |
doc_23535517
|
lon
lat
output
4050
-47.812224
-19.043365
1890.283215
5149
-47.812224
-19.043365
1890.283215
7316
-47.812224
-19.043365
1890.283215
8406
-47.812224
-19.043365
1890.283215
511
-47.812014
-19.007094
1813.785728
1555
-47.812014
-19.007094
1813.785728
3764
-47.812014
-19.007094
1821.363582
4846
-47.812014
-19.007094
1813.785728
29
-47.811177
-19.008053
1763.091936
1114
-47.811177
-19.008053
1763.091936
3262
-47.811177
-19.008053
1763.091936
4357
-47.811177
-19.008053
1763.091936
1436
-47.774424
-19.008700
2172.781911
2557
-47.774424
-19.008700
2174.394848
4725
-47.774424
-19.008700
2172.781911
5840
-47.774424
-19.008700
2172.781911
5211
-47.774166
-19.043847
2897.092502
6313
-47.774166
-19.043847
2897.092502
8460
-47.774166
-19.043847
2897.092502
9543
-47.774166
-19.043847
2897.092502
1679
-47.773958
-19.007574
2179.670924
2770
-47.773958
-19.007574
2179.670924
4998
-47.773958
-19.007574
2179.670924
6088
-47.773958
-19.007574
2179.670924
1937
-47.773121
-19.008533
2236.769862
3004
-47.773121
-19.008533
2236.769862
5231
-47.773121
-19.008533
2236.769862
6332
-47.773121
-19.008533
2236.769862
I would like to drop the duplicates by using groupby on lon and lat but keep the most repeated value on output
for example
lon
lat
output
-47.812224
-19.043365
1890.283215
-47.812014
-19.007094
1813.785728
-47.811177
-19.008053
1763.091936
-47.774424
-19.008700
2172.781911
-47.774166
-19.043847
2897.092502
-47.773958
-19.007574
2179.670924
-47.773121
-19.008533
2236.769862
Could anyone tell me how to do this?
A: You can combine .groupby with Series.mode:
x = df.groupby(["lon", "lat"])["output"].apply(lambda x: x.mode()[0])
print(x.reset_index())
Prints:
lon lat output
0 -47.812224 -19.043365 1890.283215
1 -47.812014 -19.007094 1813.785728
2 -47.811177 -19.008053 1763.091936
3 -47.774424 -19.008700 2172.781911
4 -47.774166 -19.043847 2897.092502
5 -47.773958 -19.007574 2179.670924
6 -47.773121 -19.008533 2236.769862
A: We can use the .groupby aggregate methods as an alternative to the Andrej's method of using .apply and computing for each row.
While it does solve our problem .apply methods tend to become slower for a large dataset due to lack of vectorization.
Also, reset_index works much faster when used along with 'inplace=True'.
%%timeit
df.groupby(['lat', 'lon']).agg(pd.Series.mode).reset_index(inplace=True)
Hope that helps!!
| |
doc_23535518
|
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, $fileSize);
$content = addslashes($content);
I tried this:
echo '<img src="data:image/jpeg;base64,' . base64_encode( $content ) . '" height=200 width=200 />';
and this:
header("content-type: image/jpeg");
echo $content;
A: take a look at this jquery plugin. See Documentation section and it's a PHP implementation example. Basically, the plugin upload the image, save temporally on server file system and then send back so client to be rendered. Once it's on your file system you can do whatever you want with it (make the query, delete it for example). I think it's a good aproach, it was to me!!.
Hope This Helps!!
| |
doc_23535519
|
Here I am having Two scenarios.
1) I have to call SFN3 from SFN2 and Stop the EMR in SFN2.
2) I have to Stop EMR after Execution of All Step funcitons.
I have included Attachment for your reference.
Kindly help me.
Many thanks.
A: You can call StartExecution from Task State (Lambda or Activity) and then wait for it to complete (or not, if you do not require it).
If you do not need to wait for it to complete (I may have misunderstood the question, but I believe this is not the case), you may just fire&forget with StartExecution.
In the opposite case, when you want to wait for nested State Machine to finish, you may be interested in Job Status Poller pattern (https://docs.aws.amazon.com/step-functions/latest/dg/job-status-poller-sample.html) or implement waiting as an Activity running on a EC2 / ECS / etc. (losing serverless approach).
There is also another approach to the problem of waiting for nested State Machine without active loop (status poller) or servers. It is described here: https://medium.com/semantive/part-1-asynchronous-actions-within-aws-step-functions-without-servers-f58e030a0e8b
A: Recently, AWS Step function added a functionality to call one step function from another step function.
It works like calling any other service ( AWS Glue, AWS Lambda, AWS Sagemaker , AWS Batch ).
It does support both Sync and aysnc. Will need to check for callback support though.
You might also want to check permissions which is required to invoke one state function from another.
Official documentation links:
https://docs.aws.amazon.com/step-functions/latest/dg/sample-start-workflow.html
https://docs.aws.amazon.com/step-functions/latest/dg/connect-stepfunctions.html
A: Fire and Forget the Inner Workflow from the Main Workflow
Step Function Code for the Main Workflow
"<StepName>":{
"Type": "Task",
"Next":"<NextStepName>",
"Resource": "arn:aws:states:::states:startExecution",
"Parameters":{
"Input":{
"Comment": "Hello world!"
},
"StateMachineArn":"<InnerStepFunctionArn>"
}
},
IAM Policy for the Main Workflow Role
Start Execution Policy
StepFunctions/Write/Start Execution
Resource:Inner Step Function
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": "states:StartExecution",
"Resource": "<InnerStepFunctionARN>"
}
]
}
Wait for the Inner Workflow Execution to Finish
Step Function Code for the Main Workflow
"<StepName>":{
"Type": "Task",
"Next":"<NextStepName>",
"Resource": "arn:aws:states:::states:startExecution.sync",
"Parameters":{
"Input":{
"Comment": "Hello world!"
},
"StateMachineArn":"<InnerStepFunctionArn>"
}
},
IAM Policy for the Main Workflow Role
Start Execution Policy
StepFunctions/Write/Start Execution
Resource:Inner Step Function
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": "states:StartExecution",
"Resource": "<InnerStepFunctionARN>"
}
]
}
Event Policy
CloudWatchEvent Full Access
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "CloudWatchEventsFullAccess",
"Effect": "Allow",
"Action": "events:*",
"Resource": "*"
},
{
"Sid": "IAMPassRoleForCloudWatchEvents",
"Effect": "Allow",
"Action": "iam:PassRole",
"Resource": "arn:aws:iam::*:role/AWS_Events_Invoke_Targets"
}
]
}
| |
doc_23535520
|
The width limit works fine, but the grid goes over the height limit. How can I fix this?
I'd also like the images to have no spaces or gaps between them (both on the y and x axis) no matter their size.
https://jsfiddle.net/od3tyepr/
* {
margin: 0;
border: 0;
padding-right: 0;
padding-left: 0;
padding: 0;
}
#_parent {
display: flex;
height: 100vh;
width: 50vw;
align-content: center;
align-items: center;
margin: auto;
}
#_grid {
position: relative;
display: flex;
align-items: flex-start;
height: 80%;
width: 100%;
}
#_row {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
._img {
max-width: 100%;
max-height: 100%;
width: calc(100% / 3);
object-fit: contain;
}
<div id="root">
<div id="_parent">
<div id="_grid">
<div id="_row">
<img id="" src="//placeimg.com/600/400?text=1" class="_img">
<img id="" src="//placeimg.com/600/400?text=2" class="_img">
<img id="" src="//placeimg.com/600/400?text=3" class="_img">
<img id="" src="//placeimg.com/600/400?text=4" class="_img">
<img id="" src="//placeimg.com/600/400?text=5" class="_img">
<img id="" src="//placeimg.com/600/400?text=6" class="_img">
<img id="" src="//placeimg.com/600/400?text=7" class="_img">
<img id="" src="//placeimg.com/600/400?text=8" class="_img">
<img id="" src="//placeimg.com/600/400?text=9" class="_img">
<img id="" src="//placeimg.com/600/400?text=10" class="_img">
<img id="" src="//placeimg.com/600/400?text=11" class="_img">
<img id="" src="//placeimg.com/600/400?text=12" class="_img">
<img id="" src="//placeimg.com/600/400?text=13" class="_img">
<img id="" src="//placeimg.com/600/400?text=14" class="_img">
<img id="" src="//placeimg.com/600/400?text=15" class="_img">
</div>
</div>
</div>
</div>
As you can see, the image doesn't get resized to fit the height and instead there is a lot of scrolling.
A: CSS grid can do better job here:
#_parent {
display: flex;
height: 100vh;
width: 50vw;
place-items: center;
justify-content: center;
margin: auto;
}
#_grid {
display: flex;
min-height: 0;
height: 80%;
}
#_row {
display: grid;
height: 100%;
grid-template-columns: 1fr 1fr 1fr;
}
._img {
min-height: 100%;
height: 0;
width: 100%;
object-fit: contain;
}
body {
margin: 0;
}
<div id="root">
<div id="_parent">
<div id="_grid">
<div id="_row">
<img id="" src="//placeimg.com/600/400?text=1" class="_img">
<img id="" src="//placeimg.com/600/400?text=2" class="_img">
<img id="" src="//placeimg.com/600/400?text=3" class="_img">
<img id="" src="//placeimg.com/600/400?text=4" class="_img">
<img id="" src="//placeimg.com/600/400?text=5" class="_img">
<img id="" src="//placeimg.com/600/400?text=6" class="_img">
<img id="" src="//placeimg.com/600/400?text=7" class="_img">
<img id="" src="//placeimg.com/600/400?text=8" class="_img">
<img id="" src="//placeimg.com/600/400?text=9" class="_img">
<img id="" src="//placeimg.com/600/400?text=10" class="_img">
<img id="" src="//placeimg.com/600/400?text=11" class="_img">
<img id="" src="//placeimg.com/600/400?text=12" class="_img">
<img id="" src="//placeimg.com/600/400?text=13" class="_img">
<img id="" src="//placeimg.com/600/400?text=14" class="_img">
<img id="" src="//placeimg.com/600/400?text=15" class="_img">
</div>
</div>
</div>
</div>
A: You can fix it by adding the attribute overflow: auto; to the parent element _parent.
A:
* {
margin: 0;
border: 0;
padding-right: 0;
padding-left: 0;
padding: 0;
}
#_parent {
height: 100vh;
width: 50vw;
margin: auto;
overflow: auto;
}
#_grid {
position: relative;
display: flex;
align-items: flex-start;
width: 100%;
}
#_row {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
._img {
max-width: 100%;
max-height: 100%;
width: calc(100% / 3);
object-fit: contain;
}
<div id="root">
<div id="_parent">
<div id="_grid">
<div id="_row">
<img id="" src="//placeimg.com/600/400?text=1" class="_img">
<img id="" src="//placeimg.com/600/400?text=2" class="_img">
<img id="" src="//placeimg.com/600/400?text=3" class="_img">
<img id="" src="//placeimg.com/600/400?text=4" class="_img">
<img id="" src="//placeimg.com/600/400?text=5" class="_img">
<img id="" src="//placeimg.com/600/400?text=6" class="_img">
<img id="" src="//placeimg.com/600/400?text=7" class="_img">
<img id="" src="//placeimg.com/600/400?text=8" class="_img">
<img id="" src="//placeimg.com/600/400?text=9" class="_img">
<img id="" src="//placeimg.com/600/400?text=10" class="_img">
<img id="" src="//placeimg.com/600/400?text=11" class="_img">
<img id="" src="//placeimg.com/600/400?text=12" class="_img">
<img id="" src="//placeimg.com/600/400?text=13" class="_img">
<img id="" src="//placeimg.com/600/400?text=14" class="_img">
<img id="" src="//placeimg.com/600/400?text=15" class="_img">
</div>
</div>
</div>
</div>
I think it woks for you
| |
doc_23535521
|
I'm a newbie in the OpenGL(ES) world, the issue I'm facing is that I get no errors from glGetError, but the video isn't being shown until I rotate the iPad then it works and I can rotate it back to the original orientation and it keeps working. The same behaviour happens with the simulator.
It also works after using the XCode GL debugging features (that shows the GL buffers and objects), after activating it and letting the program run again, the video is rendered nicely.
What could be the reason for this? Any GL command that rotating the device or enabling the GL debugging could be running that I might be missing?
A: black screen / no events in iOS OpenGL ES 2
This question had the same issue as mine, and the same solution worked.
Great!
| |
doc_23535522
|
It should be roughly 50GB, but the last time it happened, it showed 34GB. My main problem is that I am unsure of what error to try/catch.
I am still learning Python as I go, so bare with me.
from progress import ProgressPercentage # class file progress.py
from slack import * # function file for Slack notifications
import random
import glob
import os
import boto3
import botocore
from boto3.s3.transfer import TransferConfig
bucket = "my-s3-backup"
s3 = boto3.resource('s3')
# Grabbing the last file, and removing the full path from the string
pattern = "/path/to/backup/file/xb_*"
files = list(filter(os.path.isfile, glob.glob(pattern)))
files.sort(key=lambda x: os.path.getmtime(x))
file_to_upload = files[-1]
file_name = file_to_upload.replace('/path/to/backup/file/', '')
key_path = 'physical_db_backups/' + file_name
# Multipart upload function
def multi_part_upload():
config = TransferConfig(multipart_threshold=1024 * 25,
max_concurrency=10,
multipart_chunksize=1024 * 25,
use_threads=True)
try:
s3.meta.client.upload_file(file_to_upload, bucket, key_path, Config=config,
Callback=ProgressPercentage(file_to_upload))
# Custom Slack notification to inform completion
sendslacksuccess("Physical Backup to S3 Complete:\n" + file_name)
except botocore.exceptions.ClientError as error:
# Custom Slack notification to inform of failure
sendslackerror("Physical Backup to S3 Failed:\n" + file_name + "\nError: " + error)
if __name__ == '__main__':
multi_part_upload()
If the script is not "failing," but it's not uploading the complete file size, what exception am I trying to catch here? Should I log output somewhere?
I'm looking through the Botocore Exceptions documentation. I'm just unsure of what to try/catch with this.
For reference, here is the file size difference:
aws s3 ls --summarize --human-readable --recursive s3://my-s3-backup/physical_db_backups/
2022-05-07 14:31:28 50.7 GiB physical_db_backups/xb_202205070101.xb.zst
2022-05-08 12:48:07 50.8 GiB physical_db_backups/xb_202205080101.xb.zst
2022-05-09 01:30:04 34.2 GiB physical_db_backups/xb_202205090101.xb.zst <--- WRONG
A: Alright, since I was an idiot and didn't realize the file had not completed yet, I made a couple of changes.
*
*I edited the cron to start later.
*I have created logic to determine if the backup script is running.
*I may incorporate additional checks to make sure the file exists, but for now this is a working POC that has been tested.
from progress import ProgressPercentage # class file progress.py
from slack import * # function file for Slack notifications
import random
from time import sleep
import psutil
import glob
import os
import boto3
import botocore
from boto3.s3.transfer import TransferConfig
import logging
bucket = "fsn-s3-backup"
s3 = boto3.resource('s3')
pattern = "/path/to/backup/file/xb_*"
files = list(filter(os.path.isfile, glob.glob(pattern)))
files.sort(key=lambda x: os.path.getmtime(x))
file_to_upload = files[-1]
file_name = file_to_upload.replace('/path/to/backup/file/', '')
key_path = 'physical_db_backups/' + file_name
logging.basicConfig(filename='/var/log/s3-backup.log', format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', filemode='a')
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def multi_part_upload():
config = TransferConfig(multipart_threshold=1024 * 25,
max_concurrency=10,
multipart_chunksize=1024 * 25,
use_threads=True)
try:
s3.meta.client.upload_file(file_to_upload, bucket, key_path, Config=config,
Callback=ProgressPercentage(file_to_upload),
ExtraArgs={'ContentType': 'application/zstd'})
logger.info("Physical Backup to S3 Complete")
sendslacksuccess("Physical Backup to S3 Complete:\n" + file_name)
except botocore.exceptions.ClientError as error:
logger.error("Physical Backup to S3 Failed: " + error)
sendslackerror("Physical Backup to S3 Failed:\n" + file_name + "\nError: " + error)
def checkIfProcessRunning(processName):
for proc in psutil.process_iter():
cmdline = proc.cmdline()
if processName in cmdline:
return True
return False
if __name__ == '__main__':
backuprunning = True
while backuprunning:
logger.info("Checking if backup shell script is running")
if checkIfProcessRunning('/path/to/physical_backup.sh'):
logger.info("Backup shell script still running. Sleeping for 60s")
sleep(60)
else:
backuprunning = False
logger.info("Beginning multipart upload")
multi_part_upload()
| |
doc_23535523
|
I have used JS which is able to display the icon and change its color on hover but I'm unable to achieve the response.
var feedback = document.createElement("div");
feedback.className = "rating";
responsePara.appendChild(feedback);
// like button
var like = document.createElement("div");
like.className = "like grow";
var thumbsUp = document.createElement('i')
thumbsUp.className = "fa fa-thumbs-up fa-2x like";
thumbsUp.ariaHidden = true;
feedback.appendChild(like);
like.appendChild(thumbsUp)
// dislike button
var dislike = document.createElement("div");
dislike.className = "dislike grow";
var thumbsDown = document.createElement('i')
thumbsDown.className = "fa fa-thumbs-down fa-2x dislike";
thumbsDown.ariaHidden = true;
feedback.appendChild(dislike);
dislike.appendChild(thumbsDown)
$('.like, .dislike').on('click', function() {
event.preventDefault();
$('.active').removeClass('act`enter code here`ive');
$(this).addClass('active');
})
| |
doc_23535524
|
// app analytics flurry
new FlurryAgent.Builder()
.withLogEnabled(false)
.build(this, getString(R.string.flurryID));
FlurryEventRecordStatus a = FlurryAgent.logEvent("App Start.");
"a" is "kFlurryEventFailed". Why???
compile 'com.flurry.android:analytics:6.3.1'
<uses-permission android:name="android.permission.INTERNET" />
Flurry Analytics got a log.But Flurry event is none.
A: The event is likely failing because it is invoked immediately after the call to start the Flurry session. You can use a session listener in this instance to resolve this:
new FlurryAgent.Builder()
.withLogEnabled(true)
.withListener(new FlurryAgentListener() {
@Override
public void onSessionStarted() {
// your session handling code
FlurryEventRecordStatus a = FlurryAgent.logEvent("App Start.");
}
})
.build(this, R.string.flurryID);
Also note you are using an older sdk version. Check the integration guide here:
https://developer.yahoo.com/flurry/docs/integrateflurry/android/
compile 'com.flurry.android:analytics:8.0.2@aar'
| |
doc_23535525
|
View:
<div class="col-xs-12">
<p ng-repeat="item in items" ng-click="gotoAnchor(item .visibleName)"> {{item .visibleName}}</p>
</div>
<div class="col-xs-12" ng-repeat="item in items" >
<div id="anchor{{item .visibleName}}">
<h1>{{item.idPrimary}}</h1>
</div>
Controller:
$scope.gotoAnchor = function(x) {
var newHash = 'anchor' + x;
if ($location.hash() != newHash) {
$location.hash('anchor' + x);
} else {
$anchorScroll();
}
};
| |
doc_23535526
|
href="index.html#mysectionid"
in Html I have something Like this
<section id="mysection">
</section>
I want to Know How I am gonna do this thing in mvc. Thanks
A: You can mix C# code with normal html in Razor:
<a href="@Url.Action("Contact", "Home")#mysection">Test</a>
| |
doc_23535527
|
I'm trying to find the LIKE operator to do a wildcard search on an attribute value
/MAP[@MODE='INPUT']/MAPSET[@FIELD LIKE '/documentTypeName*']/DATA/Values/value
In XQuery, I was using the matches() function. Have been surprised at my lack of finding an answer through searching. My best bet was http://www.ibiblio.org/xql/xql-proposal.html which says it should be keyword contains but this doesn't seem correct.
A: Pretty much a necro, but i believe you are looking for 'icontains'.
http://www.ibiblio.org/xql/xql-proposal.html#Comparisons
Section 1.4.3 Comparisons. This should be a case insensitive version of 'contains'
(field icontains "/documentTypeName*")
| |
doc_23535528
|
Suppose I have 3 screens A,B,C. What I don't understand is why when my app is loaded on screen B, componentDidMount works implicitly (I don't need 'didFocus') on screen B from C->B but not work from A->B
ComponentDidMount()
{
//ComponentDidMount Located in Screen B
execute code1. //works from C->B, Does not work from A->B
this.props.navigation.addListener('didFocus'{
execute code2. //Works for both
})
}
The stack navigator looks like the this
createStackNavigator({
FriendsArea: {
screen:B,
navigationOptions:{
header:null
}
},
HostArea: {
screen:C,
navigigationOptions:{
header:null
}
},
Profile: {
screen:A,
navigationOptions:{
header:null
}
},
})
Could someone help? I can clarify some more if need, thank you.
A: The sequence is matters in stack navigator, you should arrange the stack like this:
createStackNavigator({
FriendsArea: {
screen:A,
navigationOptions:{
header:null
}
},
HostArea: {
screen:B,
navigigationOptions:{
header:null
}
},
Profile: {
screen:C,
navigationOptions:{
header:null
}
},
})
A = first page, B = next page after A, C = next page after B
Your problem happened because the B component already called the componentDidMount method while creating the A component so that you have to call the didFocus listener which is usually used to execute the code when we are navigating back from other page.
| |
doc_23535529
|
Now I have to do something with it. One of the options is to just remove "xmlns", "xmlns:xsi" and "xsi:schemaLocation" attributes.
Will removing them likely break existing users? Would such XML be valid?
A: If you previously had a xmlns attribute in your document element, it means that all XML elements (with no prefix) were in a namespace. If you now remove that namespace, this is no true anymore and the output of any (namespace-aware) parser changes. And with that, most probably the behavior of the programs working on the parsed data.
Just as an example, using XPath in Java is different if the XML elements are in a namespace: How to query XML using namespaces in Java with XPath?. Although the accepted answer shows a way to use XPath in a namespace-agnostic way, most programs will probably not use this approach.
The XML should still be valid (actually well-formed), you can easily check that in a decent XML editor that supports validation (including Eclipse for example). But because you removed the reference to the Schema, validation will only cover basic XML rules (as I said, the well-formedness), not the rules set up by the Schema.
So in short, yes, you may break your clients but yes, the XML would (probably) still be valid.
A: The XML files will still be well-formed if they were well-formed previously. Validity doesn't really apply because you weren't pointing to a proper schema document with the xsi:location attribute anyway.
In fact, the user complaining is probably the only one who is trying to validate your files. The rest of your consumers were doing fine with the placeholders. They may fare just as well without those attribute specifications altogether, unless they have software specifically customized to "recognize" your blahblahblah inventions.
| |
doc_23535530
|
Whenever I try to use a '/s', '/n', or anything to continue the pattern search onto the next line, it fails to find any pattern at all.
e.g. SEARCHING FOR THE FOLLOWING PATTERN
for i in range(60):
try:
if self.is_element_present(By.CSS_SELECTOR, "div[id=Navigation] ul[id=mainNav] a[href='/DataValues/']"): break
except: pass
time.sleep(1)
else: self.fail("time out")
So when I try: type file.py | repl "\sfor i in range\(60\)\:" "cookie" file.py.new
...to represent the first line, it will find the first line successfully.
However if I add a '\n' or '\s' to continue searching for the pattern past the first line:
** type file.py | repl "\sfor i in range\(60\)\:\stry" "cookie" file.py.new **
...it fails to find anything and no changes are made. I've tried different combinations of \n and \s & the results are always the same. Thanks ahead of time for your help!
A: Read the documentation more carefully. You need the M option to be able to match across multiple lines.
For example, given test.txt
red
+
blue
Then
type test.txt | repl "red\s*\+\s*blue" "purple" m
yields
purple
| |
doc_23535531
|
I guess I could change the Django Site model code itself (shown below), but I don't really want to do that. I'd rather overwrite the setting in my app or the form view, but I can't figure out how to do either.
class Site(models.Model):
domain = models.CharField(
_('domain name'),
max_length=100,
validators=[_simple_domain_name_validator],
unique=True,
)
name = models.CharField(_('display name'), max_length=50)
objects = SiteManager()
class Meta:
db_table = 'django_site'
verbose_name = _('site')
verbose_name_plural = _('sites')
ordering = ['domain']
def __str__(self):
return self.domain
def natural_key(self):
return (self.domain,)
When I subclass the Site model, my CustomSite tries to do a join with the Site model and causes complications, so it seems like that approach isn't ideal.
class CustomSite(Site):
objects = SiteManager()
def __str__(self):
return self.name
class Meta:
db_table = 'django_customsite'
A simplified version of the form I was testing with is below. The form works. It updates the object with the right site, but I'd still like to know how to use the name as the representation instead of the domain.
class StoreUpdateView(UpdateView):
model = Site
fields = [
'store',
'site_id',
]
template_name = 'app/group-updateview.html'
I've basically made an intermediary table (Site > Store > Products), but I'd prefer to know how to change the _str_ setting of the Site model. How can I overwrite the _str_ setting of the Site model to return the Site name field instead of the domain?
| |
doc_23535532
|
public class MyObject
{
public bool B;
public string Txt;
}
List<MyObject> list; //list of a bunch of MyObject's
With lambda expression, how can I produce a string consisting of comma separated values of Txt of those objects, where B is true?
Thank you.
A: for .net 3.5:
string.Join(",", list.Where(o => o.B).Select(o => o.Txt).ToArray())
for .net 4.0:
string.Join(",", list.Where(o => o.B).Select(o => o.Txt))
A: string myString = string.Join(",", list.Where(x => x.B).Select(x=>x.Txt));
A: var strFinal = "";
myList.ForEach(pq => strFinal += ", " + pq.ItemId);
| |
doc_23535533
|
Here is the server that my computer is running.
public static void main (String[] args) throws IOException
{
ServerSocket server = new ServerSocket(31350);
Socket client1 = server.accept();
}
Here is the client code that my friend is running on his computer
public static void main(String[] args) throws IOException, UnknownHostException
{
Socket socket;
// #'s are what I got from whatismyip.org on the server computer)
byte[] serverb = new byte[] {(byte)##, (byte)##, (byte)###, (byte)###};
socket = new Socket(InetAddress.getByAddress(serverb),31350);
}
This is what it says when I run the client
Exception in thread "main" java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.(Socket.java:425)
at java.net.Socket.(Socket.java:241)
at ClientTest.main(ClientTest.java:22) // 22 is the line socket = new Socket(InetAddress.getByAddress(serverb),31350);
firewalls are disabled. the port 31350 on my router is forwarded to my computer's local ip address that I got from using ipconfig in cmd. But it still doesnt work, I just get IOException when trying to create the socket from the client computer. Nothing happens on the server computer. What's wrong?
A: [update]
As you might expect, connection timed out indicates it's some kind of a network problem. The packets from your client are not arriving at the server machine. The exact solution will depend on the type of router, but the term to google for is "port forwarding". Here is an article I found at random that might help: http://www.rhinosoft.com/KnowledgeBase/kbarticle.asp?RefNo=1289
Basically you program the router so that any connection request at port 31350 will be forwarded to your computer on the lan at it's local IP address.
Good luck!
[original comment]
This is more of a comment than an answer (but I needed the extra room). Your try catch logic is going to make it much more difficult to diagnose the problem. Simplify the code as follows:
public static void main(String[] args) throws IOException, UnknownHostException
{
Socket socket;
// #'s are what I got from whatismyip.org on the server computer)
byte[] serverb = new byte[] {(byte)##, (byte)##, (byte)###, (byte)###};
socket = new Socket(InetAddress.getByAddress(serverb),31350);
}
Just let the original IOException propagate and update your question to include the exception stack trace. The original exception contains valuable information - if it says connection refused it means one thing - perhaps your port number is incorrect. If it says connection timed out it means something else - either you really do have a firewall problem or perhaps your ip address is wrong.
Your code is catching the useful exception, swallowing it and throwing a much less useful exception.
Do the same thing to your server code:
public static void main (String[] args) throws IOException
{
ServerSocket server = new ServerSocket(31350);
Socket client1 = client1 = server.accept();
}
The stack trace will show which method threw the exception so you don't need redundant text like InetAddress creation failed
| |
doc_23535534
|
*
*Brand (containing Apple and Samsung)
*Model (containing iPhone 5, iPhone 5C, iPhone 5S, iPhone 56, Galaxy S3, Galaxy S4, etcc..)
And this is how they are arranged together:
When looking at the product this shows Brand and Model as a dropdown list, which is great, but when selecting Apple, shows ALL of the Models, and if I select Apple > Galaxy S3 just says "The product does not exist in this model".
Is there a way I can HIDE any non-matching Models based on their Brand?
(When selecting Apple only the one for apple should show up).
A: I sorted the problem with Attribute Wizard module. This module allows you to filter attributes according to the existing combination, as in the sown example.
| |
doc_23535535
|
Thanks!
A: You can do something like this in your tableView:cellForRowAtIndexPath: method
cell.textLabel.text = [NSString stringWithFormat:@"%i", indexPath.row+1];
Edit:
Then make sure you do the following:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 10; <<<<====specify here the number of rows to be displayed.
}
Addendum:
If you already have things stored in your labels and would like to store still the numbers, try the do the following:
In your storyboard, click on the cell and then change the style to "Subtitle".
Then back to your table view controller, add the following line to the aforementioned method:
cell.detailTextLabel.text = [NSString stringWithFormat:@"%i", indexPath.row+1];
So now you have both labels, one in which you would like to store your strings and the sub labels where you have the number of rows as discussed.
Adding screenshot:
A: Try the following in your tableView:cellForRowAtIndexPath: implementation:
cell.textLabel.text = [NSString stringWithFormat:@"%@ %i",[tableData objectAtIndex:indexPath.row], ((indexPath.row)+1)];
A: You could do something like this where you can keep "textLabel" for whatever you want to put there and use "detailTextLabel" to show the number of the row on the right while using UITableViewCellStyleValue1.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
[[cell textLabel] setText:@"Your Label"];
[[cell detailTextLabel] setText:[NSString stringWithFormat:@"%d", [indexPath row]+1]]; //Note the +1 because the first row will have an indexpath 0
return cell;
}
| |
doc_23535536
|
Execution failed for task ':app:checkDebugDuplicateClasses'.
> Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
> Failed to transform lifecycle-common-java8-2.4.0.jar (androidx.lifecycle:lifecycle-common-java8:2.4.0) to match attributes {artifactType=enumerated-runtime-classes, org.gradle.category=library, org.gradle.dependency.bundling=external, org.gradle.jvm.version=8, org.gradle.libraryelements=jar, org.gradle.status=release, org.gradle.usage=java-runtime}.
> Could not find lifecycle-common-java8-2.4.0.jar (androidx.lifecycle:lifecycle-common-java8:2.4.0).
Searched in the following locations:
https://dl.google.com/dl/android/maven2/androidx/lifecycle/lifecycle-common-java8/2.4.0/lifecycle-common-java8-2.4.0.jar
I'm able to download this file by using a browser, but the build procedure cannot download it. even I thought if I know the download place I will put the file there and maybe it helps, but I don't know where does the build procedure use to store the file and then use it.
A: This solution works for me:
Step 1: creating a socks proxy with ssh tunnel:
ssh -f -N -M -S /tmp/sshtunnel -D 1086 root@x.x.x.x
Step 2: passing my system traffic through the socks proxy by Shadowrocket (needs m1 macbook)
| |
doc_23535537
|
public class Stepik_05_04_Clone {
public static void main(String[] args) throws CloneNotSupportedException {
MyObj myObj1 = new MyObj();
myObj1.i = 1;
myObj1.s = "abc1";
myObj1.innerObj.j = 2;
MyObj myObj2 = myObj1.clone();
myObj2.i = 10;
myObj2.s = "abc2";
myObj2.innerObj.j = 20;
System.out.println(myObj1.i);
System.out.println(myObj1.s);
System.out.println(myObj1.innerObj.j);
System.out.println();
System.out.println(myObj2.i);
System.out.println(myObj2.s);
System.out.println(myObj2.innerObj.j);
}
}
class MyObj implements Cloneable {
int i;
String s;
InnerObj innerObj = new InnerObj();
@Override
protected MyObj clone() throws CloneNotSupportedException {
MyObj myObj = (MyObj)super.clone();
myObj.innerObj = innerObj.clone();
return myObj;
}
}
class InnerObj implements Cloneable{
int j;
@Override
protected InnerObj clone() throws CloneNotSupportedException {
return (InnerObj)super.clone();
}
}
A: You are only dealing with primitives and immutable objects here - String is such, so no need to worry about clone in this case; it will work just fine. In general, clone is a pretty terrible idea and can get very complicated unless you truly understand what it does. To better visualize how broken it can get, just comment the myObj.innerObj = innerObj.clone(); line and add one more output line:
System.out.println(myObj2.innerObj.j);
System.out.println(myObj1.innerObj.j);
Can you explain to yourself why you would get an output of 20, 20?
| |
doc_23535538
|
See below:
DATE
FIC02
08-jan-08 06:30:00
?
08-jan-08 13:30:00
?
08-jan-08 20:30:00
?
I'm using PI DataLink's 'Calculated data' function in Excel with:
start time: 08-jan-08 06:30:00 - (4/24)
end time 08-jan-08 06:30:00
The code used is below:
=PIAdvCalcVal("FIC02";"'Planilha1'!$A$6 - (4/24)";Planilha1!$A$6;"average";"time-weighted";0;1;0;"")
The following error message appears: The time is invalid.
A: You have to specify a time range
See below. I have a start time and 4h later an end time.
If you need an hourly average over the same time range, then specify the optional "Time interval"
As an example I calculate an hourly (60m=60minutes, you can also write 1h) average over the same timespan
You can indeed make a calculation relative to a single time field. Just make sure the time format in excel is correct.
As you ca see both ways (start end time & end time - 5h) yields the same result,
| |
doc_23535539
|
My example HTML file is:
<!DOCTYPE html>
<meta charset='utf-8'>
<html>
<head>
<script src="http://d3js.org/d3.v5.min.js" charset="utf-8"></script>
</head>
<body>
<table id="muell"></table>
<script type='text/javascript' src='script.js'></script>
<script>
var intern_data = [{
Proton: "A",
Multiplett: "dd",
Formel: "\<sup\>1\</sup\>H\<sub\>3\</sub\>"
},
{
Proton: "B",
Multiplett: "dq",
Formel: "<sup>1</sup>C<sub>3</sub>"
}
];
var spalten = ['Proton', 'Multiplett', 'Formel'];
tabulate("#muell", intern_data, spalten);
</script>
</body>
</html>
The Javascript is stolen from from bl.ocks.org and became a little bit modified to add the new table content into a preformatted region.
var tabulate = function (table_id,data, columns) {
var table = d3.select(table_id)
var thead = table.append('thead')
var tbody = table.append('tbody')
thead.append('tr')
.selectAll('th')
.data(columns)
.enter()
.append('th')
.text(function (d) {
return d
})
var rows = tbody.selectAll('tr')
.data(data)
.enter()
.append('tr')
var cells = rows.selectAll('td')
.data(function (row) {
return columns.map(function (column) {
return {
column: column,
value: row[column]
}
})
})
.enter()
.append('td')
.text(function (d) {
return d.value
})
return table;
}
In principle everything works fine as long as I use plain text. Unfortunately
HTML tags become modified. For instance ">" becomes "_gt;" (& instead of _, cannot use it here, otherwise the expression becomes ">" :-) ).
I tried to use \ to keep pure HTML, but this doesn't seem to work.
A: d3 has two functions, text and html. If you want to output html you can use the html function instead:
var cells = rows.selectAll('td')
.data(function (row) {
return columns.map(function (column) {
return {
column: column,
value: row[column]
}
})
})
.enter()
.append('td')
.html(function (d) {
return d.value
})
But be careful, this is dangerous if the value doesn't come from a trusted source - since a user might be able to inject malicious HTML.
| |
doc_23535540
|
Folder Structure
app
- api
- api1
__mocks__
index.js
- index.js
- api2
__mocks__
index.js
- index.js
- components
-component1
- index.js
__tests__
component1.test.js
Right now I have component1 which internally uses api1 to do some requests.
There are two issues that I am facing with the current folder structure and mocking the api modules.
*
*How should I be naming the files under api/__mocks__? should it be index.js (the same of as index.js under api1) or should it be api1.mocks.js? Is there a naming convention that is required for jest?
*Right now with the current structure jest is throwing me the following error,
Jest Error:
jest-haste-map: duplicate manual mock found: Module name: index
Is there a documentation somewhere that talks about naming mocks?
This is my jest configuration from package.json,
package.json:
"jest": {
"testEnvironment": "jsdom",
"testPathDirs": [
"<app-path>"
],
"modulePaths": [
"<app-path>"
],
"enableAutomock": true,
"moduleNameMapper": {
"^components": "<rootDir>/components",
"^services": "<rootDir>/services",
"^api": "<rootDir>/api",
"^.+\\.less$": "<rootDir>/__mocks__/styleMocks.js"
}
}
Simple unit test:
import React from 'react';
import {mount} from 'enzyme';
import Component from 'components/Component1';
jest.mock('api/api1');
describe('Component1 Unit tests', () => {
it('Should render', () => {
const c1 = mount(
<Component1 />
);
expect(...);
});
});
A: ‘Is there a documentation somewhere that talks about naming mocks?’
Yes, the documentation specifies that in Manual mocks section:
Manual mocks are defined by writing a module in a __mocks__/ subdirectory immediately adjacent to the module. For example, to mock a module called user in the models directory, create a file called user.js and put it in the models/__mocks__ directory.
That is the name of the mock should be the same as of the module.
‘Duplicate manual mock found’
When using moduleNameMapper the docs read:
Modules that are mapped to an alias are unmocked by default.
I am not sure is Jest does not look for the mock either way.
Also please not that moduleNameMapper does not work as you seem to assume it does. It does not replace the path parts, it resolves every require starting with e.g. api to <rootDir>/api! (This the does not have any root file.). You should use ModulePaths instad.
The latest Jest v17 should give you more info about the duplicate.
Note: The config option enableAutomock does not exist, did you mean automock? (Or it should not be there at all?)
Note: Similar to naming convention for mocks, inside __tests__ folder test files usually keep the name of the module, too. The other approach is to add .spec or .test suffix and keep the test file in the same folder. In both cases it is the easy to find the corresponding test file. Therefore __tests__/index.js or index.test.js would be good names.
| |
doc_23535541
|
SELECT * FROM table WHERE 4 IN(col1, col2) && (col3 = 0 || col4 = 0)
The or is not working. It returns zero rows and I know that there are 4
A: && and || in SQL are AND and OR.
Rewrite that to:
SELECT * FROM table WHERE (col1 = 4 AND col2 = 4) AND (col3 = 0 OR col4 = 0)
You can't use IN for column names. You can use IN like this:
WHERE col3 IN('4','a','another valid value'),
which is equals to WHERE (col3 = '4' OR col3 = 'a' OR ...)
A: Try like below instead cause per your posted code 4 IN (col1, col2) will be col1=4 or col2 = 4 whereas you want it to be and condition
Per last comment update; below query will get you exactly those records
There is a total of 4 rows where column1 or column2 = 4. of those
rows I only want to return the rows where col3 or col4 = zero
SELECT *
FROM test4
WHERE (col1 = 4 or col2 = 4)
and (col3 = 0 or col4 = 0)
| |
doc_23535542
|
here's what I have so far
My question is how would I do the sort function more efficiently? is there a way to identify based off of the var first that I declared and its id relative to the rows and determine something like #something5 is the fifth row, so iterate from the 6th row to the 11th row? instead of using the .next() functions as shown.
<div id="rows">
<div class="row" id="something1">something1</div>
<div class="row" id="something2">something2</div>
<div class="row" id="something3">something3</div>
<div class="row" id="something4">something4</div>
<div class="row" id="something5">something5</div>
<div class="row" id="something6">something6</div>
<div class="row" id="something7">something7</div>
<div class="row" id="something8">something8</div>
<div class="row" id="something9">something9</div>
<div class="row" id="something10">something10</div>
<div class="row" id="something11">something11</div>
<div class="row" id="something12">something12</div>
</div>
<a href="#" id="prev">prev</a>
<a href="#" id="next">next</a>
<br />
<span id="total"></span>
var max = 5;
function sort(x) {
if (x == "prev") {
var first = $('#rows .row:visible').first().attr('id');
if (first != "something5") {
$('#rows .row').hide();
$('#'+first).prev('div').show();
$('#'+first).prev('div').prev('div').show();
$('#'+first).prev('div').prev('div').prev('div').show();
$('#'+first).prev('div').prev('div').prev('div').prev('div').show();
$('#'+first).prev('div').prev('div').prev('div').prev('div').prev('div').show();
}
} else {
var last = $('#rows .row:visible').last().attr('id');
$('#rows .row').hide();
$('#'+last).next('div').show();
$('#'+last).next('div').next('div').show();
$('#'+last).next('div').next('div').next('div').show();
$('#'+last).next('div').next('div').next('div').next('div').show();
$('#'+last).next('div').next('div').next('div').next('div').next('div').show();
}
}
$(document).ready(function() {
var total = $('#rows .row').size();
var pages = total / max;
$("#total").text("page " + pages + " of " + total);
$('#rows .row').hide();
for (i = 0; i < max; i++) {
$('#rows .row').eq(i).css('display', 'block');
}
$('#prev').click(function() {
sort("prev");
});
$('#next').click(function() {
sort("next");
});
});
Jsfiddle here http://jsfiddle.net/DcNLJ/
A: Try this :
http://jsfiddle.net/DcNLJ/1/
What left fot u to do is to take care of edge scenario (prevent to prev at start or next at end)
var max = 5;
var pageNum = 0;
var _ = $('#rows .row');
$(document).ready(function ()
{
var total = _.length;
var pages = total / max;
$('#prev').click(function ()
{
pageNum--;
sort("prev");
});
$('#next').click(function ()
{
pageNum++;
sort("next");
});
$('#next').trigger('click');
});
function sort(a)
{
_.hide();
_.filter(function (i)
{
return i >= (pageNum - 1) * max && i < (pageNum) * max;
}).show();
$("#total").text("page " + pageNum + " of " + Math.ceil($('#rows .row').length / max));
}
| |
doc_23535543
|
I have just started using spring boot. For understanding how it works I have tried to convert my existing project (spring MVC, JSP in frontend) to spring boot approach with REST-controller and AngularJS in frontend.
Facing problem:
During migration I have faced to big problem with security. As I understood the best way for having good security layer now is working with JWT tokens and supporting oauth2, on which there are a lot of posts/tutorials which give different information even about basics of the security layer architecture.
So the question is:
Could someone point out full list of security-layer parts/classes which are needed for having basic (but not hello world) security features for spring boot app with REST controllers. Please don't suggest to use stormpath: I want to implement it myself to get better understanding.
Reasoning of asking this big question here:
I have done my own investigation on this topic, but I thought that most of the links which I have checked contain a lot of bad practices, so possible incorrect architecture of security layer. so I really would like to know some kind of good practice of designing architecture of security layer.
Details on needed features:
I have standard list of features which I want to support.
*
*oauth2 support (but also to have possibility to authenticate without it)
*register request (creation of jwt token and returning to client)
*login request (acquiring jwt token if user was registered)
*logout request (releasing jwt token)
*token timeout
*multiple roles
*business rest controllers which checks for authentication and authorization (could you please give an example portion of code)
*business rest controllers which doesn't require security
*basic filtering http urls (like excluding "statics" from allowed url addresses)
Current layers of the project:
Below are some additional information about my current project structure:
Currently I have implemented the following modules:
*
*controller: Currently MVC controllers, but I am going to convert them to REST
*dto: Possibly will be changed a little bit, because of REST approach
*model: Will stay unchanged after conversation
*exception: For business logic
*repository: Will stay unchanged after conversation
*service: Possibly will be changed a little bit, because of micro-services
*validator: Will stay unchanged after conversation
*other business logic modules
If I understood correctly I will need to add two additional layers here:
*
*configuration: I have already converted some xml configurators to java-configs, but haven't touched security configurators
*security: I guest here will be placed authentication/authorization managers/tools. One of the goals of this question is to understand what exactly to place here.
*app class with main method in the root package (relative root)
A: You can start by creating 3 projects.
*
*Auth Server: This will take care of authenticating clients and users, issuing token, revoking token etc.
*Rest API: All rest controllers, business logic, persistence layer etc.
*Front-end: Angular JS, HTML, CSS etc.
Read about OAuth2 grant types.
We use password authorization grant type when authorization server and client is developed by same organization, or when there is a high degree of trust between the resource owner and the client.
Following are the essential classes you'd need for OAuth2 implementation:
A class which extends AuthorizationServerConfigurerAdapter to configure authorization server.
Here you can configure endpoints like userDetailsService (custom class to load user data by username from database), tokenStore (to store tokens in database and perform operations on it), clientDetailsService (load client details from database; your Rest API project could be client).
@Override
public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
endpoints.userDetailsService(userDetailsService);
endpoints.tokenStore(tokenStore);
endpoints.setClientDetailsService(clientDetailsService);
endpoints.accessTokenConverter(accessTokenConverter);
}
@Override
public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
//The expression below easies access to /oauth/check_token endpoint from the default denyAll to isAuthenticated.
oauthServer.checkTokenAccess("isAuthenticated()");
oauthServer.allowFormAuthenticationForClients();
oauthServer.passwordEncoder(passwordEncoder);
}
@Override
public void configure(final ClientDetailsServiceConfigurer clients) throws Exception {
clients.withClientDetails(clientDetailsService);
}
A class which extends ResourceServerConfigurerAdapter. Here you can configure security configuration for the resource server. Resources would be Rest controllers defined in Auth Servers (like controllers for performing CRUD operation on a user object, endpoint to revoke token; controllers which need to be in Auth Server).
@Override
public void configure(final HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().fullyAuthenticated(); //To restrict all http requests.
/*http.authorizeRequests().antMatchers("/users/**").permitAll(); //Notice ant matcher here, this tells endpoints which do not require authentication. Lots of http configuration options (like applying filters, cors, csrf etc.) are available here. Please explore*/
}
Check out TokenStore default implementation classes (like JdbcTokenStore, JwtTokenStore). If you'd like to use NoSQL db like Cassandra then provide custom TokenStore implementation.
Following is the sample code snippet for custom Token Store used for Cassandra:
@Override
public void storeAccessToken(final OAuth2AccessToken token, final OAuth2Authentication authentication) {
String refreshToken = null;
if (token.getRefreshToken() != null) {
refreshToken = token.getRefreshToken().getValue();
}
if (readAccessToken(token.getValue()) != null) {
removeAccessToken(token.getValue());
}
final AccessTokenBuilder accessTokenBuilder = new AccessTokenBuilder();
accessTokenRepository.save(accessTokenBuilder
.withAuthenticationId(authenticationKeyGenerator.extractKey(authentication))
.withTokenId(extractTokenKey(token.getValue()))
.withTokenBody(ByteBuffer.wrap(serializeAccessToken(token)))
.withUsername(authentication.getName())
.withClientId(authentication.getOAuth2Request().getClientId())
.withAuthentication(ByteBuffer.wrap(serializeAuthentication(authentication)))
.withRefreshTokenId(extractTokenKey(refreshToken))
.build());
}
@Override
public void storeRefreshToken(final OAuth2RefreshToken refreshToken, final OAuth2Authentication authentication) {
final RefreshTokenBuilder refreshTokenBuilder = new RefreshTokenBuilder();
refreshTokenRepository.save(refreshTokenBuilder
.withTokenId(extractTokenKey(refreshToken.getValue()))
.withTokenBody(ByteBuffer.wrap(serializeRefreshToken(refreshToken)))
.withAuthentication(ByteBuffer.wrap(serializeAuthentication(authentication)))
.build());
}
@Override
public OAuth2Authentication readAuthentication(final OAuth2AccessToken token) {
return readAuthentication(token.getValue());
}
@Override
public OAuth2Authentication readAuthentication(final String token) {
OAuth2Authentication authentication = null;
try {
final AccessToken authAccessToken = accessTokenRepository.findByTokenId(extractTokenKey(token));
authentication = deserializeAuthentication(authAccessToken.getAuthentication().array());
} catch (final IllegalArgumentException e) {
removeAccessToken(token);
}
return authentication;
}
@Override
public OAuth2AccessToken readAccessToken(final String tokenValue) {
final AccessToken accessToken = accessTokenRepository.findByTokenId(extractTokenKey(tokenValue));
return accessToken != null ? deserializeAccessToken(accessToken.getTokenBody().array()) : null;
}
@Override
public OAuth2RefreshToken readRefreshToken(final String tokenValue) {
final RefreshToken refreshToken = refreshTokenRepository.findOne(extractTokenKey(tokenValue));
return refreshToken != null ? deserializeRefreshToken(refreshToken.getTokenBody().array()) : null;
}
@Override
public OAuth2Authentication readAuthenticationForRefreshToken(final OAuth2RefreshToken token) {
return readAuthenticationForRefreshToken(token.getValue());
}
OAuth2Authentication readAuthenticationForRefreshToken(final String tokenValue) {
final RefreshToken refreshToken = refreshTokenRepository.findOne(extractTokenKey(tokenValue));
return refreshToken != null ? deserializeAuthentication(refreshToken.getAuthentication().array()) : null;
}
@Override
public OAuth2AccessToken getAccessToken(final OAuth2Authentication authentication) {
OAuth2AccessToken oAuth2AccessToken = null;
final String key = authenticationKeyGenerator.extractKey(authentication);
final AccessToken accessToken = accessTokenRepository.findOne(key);
if (accessToken != null) {
oAuth2AccessToken = deserializeAccessToken(accessToken.getTokenBody().array());
if (oAuth2AccessToken != null && !key.equals(authenticationKeyGenerator.extractKey(readAuthentication(oAuth2AccessToken.getValue())))) {
removeAccessToken(oAuth2AccessToken.getValue());
storeAccessToken(oAuth2AccessToken, authentication);
}
}
return oAuth2AccessToken;
}
You'd need to declare repository interfaces for db operations. Interfaces which extends CrudRepository. For most of the DB operations we don't need to provide implementation, it is handled by Spring. For Cassandra implementation is in SimpleCassandraRepository class. Sample code for Access Token:
public interface AccessTokenRepository extends CrudRepository<AccessToken, String> {
@Query("SELECT * FROM auth_service.oauth_access_token WHERE token_id = :tokenId ALLOW FILTERING")
AccessToken findByTokenId(@Param("tokenId") String tokenId);
}
Sample code for ClientDetails
public interface ClientDetailsRepository extends CrudRepository<ClientDetails, String> {
}
Please note, we don't need to provide implementation for these interfaces. Regular CRUD queries are already implemented and taken care by Spring.
public interface RefreshTokenRepository extends CrudRepository<RefreshToken, String> {
}
Rest API project
Controllers declared here would get called when request received from frontend (AJAX request from javascript). All business logic and persistence layer would go here.
Here you can think about creating a module, a gateway, which talks to Auth Server. This gateway would be between your Rest API and Auth Server.
You can use RestTemplate to call remote Rest service.
If you need that not any Rest API project can make remote calls to Auth Server, then user client_credentials as well along with password grant type. And, use OAuth2RestTemplate instead of RestTemplate. Sample code:
<bean id="oAuth2RestTemplate" class="org.springframework.security.oauth2.client.OAuth2RestTemplate">
<constructor-arg ref="clientCredentialsResourceDetails"/>
<constructor-arg ref="defaultOAuth2ClientContext"/>
<property name="requestFactory" ref="httpComponentsClientHttpRequestFactory"/>
</bean>
<bean id="httpComponentsClientHttpRequestFactory" class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
<constructor-arg ref="selfSignedHttpsClientFactory"/>
</bean>
<bean id="clientCredentialsResourceDetails" class="org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails">
<property name="accessTokenUri" value="${authentication.service.client.token.url:https://localhost:8443/oauth/token}"/>
<property name="clientId" value="${authentication.service.client.id:testClient}"/>
<property name="clientSecret" value="${authentication.service.client.secret:password}"/>
</bean>
<bean id="defaultOAuth2ClientContext" class="org.springframework.security.oauth2.client.DefaultOAuth2ClientContext"/>
I hope this was helpful.
A: Not sure if you have seen this, but here is a nice article:
https://www.toptal.com/java/rest-security-with-jwt-spring-security-and-java
. And a project on github, more or less based on that article:
https://github.com/szerhusenBC/jwt-spring-security-demo
| |
doc_23535544
|
I want to select the NEWEST value based on criteria of week and year. Meaning i only have the year and week to find the newest value.
if you do the following
SELECT TOP 1 Value from tbl WHERE year(Date)<=year and format(date,"WW")<= weeknumber
you get a problem. because if the year is 2020 and the week is 30. then if there is a value from the 31/12/2019 it wont return it because format(date,"WW") is greater than the week.
Example: dateformat=dd/mm/yyyy
ID Date Value
1 15/01/2019 15
2 31/12/2019 18
3 15/04/2020 19
if the week is 5 and the year is 2020
the result of the sql should be 18 since that is the newest value before the week and year. But the query i wrote above returns 15, which makes sence because of the week of 31/12/2019>5 and therefore wont be returned.
But how do i do this correctly?
A: As this probably is ISO 8601 week numbering, the year is not the calendar year but the ISO 8601 year, which native VBA knows nothing about, thus a custom function is needed:
' First day of the week.
WeekStart = DateYearWeek(5, 2020, vbMonday)
' WeekStart -> 2020-01-27
The function is not that convoluted:
' Returns the date of Monday for the ISO 8601 week of IsoYear and Week.
' Optionally, returns the date of any other weekday of that week.
'
' 2017-05-03. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function DateYearWeek( _
ByVal IsoWeek As Integer, _
Optional ByVal IsoYear As Integer, _
Optional ByVal DayOfWeek As VbDayOfWeek = VbDayOfWeek.vbMonday) _
As Date
Dim WeekDate As Date
Dim ResultDate As Date
If IsoYear = 0 Then
IsoYear = Year(Date)
End If
' Validate parameters.
If Not IsWeekday(DayOfWeek) Then
' Don't accept invalid values for DayOfWeek.
Err.Raise DtError.dtInvalidProcedureCallOrArgument
Exit Function
End If
If Not IsWeek(IsoWeek, IsoYear) Then
' A valid week number must be passed.
Err.Raise DtError.dtInvalidProcedureCallOrArgument
Exit Function
End If
WeekDate = DateAdd(IntervalSetting(dtWeek), IsoWeek - 1, DateFirstWeekYear(IsoYear))
ResultDate = DateThisWeekPrimo(WeekDate, DayOfWeek)
DateYearWeek = ResultDate
End Function
but - as you can see - it calls some helper functions, which again call other functions, which will be too much to post here.
I can upload it somewhere, if you feel this will provide a solution for you.
There is no simple work-around. On the other hand, once held in a module, the code is simple to implement - as you can see.
| |
doc_23535545
|
data Tree t = NilT
| Node t (Tree t) (Tree t)
instance Show (Tree t) where
show NilT = ""
show Node t l r = (show t) ++ ", " ++ (show l) ++ ", " ++ (show r)
how to use "show" in "t show" with the default setting and use "show" with the tree data with the definition given by myself?
A: In order to use show t, you must add the constraint Show t to your instance definition.
instance Show t => Show (Tree t) where
show NilT = ""
show (Node t l r) = show t ++ ", " ++ show l ++ ", " ++ show r
You were also missing parenthesis around your pattern Node t l r, and I removed the parenthesis around the calls to show, as they were redundant since function application already has the highest precedence.
A: Just a side note: There is a function Data.List.intersperse for putting a value between list elements.
show (Node t l r) = concat $ intersperse ", " [show t, show l, show r]
Or shorter, as hammar pointed out:
show (Node t l r) = intercalate ", " [show t, show l, show r]
Unfortunately you can't write map show [t, l, r], as the list elements need to have a unique type.
| |
doc_23535546
|
Is this possible? If yes then how?
A: If you want most of the elements to remain in place you are not refreshing necessarily. What you would want to do is an AJAX request to retrieve the new information for the_content and update the DOM with JavaScript.
You would need a function that intercepts the click event for links, handles the AJAX, and then returns false to prevent navigating away from the page.
A: What you try to achieve is technically possible, however your wordpress theme must support that. You need to use AJAX for it and your theme needs to provide server endpoints for the type of content that is going to be requested.
This can be done by providing fragment templates inside your theme which only return the fragment in question (e.g. content column, menu). However depending on your site's layout this might not be always possible, e.g. if the layout changes from one page to another.
A possible workaround is to request the new page via AJAX and only replace the parts inside the DOM that are changed.
In any case you need to register an AJAX PHP callback function within wordpressCodex.
| |
doc_23535547
|
Can I use Custom Renderer or DependencyService or any other approaches is there ?
A: If you want to set the UI desinger on a specific control or layout .Such as entry or button.You can use custom renderer.
Custom renderers provide a powerful approach for customizing the appearance and behavior of Xamarin.Forms controls. They can be used for small styling changes or sophisticated platform-specific layout and behavior customization. This article provides an introduction to custom renderers, and outlines the process for creating a custom renderer.
And you can use DependencyService if you
just want to call some native API .
DependencyService allows apps to call into platform-specific
functionality from shared code. This functionality enables
Xamarin.Forms apps to do anything that a native app can do.
And you can also use Effects.In some cases, all three can help you implement your requirements.
There are some relevant cases that use one of them to solve the issue.I hope they can help you better understand their differences and usage, and how to choose them as a solution in specific cases.
CustomRenderer case
DependencyService case
Effect case
| |
doc_23535548
|
"transform": {
"script": "here_goes_the_processing_logic",
"lang": "groovy"
}
But, when I tried to do this I got the following error:
"error": {
"root_cause": [
{
"type": "mapper_parsing_exception",
"reason": "Root mapping definition has unsupported parameters: [transform : {the script body}
]
}
Does the ES 5.5.2 support such mechanism? If no, then how can I accomplish this problem?
A: I think that you're trying to use mapping transform, but it was deprecated in 2.0.0 and removed after 5.0. To accomplish something like this in ES 5, you can use an ingest node and add your transformation as a script processor in the pipeline.
| |
doc_23535549
|
After we investigate deeper, we found out that there are few hundred ssh processes running, and they are all trying to connect to the same host (i.e it's almost like ddos attack against that host).
ps aux | grep ssh
root 971 0.0 0.0 61364 3084 ? Ss Dec11 0:00 /usr/sbin/sshd -D
root 7649 0.0 0.0 105628 4228 ? Ss 03:57 0:00 sshd: ubuntu [priv]
ubuntu 7811 0.0 0.0 106404 2740 ? S 03:57 0:00 sshd: ubuntu@pts/0
ubuntu 8616 0.0 0.0 44012 2516 pts/2 S 04:02 0:00 ssh deploy@xxx.xxx.xxx.xxx
ubuntu 8618 0.0 0.0 44012 2512 pts/2 S 04:02 0:00 ssh deploy@xxx.xxx.xxx.xxx
ubuntu 8620 0.0 0.0 44012 2512 pts/2 S 04:02 0:00 ssh deploy@xxx.xxx.xxx.xxx
ubuntu 8622 0.0 0.0 44012 2512 pts/2 S 04:02 0:00 ssh deploy@xxx.xxx.xxx.xxx
ubuntu 8624 0.0 0.0 44012 2516 pts/2 S 04:02 0:00 ssh deploy@xxx.xxx.xxx.xxx
...
Here I logged in as ubuntu. I vaguely remember I executed the command a while ago trying to connect to the host, but ssh outputs many instances of itself and the terminal got frozen, and since then we have been experiencing the slow connection issue.
Anyhow, I tried to kill all of the ssh processes, but they just keep coming back and eventually slow down the whole system connection again.
$ killall -9 ssh
Any idea what went wrong and how can I solve this problem?
| |
doc_23535550
|
| render() {
| return (
> <>
| <Sidebar/>
| <Footer/>
| </>
@ ./src/index.js 1:0-24
I looked most of the answers here and my configs look like correct. Any solutions why it's still complaining?
.babelrc file
{
"presets": [
"@babel/preset-env",
"@babel/preset-react"
]
}
webpack.config.js
const HtmlWebPackPlugin = require("html-webpack-plugin");
module.exports = {
output: {
publicPath: '/'
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: "babel-loader",
options: {
presets: ["@babel/preset-react"]
}
}
},
{
test: /\.html$/,
use: [
{
loader: "html-loader"
}
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: ["file-loader"]
},
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
},
]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
devServer: {
historyApiFallback: true,
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
})
]
};
package.json
{
"name": "myWebsite",
"version": "1.0.0",
"description": "",
"main": "index.js",
"engines": {
"npm": "6.12.0",
"node": "12.13.0"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack-dev-server --open --mode development",
"build": "webpack --mode production"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/preset-env": "^7.6.3",
"@babel/preset-react": "^7.6.3",
"css-loader": "^3.2.0",
"file-loader": "^4.2.0",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"react-social-icons": "^4.1.0",
"style-loader": "^1.0.0",
"webpack": "^4.41.2",
"webpack-cli": "^3.3.9",
"webpack-dev-server": "^3.8.2"
},
"dependencies": {
"@babel/core": "^7.6.4",
"babel-loader": "^8.0.6",
"react": "^16.10.2",
"react-dom": "^16.10.2",
"react-router-dom": "^5.1.2",
"react-split-pane": "^0.1.87"
}
}
as per request here is my full error output
Enumerating objects: 68, done.
Counting objects: 100% (68/68), done.
Delta compression using up to 4 threads
Compressing objects: 100% (65/65), done.
Writing objects: 100% (68/68), 1.17 MiB | 765.00 KiB/s, done.
Total 68 (delta 23), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Node.js app detected
remote:
remote: -----> Creating runtime environment
remote:
remote: NPM_CONFIG_LOGLEVEL=error
remote: NODE_ENV=production
remote: NODE_MODULES_CACHE=true
remote: NODE_VERBOSE=false
remote:
remote: -----> Installing binaries
remote: engines.node (package.json): 12.13.0
remote: engines.npm (package.json): 6.12.0
remote:
remote: Resolving node version 12.13.0...
remote: Downloading and installing node 12.13.0...
remote: npm 6.12.0 already installed with node
remote:
remote: -----> Installing dependencies
remote: Installing node modules (package.json)
remote: added 823 packages from 403 contributors and audited 10614 packages in 25.88s
remote: found 0 vulnerabilities
remote:
remote:
remote: -----> Build
remote: Running build
remote:
remote: > myWebsite@1.0.0 build /tmp/build_aecdb33dae6f65fc1053619440b756ef
remote: > webpack --mode production
remote:
remote: Hash: 71478ca5630665d9995b
remote: Version: webpack 4.41.2
remote: Time: 205ms
remote: Built at: 11/07/2019 7:44:19 PM
remote: 1 asset
remote: Entrypoint main = main.js
remote: [0] ./src/index.js 24 bytes {0} [built]
remote: [1] ./src/App.js 315 bytes {0} [built] [failed] [1 error]
remote:
remote: ERROR in ./src/App.js 14:6
remote: Module parse failed: Unexpected token (14:6)
remote: You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
remote: | render() {
remote: | return (
remote: > <>
remote: | <Sidebar/>
remote: | <Footer/>
remote: @ ./src/index.js 1:0-24
remote: npm ERR! code ELIFECYCLE
remote: npm ERR! errno 2
remote: npm ERR! myWebsite@1.0.0 build: `webpack --mode production`
remote: npm ERR! Exit status 2
remote: npm ERR!
remote: npm ERR! Failed at the myWebsite@1.0.0 build script.
remote: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
remote:
remote: npm ERR! A complete log of this run can be found in:
remote: npm ERR! /tmp/npmcache.7aIPm/_logs/2019-11-07T19_44_19_386Z-debug.log
remote:
remote: -----> Build failed
remote:
remote: We're sorry this build is failing! You can troubleshoot common issues here:
remote: https://devcenter.heroku.com/articles/troubleshooting-node-deploys
remote:
remote: If you're stuck, please submit a ticket so we can help:
remote: https://help.heroku.com/
remote:
remote: Love,
remote: Heroku
remote:
remote: ! Push rejected, failed to compile Node.js app.
remote:
remote: ! Push failed
remote: Verifying deploy...
remote:
remote: ! Push rejected to guarded-fortress-36341.
remote:
To https://git.heroku.com/guarded-fortress-36341.git
! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/guarded-fortress-36341.git'
A: Since nobody answered. I ended up moving my project to create-react-app. Where configurations are mostly set up for me. (Specifically loaders where i was getting an error)
| |
doc_23535551
|
And I was hoping if anyone can help, thanks.
A: Here's what I've used:
public class CustomUserDetails implements UserDetails {
private User user;
public CustomUserDetails(final User _user) {
this.user = _user;
}
public CustomUserDetails() {
}
@Override
public Collection<GrantedAuthority> getAuthorities() {
final Set<GrantedAuthority> _grntdAuths = new HashSet<GrantedAuthority>();
List<UserRole> _roles = null;
if (user!=null) {
_roles = user.getRoles();
}
if (_roles!=null) {
for (UserRole _role : _roles) {
_grntdAuths.add(new GrantedAuthorityImpl(_role.getRole()));
}
}
return _grntdAuths;
}
@Override
public String getPassword() {
return user.getPassword();
}
@Override
public String getUsername() {
if (this.user == null) {
return null;
}
return this.user.getUser_name();
}
@Override
public boolean isAccountNonExpired() {
return this.user.isAccountNonExpired();
}
@Override
public boolean isAccountNonLocked() {
return this.user.isAccountNonLocked();
}
@Override
public boolean isCredentialsNonExpired() {
return this.user.isCredentialsNonExpired();
}
@Override
public boolean isEnabled() {
return this.user.isEnabled();
}
public User getUser() {
return user;
}
@Override
public String toString() {
return "CustomUserDetails [user=" + user + "]";
}
}
| |
doc_23535552
|
Checking Android requirements...
Creating android project...
[Error: An error occured during creation of android sub-project. Creating Cordova project for the Android platform:
Command failed to execute : ant jar
I did a lot of research and tried a lot of potential solutions that did not work. So my last hope is Stackoverflow.
*
*I am using Java jdk 1.7.0_45 (also tried the JRE) which is properly installed
*I am using ant 1.9.2 where I'm perfectly able to check the version of ant in the command line. The only problem here is that ant jar gives me a build.xml error. I think this is the main cause why I get the Command failed to execute : ant jar error.
*I installed phonegap and cordova throughout node and those work perfectly as well.
*My paths are all configured properly.
I dont know what to do, I need to know a way to get a proper build.xml. I hope someone can help me out!
A: ANT tools could not find tools.jar in JRE lib directory.
In order to solve your issue just :
Copy tools.jar from Java/JDK1.7.0_45/lib directory to Java/JRE7/lib directory and
Run the command cordova platform add android again.
Hope this helps you.
| |
doc_23535553
|
My code:
let historicPrecipitation = [{"indicator":"Historic Precipitation","month":"1","year":"2014","value":"228.5"},{"indicator":"Historic Precipitation","month":"2","year":"2014","value":"144.7"},{"indicator":"Historic Precipitation","month":"3","year":"2014","value":"120.3"},{"indicator":"Historic Precipitation","month":"4","year":"2014","value":"146.9"},{"indicator":"Historic Precipitation","month":"5","year":"2014","value":"146.4"},{"indicator":"Historic Precipitation","month":"6","year":"2014","value":"128.1"},{"indicator":"Historic Precipitation","month":"7","year":"2014","value":"139.2"},{"indicator":"Historic Precipitation","month":"8","year":"2014","value":"150.0"},{"indicator":"Historic Precipitation","month":"9","year":"2014","value":"199.7"},{"indicator":"Historic Precipitation","month":"10","year":"2014","value":"268.4"},{"indicator":"Historic Precipitation","month":"11","year":"2014","value":"98.5"},{"indicator":"Historic Precipitation","month":"12","year":"2014","value":"139.9"}];
let monthsWithoutRegistration = [4, 5];
for (let i = 0; i < monthsWithoutRegistration.length; i++) {
for (let j = 0; j < historicPrecipitation.length; j++) {
if (parseInt(historicPrecipitation[j]['month']) === parseInt(monthsWithoutRegistration[i])) {
historicPrecipitation.splice(historicPrecipitation[j], 1);
}
}
}
console.log(historicPrecipitation);
A: You need use j instead of historicPrecipitation[j] in splice because you should pass index not object:
let historicPrecipitation = [{
"indicator": "Historic Precipitation",
"month": "1",
"year": "2014",
"value": "228.5"
}, {
"indicator": "Historic Precipitation",
"month": "2",
"year": "2014",
"value": "144.7"
}, {
"indicator": "Historic Precipitation",
"month": "3",
"year": "2014",
"value": "120.3"
}, {
"indicator": "Historic Precipitation",
"month": "4",
"year": "2014",
"value": "146.9"
}, {
"indicator": "Historic Precipitation",
"month": "5",
"year": "2014",
"value": "146.4"
}, {
"indicator": "Historic Precipitation",
"month": "6",
"year": "2014",
"value": "128.1"
}, {
"indicator": "Historic Precipitation",
"month": "7",
"year": "2014",
"value": "139.2"
}, {
"indicator": "Historic Precipitation",
"month": "8",
"year": "2014",
"value": "150.0"
}, {
"indicator": "Historic Precipitation",
"month": "9",
"year": "2014",
"value": "199.7"
}, {
"indicator": "Historic Precipitation",
"month": "10",
"year": "2014",
"value": "268.4"
}, {
"indicator": "Historic Precipitation",
"month": "11",
"year": "2014",
"value": "98.5"
}, {
"indicator": "Historic Precipitation",
"month": "12",
"year": "2014",
"value": "139.9"
}];
let monthsWithoutRegistration = [4, 5];
for (let i = 0; i < monthsWithoutRegistration.length; i++) {
for (let j = 0; j < historicPrecipitation.length; j++) {
if (parseInt(historicPrecipitation[j]['month']) === parseInt(monthsWithoutRegistration[i])) {
historicPrecipitation.splice(j, 1);
}
}
}
console.log(historicPrecipitation);
A: The splice syntax is wrong,
replace with this
historicPrecipitation.splice(j, 1);
A: You can make use of filter instead of the nested for loops:
let filteredHistoricPrecipitation = historicPrecipitation.filter(x =>
!monthsWithoutRegistration.includes(parseInt(x['month']))
);
| |
doc_23535554
|
Hi! I am currently learning front end developing languages. I want to move my image to where the div.kitchen-image container is... but it will not move. My code at queries is this:
/*media queries*/
@media only screen and (max-width: 600px) {
nav{
display: flex;
flex-wrap: wrap;
line-height: 2;
}
.logo {
margin:0 auto;
}
.nav-links ul li a{
margin-left:15px;
}
.kitchen-image {
height:200px;
}
.main-pic{
width:400px;
}
}
tried changing the width and height of the image itself, but still no result.
A: You can use the CSS property transform: translate()
use this CSS in the Image's class
eg: The co-odinates given below are just an example.
.kitchen-image {
height:200px;
transform: translate(50px, 100px);
}
| |
doc_23535555
|
A: The way I figure this out is to look at the top right of the console.
If you just see a username then you're using a root user.
If you're seeing a username@account-id you're not a root user.
| |
doc_23535556
|
When I launch my app, I have a search bar controller, when I click on it a keyboard appear like before but I can't write something with my Mac keyboard or with the simulator keyboard.
But, when I use my ShareKit button, a view appear from the toolbar. If I try to use my search bar controller after shown this ShareKit view it works !!
This methods are called :
- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller
- (void)searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller
But this methods are not called, because keyboard it not responding and I can't type text.
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchScope:(NSInteger)searchOption
But when I use this method :
- (IBAction)share:(id)sender
{
if (!_url) {
return;
}
SHKItem *item = [SHKItem URL:_url title:@"Share this URL"];
SHKActionSheet *actionSheet = [SHKActionSheet actionSheetForItem:item];
// ShareKit detects top view controller (the one intended to present ShareKit UI) automatically,
// but sometimes it may not find one. To be safe, set it explicitly
[SHK setRootViewController:self];
[actionSheet showFromToolbar:self.navigationController.toolbar];
}
After I can use search bar keyboard.
Can someone help me please, because it was working perfectly before iOS 6 simulator ...
Thanks !
EDIT :
Great thank you for you're help it works !!
I just check "Visible at launch" for my mainWindow.xib Window element and it works !
Hope this will help some others !
A: You need to set delegate properly. Write this line in ViewDidLoad
SearchbarObj.delegate=self;
or set delegate connection to File's Owner in xib.
| |
doc_23535557
|
When the application is started the first time it should insert some data into the database with initial data like the credentials for an admin account.
What is the best way to do this?
| |
doc_23535558
|
4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET CLR 1.1.4322; .NET4.0E; Tablet PC 2.0)
Does That mean it uses IE7? why? and how can i check if a method is supported by this useragent. Does it uses the windows script host? Is there a way to update the javascript engine on my windows. Also if that have to be with IE, I have IE11 installed.
A: It sounds like you are talking about this appVersion
If so, that is set by the browser and you're best off ignoring it. Some software, using outdated programming models, try to use this information to tell the browsers capabilities.
| |
doc_23535559
|
I have this
this is the best I have achieved but is not what I want the cylinder is not tangent
cylinder(position: THREE.Vector3, radius: number, height: number, name: string = 'cylinder') {
const geometry = new THREE.CylinderGeometry( radius, radius, height, 32 );
geometry.translate( 0, height / 2, 0 );
const material = new THREE.MeshBasicMaterial( {color: 0xffff00} );
const normal_material = new THREE.MeshNormalMaterial({transparent: true, opacity: 0.4});
const cylinder = new THREE.Mesh( geometry, normal_material );
cylinder.position.set(position.x, position.y, position.z);
// this.scene.add( cylinder );
return cylinder;
}
const cylinder = this.examples.cylinder(p, 2.0, 5.0, `cylinder_a_${this.points.length}`);
cylinder.geometry.rotateX((-94 * Math.PI) / 180);
cylinder.lookAt(this.intersection.normal);
// const vector = new THREE.Vector3(100, 60, 20);
// const axis = new THREE.Vector3(0, 1, 0);
// cylinder.quaternion.setFromUnitVectors(axis, b.clone().normalize());
this.scene.add( cylinder );
I try and this but for some reason is not accurate
const position = p;
const length = 9.99;
const radius = 2.0;
const depth = 0.0;
const name = `cylinder_a_${this.points.length}`;
const cylinder = this.examples.cylinder(position, radius, length, depth, name);
cylinder.geometry.rotateX((90 * Math.PI) / 180);
cylinder.lookAt( cylinder.position.clone().add(this.intersection.normal) );
this.scene.add( cylinder );
| |
doc_23535560
|
Log.v("getFilesDir", "" + getFilesDir().toString());
file = getFilesDir();
Log.v("file.getAbsolutePath",""+file.getAbsolutePath());
Result:
V/getFilesDir﹕ /data/data/com.kingbell.interprocesscommunication_simple/files
V/file.getAbsolutePath﹕/data/data/com.kingbell.interprocesscommunication_simple/files
A: As explained in android docs.
getFilesDir()
Returns the absolute path to the directory on the filesystem where files created with openFileOutput(String, int) are stored.
This means that it returns a File Object, A File could represent files or directories, in this case a directory. you can check it by calling the isDirectory() method.
getAbsolutePath()
Returns the absolute path of this file.
This is the path of this file, but rememeber that directories are represented with the same file objects just like a real file. you can verify it by checking the isDirectory() or isFile() method.
So, in your case they point to the same place.
You called getFilesDir(), so your context give you a directory represented in an instance of the File class. In that file object you call getAbsolutePath() so they represent the same thing, since this is an actual directory.
Clear?
A: Maybe it will be more clear with the source code.
getAbsolutePath()
package java.io.file
public class File {
public String getAbsolutePath() {
return fs.resolve(this);
}
}
and getFilesDir()
package android.content
public abstract class Context {
public abstract File getFilesDir();
}
and for a specific Context(typically is an activity), the return value for the getFilesDir() call is fixed and should be always same, it tells you a location you can use to save your file.
At the same time, you can call getAbsolutePath() on any File object to get a full file path, either the file created by you or the file carried in an URI sent to you.
That is why these two calls are in the different packages.
Hope the explanation helps.
| |
doc_23535561
|
public class Mark
{
public int MarkId { get; set; }
[Required(ErrorMessage = "Please provide Grade")]
[Display(Name = "Grade Value")]
public int MarkValue { get; set; }
[Required(ErrorMessage = "Please provide grade type")]
[Display(Name = "Grade Type")]
public string Type { get; set; }
[Required(ErrorMessage = "Please provide Subject")]
[Display(Name = "Subject")]
public virtual Subject Subject { get; set; }
public virtual User User { get; set; }
public virtual Professor Professor { get; set; }
}
In my view I have a dropdown to select a professor who put the mark.
I implemented it like this:
//controller
public MarksController() : this(new MarkRepository())
{
IProfessorRepository professorsRepo = new ProfessorRepository();
List<Professor> professors = professorsRepo.All.ToList<Professor>();
List<SelectListItem> items = new List<SelectListItem>();
foreach (Professor p in professors)
{
items.Add(new SelectListItem
{
Text = String.Concat(p.FirstName, " ", p.LastName), Value = p.ProfessorId.ToString()
});
}
items.Add(new SelectListItem
{
Text = "Please select Professor", Value = "0", Selected = true
});
ViewBag.Professors = items;
}
//view create or edit
<div class="editor-label">
@Html.LabelFor(model => model.MarkValue)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.MarkValue)
@Html.ValidationMessageFor(model => model.MarkValue)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Type)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Type)
@Html.ValidationMessageFor(model => model.Type)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Professor)
</div>
<div class="editor-field">
@Html.DropDownList("Professors");
</div>
Yes, I know that there is is a metod in Controller called Create which appeals repository method InsertOrUpdate.
[HttpPost]
public ActionResult Create(Mark mark)
{
if (ModelState.IsValid) {
markRepository.InsertOrUpdate(mark);
markRepository.Save();
return RedirectToAction("Index");
} else {
return View();
}
}
public void InsertOrUpdate(Mark mark)
{
if (mark.MarkId == default(int)) {
// New entity
context.Marks.Add(mark);
} else {
// Existing entity
context.Entry(mark).State = EntityState.Modified;
}
}
Everything seems logic, but how can I save a newly created Mark object with the professor selected? How does ASP.NET arranges the object which is passed to Create method on Controller? How should I match the selected professor with the mark I am creating?
A: Take a look at this, you need a ProfessorId in the model.
Model binding dropdown selected value
public class Mark
{
// this will hold the selected value
public string ProfessorID { get; set; }
public IEnumerable<SelectListItem> Professors
{
get
{
return Proffessors
.Select(x => new SelectListItem {
Value = x.ProfessorId.ToString(),
Text = String.Concat(p.FirstName, " ", p.LastName)
});
}
}
public IEnumerable<Professor> Proffessors
{
get
{
IProfessorRepository professorsRepo = new ProfessorRepository();
return professorsRepo.All;
}
}
//the rest of your code
}
in the view do
@Html.DropDownListFor(
x => x.ProfessorId,
new SelectList(Model.Professors, "Value", "Text")
)
| |
doc_23535562
|
A: By definition, L1 regularization (lasso) forces some weights to zero, thus leading to sparser solutions; according to the Wikipedia entry on regularization:
It can be shown that the L1 norm induces sparsity
See also the L1 and L2 Regularization Methods post at Towards Data Science:
The key difference between these techniques is that Lasso shrinks the less important feature’s coefficient to zero thus, removing some feature altogether. So, this works well for feature selection in case we have a huge number of features.
For more details, see the following threads @ Cross Validated:
Sparsity in Lasso and advantage over ridge
Why does the Lasso provide Variable Selection?
| |
doc_23535563
|
I have two files called ApplicationConfig.java and Controller.java tasked with returning a string when a certain URL is hit. When I visit localhost:8080 it renders my index.html with a link to the URL I wish to return a string at. When I visit the URL localhost:8080/home/greet it returns a 404.
My ApplicationConfig.java:
package application;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ApplicationConfig {
public static void main(String[] args) {
SpringApplication.run (ApplicationConfig.class, args);
}
}
and my Controller.java
package controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/home")
public class Controller {
@RequestMapping("/greet")
public String greeting() {
return "Hello";
}
}
As far as I see /home/greet/ should produce a page that just reads "Hello" but this isn't the case. What is the issue?
Here is my pom.xml and what my project structure looks like, should they be relevant.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework</groupId>
<artifactId>gs-rest-service</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>
A: Your entrypoint class ApplicationConfig.java is in application package and Controller.java is in controller package.
SpringBoot scans for Spring components in the package( and sub-packages) where EntryPoint class is.
So move your controller to application or any nested package under application.
A: Step 1 : Add your ApplicationConfig.java in package abc.app;
Step 2 : Add your Controller.java in package abc.app.controller;.
Step 3 : add @ComponentScan("abc.app") in ApplicationConfig.java.
For Example :
ApplicationConfig.java:
package abc.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@ComponentScan("abc.app")
public class ApplicationConfig {
public static void main(String[] args) {
SpringApplication.run (ApplicationConfig.class, args);
}
}
Controller.java :
package abc.app.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Controller {
@RequestMapping("/greet")
public String greeting() {
return "Hello";
}
}
I Hope you Find your Right Solution here.
| |
doc_23535564
|
I'm new with c++ stl and got stuck at this point.
I have created this function for solving crossword puzzle in c++ but it is showing me the
prog.cpp:17:49: error: no match for ‘operator==’ (operand types are ‘__gnu_cxx::__alloc_traitsstd::allocator<std::__cxx11::basic_string<char > >::value_type {aka std::__cxx11::basic_string}’ and ‘__gnu_cxx::__alloc_traitsstd::allocator<char >::value_type {aka char}’)
if(matrix[i][j]=='-' || matrix[i][j]==word[0])
void solve(vector<vector<string>> &matrix,vector<string> &puzzleWords,int idx)
{
if(idx==puzzleWords.size())
{
return;
}
string word=puzzleWords[idx];
for(int i=0;i<matrix.size();i++)
{
for(int j=0;j<matrix[i].size();j++)
{
if(matrix[i][j]=='-' || matrix[i][j]==word[0])
{
if(canPlacedHorizontally(matrix,word,i,j))
{
vector<bool> wePlaced=placeWordHorizontally(matrix,word,i,j);
solution(matrix,word,idx+1);
unplaceWordHorizontally(matrix,wePlaced,i,j);
}
if(canPlacedVertically(matrix,word,i,j))
{
vector<bool> wePlaced=placeWordVertically(matrix,word,i,j);
solution(matrix,word,idx+1);
unplaceWordVertically(matrix,wePlaced,i,j);
}
}
}
}
}
A: You're clearly getting confused between strings (which are sequences of characters) and chars (which are individual characters).
Look at this code
if(matrix[i][j]=='-' || matrix[i][j]==word[0])
matrix[i][j] is a string (because matrix is a 2D vector of strings) but '-' is a char and word[0] is a char (because word is a string). You can't compare a string and a char for equality.
You have a 2D vector for your crossword, but each square of that crossword is a string. Most crosswords you can only write a single letter in each square, so probably you should have this
void solve(vector<vector<char>> &matrix,vector<string> &puzzleWords,int idx)
With that change the if statement above will compile because you will be comparing chars with chars, not chars with strings.
| |
doc_23535565
|
Also, I track ram usage on the profiler and the result was normal as it is.
I did like the below code:
var flagHeight: Int = 100
private fun startAnimation() {
val animation = tv_hello_world.animate().apply {
translationYBy(flagHeight.toFloat())
setListener(object : Animator.AnimatorListener {
override fun onAnimationStart(p0: Animator?) {
// do nothing
}
override fun onAnimationEnd(p0: Animator?) {
flagHeight = flagHeight.not()
startAnimation()
}
override fun onAnimationCancel(p0: Animator?) {
// do nothing
}
override fun onAnimationRepeat(p0: Animator?) {
// do nothing
}
})
duration = 1000
}
animation.start()
}
fun Int.not() = run { if (this > 0) -this else (this * -1) }
A: The proper way to do it by using ValueAnimator instead on PropertyAnimator since you have more control over it. Try it this way:
val animator = ValueAnimator.ofFloat(0f, 100f).apply {
duration = 1000
repeatCount = ValueAnimator.INFINITE
repeatMode = ValueAnimator.REVERSE
addUpdateListener {
tv_hello_world.translationY = it.animatedValue as Float
}
}
animator.start()
| |
doc_23535566
|
My app has a music playlist. When a track has finished playing, it goes to the next one automatically.
Problem is, when the browser tab do not have the focus (background tab), it doesn't play the next track since it seems to be blocked by the browser's autoplay policy (have tested with Chrome & Firefox).
See documentation here: https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide
I was suggested to turn on autoplay for particular websites (for Chrome, go to chrome://settings/content/sound); but it doesn't work either. Anyway, this is not a solution for my visitors.
I've been struggling with this problems for days; any ideas on how achieve this ?
*
*I have multiple providers (Youtube, Soundcloud, ...) so player does not always play things from the same service.
*I'm able to detect the visibility of the tab using the Page Visibility API.
*In my console, I can see that the onready event of react-player is fired; but the player is "stuck" until I go back to the tab again - then it plays.
Here's a pastebin of the current code of my player. The function responsible for getting the source to play is
const resolveTracks = async(track,source,backwards) => {
...
}
Thanks!
| |
doc_23535567
|
Now I want to introduce access based permission in my application in such a way that it should work with earlier roles, as well as with my new access based approach.
I have list of existing roles in an enum, if the role of user is in that enum then existing authorization should work. But if role of user does not exist in the enum, then my new logic should check the access.
Typically my controller method will look like:
[CustomAuthorize(Roles=Roles.Role1,Roles.Role2, Access="CanDoThis")]
void MethodName(parameters)
{
//Some code.
}
Now if current user has Role1 or Role2 then he should get access and if not, then his role (whatever it may be) should have "CanDoThis" permission.
I looked for solution and found a near by solution Here, but it answers the second part only and not with the combination of first one.
Even if not the exact solution but a pointer in that direction will also be helpful.
| |
doc_23535568
|
Because the file is hosted on that website I have to embed it using their infrastructure (with an xml playlist and their own jwPlayer, version 5.7).
I've got everything working except a continuous repeat. The 'repeat: always' option doesn't work. The onComplete event doesn't fire either. This is the code, which is almost similar to their own embed code:
http://dev.jasperheeffer.nl/dinovid/schooltv_new.html
The onTime event does work for repeat on my pc (commented out in the code). But alas it doesn't seem to fire on the pc where this app needs to be installed. For debugging I added the controlbar and playlist to the player.
<html>
<head>
<title>NMB Video</title>
<link rel="stylesheet" href="assets/nmb_video.css">
<script type="text/javascript" src="assets/jquery.js"></script>
<script type='text/javascript' src='http://www.schooltv.nl/beeldbank/shared/applications/jwplayer/js/jwplayer.js'></script>
<script type="text/javascript" src="http://www.ntr.nl/static/js/loadAAPIVideo.js"></script>
<script type='text/javascript'>
$(function() {
loadAAPIVideoUrl("20101210_dino01",function(streamid,streamurl){
jwplayer("stvbb3054251").setup({
link:"http://www.schooltv.nl/beeldbank/clip/20101210_dino01",
width: 800,
height: 500,
image: "http://www.schooltv.nl/beeldbank/mmbase/images/3683800/20101210_dino01.jpg",
file: streamurl,
modes: [
{type: "flash",
src: "http://www.schooltv.nl/beeldbank/shared/applications/jwplayer/swf/NTRPlayer.swf",
config:{
provider: "http://www.schooltv.nl/beeldbank/shared/applications/jwplayer/swf/adaptiveProvider.swf"
}
},
{type: "html5"
}
],
title:'Dinosaurus op de vlucht',
author:'NTR',
date:'17-01-2011',
description:'Timo de T-rex wil een ei eten. Dat is niet zonder gevaar.',
controlbar: 'top',
'playlist.position': 'top',
image:'http://www.schooltv.nl/beeldbank/mmbase/images/3683801/20101210_dino01.jpg',
repeat: 'always',
dock: false,
autostart: true,
fullscreen:true,
events: {
/*
onTime: function(event) {
if (event.position > 280) {
alert('time!'); jwplayer().seek(0).play(true); }
},
*/
onComplete: function() {
alert('complete');
jwplayer().seek(0).play(true);
}
}
});
});
});
</script>
</head>
<body style="overflow: hidden;">
<!--
<div id="standby">
<h1><span>SchoolTV: Timo de T-Rex</span><br>Raak het scherm aan om de film te bekijken.</h1>
</div>
-->
<div class="player flash schooltv_beeldbank mediaplayer">
<div id="ivpd3054251" class="ivplayerdata" style="display:none;"></div>
<video id="stvbb3054251" controls width="348" height="178" poster="http://www.schooltv.nl/beeldbank/mmbase/images/3683800/20101210_dino01.jpg">
</video>
</div>
</body>
</html>
A: I am not sure why it isn't firing here.
Here is a very stripped down example that you can simply copy/paste though, which does fire:
<html>
<head>
<title>Test Page</title>
</head>
<body>
<script type="text/javascript" src="http://player.longtailvideo.com/jwplayer.js"></script>
<div id="player"></div>
<script type="text/javascript">
jwplayer("player").setup({
file: "http://www.longtailvideo.com/jw/upload/bunny.mp4",
flashplayer: "http://player.longtailvideo.com/player.swf",
width: 465,
height: 300,
events:{
onComplete: function() {
alert("hi!");
}
}
});
</script>
</body>
</html>
| |
doc_23535569
|
I've seen people using native android menu handler, but I want a JavaScript one
http://docs.phonegap.com/en/1.3.0/phonegap_events_events.md.html#menubutton
Can someone help me? Please?
A: Simon is right wait for the deviceready event to be sure phonegap is running
| |
doc_23535570
|
$errors = $this->validator()->validate($reg);
if (count($errors) > 0) {
$errorsString = (string) $errors;
throw new HttpException(521,$errorsString );
}
the result is:
"Object(NameSpace\Bundle\Validator\RegValidator).email:\n This value should not be blank.\n
but I would like to show
email : this value should not be blank
and if i have more then one so with "," between them
A: You have a ConstraintViolationList as the result of $this->validator()->validate($reg);. So you can format your string in a way you want.
if (count($errors) > 0) {
$errorStrings = '';
foreach ($errors as $error) {
$errorStrings[] = sprintf("%s: %s\n", $error->getPropertyPath(), $error->getMessage());
}
$errorString = implode(', ', $errorStrings);
throw new HttpException(521, $errorsString);
}
| |
doc_23535571
|
type BooleanAttributeName = string;
type PairedAttribute = {
[_: string]: string | number;
};
type CompositeAttribute = [
PairedAttribute,
BooleanAttributeName | BooleanAttributeName[]
];
type Attributes = CompositeAttribute | PairedAttribute;
function SetAttributes(attributes: Attributes) {
if (attributes.length === undefined) {
for (const key in attributes) {
console.log(key, attributes[key]); /*Error: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Attributes'. No index signature with a parameter of type 'string' was found on type 'Attributes'.*/
}
}
attributes.map((item) => { /*This expression is not callable. Not all constituents of type 'string | number | (<U>(callbackfn: (value: string | PairedAttribute | string[], index: number, array: (string | PairedAttribute | string[])[]) => U, thisArg?: any) => U[])' are callable. Type 'string' has no call signatures.*/ /*Parameter 'item' implicitly has an 'any' type.*/
if (item.length === undefined) {
for (const key in item) {
console.log(key, item[key]);
}
} else if (typeof item === "object") {
item.map((BooleanAttributeName) => { /*Parameter 'BooleanAttributeName' implicitly has an 'any' type.*/
console.log(BooleanAttributeName);
});
} else {
console.log(item);
}
});
}
let sample: Attributes = [
{
key1: "value1",
key2: "value2",
},
["BooleanAttribute1", "BooleanAttribute2"],
];
SetAttributes(sample);
I tried to use some concepts of narrowing from the official TypeScript docs but still I am facing these problems.
I want to know what can be solution for the problem.
A: Try to add some type casting and checking:
type BooleanAttributeName = string;
type PairedAttribute = {
[_: string]: string | number;
};
type CompositeAttribute = [
PairedAttribute,
BooleanAttributeName | BooleanAttributeName[]
];
type Attributes = CompositeAttribute | PairedAttribute;
function SetAttributes(attributes: Attributes) {
if (typeof attributes === 'object') {
const attr = attributes as PairedAttribute;
for (const key in attr) {
console.log(key, attr[key]);
}
}
if (attributes instanceof Array) {
const attr = attributes as CompositeAttribute;
attr.map((item) => {
if (typeof item === "object") {
const it = item as PairedAttribute;
for (const key in it) {
console.log(key, it[key]);
}
} else {
console.log(item);
}
});
}
}
let sample: Attributes = [
{
key1: "value1",
key2: "value2",
},
["BooleanAttribute1", "BooleanAttribute2"],
];
SetAttributes(sample);
Link to playground
| |
doc_23535572
|
app.get('/create-checkout-session', async (req, res) => {
let customer = {
price: req.query.price,
quantity: req.query.number,
page: req.query.page
}
let successurl = 'http://localhost:1111/' + customer.page + ''
let failedurl = 'http://localhost:1111/' + customer.page + ''
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: [
{
price_data: {
currency: 'cad',
product_data: {
name: 'Giveaway Entry',
},
unit_amount: customer.price,
},
quantity: customer.quantity,
},
],
mode: 'payment',
success_url: successurl,
cancel_url: failedurl,
});
console.log(session)
res.redirect(303, session.url);
});
it is working fantastic. Except that after the checkout session completes, it redirects me back to my page. But it doesn't store the email address that they type in (on the stripe checkout page) in the session object. so I logged it like this:
console.log(session)
and it returns:
customer_email: null
why is this happening and how can i fix it?
A: The Checkout Session's customer_email property is for creating a Checkout Session with an email pre-filled[1]. To see the email that your customer entered in to the Checkout form, check the Session's customer_details.email property[2].
[1] https://stripe.com/docs/api/checkout/sessions/object#checkout_session_object-customer_email
[2] https://stripe.com/docs/api/checkout/sessions/object#checkout_session_object-customer_details-email
| |
doc_23535573
|
This is how my directive looks like:
myapp.directive('enter', function(){
return {
restrict: 'A', // link to attribute... default is A
link: function (scope, element){
element.bind('mouseenter',function() {
console.log('MOUSE ENTER: ' + scope.movie.title);
});
element.bind('mouseleave',function() {
console.log('LEAVE');
});
}
}
});
Here is an example: http://jsfiddle.net/dJGfd/1/
You have to open the Javascript console to see the log messages.
What is the best way to achieve the functionality that I want in AngularJS? I prefer to not use jQuery if there is a reasonable AngularJS solution.
A: You can try this:
myapp.directive('enter', function () {
return {
restrict: 'A',
controller: function ($scope, $timeout) {
// do we have started timeout
var timeoutStarted = false;
// pending value of mouse state
var pendingMouseState = false;
$scope.changeMouseState = function (newMouseState) {
// if pending value equals to new value then do nothing
if (pendingMouseState == newMouseState) {
return;
}
// otherwise store new value
pendingMouseState = newMouseState;
// and start timeout
startTimer();
};
function startTimer() {
// if timeout started then do nothing
if (timeoutStarted) {
return;
}
// start timeout 10 ms
$timeout(function () {
// reset value of timeoutStarted flag
timeoutStarted = false;
// apply new value
$scope.mouseOver = pendingMouseState;
}, 10, true);
}
},
link: function (scope, element) {
//**********************************************
// bind to "mouseenter" and "mouseleave" events
//**********************************************
element.bind('mouseover', function (event) {
scope.changeMouseState(true);
});
element.bind('mouseleave', function (event) {
scope.changeMouseState(false);
});
//**********************************************
// watch value of "mouseOver" variable
// or you create bindings in markup
//**********************************************
scope.$watch("mouseOver", function (value) {
console.log(value);
});
}
}
});
Same thing at http://jsfiddle.net/22WgG/
Also instead
element.bind("mouseenter", ...);
and
element.bind("mouseleave", ...);
you can specify
<tr enter ng-mouseenter="changeMouseState(true)" ng-mouseleave="changeMouseState(false)">...</tr>
See http://jsfiddle.net/hwnW3/
| |
doc_23535574
|
Basically what i have (in angular) is 2 mutable arrays in my component, a displayList and a fullList of items... The template does an ngFor on the displayList.
Filters on the screen call a filter function in the component that clears displayList, then loops through fullList and if the filter applies, it pushes it to display list - giving a real time list filtering effect on the screen...
I know this is the wrong way to approach this, but i cannot wrap my head around the architecture/pattern needed to do this with observables. Do i make a main list and run a .filter() on it based on a component private property? do i do the ngFor on a method that returns the observable list with the .filter in place?
Thanks in advance.
A: Yes, yes, no, yes, no... in other words: There is no correct answer, it depends. (On your personal, preference, on the general use-case, on the existing architecture of your application, ect. ect...)
Filtering in the controller
In your case, there might not be the need for rxjs, though you should avoid mutable objects/data if possible, so your idea with using .filter would be the way to go here.
Custom Pipe
Another way to go would be to implement a custom pipe and filter the data directly in your template:
<div *ngFor="let item of fullList | customFilterPipe:filterSettings">...</div>
The RxJS-Way
Since you asked for the rxjs-way, here is how I would do it:
filterSettings$: BehaviorSubject<IFilterData> = new BehaviorSubject(INITIAL_FILTER_SETTINGS); // this is updated with filterSettings$.next(newFilterSettings)
fullList$: BehaviorSubject<IData[]> = new BehaviorSubject([]); // updated through fullList$.next(newFullList);
displayList$ = Observable.combineLatest(this.fullList$, this.filterSettings$)
.map(([list, filterSettings]) => {
return list.filter(/* your custom filter based on the filterSettings... */);
});
This will automatically update the displayList$ whenever the filterSettings$ or the fullList$ changes.
To use it in the templare you can use the async-Pipe:
<div *ngFor="let item of displayList$ | async">...</div>
But again: Any of those solutions, as well as your current implementation could be a perfectly valid implementation for a given case.
A: In RxJS 5 the best candidate for this is the combineLatest() operator (it has both static and instance method variants) that calls its selector function when any of its source Observables emit a value.
let userInput$ = Observable.from(['a', 'ac', 'aca', 'acarp'])
.concatMap(char => Observable.of(char).delay(500))
.startWith(null);
let list$ = Observable.of(['abstemious', 'abstentious', 'abulia', 'abut', 'aby', 'acalculia', 'acarophobia', 'acarpous', 'accidence', 'accismus', 'acclamation']);
let filteredList$ = Observable.combineLatest(list$, userInput$, (list, filterString) => {
if (filterString) {
// Note that this is Array.filter() method, not an RxJS operator
return list.filter(name => name.indexOf(filterString) === 0);
}
return list;
});
filteredList$.subscribe(val => console.log(val));
See live demo: https://jsbin.com/jihuxu/2/edit?js,console
This simulates a situation where the user types one character every 500ms and filters the list$ accordingly. Note that also the list$ can emit a new array that'll be filtered right away.
One important thing to be aware of is that each source Observable has to emit at least one value before .combineLatest() is able to emit on every change. This is why I have also the startWith(null), to be sure that the selected filter is null at the beginning.
| |
doc_23535575
|
Page url: site.com/dir/page.aspx
Expected url for redirection: site.com/security/login.aspx
Real url: site.com/dir/security/login.aspx
In my web.config there is next code:
<authentication mode="Forms">
<forms loginUrl="~/security/login.aspx" timeout="120" enableCrossAppRedirects="true" />
</authentication>
Why so and how to fix it?
There are no additional code in application events in global.asax. Application builds this path itself
A: Change to below,
<authentication mode="Forms">
<forms loginUrl="/security/login.aspx" timeout="120" enableCrossAppRedirects="true" />
</authentication>
| |
doc_23535576
|
A: You can check the IsPostBack property. Eg:
<script type="text/javascript">
$(function()
{
var isPostBack = <%=Page.IsPostBack.ToString().ToLower()%>;
if (isPostBack)
{
alert("Postback");
}
});
</script>
A: Stolen from this post:
On the server side have this
if(IsPostBack)
{
// NOTE: the following uses an overload of RegisterClientScriptBlock()
// that will surround our string with the needed script tags
ClientScript.RegisterClientScriptBlock(GetType(), "IsPostBack", "var isPostBack = true;", true);
}
On client side this
if(isPostBack) {
// do your thing
}
A: I put this variable inside the header tag of my asp.net web forms page.
<script type="text/javascript">
var isPostBack = ("true"==="<%= Page.IsPostBack ? "true" : "false" %>");
</script>
The var contains a Boolean. The comparison can probably be shortened.
A: Simple:
if you're using jquery it has to go after(jquery goes nuts otherwise):
$(document).ready(function(){
});
var isPostBack = <%=Convert.ToString(Page.IsPostBack).ToLower()%>;
Then
function whatever(){
if (isPostBack){
//Whatever you want to do
}else{
//Whatever else you want to do
}
}
I'm actually using it with jquery to show a web service status box then force a postback to refresh a ListView, so when it posts back it doesn't invoke the web service or show the status box just the updated ListView data.
A: $("a[href^='javascript:__doPostBack']").click(function () {
// do something
});
| |
doc_23535577
|
Also please suggest is there any way to carry the pinned columns in all pages of print preview through coding apart from excel.
| |
doc_23535578
|
I have a routing system which works like this:
/config/routes.php:
$route->add('/' , function() {
require_once("/application/pages/index.php");
});
$route->add('/register', function() {
require_once("/application/pages/register.php");
});
$route->add('/login', function() {
require_once("/application/pages/login.php");
});
$route->add('/logout', function() {
require_once("/application/pages/logout.php");
});
$route->add('/panel', function() {
require_once('/application/pages/panel/index.php');
});
And in my index.php:
require_once('application/pages/header.php');
include('config/routes.php');
require_once('application/pages/footer.php');
Everything works fine but I need a different header.php and footer.php for when the user goes into the panel. file: /application/pages/panel/index.php
When I require_once a new header file in the panel/index.php then both the new and old header file is loaded. How can I unrequire the header and footer files in the /panel/index.php so I can require different ones? Any suggestions?
A: Note: Routing comes from an MVC design pattern, you should keep your controllers separate from your views.
Templates and Views could be kept separate, also. This meaning our directory set-up can look something like this:
- Templates
- header_one.php
- footer_one.php
- header_two.php
- footer_two.php
- Views
- index.php
- someOtherBody.php
Here is a simple, but unfinished (that is your challenge) example of an Object that could do what I am explaining:
class Page {
private $template_path = dirname(dirname(__FILE__)) . '/templates/';
private $view_path = dirname(dirname(__FILE__)) . '/views/';
protected $header;
protected $footer;
protected $body;
public function setHeader($file_name)
{
if(is_readable($this->template_path . $file_name))
{
$this->header = $this->template_path . $file_name;
return $this;
}
// add an exception
}
/* TODO: */
public function setFooter() {}
public function setBody() {}
/* Render page */
public function render()
{
$page = [$this->header,$this->body,$this->footer];
foreach($page as $file)
{
require_once($file);
}
}
}
The idea here is that we can set our page layout, using the above object, within the route method closure, then render / require all the files after the logic.
$route->add('/', function() {
$page = new Page();
$page->setHeader('header_one.php')
->setBody('index.php')
->setFooter('footer_one.php');
/* todo: add your logic here */
$page->render();
});
Each route can now have its own header, footer and body.
Hope this helped.
A: At your place, I will do something like that :
Use out buffer and check if the file is already required. I give you an quick example but adapt the code for you.
And check the function : http://php.net/manual/en/function.get-included-files.php
$route->add('/panel', function() {
include_once('YOUR_SPECIFIC_PATH/header.php');
require_once('/application/pages/panel/index.php');
include_once('YOUR_SPECIFIC_PATH_header/footer.php');
});
And :
ob_start();
include_once('config/routes.php');
$mainContent = ob_get_contents();
ob_end_clean();
include_once('application/pages/header.php');
echo $mainContent;
include_once('application/pages/footer.php');
I've not the time for help more sorry but I can explain later if you need
A: This solution requires you to have a header.php and footer.php in each folder where your sub-controllers (application/<module name>/index.php) are.
index.php only call your sub-controllers via routing:
// require not include, because "no routing" = "no web site" ;)
require_once('config/routes.php');
application/pages/index.php include appropriate header/footer w/ relative path
require_once('header.php');
// page code
require_once('footer.php');
application/register/index.php include appropriate header/footer w/ relative path
require_once('header.php');
// page code
require_once('footer.php');
etc
A: @KDOT , thanks you for your help but using your code I was getting an error that I could not fix:
Call to a member function setBody() on null
but thanks to your code, I managed to rewrite the class my way and now it works ;)
Thanks again @KDOT !
If anyone needs it:
class Page {
private $TEMPLATE_PATH = '/application/templates/';
private $VIEW_PATH = '/application/views/';
protected $header;
protected $footer;
protected $body;
public function __construct($header_file, $body_file, $footer_file) {
$this->header = $this->TEMPLATE_PATH . $header_file;
$this->body = $this->VIEW_PATH . $body_file;
$this->footer = $this->TEMPLATE_PATH . $footer_file;
}
public function render(){
$page = [$this->header, $this->body, $this->footer];
foreach($page as $file) {
require_once($file);
}
}
}
and:
$route->add('/', function() {
$page = new Page('header.php', 'home.php', 'footer.php');
$page->render();
});
| |
doc_23535579
|
On the page I can see that there is text in the label, but when I debug it shows this: "".
So how do I get the text out of a label that is set with Javascript, at least that is what I think is the problem.
My code:
<asp:TextBox ID="txtCount" runat="server" Width="50px" Font-Names="Georgia, Arial, sans-Serif" ForeColor="#444444"></asp:TextBox>
<ajaxToolkit:NumericUpDownExtender ID="NumericUpDownExtender1" runat="server" Minimum="1"
TargetButtonDownID="btnDown" TargetButtonUpID="btnUp" TargetControlID="txtCount" Width="20" />
<asp:ImageButton ID="btnUp" runat="server" AlternateText="up" ImageUrl="Images/arrowUp.png"
OnClientClick="setAmountUp()" ImageAlign="Top" CausesValidation="False" />
<asp:ImageButton ID="btnDown" runat="server" AlternateText="down" ImageUrl="Images/arrowDown.png" OnClientClick="setAmountDown()" ImageAlign="Bottom"
CausesValidation="False" />
<asp:Label ID="lblKorting" runat="server" />
<asp:Label ID="lblAmount" runat="server" />
<asp:Button ID="btnBestel" runat="server" CssClass="btn" Text="Bestel" OnClick="btnBestel_Click1" />
JS
function setAmountUp()
{
var aantal = document.getElementById('<%=txtCount.ClientID%>').value-0;
aantal+=1;
calculateAmount(aantal);
}
function setAmountDown()
{
var aantal = document.getElementById('<%=txtCount.ClientID%>').value-0;
if(aantal > 1)
aantal -=1;
calculateAmount(aantal);
}
function calculateAmount(aantal)
{
var prijs = document.getElementById('<%=lblPriceBestel.ClientID%>').innerHTML -0;
var totaal = 0;
if(aantal < 2)
{
totaal = prijs * aantal;
document.getElementById('<%=lblKorting.ClientID%>').innerHTML = "";
}
else if(aantal >= 2 && aantal < 5)
{
totaal = (prijs * aantal)*0.95;
document.getElementById('<%=lblKorting.ClientID%>').innerHTML = "-5%";
}
else if(aantal >= 5)
{
totaal = (prijs * aantal)*0.90;
document.getElementById('<%=lblKorting.ClientID%>').innerHTML = "-10%";
}
document.getElementById('<%=lblAmount.ClientID%>').innerHTML = totaal;
}
C#
private OrderBO bestelling;
protected void btnBestel_Click1(object sender, EventArgs e)
{
bestelling = new OrderBO();
bestelling.Amount = Convert.ToInt32(lblAmount.Text); //<--- THIS IS "" in the debugger, but on the page 10
}
A: Text stored inside a label is not sent back to the server on a postback. It's a one-way kind of thing.
What you should do instead is put any text you want to go back to the server into a hidden form field, like so:
ASP.NET:
<asp:HiddenField runat="server ID="hfAmount" />
JavaScript:
document.getElementById('<%=hfAmount.ClientID%>').value = totaal;
C#:
bestelling.Amount = Convert.ToInt32(hfAmount.Value);
| |
doc_23535580
|
The program write five times five.(Why just five? Why not 1,2,3 or 4)
and what is the difference when I comment line sleep(5) and not?
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *dretva (void *x)
{
sleep(2);
printf("%d\n", *((int *)x));
return NULL;
}
int main()
{
pthread_t id[5];
int i;
for(i=0;i<5;i++)
{
pthread_create(&id[i], NULL, dretva, (void*)&i);
}
sleep(5); // why is different when this line is commented?
return 0;
}
A: You cannot accurately predict the output in this case because the order in which the threads run is not guaranteed. And because of the sleep in each of the threads, it so happens (in this particular case) that the value of i has already been incremented to 5 in the for loop before the first thread has executed.
If you want to see the output of i in an ascending order, just call pthread_join in the for loop.
for(i=0;i<5;i++)
{
pthread_create(&id[i], NULL, dretva, (void*)&i);
pthread_join(id[i], NULL);
}
See Demo
A:
The program write five times five.(Why just five? Why not 1,2,3 or 4)
When all the threads started executing, the value of i was already set to 5 in the main thread. But it is not guaranteed to print 5 five times always. Whatever the value of i at the time of execution of a thread will be, that value will be printed.
what is the difference when I comment line sleep(5)
The developer of this code is making the main thread wait for 5 seconds. You should use join to block the main thread until the other threads have returned.
A: You face likely a race condition here. The point is - as Naveen Kumar pointed out - by the time your threads become active, the content at address of i is 5, hence each of your threads prints out what it finds on address of i.
If you alternatively provide the value, you should get your desired result.
With the sleep-statement, you are sending your main thread into background keeping contents at the address of i intact. Without this statement, your main thread terminates thus freeing the memory at address of i. As result your threads may find random numbers to print. If you want to avoid that, try getting familiar with pthread_join.
A: You are passing address of i as an argument. After the loop ends, value of i will be 5. All the threads sleeps for 2 seconds and prints the same value.
(void*)&i
pthread_create(&id[i], NULL, dretva, (void*)&i);
you can use an array to store the tid.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *dretva (void *x)
{
sleep(2);
printf("%d\n", *((int *)x));
return NULL;
}
int main()
{
pthread_t id[5];
int args[5];
int i;
for(i=0;i<5;i++)
{ int j;
args[i] = i; // storing tid
pthread_create(&id[i], NULL, dretva, &args[i]);
}
sleep(5);
return 0;
}
| |
doc_23535581
|
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
[self.superview exchangeSubviewAtIndex:[[self.superview subviews] indexOfObject:self] withSubviewAtIndex:[[self.superview subviews] indexOfObject:[touch view]]];
}
But this does not work. Any help would be appreciated.
UIImages are created by following code
TouchImageView *touchImageView = [[TouchImageView alloc]initWithImage:displayImage];
touchImageView.identy = [NSString stringWithFormat:@"Image ID %d",i];
So each touch image is associated some string to describe itself.
In touch end, I have just added following code to know ID of image views
UITouch *touch = [touches anyObject];
TouchImageView *dragImage = (TouchImageView*)[touch view];
NSLog(@"Ended %a%a",[dragImage identy],[self identy]);
But the o/p I got is totally different
2011-11-21 11:50:34.404 OrganizeMe[882:f803] Ended 0x1.6d96006a6d96p-9170x1.807p-1022
FInal code
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
__block int tag = -1;
__block float distance = 100000.0;
[[self.superview subviews] enumerateObjectsUsingBlock:^(UIView *view, NSUInteger index, BOOL *stop) {
BOOL interSect = CGRectIntersectsRect([self frame], [view frame]);
if(interSect && ([self tag]!=[view tag])){
[self.image CGImage];
CGPoint currPoint = [[touches anyObject]locationInView:[self superview]];
CGPoint underPoint = view.center;
if(distance >= [self distanceBetweenPoint1:currPoint Point2:underPoint]){
distance = [self distanceBetweenPoint1:currPoint Point2:underPoint] ;
tag = [view tag];
}
}
}];
NSLog(@"Tag and Distance %d,%f",tag,distance);
TouchImageView* imageView1 = (TouchImageView*)[self.superview viewWithTag:tag];
CGRect point1 = [imageView1 frame];
CGRect point2 = [self frame];
if(tag != -1){
[imageView1 setFrame:point2];
[self setFrame:point1];
}else{
CGPoint lastTouch = [[touches anyObject]previousLocationInView:[self superview]];
self.center = lastTouch;
}
[self.superview setNeedsLayout];
}
A: The index is just the UIView's position in the subview array. It does not set the location within the superview.
Relayout the superview based on the subview's index.
In your above method, also call setNeedsLayout in order to relayout the superview.
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
[self.superview exchangeSubviewAtIndex:[[self.superview subviews] indexOfObject:self] withSubviewAtIndex:[[self.superview subviews] indexOfObject:[touch view]]];
[self.superview setNeedsLayout]; // Should call the method below
}
Implement the following method for the superview:
- (void)layoutSubviews
{
// Iterate over all subviews
[self.subviews enumerateObjectsUsingBlock:^(UIView *view, NSUInteger index, BOOL *stop) {
// This block will be executed for each subview. You have the subview's index.
// Now set the subview's position accordingly to the index.
// I don't know your layout logic, but let's assume you have 14 subviews spread over 4 columns, this will be the subviews' position:
/* 0 1 2 3
4 5 6 7
8 9 10 11
12 13 */
int col = index % 4; // Column from 0 to 3
int row = (int)(index / 4); // Row starting from 0
int w = view.frame.size.width;
int h = view.frame.size.height;
CGPoint p = CGPointMake(col * w + w / 2, row * h + h / 2);
[view setCenter:p];
}];
}
It's been a long time I last used Cocoa touch, so I can't guarantee that the code is working.
| |
doc_23535582
|
public static ISalesPersonManager SalesPersons { get; }
But this is in a dll class. So I can't modify this class.
But I want to add a set method to this method.
So like this:
public static ISalesPersonManager SalesPersons { get;set; }
But how to do this?
Thank you
A: It is not possible to override a get only property to have a setter. Even though the concept of base class is only to describe what it's child "should do" and not what its child "shouldn't", that's how Microsoft has designed it.
| |
doc_23535583
|
<output xmlns="http://www.abcde.com/pqwlv/dwh" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" id="46177" xsi:schemaLocation="dwhOutput.xsd">
<parameter>
<isCoupon>0</isCoupon>
</parameter>
<schedule>
<executionDate businessDay="2020-01-09">2020-01-09</executionDate>
<endDates>
<item businessDay="2019-03-18">2019-03-17</item>
<item businessDay="2019-06-17">2019-06-17</item>
<item businessDay="2019-09-17">2019-09-17</item>
<item businessDay="2019-12-17">2019-12-17</item>
<item businessDay="2020-03-17">2020-03-17</item>
<item businessDay="2020-06-17">2020-06-17</item>
</endDates>
</schedule>
</output>
And I want to select the dates list ("businessDay") from "endDates" field, So the output will be (as a table):
endDates
----------
2019-03-18
2019-06-17
2019-09-17
2019-12-17
2020-03-17
2020-06-17
I have tried to use this query:
SELECT endDates.query('.') AS endDates
FROM [table]
CROSS APPLY
OUTPUT.nodes('declare namespace ns="http://www.abcde.com/pqwlv/dwh"; /ns:output/ns:schedule/ns:endDates') AS T1(endDates)
And got:
<p1:endDates xmlns:p1="http://www.abcde.com/pqwlv/dwh">
<p1:item businessDay="2019-03-18">2019-03-17</p1:item>
<p1:item businessDay="2019-06-17">2019-06-17</p1:item>
<p1:item businessDay="2019-09-17">2019-09-17</p1:item>
<p1:item businessDay="2019-12-17">2019-12-17</p1:item>
<p1:item businessDay="2020-03-17">2020-03-17</p1:item>
<p1:item businessDay="2020-06-17">2020-06-17</p1:item>
</p1:endDates>
How can I dig deeper and select the dates?
A: You weren't far off. You need to use WITH XMLNAMESPACES at the start of your query, to define the namespace, and then you can transverse the nodes in the FROM:
DECLARE @xml xml = '<output xmlns="http://www.abcde.com/pqwlv/dwh" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" id="46177" xsi:schemaLocation="dwhOutput.xsd">
<parameter>
<isCoupon>0</isCoupon>
</parameter>
<schedule>
<executionDate businessDay="2020-01-09">2020-01-09</executionDate>
<endDates>
<item businessDay="2019-03-18">2019-03-17</item>
<item businessDay="2019-06-17">2019-06-17</item>
<item businessDay="2019-09-17">2019-09-17</item>
<item businessDay="2019-12-17">2019-12-17</item>
<item businessDay="2020-03-17">2020-03-17</item>
<item businessDay="2020-06-17">2020-06-17</item>
</endDates>
</schedule>
</output>';
WITH XMLNAMESPACES(DEFAULT 'http://www.abcde.com/pqwlv/dwh',
'http://www.w3.org/2001/XMLSchema-instance' AS xsi)
SELECT eD.item.value('@businessDay','date') AS endDate
FROM (VALUES(@XML))V(YourXML) --This would be your table
CROSS APPLY V.YourXML.nodes('/output/schedule/endDates/item') eD(item);
A: You are close to your desired output.
SELECT T1.endDates.value('@businessDay','DATE')
FROM(
SELECT @X AS COL
)A
CROSS APPLY
A.COL.nodes('declare namespace ns="http://www.abcde.com/pqwlv/dwh";
/ns:output/ns:schedule/ns:endDates/ns:item') AS T1(endDates)
Output:
(No column name)
2019-03-18
2019-06-17
2019-09-17
2019-12-17
2020-03-17
2020-06-17
A: It seems here is the fastest and clean method. No need to declare the xsi namespace because it is not used.
SQL
-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY(1,1) PRIMARY KEY, xml_data XML);
INSERT INTO @tbl
VALUES (N'<output xmlns="http://www.abcde.com/pqwlv/dwh" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
id="46177" xsi:schemaLocation="dwhOutput.xsd">
<parameter>
<isCoupon>0</isCoupon>
</parameter>
<schedule>
<executionDate businessDay="2020-01-09">2020-01-09</executionDate>
<endDates>
<item businessDay="2019-03-18">2019-03-17</item>
<item businessDay="2019-06-17">2019-06-17</item>
<item businessDay="2019-09-17">2019-09-17</item>
<item businessDay="2019-12-17">2019-12-17</item>
<item businessDay="2020-03-17">2020-03-17</item>
<item businessDay="2020-06-17">2020-06-17</item>
</endDates>
</schedule>
</output>');
-- DDL and sample data population, end
;WITH XMLNAMESPACES(DEFAULT 'http://www.abcde.com/pqwlv/dwh')
SELECT ID
, col.value('.','DATE') AS endDates
FROM @tbl AS tbl
CROSS APPLY tbl.xml_data.nodes('/output/schedule/endDates/item/@businessDay') AS tab(col);
Output
+----+------------+
| ID | endDates |
+----+------------+
| 1 | 2019-03-18 |
| 1 | 2019-06-17 |
| 1 | 2019-09-17 |
| 1 | 2019-12-17 |
| 1 | 2020-03-17 |
| 1 | 2020-06-17 |
+----+------------+
| |
doc_23535584
|
*
*Using a Release Pipeline and Defined Deployment Groups to deploy across stages (environments) See here
*Using a Deployment Job in a Pipeline, then using a release pipeline to orchestrate pushing it to different environments - See here
It's interesting that the first link MS docs refer to as being classic, however the latter is not.
I'm currently using Deployment Groups to define the App Servers I deploy to for each environment - then each stage in my Release pipeline targets a different deployment group (environment). This seems the most fluent and natural of the solutions. However, it niggles me that the Environments I setup in the Environments section still maintain that they have never been deployed to - but the deployment groups have recorded the deployments as I expect. Also, the environments allow me to set useful stuff like "business hours" to wake the environment machines.
I looked and tried out some of the approach in the second link I posted - however, this just didn't seem intuative to me - and I can't find much in the DevOps docs to support this approach. I can see the benefits in that you can store your deployment pipeline as code in your repo, and that you have finer controller over the whole process - but I couldn't get variables from the library to be used in any of the replace variables steps or really understand where the release pipelines fit in.
So, I guess I after an inkling of what "best practice" is in this fairly straight forward scenario. I wondering if it's a blend of the two, but to be honest - I'm a bit lost.
A: Release pipelines and deployment groups have been around for longer than Azure DevOps has been named Azure DevOps. The YAML releases are rather recent. It isn't ever spelled out explicitly, but in my mind it comes down to how you plan on delivering your product.
If you are doing Continuous delivery (choosing when to release, maybe daily, weekly, or quarterly) then I think you must use release pipelines. You might choose this also if you have multiple environments that maybe aren't in the path to production that would want to deploy.
If you are doing Continuous deployment (every push that passes tests goes to production without any real human intervention), then I imagine you'd choose to use the YAML stages. This is kind of spelled out in your second link as the approach for deploying with "release flow", which is Microsoft's approach for delivering changes for Azure DevOps.
| |
doc_23535585
|
Objective C:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.modalPresentationStyle = UIModalPresentationCustom;
self.transitioningDelegate = self;
}
return self;
}
Here is where i am in swift so far:
override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.modalPresentationStyle = UIModalPresentationStyle.Custom
self.transitioningDelegate = self
}
However i keep getting this error:
Class "ViewController" does not implement its superclass's required members
I thought the init method above was it required members?
Edit - Goes into more detail below:
Class does not implement its superclass's required members
A: You must implement base class required initializers. In your case you should add code bellow to your VC class:
required init(coder aDecoder: NSCoder!) {
super.init(coder: aDecoder)
}
Since Beta 5:
The required modifier is written before every subclass implementation
of a required initializer. Required initializers can be satisfied by
automatically inherited initializers.
Remarks:
required init(coder aDecoder: NSCoder!) { ... } should be added only if you override at least one init method in your class.
| |
doc_23535586
|
class Change(models.Model):
RFC = models.CharField(max_length=10)
Ticket_Number = models.CharField(max_length=10)
Plan_Owner = models.ForeignKey(User)
Plan_validater = models.ForeignKey(User)
My admin.py looks like this :
class ChangeAdmin(admin.ModelAdmin):
search_fields = ('RFC', 'Ticket_Number','Plan_Owner','Plan_validater')
list_display = ('RFC', 'Ticket_Number','Plan_Owner','Plan_validater')
fieldsets = [
('Ticket Details', {
'fields': ['RFC', 'Ticket_Number', 'Plan_Owner','Plan_validater']}),
]
admin.site.register(Change, ChangeAdmin)
What I want to ensure that only the plan owner or the plan validater for a particular change can edit it.Everyone can view it,but doing changes to a row should be restricted to only the change or plan owner.Also they can only edit it and not delete it.Only the superuser can add or delete changes. This link on the django site does mention some clues but my lack of experience with the framework prevents me from implementing it...
A: It should be something like this:
class ChangeAdmin(ModelForm):
def clean(self):
if self.request.user != self.Plan_Owner or self.request.user != self.Plan_validater or not :
raise ValidationError(u'Permission denied')
else:
return self.cleaned_data
To access the current user, override the ModelAdmin.get_form, by adding the request as an attribute of the newly created form class .
class EntryAdmin(admin.ModelAdmin):
form = EntryAdminForm
def get_form(self, request, *args, **kwargs):
form = super(EntryAdmin, self).get_form(request, *args, **kwargs)
form.request = request
return form
| |
doc_23535587
|
Suppose I want to use "Tally table" in my procedure, and my co-worker planning to use "Tally table" in his procedure.
Do we have to use different Tally table for each procedure.
If it so, I think it will be so many different "Tally tables" in our database (one Tally table on each procedure).
If we could use the only Tally table for each procedure then how to fill this table sequential data? I need 1000 rows, somebody else can decide that it's too much and decrease the amount...
Please clear this moment for me...
A: There is no reason you couldn't use the same table in multiple procedures or by different people. If you only need 1000 rows for you query and it doenst run multiple times per second you could consider creating and populating it in your query as a temp table because 1000 rows of just an incremental number is nothing to the engine.
| |
doc_23535588
|
- String: str
- MD4 hash of the string: MD4(str)
- MD5 hash of the string: MD5(str)
MD4 and MD5 are cryptographically "broken" algorithms, meaning it is not difficult to:
1) find str_2 where MD4(str) = MD4(str_2) (i.e. attack on MD4)
2) find str_3 where MD5(str) = MD5(str_3) (i.e. attack on MD5)
But how hard would it be to:
3) find str_4 where MD4(str) = MD4(str_4) AND MD5(str) = MD5(str_4)
(i.e. attack on MD4 and MD5 simultaneously)?
The obvious (probably not very efficient) way would be to:
1) Find a string STR where MD4(STR) = MD4(str)
2) Check if MD5(STR) = MD5(str)
3) If so, we're done. If not, go back to step 1 and satisfy step 1 with a different string.
But the above algorithm doesn't seem fast to me (or is it?). So is it true that a string hashed by both MD4 and MD5 would be quite safe from a second preimage attack?
EDIT:
(1) The main concern is enhancing second pre-image resistance
(2) The main motivation is not to use outdated hashes for today's applications. Rather, it is two-fold: first, I am anticipating the day that hashes considered secure today become broken. For example, If I use only SHA-2, then the day it becomes broken is the same day I will become very worried about my data. But if I use SHA-2 and BCrypt, then even if both become individually broken, it may still be unfeasible to defeat the second pre-image resistance of concat(Sha2_hash, Bcrypt_Hash). Second, I want to reduce the chance of accidental collision (server thinks two inputs are the same because two hashes JUST so happens to be the same)
A: This sort of thing doesn't improve security as much as you think. The resulting (M+N) bit value is actually weaker than the output of a hash that natively generates (M+N) bits of output. This answer on crypto.stackexchange.com goes a little deeper if you want to know more details.
But the bottom line is that when constructing a hash function whose output is the concatenation of other hash functions, the output you get is, at best, as strong as the strongest constituent hash.
And I have to ask why even use MD4 or MD5 and go to this trouble to begin with? Use SHA-3. If you want to feel "extra safe" then calculate the margin of safety that you feel comfortable with, and increase it by some percentage. That is, if you feel that 384 bits are enough, then go for 512.
So, with some more information about you are trying to do, which is to use the file contents to generate both a "quick checksum" value and generate a unique locator/identifier for the file at the same time I still think that choosing a single hash is the better approach.
If you insist on using two hash functions, then I would submit that instead of concatenating two hashes the better approach would be to instead use a HMAC using two different hash functions/algorithms. Please note, that I do not have a rigorous proof that this works better, or that this construct won't generate horrible output. So take it with a grain of salt:
Let H1 and H2 be two cryptographically secure hash functions, and let P be your input data. Then, the hash & file identifier for your file is given by the construct:
HMAC (K,P) = H1((KGEN(P) ⊕ PAD1) ∥ H1((KGEN(P) ⊕ PAD2) ∥ P)))
Where
KGEN (P) = H2(P)
A: It is kinda more difficult. Because one would need to calculate collision for MD4 and simultaneously for MD5. But kinda is a lame term in cryptography. Rolling your own security scheme is the enemy #1. However, there are examples, when people chain algorithms, such as DES => 3 DES or TrueCrypt allows chaining several encryption algorithms or PBKDF2 key derivation runs the same algorithms N times.
Seriously, if you need a strong hash - use SHA2 and onwards.
The problem with finding MD4 and MD5 hash collisions is that it's possible to make a chain of devices that would allow attacker to linearly scale number of attack attempts, and given large enough budget this sounds plausible.
| |
doc_23535589
|
It's been only recently that I've noticed that my database include tweets like this:
tweet example.
I searched for "ozone hole" and it returned a tweet whose text doesn't actually include "ozone hole", but "ozone hole" can be found in the title of the news, to which the author of the tweets made a reference.
Is there any way to avoid tweets like that and to search for tweets that include my keywords in the actual tweet text?
Chunk of my code that searches for tweets:
for tweet in tweepy.Cursor(api.search,
q="ozone hole",
lang="en",
#Since="2019-11-27",
#until="2019-11-14",
tweet_mode='extended').items():
A: This is simply how Twitter's search works. If you search for the same query through Twitter's website, you'll see that it comes up with those same results.
Note though, that it's likely due to the query showing up in the URL itself, not in the title of that site.
A: Try these commands for the date that you are looking for first:
unitl= datetime.date.today()
print("Today's date:", until)
since= until- datetime.timedelta(days=50) #the number isdentify the number of days that you are looking for the tweets
print(since)
Then you can use the command below to specify the keyword
tweets_list = tweepy.Cursor(...)
| |
doc_23535590
|
What ended up working was the FactoMineR package (a combination of the PCA, coord.ellipse, and plot.PCA functions). While I can draw now confidence ellipses, I do not understand what the level.conf option of the coord.ellipse function actually does. I was expecting smaller ellipses with increased confidence levels, but the opposite is happening.
Thank you for your help!
A: If you want to have a higher degree of confidence that your ellipses includes the "true" value (in the case of parameter estimation) or that it includes a higher proportion of the population (in the case of prediction ellipses) then you use a higher confidence figure. This principle applies very widely. Higher degrees of confidence require wider intervals to meet the demands you are specifying.
| |
doc_23535591
|
We can issue "seek" command to the process, which is working: we start receiving data corresponding the new position we specify.
So far so good.
However, there is delay between the time we issue the seek and the time we start playing the data at the correct position.
I'm pretty sure this is because we buffer data.
So I would like to flush the data buffered in our pipeline when we issue the seek command.
However, I didn't managed to do this: I used gst_pad_push_event (gst_event_new_flush_start()) on the pad, then gst_event_new_flush_stop short after, which both return TRUE.
However, music stops, and never start again.
Using export GST_DEBUG=2 I can see the following warning:
gdpdepay gstgdpdepay.c:429:gst_gdp_depay_chain:<gdpdepay-1> pushing depayloaded buffer returned -2
As the other process continue to push data while flush might be "on" for a short amount of time, that might explain this warning. But I would expect the other process to be able to continue to push data, and our pipeline to be able to continue to read data from this socket and process them in the pipeline, after sending a flush_stop event.
Googling this issue, I found some suggestions like changing the pipeline state, but that didn't help either.
Any help very welcome!
| |
doc_23535592
|
<div ng-repeat="row in rows">
<table>
<td ng-repeat="row2 in rows2">
<tr ng-repeat="col in cols">
{{blablabla}}
</tr>
</td>
</table>
</div>
The table is always quite the same, but Angular just redraw it every times (for each elements in 'rows'), which leads to some performance issues.
Is there a way to tell angular to pre render the table in the middle, and then display the list ?
| |
doc_23535593
|
macOS 10.15.2 (19C57); Xcode: 11.3 (11C29)
(question was updated because of I have found new relations in the issue)
I have the following code:
List(model.filteredStatus) { status in
StatusViewRow(status: status, model: self.model)
.contextMenu{
Text("menu 1")
Text("menu 2")
}
}
It's works perfectly.
But in case of I want to use ForEach instead ( no matter why):
ForEach(model.filteredStatus) { status in
StatusViewRow(status: status, model: self.model)
.contextMenu{
Text("menu 1")
Text("menu 2")
}
}
Context menu doesn't appear.
I have found the reason. Reason was in incorrect work of ForEach + contextMenu + if statement combination!
ContextMenu doesn't work exactly on part of row inside of the if statement. Works well on the ful row with List and works only on the toogle row part when I'm using ForEach.
Can somebody explain why so?
I have an if statement inside of StatusViewRow contextMenu doesn't appear on this part:
struct StatusViewRow : View {
@ObservedObject var status : FileStatusViewModel
@ObservedObject var model : StatusViewModel
var body: some View {
HStack {
TaoToggle(state: status.stageState) { self.status.toggleStageState() }
// you can replace to just a toogle
// ISSUE START HERE
if(model.fileNamesOnly) {
StyledText(verbatim: status.fileName )
.style(.highlight(), ranges: { [$0.lowercased().range(of: model.filterStr.lowercased() )]})
}
else {
StyledText(verbatim: status.path )
.style(.foregroundColor(.gray), ranges: { [$0.range(of: status.fileDir) ] } )
.style(.bold(), ranges: { [$0.range(of: status.fileName) ] })
.style(.highlight(), ranges: { [$0.lowercased().range(of: model.filterStr.lowercased() )]})
}
// ISSUE END HERE
}
}
}
A: You need to wrap ForEach inside a List or relevant.
Any view that contains Text("...") needs to be either inside a VStack, HStack, ZStack, etc or a List. It won't render otherwise.
When you create a SwiftUI view, the protocol defines that we need to return “some View”. The word “some” means that we are dealing with an opaque result type. This is a new feature added in Swift 5.1. An opaque result type means that we must return one, and only one, of the specified type, in this case something that conforms to the “View” protocol.
ForEach conforms to Hashable:
struct ForEach<Data, ID, Content> where Data : RandomAccessCollection, ID : Hashable
...whereas stacks (VStack in this case) conforms to View:
@frozen struct VStack<Content> where Content : View
...and List also conforms to View:
struct List<SelectionValue, Content> where SelectionValue : Hashable, Content : View
So you need something like this:
ForEach (model.filteredStatus) { status in
VStack { // stack View
StatusViewRow(status: status, model: self.model)
.contextMenu {
Text("Menu 1")
Text("Menu 2")
}
}
}
OR:
ForEach (model.filteredStatus) { status in
StatusViewRow(status: status, model: self.model)
.contextMenu {
VStack { // stack View
Text("Menu 1")
Text("Menu 2")
}
}
}
OR:
List { // List works because it conforms to View
ForEach (model.filteredStatus) { status in
StatusViewRow(status: status, model: self.model)
.contextMenu {
Text("Menu 1")
Text("Menu 2")
}
}
}
This article does a good job of explaining why it's necessary.
| |
doc_23535594
|
A: Give the following code in viewDidLoad
-(void) ViewDidLoad
{
UITapGestureRecognizer *tapScroll = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapped)];
tapScroll.cancelsTouchesInView = NO;
[scrollview addGestureRecognizer:tapScroll];
}
And define the function as follows
- (void) tapped
{
[self.view endEditing:YES];
}
A: Try to use this one. And i hope it will be helpful.
- (void)viewDidLoad
{
[super viewDidLoad];
UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyBoard:)];
gestureRecognizer.delegate = self;
[scrollView addGestureRecognizer:gestureRecognizer];
}
-(void) hideKeyBoard:(UIGestureRecognizer *) sender
{
[self.view endEditing:YES];
}
A: set the scrollview Delegate to self
self.scrollView.delegate=self;
then
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
if (sTitle.isFirstResponder) {
[sTitle resignFirstResponder];
}
}
A: You can use this code to hide the keyboard:
-(void)viewDidLoad
{
[super viewDidLoad];
UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideTheKeyBoard:)];
gestureRecognizer.delegate = self;
[scrollView addGestureRecognizer:gestureRecognizer];
}
-(void) hideTheKeyBoard:(UIGestureRecognizer *)sender
{
[self.view endEditing:YES];
}
A: UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)];
[tapRecognizer setNumberOfTapsRequired:1];
[tapRecognizer setDelegate:self];
[scrollview addGestureRecognizer:tapRecognizer];
-(void)tapped:(id)sender {
[textField resignFirstResponder];
// your code what you want
}
A: if you are using xib then just connect a tapRecognizer to your scrollview and then create tapRecognizer's selector event to [self.view endEditing:YES]
A: add custom button on scrollview and
-(IBAction)btn:(id)sender
{
[txt resignfirstresponder];
}
enjoy it!!
A: UITapGestureRecognizer *tapScroll = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(Click)];
ScrollClick.cancelsTouchesInView = NO;
[YOUR scrollview addGestureRecognizer:ScrollClick];
- (void)Click
{
[self.view endEditing:YES];
}
Try this one. And i hope it will be helpful For You . enjoy it !
| |
doc_23535595
|
Is there a general way to save and retrieve files to and from sql server? The worst part is retrieving, let's imagine we found a way to save any file to sql server, now how can we rebuild the file from db? We don't know what the file extension was before saving?
A: Well, Generally speaking, it's considered bad practice to save actual files to the database.
a part of the reason is the problems you mentioned in your post, and an even bigger part is that saving files directly to the database has a large overhead (such as translating an image to a byte array and back).
the easy (and recommended in most cases) way to handle files and databases is to save the files directly to the file system, and keep the path in the database along with other file-related data such as the user id that uploaded the file.
this way you don't need to worry about braking and rebuilding the files, you just send them to the server and back to the user as is.
Keep in mind it's not recommended to keep the full path of the file, only a relative path.
What I normally do is save all files from the users either on the serer itself or on the users's computer (in a desktop application). in any of these cases, there is a dedicated folder with only read/write permissions (NEVER let a user save a file into a directory with execute permissions!), and keep the path of this directory either on a 'General Params' table in the database or in the configuration file of the website / application / webservice.
A: Well, the file attributes (name, extension, author, etc) are usually kept in relational way, in table inside SQL Server. The file itself should be kept in SQL Server database, exactly how depends on version od SQL Server and size of file. Use FILESTREAM or FILETABLES feature for larger, or VARBINARY(MAX) for smaller files.
It doesn't matter whether its an image, or doc or pdf -- if you car read into a FileStream, you can save it to database.
Advantages of storing files in a database is simplified management, backups, security, integrity. With FILESTREAM and FILETABLES feature, accessing a file is almost the same as if it were on a file system, using the SqlFileStream object from .NET.
See more here:
http://technet.microsoft.com/en-us/library/gg471497.aspx
And here:
http://technet.microsoft.com/en-us/library/ff929144.aspx
| |
doc_23535596
|
I have a value change listener on a combobox that opens a confirm dialog, allowing the user to confirm the change. Because this is within a value change listener, the value has technically already changed. Thus when they select "No" I need to revert the value. There doesn't appear to be any part of the API that can do this, aside from manually setting the value.
But when reverting via setValue(...) the listener fires a second time. I need to prevent it from firing again. Currently the only way I'm able to do it is with an extra "ignoreNextChange" boolean variable, which prevents the logic from running a second time. Is there an easier way to do this? I don't see anyway to add a listener that fires before the value change.
I can't simply ignore all non-client changes, because that breaks the binder. And altering the listener registration won't work from inside the listener because I would also need to add it back, which would cause it to fire anyway.
A: You are right to assume, that you can not prevent the propagation of the
change inside an value change handler (it's happening after the fact).
Your main options are:
*
*You react only to "human made" change (from the client). See
isFromClient inside the
`ValueChangeEvent
*Or de-couple the UI from the action (give the User some UI to request the
change, ask again, then do the change) -- this could be done with a number of
ways. One way to do that could be writing your own field wrapping the combo
box and only fire a change once the selection is confirmed.
A: I assume you're using unbuffered Binder, with binder.setBean()? That has the underlying assumption that every write happens directly after the field value changes, not after a "confirm" step. If you want to delay the write (buffered binding), you should use binder.writeBean(bean) once you're ready. Note that this should be done without calling setBean.
| |
doc_23535597
|
Why? And how do I overcome this?
<custom-one>
<core-label for=".cls{{myObj.hashCode}}" type="checkbox">
</core-label>
</custom-one>
<custom-two>
<input class="cls{{myObj.hashCode}}" type="checkbox">
</custom-two>
Please note:
*
*myObj specified in both elements is same.
*I have tried "for=" without
the "." prefix too.
*The html generated does have proper class in both places.
| |
doc_23535598
|
I followed this django book instruction for inspectdb.
http://django-book.readthedocs.io/en/latest/chapter18.html
When i enter the command
python manage.py inspectdb > interface/models.py
I get following error
Traceback (most recent call last):
File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\sqlserver_ado\dbapi.py", line 547, i
n _execute_command
recordset = self.cmd.Execute()
File "<COMObject ADODB.Command>", line 3, in Execute
File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\win32com\client\dynamic.py", line 28
7, in _ApplyTypes_
result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft SQL Server Native C
lient 11.0', "Invalid object name 'Attribute'.", None, 0, -2147217865), None)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 6
2, in execute
return self.cursor.execute(sql)
File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\sqlserver_ado\dbapi.py", line 647, i
n execute
self._execute_command()
File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\sqlserver_ado\dbapi.py", line 558, i
n _execute_command
self._raiseCursorError(klass, _message)
File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\sqlserver_ado\dbapi.py", line 488, i
n _raiseCursorError
eh(self.connection, self, errorclass, errorvalue)
File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\sqlserver_ado\dbapi.py", line 103, i
n standardErrorHandler
raise errorclass(errorvalue)
sqlserver_ado.dbapi.DatabaseError: (-2147352567, 'Exception occurred.', (0, 'Microsoft SQL Se
rver Native Client 11.0', "Invalid object name 'Attribute'.", None, 0, -2147217865), None)
Command:
SELECT * FROM [Attribute] where 1=0
Parameters:
[]
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\django\core\management\__init__.py",
line 338, in execute_from_command_line
utility.execute()
File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\django\core\management\__init__.py",
line 330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\django\core\management\base.py", lin
e 390, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\django\core\management\base.py", lin
e 441, in execute
output = self.handle(*args, **options)
File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\django\core\management\commands\insp
ectdb.py", line 25, in handle
for line in self.handle_inspection(options):
File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\django\core\management\commands\insp
ectdb.py", line 76, in handle_inspection
for row in connection.introspection.get_table_description(cursor, table_name):
File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\sqlserver_ado\introspection.py", lin
e 101, in get_table_description
cursor.execute("SELECT * FROM [%s] where 1=0" % (table_name))
File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 79, in e
xecute
return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 64, in e
xecute
return self.cursor.execute(sql, params)
File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\django\db\utils.py", line 97, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\django\utils\six.py", line 658, in reraise
raise value.with_traceback(tb)
File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 62, in e
xecute
return self.cursor.execute(sql)
File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\sqlserver_ado\dbapi.py", line 647, in execu
te
self._execute_command()
File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\sqlserver_ado\dbapi.py", line 558, in _exec
ute_command
self._raiseCursorError(klass, _message)
File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\sqlserver_ado\dbapi.py", line 488, in _rais
eCursorError
eh(self.connection, self, errorclass, errorvalue)
File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\sqlserver_ado\dbapi.py", line 103, in stand
ardErrorHandler
raise errorclass(errorvalue)
django.db.utils.DatabaseError: (-2147352567, 'Exception occurred.', (0, 'Microsoft SQL Server Native
Client 11.0', "Invalid object name 'Attribute'.", None, 0, -2147217865), None)
Command:
SELECT * FROM [Attribute] where 1=0
Parameters:
[]
I cannot figure out how to debug this issue. It seems there is some hint on last lines of error
Command:
SELECT * FROM [Attribute] where 1=0
Parameters:
[]
but i don't know what to change. Any suggestion?
A: https://github.com/denisenkom/django-sqlserver/issues/3
Apparently it's one of the open issues present in the django ms-sql package.
If anyone is having the same trouble, make your own models or look at the workaround recommended at the end of this issue
| |
doc_23535599
|
Example of a deck of cards with both methods where you need to define new types for the values and suits of a card:
enum Value{
ace = 1,
//Biggest issue is I dont want to have two = 2 etc. until 10
jester = 11,
queen = 12,
king = 13
};
In this example the problem is if I want a new Value to be numerical, lets say 7 I can't do:
Value a_value = 7; //Won't allow int to Value
Value a_value = seven; //This extra enum seems just bad
Another option would be to do:
typedef char Value
#define ace 1
#define jester 11
#define queen 12
#define king 13
This is essentially the same result but with this method it'll let me do:
Value a_value = 7;
Can I use the 2nd method with #define or it's the wrong way to do this?
A: In your example, I think the enum solution is better, it prevents usage like:
Value a = 0; //illegal
Value b = 14; //illegal
Just fill in the blanks between ace and jester. That seems no harms. In my opinion, the code even looks cleaner:
enum Value{
ace = 1,
two,
three,
four,
five,
six,
seven,
eight,
nine,
ten,
jester,
queen,
king
};
A: You may do like this
enum Value ={ace=1, two,...};
Value a_value = static_cast<Value>(some int value, in enum range);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.