id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_1600
|
Any feedback about this would be much appreciated! Thank you!
Note: Im using TF v2
A: Yes, TFX Pipeline supports TPU out-of-the-box for TPU-enabled Estimators, the same model_config.model can be used to configure an estimator regardless of whether it is trained on CPU or TPU.
To train in TPU, you should follow the following actions:
*
*Configure a tpu_footprint in your deployment file and the desired
trainer stanza of your service file.
*Include an empty TPUSettings
message in your custom_config file.
*And as an optional action,
configure a TPUEstimator-specific args in
model_config.tpu_estimator.
| |
doc_1601
|
But when I run it, I just get the slider. No Component. Why?
My main:
JFrame mainFrame = new JFrame();
JPanel content = new JPanel();
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
Component paintArea = new PaintingArea();
JSlider slider = new JSlider();
content.add(paintArea);
content.add(slider);
mainFrame.add(content);
mainFrame.pack();
mainFrame.setVisible(true);
My Painting class:
public class PaintingArea extends Component implements Paintable
{
@Override
public void paint (Graphics g)
{
if (g instanceof Graphics2D)
{
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.red);
g2.draw(new Line2D.Double(a.getX(), a.getY(), b.getX(), b.getY()));
}
}
}
| |
doc_1602
|
I want to know the relationship between the unit of the value of mPitch, mRoll, mYaw, and mThrottle specified by the argument of mFlightController.sendVirtualStickFlightControlData and the flight distance.
What value must be set for mRoll to advance MAVIC by 5 meters?
I want to know the calculation method.
This is the example code.
// What value must be set for mRoll to advance MAVIC by 5 meters?
float distance = 0.5f;
float rollJoyControlMaxSpeed = 10;
float mPitch = 0.0f;
float mRoll = (float)(rollJoyControlMaxSpeed * distance);
float mYaw = 0.0f;
float mThrottle = 0.0f;
mFlightController.sendVirtualStickFlightControlData(
new FlightControlData(
mPitch, mRoll, mYaw, mThrottle
), new CommonCallbacks.CompletionCallback() {
@Override
public void onResult(DJIError djiError) {
if (djiError!=null){
setResultToToast(djiError.getDescription());
}
}
}
A: What you're asking for is inertial navigation and the DJI SDK contains no class or function for that at the moment.
In inertial navigation the standard approach is to use the velocity and acceleration in order to calculate the distance moved so far.
The velocity is provided by FlightControllerStateCallback:
aircraft.getFlightController().setStateCallback(new FlightControllerState.Callback() {
@Override
public void onUpdate(@NonNull FlightControllerState flightControllerState) {
//get current velocity
float velocityX = flightControllerState.getVelocityX();
float velocityY = flightControllerState.getVelocityY();
float velocityZ = flightControllerState.getVelocityZ();
}
});
The acceleration values are not accessible.
In theory you need to fly at a speed of 1 m/s for 5 seconds to reach your goal of 5 meters. In reality you need to account for the acceleration and braking distance.
The most promising approach I see is to test how much time the Mavic needs to accelerate to a certain speed and also how long the braking distance is in relation to the speed. Based on these you should be able to approximate the distance flown at an acceptable level. Here's some pseudocode of how I imagine it to be working:
set velocity to 1 m/s
-> the drone needs 2 seconds to achieve the speed and will fly 1.5m during that time. [1]
once the velocity has been reached(information from callback), wait 2 seconds.
-> the drone flies 2m
set velocity to 0
-> the braking distance for 1m/s is 1.5m [1]
the total distance flown: 5m
Please note that these values [1] are purely made up and you need to get approximate values for these via probably tedious testing.
| |
doc_1603
|
I found this https://www.gameplay-time-tracker.info/en/default.aspx to track the applications.
Is there a way to retrieve from the program the datas of each game and display them in HTML ?
Or is there any friendlier alterntive for application tracking for the web ?
Thank you.
A: https://www.gameplay-time-tracker.info/en/faq.aspx
question 16:
Question: I want to study raw data collected by this application
(to plot custom diagrams etc.).
Is there a way to export raw data to other software?
Answer: yes, there is. For versions prior to 3.0, you can open XML files in your user profile folder with Microsoft Excel.
For example, open “DailyStatistics.xml” to export gameplay times on a daily basis, open “Applications.xml” to export statistics of individual games.
Starting with version 3.0, you can fetch data from SQLite database file “GameplayTimeTracker.sqlite” (it is unprotected).
It can be done with SQLiteStudio (free software, excellent tool which I highly recommend).
Starting with version 3.0.2, you can export all applications and statistics to CSV files (comma-delimited, quoted).
These CSV files can be opened with Microsoft Excel or any other software supporting CSV file format.
so the answer looks like yes... but getting 'live' data as you play. I don't know... (but it would be a SQLite query it looks like if it is possible to query while it's open).
| |
doc_1604
|
MessageContext.jsx file :
import { useState, useContext, createContext } from "react";
export const MessageContext = createContext("KITA KO SALAMA")
export const MessageUpdateContext = createContext()
export function useMessage(){
return useContext(MessageContext)
}
export function useMessageUpdate(){
return useContext(MessageUpdateContext)
}
export function MessageProvider({ children }){
const [messageContent, setMessageContent] = useState()
return (
<MessageContext.Provider value={messageContent}>
<MessageUpdateContext.Provider value={setMessageContent}>
{children}
</MessageUpdateContext.Provider>
</MessageContext.Provider>
)
}
App.jsx file
import { Routes, Route } from "react-router-dom"
import Navbar from "./components/Navbar"
// Pages //
import Home from "./pages/Home"
import SignUp from "./pages/Auth/SignUp"
import Welcome from "./pages/Auth/Welcome"
// Pages //
import Message from "./components/Message"
// Other Imports //
import { MessageProvider } from "./context/MessageContext"
// Other Imports //
function App() {
return (
<>
<MessageProvider>
<Navbar />
<Message />
<Routes>
<Route path="/" exact element={<Home />} />
<Route path="/signup" exact element={<SignUp />} />
<Route path="/support" exact element={<Support />} />
<Route path="/welcome" exact element={<Welcome />} />
</Routes>
</MessageProvider>
</>
)
}
export default App
This is how I try to display it, i imported both useContext and Message context. console.log("context value is: " + useContext(MessageContext))
| |
doc_1605
|
For some time (few months) our table might be changed. And our stored procedure might be not up to date (it just may cause any problems). In case when it is the only one procedure it is not a problem. We can check procedure manually (just try to run it once again and see if there are any errors) and fix it if it is necessary. But what in case if we have a lot of procedures and we even don't remeber which ones was connected with table which was changed.
Is there any way of automatic run all procedures (I don't want to pass any parameters I would only like to test if the procedure can compile without errors)?
@Md. Elias Hossain ->
This query will return procedure name and all parameters for this procedure for the given proceddure.
But I said the situation looks like:
I have a lot of stored procedures and I have some structure of tables. Now I need to change some tables (I don't know maybe - add some columns or rename column's name) And I DON'T need to change any procedure! But when I run my application (after some changes in the structure of tables) which uses stored procedures, it will failed (as some procedures are not correct now - i.e. some fields might not exists any more).
When I create new procedure, if it is ready I click Execute and it will run and save within all procedures. If something was wrong with it, I will get an error message and procedure won't be saved.
Now I would like to do something very similar. I would like to Execute all procedures (after any changes in tables structure) and check if they are still correct (correct in structural meanings). So I don't need to know any parameters for structures.
Next I can do it one by one, but I think it is not a good way to do it. So I asked if anyone know any good way to Execute all procedures (I don't want to insert any data to db or delete or select anything. The only one thing I would like to do is checking if all these procedures are still correct in structural meaning)
A: If you just want to make sure they're still valid, there's a feature in SQL Prompt called 'Find Invalid Objects' which should work for you.
There is a screenshot of how this works here:
http://www.red-gate.com/products/sql-development/sql-prompt/screenshots
If you want to do it 'properly' and make sure they not only compile but behave as expected, you will need to take Klas's advice and implement unit testing. The company I work for just released a preview UI tester runner, SQL Test, that builds on the open source framework, tSQLt.
For more information, visit:http://www.sql-test.com
A: This seems to be simmilar to your problem (If I got you right you want to ensure the stored procedures are compiling and are compatible with the current db schema)
Syntax check all stored procedures?
maybe can be useful?
A: You should look into a xUnit based framework. My google karma found TSQLUnit.
A: You can check/match procedures parameters with table fields with below query, assume you know the table fields up to date.
SELECT Procs.Name, Params.Name FROM
SYS.PROCEDURES Procs INNER JOIN SYS.PARAMETERS Params
ON Procs.OBJECT_ID = Params.OBJECT_ID
AND Procs.NAME = 'InsertOfficeAssignment' -- Procedure Name
ORDER BY Params.Parameter_id
| |
doc_1606
|
Code snippet :
UIDocumentPickerViewController *dvc = [[UIDocumentPickerViewController alloc]initWithDocumentTypes:arrContents inMode:UIDocumentPickerModeImport];
dvc.delegate = self;
dvc.allowsMultipleSelection = true;
[self presentViewController:dvc animated:true completion:nil];
Screenshot :
A: This is a bug Apple needs to fix. You can use this workaround. If you set animated: to YES, it will only work the first time you show the document picker.
Objective-C:
[self presentViewController:dvc animated:NO completion:^{
if (@available(iOS 11.0, *)) {
dvc.allowsMultipleSelection = YES;
}
}];
Swift 4:
self.present(dvc, animated: false) {
if #available(iOS 11.0, *) {
dvc.allowsMultipleSelection = true;
}
}
| |
doc_1607
|
I mean the actual numbers on the circles showing the value of each patch. I can't find how to remove these. Is there a way? Or is there a way to change the colour of them, so that I can just blend them into the background?
A: Borrowing the "base-code" from this question I think I have come to a solution for you:
from matplotlib import pyplot as plt
from matplotlib_venn import venn3, venn3_circles
set1 = set(['A', 'B', 'C', 'D'])
set2 = set(['B', 'C', 'D', 'E'])
set3 = set(['C', 'D',' E', 'F', 'G'])
out = venn3([set1, set2, set3], ('Set1', 'Set2', 'Set3'))
for idx, subset in enumerate(out.subset_labels):
out.subset_labels[idx].set_visible(False)
plt.show(out)
This walks through all of the subset_labels and sets the visibility to False. Effectively removing the text.
| |
doc_1608
|
I have a Spring Boot 1.3.5 application that insists on replacing my favicon with Boot's default favicon (the green leaf). To resolve the problem, I have tried the following:
*
*Install my own favicon at my application's static root.
The word on the street is that this is just supposed to work. Unfortunately, it does not.
*Set property spring.mvc.favicon.enabled to false.
This is supposed to disable org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter.FaviconConfiguration, which appears to responsible for serving Boot's default favicon. By setting a breakpoint in that class, I was able to confirm that the beans defined in that class indeed do not get created when the property is set to false.
Unfortunately, this didn't solve the problem, either.
*Implement my own favicon handler:
@Configuration
public class FaviconConfiguration {
@Bean
public SimpleUrlHandlerMapping faviconHandlerMapping() {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setOrder(Integer.MIN_VALUE);
mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", faviconRequestHandler()));
return mapping;
}
@Bean
protected ResourceHttpRequestHandler faviconRequestHandler() {
ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
ClassPathResource classPathResource = new ClassPathResource("static/");
List<Resource> locations = Arrays.asList(classPathResource);
requestHandler.setLocations(locations);
return requestHandler;
}
}
Sadly, no luck here, too.
*Rename my favicon from favicon.ico to logo.ico, and just point all my pages' favicon links to that, instead.
Now, with this potential fix, I discovered a surprising result. When I curled my newly named icon.ico resource, I was served Spring's leaf icon. However, when I deleted the resource, I got 404. But then, when I put it back, I got the leaf again! In other words, Spring Boot was happy to answer 404 when my static resource was missing, but when it was there, it would always answer with the leaf instead!
Incidentally, other static resources (PNGs, JPGs, etc.) in the same folder serve up just fine.
It was easy to imagine that there was some evil Spring Boot contributor laughing himself silly over this, as I pulled my hair out. :-)
I'm out of ideas. Anyone?
As a last resort, I may just abandon using an ICO file for my site icon, and use a PNG instead, but that comes at a cost (losing multi-resolution support), so I'd rather avoid that.
A: This is a spring boot feature:
Spring MVC auto-configuration
Spring Boot provides auto-configuration for Spring MVC that works well with most applications.
The auto-configuration adds the following features on top of Spring’s defaults:
*
*Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver
beans.
*Support for serving static resources, including support for
WebJars (see below).
*Automatic registration of Converter,
GenericConverter, Formatter beans.
*Support for HttpMessageConverters
(see below).
*Automatic registration of MessageCodesResolver (see
below).
*Static index.html support.
*Custom Favicon support.
*Automatic use of a ConfigurableWebBindingInitializer bean (see below).
You can find this document at: http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#boot-features-spring-mvc-auto-configuration
And, If you want to disable spring boot favicon, you can add this config to you yml or perperties files
spring.mvc.favicon.enabled=true # Enable resolution of favicon.ico.
Or, If you want change favicon to you own. try this:
@Configuration
public static class FaviconConfiguration {
@Bean
public SimpleUrlHandlerMapping faviconHandlerMapping() {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setOrder(Integer.MIN_VALUE);
mapping.setUrlMap(Collections.singletonMap("mylocation/favicon.ico",
faviconRequestHandler()));
return mapping;
}
}
And you can find more detail at: Spring Boot: Overriding favicon
UPDATE:
put favicon.ico to resources folder.
And, try it:
A: Why choose the hard way, when u can get the easy one?
just create a new link into ur <head> with:
<link rel="icon" type="image/png" href="images/fav.png" />
Copy and paste ur icon in src/main/resources/static/images/
Rename the file to whatever you want, just remember to change the link in the html too.
| |
doc_1609
|
private static NetSuiteService Service { get; set; } = new NetSuiteService();
private static void isOnline()
{
if (Service.applicationInfo != null) return;
Service.CookieContainer = new CookieContainer();
Service.applicationInfo = new ApplicationInfo();
var passport = new Passport();
passport.account = "aaa";
passport.email = "bbb";
var role = new RecordRef();
passport.password = "999";
try
{
var status = Service.login(passport).status;
if (!status.isSuccess)
{
Log.ErrorFormat("can't login to NetSuite - {0}", status.statusDetail);
Service.applicationInfo = null;
}
}
catch (Exception ex)
{
Log.Error("NetSuite login err", ex);
}
}
But sometimes my connection is time outed and I need to reconnect. In this situation I have exception while performing transaction.
Is it possible somehow to know was my session got timeout before making transaction?
A: The following code creates the login passport, which you can add to your service
_service = new NetSuiteService();
Passport passport = new Passport();
passport.account = _custSettings["login.acct"];
passport.email = _custSettings["login.email"];
passport.password = _custSettings["login.password"];
RecordRef role = new RecordRef();
role.internalId = _custSettings["login.roleId"];
passport.role = role;
_service.passport = passport;
You only need to set this once and can now make all your Web API calls, without timeouts. So rather than using the Service.login() method, the passport will be automatically used with each API call made.
I am reading the login details from a config file, but you can insert this however works in your application.
| |
doc_1610
|
<tr>
<td><%# Eval("name").ToString() %></td>
<td><%# Eval("ssn3").ToString() %></td>
<td><asp:Button ID="btnGeneratePDF" runat="server" Text="Generate PDF" CommandArgument='<%# Eval("name").ToString() + ", " + Eval("ssn3").ToString() %>' onclick="btnGeneratePDF_Click" /></td>
</tr>
In my code behind to evaluate the commandargument, I have a code like this:
protected void btnGeneratePDF_Click(object sender, CommandEventArgs e)
{
string[] ar = e.CommandArgument.ToString().Split(',');
MessageBox.Show(ar[0]);
MessageBox.Show(ar[1]);
this.writeData(ar[0], ar[1]);
}
public void writeData(string k, string c)
{
Conn = new SqlConnection(cString);
Conn.Open();
nameE = txtName.Text;
var pdfPath = Path.Combine(Server.MapPath("~/PDFTemplates/fw9.pdf"));
// Get the form fields for this PDF and fill them in!
var formFieldMap = PDFHelper.GetFormFieldNames(pdfPath);
formFieldMap["topmostSubform[0].Page1[0].f1_01_0_[0]"] = txtName.Text;
sqlCode = "SELECT * FROM [DB].[dbo].[TablePDFTest] WHERE [name] = '" + k + "' AND [ssn3] = '" + c + "'";
using (SqlCommand command = new SqlCommand(sqlCode, Conn))
{
command.CommandType = CommandType.Text;
using (reader = command.ExecuteReader())
{
if (reader.HasRows)
{
if (reader.Read())
{
formFieldMap["topmostSubform[0].Page1[0].f1_02_0_[0]"] = reader.GetValue(1).ToString();
formFieldMap["topmostSubform[0].Page1[0].f1_04_0_[0]"] = reader.GetValue(2).ToString();
formFieldMap["topmostSubform[0].Page1[0].f1_05_0_[0]"] = reader.GetValue(3).ToString();
formFieldMap["topmostSubform[0].Page1[0].f1_07_0_[0]"] = reader.GetValue(4).ToString();
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField1[0]"] = reader.GetValue(5).ToString();
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[0]"] = reader.GetValue(6).ToString();
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[1]"] = reader.GetValue(7).ToString();
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[2]"] = reader.GetValue(8).ToString();
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[3]"] = reader.GetValue(9).ToString();
}
}
}
}
// Requester's name and address (hard-coded)
formFieldMap["topmostSubform[0].Page1[0].f1_06_0_[0]"] = "Medical Group\n20 West Ave\nPurchase, NY 10001";
var pdfContents = PDFHelper.GeneratePDF(pdfPath, formFieldMap);
PDFHelper.ReturnPDF(pdfContents, "Completed-W9.pdf");
}
I am getting the following error:
Error 1 No overload for 'btnGeneratePDF_Click' matches delegate 'System.EventHandler' C:\Users\usrs\Documents\Visual Studio 2012\Projects\PDFForms\searchcreate.aspx 41
How can I resolve the error?
A: protected void btnGeneratePDF_Click(object sender, EventArgs e)
Change CommandEventArgs to EventArgs in click event
Try this
protected void btnGeneratePDF_Click(object sender, EventArgs e)
{
//Get the reference of the clicked button.
Button button = (sender as Button);
//Get the command argument
string commandArgument = button.CommandArgument;
}
A: You can use Command Name field to store second param or use ASP:HiddenField, CustomProperty ect
A: So, if you have this layout inside the Repeater control, here is how you should handle a command event.
<asp:Repeater runat="server" ID="Repeater1"
OnItemCommand="btnGeneratePDF_Click"
...
They way btnGeneratePDF_Click is implemented it should work as is, you do not need to adjust anything. However I do recommend renaming it properly, and using CommandName also - that will prove useful if you would like to add more commands inside the repeater later.
One more side note. Notice that Repeater's ItemCommand event actually uses RepeaterCommandEventArgs class, which is a subclass of CommandEventArgs. If you walk down the path above you might want to change this as well in your method signature.
A: You are trying to perform an command event into a click event.
The correct it should be:
<tr>
<td><%# Eval("name").ToString() %></td>
<td><%# Eval("ssn3").ToString() %></td>
<td><asp:Button ID="btnGeneratePDF" runat="server" Text="Generate PDF" CommandArgument='<%# Eval("name").ToString() + ", " + Eval("ssn3").ToString() %>' OnCommand="btnGeneratePDF_Command" /></td>
</tr>
When you create this new event, you will notice that the event parameter changes to CommandEventArgs.
The you can proceed with you code
| |
doc_1611
|
There are max 7 priorities and that needs to be divided by how many parts so example would be there are 4 parts with 4 priorities.. (in this sample code it creates the sales folder, then puts a folder underneath it called conveyors then puts 4 folders in the conveyors folder with a number ) id like that to put four different parts in four different folders based on that how many priorities)
tried diving priorities but that wont work as i cant understand how to store an array to do what im asking
powershell
$salesorder = read-host -prompt 'What is the customer name and salesorder number? (ex.. turnkey - 3335)'
$jobnumber = read-host -prompt 'what is the Plant folder plus job number? (ex... 930-12345)'
$foldername = $jobnumber + " - " + $salesorder
#$conveyornumber = read-host -prompt "what is the number for conveyors? " + " - "
$priority = read-host -prompt "how many priorities are there?"
##************************* setting variables for second level basic Folder Structure *********************************
$partpath = '\\wal-file\public\sullivan\sully_temp_part.ipt'
$layout = 'D0100 - Layout'
$footprint = 'D0101 - Footprint'
$equipment = 'D01xx - Equipment'
$Guarding = 'D85xx - Guarding'
$conveyor = 'D60xx - Conveyors'
$platform = 'D90xx - Platforms'
#*************************** creating new variables based on folder name stylings *************************************
$workdir = new-item -path "C:\vault_workspace\Temp_vault\wendt\" -name $foldername -itemtype 'directory' -force
$layoutdir = new-item -path $workdir -name $layout -itemtype 'directory'
$layoutfilename = $layoutdir -join '.ipt'
#*************************** setting work directory input **************************************************************
new-item -path $layoutdir -name "$salesorder.ipt" -itemtype "file"
$footprintdir = new-item -path $workdir -name $footprint -itemtype 'directory'
$conveyordir = new-item -path $workdir -name $conveyor -itemtype 'directory'
#looping statement to create multiple folders
$conveyorinput = read-host -prompt "how many conveyors need to be made?"
for ($i = 1; $i -le $conveyorinput; $i++){"{0:D2}" -f $number} { [system.io.directory]::CreateDirectory("$conveyordir\D51$I")}
start-sleep -seconds 5
#creating multiple files
$conveyorarray = Get-ChildItem $conveyordir | Where-Object {$_.PSChildname} | Foreach-Object {$_.Name}
foreach ($path in $conveyorarray) {copy-item -path $partpath -destination "$conveyordir\$path\$jobnumber-4-$path-DUmmy-A0.ipt "}
i tried a few things all with mixed results no here close to what im looking to d. i tried goodling it but i couldnt figure out a way to implement anything close to what im asking some form of If statement would probably do it, but where would i put it and how would it work?
Thanks for any help
A: This is just a suggestion, can you look at adding functions so your code is readable. I can't see what you want. Can you also pepper it with output if you need to see what is going on Write-Host. I don't know what a sully sample is or how it is related to this so my guess is it's a folder or an ipt file? I can't read the code code-readability as it doesn't convey what you intend to to as far as I can tell beyond creating directories? If you can leave out the 'sully sample' language and use widget I think we could understand it better. Such as I need 4 Widget files for 4 people to look at?
# powershell
$salesorder = read-host -prompt 'What is the customer name and salesorder number? (ex.. turnkey - 3335)'
$jobnumber = read-host -prompt 'what is the Plant folder plus job number? (ex... 930-12345)'
$foldername = $jobnumber + " - " + $salesorder
#$conveyornumber = read-host -prompt "what is the number for conveyors? " + " - "
$priority = read-host -prompt "how many priorities are there?"
##************************* setting variables for second level basic Folder Structure *********************************
# Dunno what this file is or how it got here?
$partpath = '\\wal-file\public\sullivan\sully_temp_part.ipt'
$layout = 'D0100 - Layout'
$footprint = 'D0101 - Footprint'
$equipment = 'D01xx - Equipment' #Are these meant to be numbers or x character?
$Guarding = 'D85xx - Guarding'
$conveyor = 'D60xx - Conveyors'
$platform = 'D90xx - Platforms'
#*************************** creating new variables based on folder name stylings *************************************
$folderArray = @() # of things you want to keep track of
function CreateNewFolder() {
param(
$path = "C:\vault_workspace\Temp_vault\wendt\",
$name = $foldername,
[switch] $force
)
$newDirectory = new-item -path $path -name $name -itemtype 'directory' -force:$force
Write-Host "Adding $name to FolderArray"
$folderArray.Add($newDirectory)
return $newDirectory
}
$workdir = CreateNewFolder -path "C:\vault_workspace\Temp_vault\wendt\" -name $foldername -force
#$workdir = new-item -path "C:\vault_workspace\Temp_vault\wendt\" -name $foldername -itemtype 'directory' -force
$layoutdir = CreateNewFolder -path $workdir -name $layout
#$layoutdir = new-item -path $workdir -name $layout -itemtype 'directory'
$layoutfilename = $layoutdir -join '.ipt' # Why are we joining the directory to ipt?
#*************************** setting work directory input **************************************************************
new-item -path $layoutdir -name "$salesorder.ipt" -itemtype "file"
#$footprintdir = new-item -path $workdir -name $footprint -itemtype 'directory'
$footprintdir = CreateNewFolder -path $workdir -name $footprint
$conveyordir = new-item -path $workdir -name $conveyor -itemtype 'directory'
#looping statement to create multiple folders
$conveyorinput = read-host -prompt "how many conveyors need to be made?"
for ($i = 1; $i -le $conveyorinput; $i++){
# This just gets printed out?
"{0:D2}" -f $number
}
{
[system.io.directory]::CreateDirectory("$conveyordir\D51$I")
}
start-sleep -seconds 5
#creating multiple files
$conveyorarray = Get-ChildItem $conveyordir | Where-Object {
$_.PSChildname
} | Foreach-Object {
@{
Name = $_.Name
FullName = $_.FullName
}
}
foreach ($path in $conveyorarray) {
$name = $_.Name
$fullName = $_.Name
$destination = '{0}\{1}\{2}-4-{3}-Dummy-A0.ipt' -f $conveyordir, $name, $jobnumber, $path
copy-item -path $fullName -destination $destination # "$conveyordir\$path\$jobnumber-4-$path-DUmmy-A0.ipt "
}
A: so i actually changed the suyntax around completely but i was able to do the following
$salesorder = read-host -prompt 'What is the customer name and salesorder number? (ex.. turnkey - 3335)'
$jobnumber = read-host -prompt 'what is the Plant folder plus job number? (ex... 930-12345)'
$topleveldir = new-item -path "C:\vault_workspace\Temp_vault\wendt\" -name "M$jobnumber - $salesorder" -ItemType 'directory'
$subfolders = "D0100 - Layout", "D0101 - Footprint", "D01xx - Equipment","D85xx - Guarding", "D60xx - Conveyors", "D90xx - Platforms", "D09XX - Chutes"
foreach($subfolder in $subfolders){new-item -path "$topleveldir" -name $subfolder -type directory }
#$partpath = '\\wal-file\public\sullivan\sully_temp_part.ipt'
#p1
$p1conveyorinput = read-host -prompt "how many p1 conveyors need to be made?"
for ($i = 1; $i -le $p1conveyorinput; $i++) {
$p1c = "{0:D2}" -f $i
[system.io.directory]::CreateDirectory("$topleveldir\D60xx - Conveyors\D61$p1c-p1")
copy-item -path "\\wal-file\public\sullivan\sully_temp_part.ipt" -destination "$topleveldir\D60xx - Conveyors\D61$p1c-p1\D61$p1c-p1-dummy.ipt" -force
}
start-sleep -seconds 1
the only issue i run into is how to loop back into that last statement
#p1
$p1conveyorinput = read-host -prompt "how many p1 conveyors need to be made?"
for ($i = 1; $i -le $p1conveyorinput; $i++) {
$p1c = "{0:D2}" -f $i
[system.io.directory]::CreateDirectory("$topleveldir\D60xx - Conveyors\D61$p1c-p1")
copy-item -path "\\wal-file\public\sullivan\sully_temp_part.ipt" -destination "$topleveldir\D60xx - Conveyors\D61$p1c-p1\D61$p1c-p1-dummy.ipt" -force
}
start-sleep -seconds 1
for as many priorities there are without copying and changing the variables (which im going to do for now because it functions)
| |
doc_1612
|
`Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) : `
The data, however, seem to be okay (data set attached below):
str(minimal)
'data.frame': 330 obs. of 2 variables:
$ swls : num 5.2 NaN 7 6 NaN NaN NaN NaN NaN NaN ...
$ exp.factor: Factor w/ 2 levels "erlebt","nicht erlebt": 1 1 1 1 2 2 2 2 NA 2 ...
There seems also to be enough variation in the data, so similar threads I found do not apply here:
table(minimal$exp.factor)
erlebt nicht erlebt
148 163
`
However, lm() still refuses to work:
lm(swls ~ exp.factor, data = minimal)
Fehler in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) :
Kontraste können nur auf Faktoren mit 2 oder mehr Stufen angewendet werden
The really strange is that lm() works as expected with other factors (e.g., sex)
Any ideas what goes wrong here?
The Dataset:
structure(list(swls = c(5.2, NaN, 7, 6, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
6.8, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, 7, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, 5.8, 2.6, NaN, NaN, NaN, NaN, NaN,
NaN, 5.4, NaN, 6.4, NaN, NaN, NaN, NaN, NaN, NaN, 6.8, NaN, NaN,
NaN, NaN, NaN, NaN, 1.2, NaN, 6.2, 6.4, 5.2, NaN, 5.4, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, 4.6, NaN, NaN,
NaN, NaN, 5.8, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, 5, NaN,
NaN, NaN, 6.8, NaN, NaN, NaN, 6, 7, NaN, NaN, NaN, NaN, 6, NaN,
6.4, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, 6.8, NaN, NaN,
6.8, NaN, NaN, NaN, NaN, NaN, 5, 5.6, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, 3, NaN, NaN, NaN, NaN, NaN, NaN, 1.2, 4.2, NaN, 5.4,
NaN, NaN, NaN, NaN, NaN, NaN, 6.6, 5.8, NaN, NaN, NaN, 6.4, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, 2.8, NaN, 4, NaN, NaN, NaN,
6, 5, NaN, NaN, NaN, 4.4, NaN, 2, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, 2.2, NaN, NaN,
NaN, 7, NaN, NaN, NaN, 5.6, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, NaN, NaN, 6.2, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
5, NaN, NaN, 5.2, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN,
NaN, 5.8, NaN, NaN, 3.6, 5.6, NaN, NaN, 2.8, NaN, NaN, NaN, 6.2,
NaN, NaN, NaN, NaN, NaN, NaN, NaN, 5.8, 6.2, NaN, NaN, 5, 6.2,
NaN, NaN, NaN, NaN, NaN, NaN, 4.8, NaN, NaN, NaN, NaN, 4.8, NaN,
NaN, NaN, NaN, NaN, NaN, 4.4, NaN, NaN, 3, 5.2, NaN, 3.8, NaN,
NaN, NaN, NaN, 3, NaN, NaN, NaN, NaN, 1.6, NaN, NaN, 6.6, NaN,
NaN, NaN, NaN, NaN, NaN, NaN, NaN), exp.factor = structure(c(1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, NA, 2L, 2L, NA, 2L, 2L, NA, 2L, 1L,
2L, 2L, 2L, NA, 2L, 1L, NA, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 2L,
1L, 1L, NA, NA, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, NA, 2L, 1L,
1L, 2L, 1L, 2L, 2L, 2L, 1L, 2L, NA, 1L, 1L, 1L, 2L, 2L, 1L, 2L,
1L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 2L, 2L, NA, 1L, 2L,
2L, 2L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 2L, 1L, 1L, 2L, 2L, 2L, 2L,
1L, 2L, 1L, 2L, NA, 2L, 1L, NA, 1L, 1L, 1L, 2L, 2L, NA, 1L, 2L,
1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L,
1L, 1L, NA, 1L, 2L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 1L,
1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L,
2L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 2L, 1L, 1L, 1L, 2L, 2L,
1L, NA, 2L, 2L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 1L,
1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 2L, 1L, 1L, 2L, 2L,
2L, 2L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, NA, 2L, 2L, 1L,
2L, NA, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 2L, 1L,
1L, 1L, 2L, 2L, 1L, 1L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
1L, 2L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 2L, 2L, 2L, 1L, 2L, 1L,
NA, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L,
1L, 1L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 2L, NA, 1L, 2L, 1L, 1L, 1L,
1L, 1L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L,
1L, 2L, 2L, 1L, 2L, 2L, 2L, 2L, 2L), .Label = c("erlebt", "nicht erlebt"
), class = "factor")), .Names = c("swls", "exp.factor"), row.names = c(7L,
9L, 19L, 36L, 50L, 63L, 67L, 75L, 84L, 85L, 94L, 100L, 109L,
122L, 128L, 135L, 137L, 145L, 156L, 158L, 163L, 182L, 188L, 198L,
204L, 213L, 221L, 240L, 251L, 254L, 258L, 261L, 271L, 284L, 286L,
295L, 308L, 309L, 313L, 319L, 334L, 340L, 344L, 351L, 354L, 365L,
372L, 382L, 385L, 391L, 398L, 404L, 427L, 431L, 435L, 438L, 441L,
452L, 468L, 469L, 474L, 483L, 486L, 493L, 502L, 508L, 513L, 519L,
524L, 528L, 537L, 543L, 546L, 557L, 572L, 578L, 591L, 606L, 611L,
613L, 624L, 633L, 640L, 642L, 651L, 662L, 667L, 672L, 673L, 696L,
703L, 709L, 718L, 722L, 732L, 735L, 747L, 749L, 753L, 770L, 780L,
787L, 799L, 801L, 812L, 818L, 825L, 838L, 864L, 874L, 887L, 896L,
897L, 906L, 909L, 920L, 923L, 929L, 944L, 959L, 964L, 973L, 978L,
986L, 991L, 996L, 1001L, 1008L, 1014L, 1017L, 1033L, 1040L, 1046L,
1067L, 1075L, 1085L, 1090L, 1100L, 1102L, 1113L, 1144L, 1145L,
1150L, 1155L, 1158L, 1165L, 1175L, 1180L, 1189L, 1196L, 1198L,
1203L, 1212L, 1217L, 1230L, 1235L, 1257L, 1264L, 1266L, 1279L,
1285L, 1290L, 1299L, 1308L, 1320L, 1331L, 1338L, 1345L, 1350L,
1366L, 1376L, 1381L, 1400L, 1403L, 1406L, 1409L, 1419L, 1424L,
1456L, 1462L, 1467L, 1469L, 1490L, 1499L, 1501L, 1509L, 1515L,
1518L, 1524L, 1531L, 1533L, 1538L, 1560L, 1571L, 1573L, 1578L,
1587L, 1600L, 1602L, 1624L, 1626L, 1631L, 1637L, 1646L, 1656L,
1661L, 1667L, 1677L, 1683L, 1692L, 1694L, 1699L, 1705L, 1712L,
1714L, 1726L, 1739L, 1741L, 1750L, 1763L, 1768L, 1780L, 1795L,
1811L, 1816L, 1821L, 1830L, 1864L, 1869L, 1883L, 1887L, 1891L,
1904L, 1914L, 1917L, 1928L, 1934L, 1939L, 1941L, 1948L, 1950L,
1961L, 1969L, 1975L, 1982L, 1992L, 1998L, 2004L, 2019L, 2025L,
2040L, 2041L, 2046L, 2051L, 2068L, 2083L, 2085L, 2090L, 2098L,
2103L, 2109L, 2116L, 2124L, 2131L, 2133L, 2138L, 2144L, 2154L,
2160L, 2161L, 2183L, 2188L, 2190L, 2203L, 2218L, 2221L, 2229L,
2234L, 2243L, 2252L, 2262L, 2265L, 2275L, 2280L, 2282L, 2286L,
2289L, 2299L, 2308L, 2309L, 2319L, 2332L, 2335L, 2350L, 2353L,
2360L, 2363L, 2366L, 2369L, 2376L, 2401L, 2406L, 2415L, 2426L,
2429L, 2436L, 2447L, 2453L, 2459L, 2476L, 2478L, 2486L, 2492L,
2499L, 2501L, 2511L, 2517L, 2522L, 2528L, 2541L, 2547L, 2552L,
2554L, 2557L, 2566L, 2580L, 2587L, 2594L, 2603L, 2608L), class = "data.frame")
And my SessionInfo():
R version 3.1.0 (2014-04-10)
Platform: x86_64-pc-linux-gnu (64-bit)
locale:
[1] LC_CTYPE=de_DE.UTF-8 LC_NUMERIC=C LC_TIME=de_DE.UTF-8 LC_COLLATE=de_DE.UTF-8 LC_MONETARY=de_DE.UTF-8 LC_MESSAGES=de_DE.UTF-8
[7] LC_PAPER=de_DE.UTF-8 LC_NAME=C LC_ADDRESS=C LC_TELEPHONE=C LC_MEASUREMENT=de_DE.UTF-8 LC_IDENTIFICATION=C
attached base packages:
[1] splines grid stats graphics grDevices utils datasets methods base
other attached packages:
[1] foreign_0.8-61 lavaan_0.5-15 plyr_1.8.1 xtable_1.7-3 Hmisc_3.14-4 Formula_1.1-1 survival_2.37-7 lattice_0.20-29 Lambda4_3.0 MBESS_3.3.3
loaded via a namespace (and not attached):
[1] cluster_1.15.2 latticeExtra_0.6-26 MASS_7.3-32 mnormt_1.4-7 pbivnorm_0.5-1 quadprog_1.5-5 RColorBrewer_1.0-5 Rcpp_0.11.1
[9] stats4_3.1.0 tools_3.1.0
A: The problem is that once the NA values are omitted from the data set, there aren't any "nicht erlebt" observations left:
summary(na.omit(minimal))
swls exp.factor
Min. :1.200 erlebt :64
1st Qu.:4.400 nicht erlebt: 0
Median :5.500
Mean :5.119
3rd Qu.:6.200
Max. :7.000
So lm is going to have trouble fitting a model to a factor with only one (remaining) level ...
You can also deduce this by looking at the cross-tabulation of exp.factor and is.na() of the response ...
with(minimal,table(exp.factor,is.na(swls)))
exp.factor FALSE TRUE
erlebt 64 84
nicht erlebt 0 163
| |
doc_1613
|
[PHP] Here it is some sample code:
<?
if (notRegistered($_GET['user'])) {
// Throw 404 Error
}
?>
Thanks in advance.
A: HTTP reports the status code via the headers. Use the header() function in PHP to set the status code:
if (notRegistered($_GET['user'])) {
header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
exit(1);
}
Also you may want to send an error page to the browser:
if (notRegistered($_GET['user'])) {
header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
readfile('path/to/error404.html');
exit(1);
}
$_SERVER\['SERVER_PROTOCOL'\] will contain HTTP/1.0 or HTTP/1.1.
| |
doc_1614
|
So the idea would look like:
*
*User starts the program
*ClickOnce update installs the update
*ClickOnce update opens my updater.exe file that will update the database
*Everything is done
*Program starts again
A: Dude, you could really do with providing more information... what is this updater.exe? How does the ClickOnce update overwrite everything in your database?
I don't think that you can tell the ClickOnce update functionality to run an executable as part of the update, but you can reference your updater.exe in the Application Files window.
Startup Project Properties > Publish Tab > Application Files Button
Set your Publish Status column to Include (Auto), Download Group column to (Required) and hash column to Include.
Doing this will ensure that the latest version of your updater.exe file is installed to your installation directory. From there, you can access and run your updater.exe file from your ClickOnce application.
| |
doc_1615
|
let's say, I have a lowdb database name 'account with the following record:
"account": [
{
"name": "bill",
"email": "[email protected]",
"balance": "500",
}
]
I only want to return the value of balance on the screen. I am using javascript as front-end.
When I sue the command below, it returns the complete record, but I only want a specific field:
console.log(db.get('account').find({email: '[email protected]'}).value());
A: You should be able to do that in lowdb directly with:
console.log(db.get('account.balance').find({email: '[email protected]'}).value());
This is possible because lowdb gives you access to all the loadash api, and that way of calling get is given by loadash:
loadash get method
Or simply access that prop in JS from the returning obj:
console.log(db.get('account').find({email: '[email protected]'}).value().balance);
A: Assuming that you receive an array of records - with only a single element in it - you can modify your statement to
console.log(db.get('account').find({email: '[email protected]'}).value()[0].balance);
| |
doc_1616
|
Thanks in advance.
A: Make sure that your extension has sufficient permissions, then make an AJAX request, then process CSV using some JavaScript CSV library or a regex.
Everything is in the documentation. You may also find relevant examples here.
| |
doc_1617
|
When I run .libPaths() I have the two libraries on the same line on one machine, while on the second machine they are dispalyed in two different lines:
.libPaths()
[1] "C:/Users/.../R/win-library/3.6" "C:/Program Files/R/R-3.6.1/library"
.libPaths()
[1] "C:/Users/.../R/win-library/3.6"
[2] "C:/Program Files/R/R-3.6.1/library"
I do not get what is the practical implication of this when I install packages, and most of all why do I get this differences in these two cases. I'd like to know what I may have done to cause this and whether one situation is preferable.
Thank you
| |
doc_1618
|
The mainactivity.xml
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:fitsSystemWindows="true"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout android:layout_height="wrap_content"
android:layout_width="match_parent" android:theme="@style/AppTheme.AppBarOverlay"
android:fitsSystemWindows="true">
<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/htab_collapse_toolbar"
android:layout_width="match_parent"
android:layout_height="256dp"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorAccent"
app:layout_collapseMode="parallax">
<com.facebook.drawee.view.SimpleDraweeView
android:id="@+id/image_view"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:fitsSystemWindows="true"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="3"
android:layout_gravity="bottom"
android:paddingBottom="16dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Followers"
android:textAlignment="center"
android:textAppearance="?android:attr/textAppearanceLarge"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Points"
android:textAlignment="center"
android:textAppearance="?android:attr/textAppearanceLarge"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Following"
android:textAlignment="center"
android:textAppearance="?android:attr/textAppearanceLarge"/>
</LinearLayout>
</FrameLayout>
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="104dp"
android:gravity="top"
android:minHeight="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:titleMarginTop="13dp" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
<android.support.design.widget.FloatingActionButton android:id="@+id/fab"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="bottom|end" android:layout_margin="@dimen/fab_margin"
android:src="@android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
The java code-
public class MainActivity extends AppCompatActivity {
ListView listView;
String[] strings={"Something","Everything","Nothing","Ok","Maybe","Whatever","Does it matter","Mybe again","Nothing","Nothing","Nothing","Nothing"};
ArrayAdapter<String> adapter;
com.facebook.drawee.view.SimpleDraweeView image;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
image= (SimpleDraweeView)findViewById(R.id.image_view);
image.setImageURI(Uri.parse("https://www.google.co.in/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"));
listView= (ListView) findViewById(R.id.list_view);
adapter=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,strings);
listView.setAdapter(adapter);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
}
My gradle dependency-
compile 'com.android.support:design:23.1.0'
A: This is because ListView does not support the NestedScrollingChild interface, which is required to deliver the scroll events that AppBarLayout and others rely on to manage their positioning.
The simplest option is to switch your usage from ListView to RecyclerView—which already implements the necessary interfaces. A more complicated choice would be to attempt to extend ListView and implement NestedScrollingChild from the support library (docs).
| |
doc_1619
|
Code:
class MapScreen extends StatefulWidget {
const MapScreen({Key? key}) : super(key: key);
@override
State<MapScreen> createState() => _MapScreenState();
}
class _MapScreenState extends State<MapScreen> {
var markers = [];
late BitmapDescriptor mapMarker;
late GoogleMapController mapController;
static final CameraPosition initicalCameraPosition = CameraPosition(
target: LatLng(31.446893146741793, 74.27705705165864),
zoom: 14.4746,
);
@override
initState() {
super.initState();
setCustomMarker();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: backButton(),
backgroundColor: Colors.blue,
elevation: 0,
title: Center(
child: Text(
'Profile ',
style: TextStyle(color: Colors.white),
),
),
),
body: GoogleMap(
initialCameraPosition: initicalCameraPosition,
onMapCreated: onMapCreate,
zoomControlsEnabled: false,
// onTap: addMarker,
markers: Set<Marker>.from(markers),
),
);
}
void onMapCreate(GoogleMapController Controller) {
mapController = Controller;
animateCamera();
}
void animateCamera() {
mapController
.animateCamera(CameraUpdate.newCameraPosition(initicalCameraPosition));
}
addMarker() async {
Marker marker = Marker(
markerId: MarkerId('123'),
infoWindow: InfoWindow(
title: 'Muhammad Abdulreman', snippet: 'Blood Group: a+'),
icon: mapMarker,
position: LatLng(31.446893146741793, 74.27705705165864));
setState(() {
markers.add(marker);
});
}
setCustomMarker() {
mapMarker =
BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueAzure);
}
}
| |
doc_1620
|
Some of these apps are:
*
*Spyder
*Orange 3
*qtconsole
For all of them I obtain the same error when I execute them:
QGtkStyle could not resolve GTK. Make sure you have installed the proper libraries.
I have been trying to sort it for hours without success.
Any idea of how to fix this?
A: As a quick fix, add
export QT_STYLE_OVERRIDE=gtk2
to your .bashrc. Then your menus should at least have some text again.
A: This is not strictly speaking a GTK theming problem. Instead, this is because your Qt version is old. You need install qt=5.9.
In my case, that problem was caused because I use conda-forge channel and qt is in 5.6 version there. When explicitly install qt=5.9 from default channel the problem was solved without change .bashrc file.
A: I soleved it by upgrading and installing pkg-config
sudo apt upgrade && sudo apt install pkg-config
AND Jupyter series just works well!
| |
doc_1621
|
Now, all other threads need to wait until a particular thread change a state, for example: one status thread is monitoring system status, if it is ready, then tell other threads to start doing their work.
How do I implement this in Linux with C?
===sudo code===
static int status = 0;
static pthread_mutex_t status_mutex = PTHREAD_MUTEX_INITIALIZER;
void good_to_go( void )
{
pthread_mutex_lock( &status_mutex );
status = 1;
pthread_mutex_unlock( &status_mutex );
}
void stop_doingg( void )
{
pthread_mutex_lock( &status_mutex );
status = 0;
pthread_mutex_unlock( &status_mutex );
}
int is_good_to_go( void )
{
int temp;
pthread_mutex_lock( &status_mutex );
temp = status;
pthread_mutex_unlock( &status_mutex );
return temp;
}
then:
void *run_thread(void *ptr)
{
if (is_monitor_thread)
{
while (check_system_status() < 0)
{
sleep (1);
}
good_to_go();
}
else
{
//below while loop looks ugly.
//is there a way to get notified once "status" is changed to 1?
while( !is_light_turned_on() )
{
sleep (1);
}
}
A: You are looking for condition variables.
See the following man pages:
pthread_cond_init()
pthread_cond_signal()
pthread_cond_broadcast()
| |
doc_1622
|
class Orders {
static const List<String> columns = [
"ID",
"Items",
"Total",
"Status",
];
List<Map<int,String>> header = [
{0:"Order"},
{1:"Items"},
{2:"Total"},
{3:"Status"},
];
List<Map<String,dynamic>> rows = [
{"Number":390,"Items":6,"Total":450.00,"Status":"PENDING","Checked":true},
{"Number":391,"Items":19,"Total":3200.00,"Status":"PENDING","Checked":false},
{"Number":392,"Items":6,"Total":450.00,"Status":"PENDING","Checked":false},
{"Number":393,"Items":"-","Total":"-","Status":"-","Checked":false},
];
void setOrderHeader(newHeader){
header = newHeader;
}
void setOrderRows(newRows){
rows = newRows;
}
}
I then created a DataTable builder which i call on my orders_screen
import 'package:flutter/material.dart';
import 'package:one/models/orders.dart';
class DataTableBuilder extends StatefulWidget {
@override
_DataTableBuilderState createState() => _DataTableBuilderState();
}
class _DataTableBuilderState extends State<DataTableBuilder> {
List<Map<int, String>> get header => Orders().header;
List<Map<String, dynamic>> get rows => Orders().rows;
int sortColumnIndex = 0;
bool sort = true;
String rowKey = "Number";
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
int col = 0;
return SingleChildScrollView(
scrollDirection: Axis.vertical,
child: DataTable(
sortAscending: sort,
sortColumnIndex: sortColumnIndex,
showCheckboxColumn: true,
columns: header.map((e) => DataColumn(
label: _getStyledText(e[col++]!.toUpperCase(),14,Colors.black),
),
).toList(),
rows: rows.map(((rowData) => DataRow(
cells: <DataCell>[
DataCell(
_getStyledText(
rowData["Number"],
12,
Colors.black87,
),
), //Extracting from Map element the value
DataCell(
_getStyledText(
rowData["Items"],
16,
Colors.black87,
),
),
DataCell(
_getStyledText(
rowData["Total"],
12,
Colors.black87,
),
),
DataCell(
_getStyledText(
rowData["Status"],
12,
Colors.deepOrange,
),
// showEditIcon:true,
placeholder: true,
),
],
selected: rowData["Checked"],
onSelectChanged: (selected) {
if (selected==true) {
onSelectedRow(selected!, rowData,rows);
print(rows);
}
},
)),
).toList(),
),
);
}
Widget _getStyledText(dynamic rowText,double size, Color bgColor) {
return Text(
rowText.toString(),
style: TextStyle(
fontSize: size==0?14:size,
color: bgColor,
),
);
}
onSelectedRow(bool selected, Map<String,dynamic> rowData,List<Map<String,dynamic>> rows) async {
if (selected) {
for(int i = 0; i < rows.length; i++) {
if(rows[i]["Number"] == rowData["Number"]){
setState(() {
rows[i]["Checked"] = true;
Orders().setOrderRows(rows);
});
}
}
}
}
}
The issue I am having is with the onSelectChanged() and setState() methods - I would like to update the orders list to set the selected row to be checked or unchecked.
I am able to update the order data in the onSelectedRow() method but it does not seem to update my global rows variable or the setState() method is not updating the table.
| |
doc_1623
|
This is a useful property, chaining constructors from subclasses, creating a list of arguments to pass to a function (e.g., myclassmethod.apply(this, arguments)), etc.
However I've found V8 will not extend the length in the same way Mozilla reports of SpiderMonkey 1.5. (Not sure what the status is with other JavaScript engines, Opera, Rhino, etc.).
Is this actually an ECMA feature? Has Mozilla got it wrong in considering this a bug, or does V8 have a bug to fix?
[Update] I've found using V8 that the arguments.length property can be assigned to, and so effectively arguments can be extended (or set to whatever length you require otherwise). However JSLint does complain this is a bad assignment.
[Update] Some test code if anyone wants to try this in Opera, FF etc., create an instance of a subclass calling the constructor with one arg while adding an element to arguments in the subclass constructor and calling the superclass constructor, the superclass should report two arguments:
function MyClass() {
if (arguments.length) {
console.log("arguments.length === " + arguments.length);
console.log("arguments[0] === " + arguments[0]);
console.log("arguments[1] === " + arguments[1]);
}
}
function MySubClass() {
console.log(arguments.length);
//arguments.length = 2; // uncomment to test extending `length' property works
arguments[1] = 2;
MyClass.apply(this, arguments);
}
MySubClass.prototype = new MyClass();
new MySubClass(1);
[Update] JSLint actually complains when you make any kind of assignment to arguments by the looks (e.g., arguments[0] = "foo"). So maybe JSLint has some work to do here also.
A: Not sure if this is what you are looking for, but you can make the arguments object into a standard array:
var args = [].slice.call(arguments, 0);
[EDIT] so you could do:
myclassmethod.apply(this, [].slice.call(arguments, 0).push(newValue));
A: ECMA-262 10.1.8 says that the prototype of the arguments object is the Object prototype and that the arguments object is initialized in a certain way, using the phrase "initial value". So, it would seem like you could assign any of its properties to whatever you want. I'm not sure if that's the correct interpretation though.
A: OK, I think we can conclude on this one.
Running the above example code on FF, Comodo Dragon, Opera and IE (all current version, Windoze) they will all accept a change of the arguments.length property to resize the (as Mozilla phrases this, 'array-like') arguemnts object. None will increase the size by assigning a value as is usual for an array (i.e., arguments[arguments.length] = "new arg").
It seems the consensus of the javascript engines is that as an 'array-like' object arguments behaves like an array, but is otherwise inclined to throw a few surprises ;) Either way the interpretation of the ECMA standard appears to be on the face of it at least consistent across the board, and so the semantics are not really an issue (the whys and wherefores being the only remaining question but of historical interest only).
Neither MSDN nor Mozilla seem to have this documented (not sure where V8 or Opera hide their JS docs) - in a nutshell to conclude some documentation would definitely not go amiss. At which point I will bow out, however if someone could opportunistically drop the hint to the relevant parties at some point it is a useful technique to use once in a while.
Thanks for all who have taken the time to look at this question.
[Update] BishopZ has pointed out above that .apply will take an array of arguments anyway (this has slipped my mind since I last used it many years ago, and which solves my problem). However the 'array-like' arguments can still be used, and might even be preferable in some situations (easier for example to pop a value onto, or just to pass on arguments to a superclass). Thanks again for looking at the issue.
| |
doc_1624
|
A: CC is the executable of your C compiler. It could be something like powerpc-linux-gcc, but really that really depends on your cross compilation environment.
| |
doc_1625
|
Here's an example call:
PrintResult(
expected: "$A$1",
actual: RST.ExcelReference.FormatReferences("{{REF:1:0:1:0}}", false, 0, 0),
arguments: "RST.ExcelReference.FormatReferences(\"{{REF:1:0:1:0}}\", false, 0, 0)");
(Named arguments added for clarity.)
As you can imagine, synchronizing the actual call and the display of that call is a pain.
I know I can't examine argument values in Environment.StackTrace, only the method definition and line number. But in my case, I don't need actual argument values. I'm generally calling this method using literals as arguments, so all I need is the line of source code for the entry point into PrintResult() in the Stack Trace.
The source code seems to be available to ASP.NET somehow, as it appears when there is an unhandled exception. How can I access it?
A: Environment.StackTrace provides you with the file name and line number in each line of the stack trace. It is clearly formatted and should be easily parseable. From the documentation:
The StackTrace property formats the stack trace information for each
method call as follows:
"at FullClassName. MethodName (MethodParams) in FileName :line
LineNumber "
The literal "at" is preceded by three spaces, and the literals "in"
and ":line" are omitted if debug symbols are not available. The
placeholders, FullClassName, MethodName, MethodParms, FileName, and
LineNumber, are replaced by actual values defined as follows:
FullClassName The full name of the class, including the namespace.
MethodName The name of the method.
MethodParms The list of parameter type/name pairs. Each pair is
separated by a comma (","). This information is omitted if MethodName
takes zero parameters.
FileName The name of the source file where the MethodName method is
declared. This information is omitted if debug symbols are not
available.
LineNumber The number of the line in FileName that contains the source
code from MethodName for the instruction that is on the call stack.
This information is omitted if debug symbols are not available.
In the question you implied that Environment.StackTrace is not the answer to your question, but it seems like you should be able to parse out the source file name and line number, then go read that line from the file. What am I missing?
| |
doc_1626
|
The slider can be found at:
http://rastastation.com/rastaradio.html
The code appears as follows in the section:
<script type = "text/javascript">
function displayImage(image) {
document.getElementById("img").src = image;
}
function displayNextImage() {
x = (x == images.length - 1) ? 0 : x + 1;
displayImage(images[x]);
window.clearInterval(this.image);
}
function displayPreviousImage() {
x = (x <= 0) ? images.length - 1 : x - 1;
displayImage(images[x]);
window.clearInterval(this.image);
}
function startTimer() {
setInterval(displayNextImage, 9000);
}
var images = [], x = -1;
images[0] = "images/carousel_anthonyb2.png";
images[1] = "images/carousel_capleton2.png";
images[2] = "images/carousel_sizzla2.png";
images[3] = "images/carousel_earlsixteen.png";
images[4] = "images/carousel_norrisreid.png";
images[5] = "images/carousel_yamibolo2.png";
images[6] = "images/carousel_fantanmojah2.png";
images[7] = "images/carousel_natural_black2.png";
images[8] = "images/carousel_admiraltibet.png";
images[9] = "images/carousel_luciano.png";
</script>
I need the click event to reset the timeout and particularly set the Internal Variable.
As shown by W3Schools, it appears as follows:
window.clearInterval(intervalVariable)
How would I easily go about doing this.
The slider works and I am adding advanced functionality. This is where I am after 30 minutes of customizing it.
Tag as follows:
<div id="rgStateSLIDER">
<img id="img" src="images/carousel_start.png">
<div id="containerSliderControls">
<div class="buttonPrevious" onclick="displayPreviousImage()"></div>
<div class="buttonNext" onclick="displayNextImage()"></div>
</div>
Thanks...William
UI Developer - Basis Interactive Inc.
A: The "Internal Variable" (I think you mean interval variable) is returned by the call to setTimeout:
function startTimer() {
setInterval(displayNextImage, 9000);
}
but you don't assign it to anything, so it's lost. Given your current design, you should create a global called (say) timerInterval. Then have a new function clearTimer:
function clearTimer() {
// Only clear it if it's been set
if (timerInterval) {
clearInterval(timerInterval);
timerInterval = null;
}
}
And in any function that sets the interval, make sure you clear it first (otherwise you'll start multiple timers):
function startTimer() {
// Make sure there's no timer running
clearTimer();
// Keep the value
timerInterval = setInterval(displayNextImage, 9000);
}
And in the other functions, re–use the startTimer function:
function displayNextImage() {
x = ++x % 12;
displayImage(images[x]);
startTimer();
}
and do the same for the other functions, e.g.
function displayPreviousImage() {
x = (x || images.length) - 1;
displayImage(images[x]);
startTimer();
}
Untested, but you should get the idea.
You should look to contain the global variables in closures so that they remain private, particularly when you are using names that are easily confused with other variables and properties (e.g. document.images).
A: try this code, it may help you solving your problem.
<script type = "text/javascript">
function displayImage(image) {
document.getElementById("img").src = image;
}
function displayNextImage() {
x = (x == images.length - 1) ? 0 : x + 1;
clearInterval(timer);
displayImage(images[x]);
timer = setInterval( displayThisImage, 5000 );
}
function displayThisImage( ) {
x = (x == images.length - 1) ? 0 : x + 1;
displayImage(images[x]);
}
function displayPreviousImage() {
x = (x <= 0) ? images.length - 1 : x - 1;
clearInterval(timer);
displayImage(images[x]);
timer = setInterval( displayThisImage, 5000 );
}
function startTimer() {
timer = setInterval( displayThisImage, 5000 );
}
var images = [], x = -1;
var timer ;
images[0] = "http://rastastation.com/images/carousel_anthonyb2.png";
images[1] = "http://rastastation.com/images/carousel_capleton2.png";
images[2] = "http://rastastation.com/images/carousel_sizzla2.png";
images[3] = "http://rastastation.com/images/carousel_earlsixteen.png";
images[4] = "http://rastastation.com/images/carousel_norrisreid.png";
images[5] = "http://rastastation.com/images/carousel_yamibolo2.png";
images[6] = "http://rastastation.com/images/carousel_fantanmojah2.png";
images[7] = "http://rastastation.com/images/carousel_natural_black2.png";
images[8] = "http://rastastation.com/images/carousel_admiraltibet.png";
images[9] = "http://rastastation.com/images/carousel_luciano.png";
</script>
A: Try this code i used your code for sample
<script type = "text/javascript">
var timer = null;
function displayImage(image) {
document.getElementById("img").src = image;
}
function displayNextImage() {
x = (x == images.length - 1) ? 0 : x + 1;
displayImage(images[x]);
// window.clearInterval(this.image); // old code
window.clearInterval(timer); // new code
}
function displayPreviousImage() {
x = (x <= 0) ? images.length - 1 : x - 1;
displayImage(images[x]);
// window.clearInterval(this.image); // old code
window.clearInterval(timer); // new code
}
function startTimer() {
timer = setInterval(displayNextImage, 9000);
}
function stopTimer() {
clearInterval(timer);
}
var images = [], x = -1;
images[0] = "images/carousel_anthonyb2.png";
images[1] = "images/carousel_capleton2.png";
images[2] = "images/carousel_sizzla2.png";
images[3] = "images/carousel_earlsixteen.png";
images[4] = "images/carousel_norrisreid.png";
images[5] = "images/carousel_yamibolo2.png";
images[6] = "images/carousel_fantanmojah2.png";
images[7] = "images/carousel_natural_black2.png";
images[8] = "images/carousel_admiraltibet.png";
images[9] = "images/carousel_luciano.png";
| |
doc_1627
|
So how can I run the script in the background and keep using the terminal without terminating it?
Edit: I tried to use the '&' operator but it didn't work:
A: You can run your script in the background with:
python myscript.py &
If your script does output something you can suppress the output with:
python myscript.py 1>/dev/null 2>&1 &
Or save the output for later:
python myscript.py 1>myoutputfile 2>&1 &
# ...
less myoutputfile
Another alternative would be to use for example screen or tmux.
| |
doc_1628
|
permutInListN( +inputList, +lengthListResult, -ListResult),
example:
permutInListN([1,2,3],2,L).
? L=[1,2].
? L=[2,1].
? L=[1,3].
? L=[3,1].
? L=[2,3].
? L=[3,2].
Combinations of [1,2,3] in a list L with length 2.
with no repetitions maybe using setoff.
this is my code but it doesn't work at all , no generate all solutions
permutInListN(_, 0, []).
permutInListN([X|Xs], N, [X|Ys]) :- N1 is N-1, permutInListN(Xs,N1,Ys).
permutInListN([_|Xs], N, Y) :- N>0, permutInListN(Xs,N,Y).
?permutInListN([1,2,3],2,L).
L = [1, 2]
L = [1, 3]
L = [2, 3]
thanks in advance.
A: What you want is a combination followed by a permutation.
For combination:
comb(0,_,[]).
comb(N,[X|T],[X|Comb]) :-
N>0,
N1 is N-1,
comb(N1,T,Comb).
comb(N,[_|T],Comb) :-
N>0,
comb(N,T,Comb).
Example:
?- comb(2,[1,2,3],List).
List = [1, 2] ;
List = [1, 3] ;
List = [2, 3] ;
false.
For Permutation just use SWI-Prolog permutation/2 in library lists
:- use_module(library(lists)).
?- permutation([1,2],R).
R = [1, 2] ;
R = [2, 1] ;
false.
Putting them together
comb_perm(N,List,Result) :-
comb(N,List,Comb),
permutation(Comb,Result).
With your query
?- comb_perm(2,[1,2,3],R).
R = [1, 2] ;
R = [2, 1] ;
R = [1, 3] ;
R = [3, 1] ;
R = [2, 3] ;
R = [3, 2] ;
false.
Modified for your predicate
permutInListN(List,N,Result) :-
comb(N,List,Comb),
permutation(Comb,Result).
Example
?- permutInListN([1,2,3],2,R).
R = [1, 2] ;
R = [2, 1] ;
R = [1, 3] ;
R = [3, 1] ;
R = [2, 3] ;
R = [3, 2] ;
false.
A: Permutating the result
Your permutInListN/3 predicate basically takes N elements in an ordered way from the given list, but the order of the elements that are picked, is the same as the original order.
We can thus post-process this list, by finding all permutations of the selected elements, so something like:
permutInListN(L, N, R) :-
takeN(L, N, S),
permutation(S, R).
with takeN/3 almost equivalent to the predicate you defined:
takeN(_, 0, []).
takeN([X|Xs], N, [X|Ys]) :-
N > 0,
N1 is N-1,
takeN(Xs,N1,Ys).
takeN([_|Xs], N, Y) :-
N > 0,
takeN(Xs,N,Y).
permutation/3 [swi-doc] is a predicate from the lists library [swi-doc].
Using N select/3s
We can also solve the problem by N times using the select/3 predicate [swi-doc]. select(X, L, R) takes an element X from a list, and R is a list, without that element. We can thus recursively pass the list and each time remove an element, until we removed N elements, like:
permutInListN(_, 0, []).
permutInListN(L, N, [X|T]) :-
N > 0,
N1 is N-1,
select(X, L, R),
permutInListN(R, N1, T).
| |
doc_1629
|
I created a function, but I never do recursive before and I obviously doing it wrong :D
I manage to display the children of the parent I can, and the children of if but I can go further
The class already created :
class MenuElement {
public $id;
public $children = array();
public function __construct($id)
{
$this->id = $id;
}
public function addChild(MenuElement $menuElement)
{
array_push($this->children, $menuElement);
}
}
The creation of the elements in index.php :
$listRecursive1 = new ListRecursive(1);
$listRecursive11 = new ListRecursive(11);
$listRecursive12 = new ListRecursive(12);
$listRecursive121 = new ListRecursive(121);
$listRecursive122 = new ListRecursive(122);
$listRecursive123 = new ListRecursive(123);
$listRecursive1211 = new ListRecursive(1211);
$listRecursive121->addChild($listRecursive1211);
$listRecursive12->addChild($listRecursive121);
$listRecursive12->addChild($listRecursive122);
$listRecursive12->addChild($listRecursive123);
$listRecursive1->addChild($listRecursive11);
$listRecursive1->addChild($listRecursive12);
My function just bellow addChild :
public function createList()
{
$html = "";
foreach ($this->children as $child)
{
$html .= "<ul><li>" . $child->id;
//If the element have a child I create a new UL
if ($child->children) {
$html .= "<ul><li>" . $child->id;
$html .= "</li></ul>";
}
$html .= "</li></ul>";
}
//Return the result
return $html;
}
I want to display the list like this :
<ul>
<li>1
<ul>
<li>11</li>
<li>12
<ul>
<li>121
<ul>
<li>1211</li>
</ul>
</li>
<li>122</li>
<li>123</li>
</ul>
</li>
</ul>
</li>
</ul>
But this is what i got :
<ul>
<li>11</li>
</ul>
<ul>
<li>12
<ul>
<li>12</li>
</ul>
</li>
</ul>
EDIT :
I try this :
public function createList()
{
$html = "";
foreach ($this->children as $child) {
$html .= "<ul><li>" . $child->id;
//If the element have a child I create a new UL
if ($child->children) {
echo "<ul>";
$child->createList();
echo "</ul>";
}
$html .= "</li></ul>";
}
//Return the result
echo $html;
}
And I got
*
*
*
*1211
*
*121
*
*122
*
*123
*
*11
*
*12
A: Almost there! You just need to make a recursive call to createList() in the first version of your code, appending its result to $html.
public function createList()
{
$html = "";
foreach ($this->children as $child) {
$html .= "<ul><li>" . $child->id;
if ($child->children) {
$html .= $child->createList();
}
$html .= "</li></ul>";
}
return $html;
}
| |
doc_1630
|
col1 col2 col3 col4
{"id": "123", "name": "xx"} {"id": "234", "name": "xy"} 123 11-12-2020
{"id": "345", "name": "fx"} {"id": "534", "name": "ry"}
{"id": "545", "name": "dx"} {"id": "734", "name": "hy"}
{"id": "823", "name": "ox"} {"id": "934", "name": "cy"} 223 12-12-2020
{"id": "923", "name": "ox"} {"id": "834", "name": "vy"}
From the above table I just want id from col1 and col2 and one row should have only one id. I want to create another column to distinguish which id it is. And col3 and col4 values will be duplicated row wise, so the output should look like,
id type col3 col4
123 col1 123 11-12-2020
234 col2 123 11-12-2020
345 col1 123 11-12-2020
534 col2 123 11-12-2020
545 col1 123 11-12-2020
734 col2 123 11-12-2020
823 col1 223 12-12-2020
934 col2 223 12-12-2020
923 col1 223 12-12-2020
834 col1 223 12-12-2020
I am using bigqyery to do this, I have tried string manipulation and pivot for it but I am not getting desired output. Looking for some nice way to do it
A: Try this:
with mydata as (
select '{"id": "123", "name": "xx"}' as col1, '{"id": "234", "name": "xy"}' as col2, 123 as col3, '11-12-2020' as col4 union all
select '{"id": "345", "name": "fx"}', '{"id": "534", "name": "ry"}', NULL, NULL union all
select '{"id": "545", "name": "dx"}', '{"id": "734", "name": "hy"}', NULL, NULL union all
select '{"id": "823", "name": "ox"}', '{"id": "934", "name": "cy"}', 223, '12-12-2020' union all
select '{"id": "923", "name": "ox"}', '{"id": "834", "name": "vy"}', NULL, NULL
),
data_with_ordered_column as (select *, row_number() over () as orderby from mydata)
select
json_value(col1, '$.id') as id,
last_value(col3 ignore nulls) OVER (ORDER BY orderby) as col3,
last_value(col4 ignore nulls) OVER (ORDER BY orderby) as col4
from data_with_ordered_column
union all
select
json_value(col2, '$.id') as id,
last_value(col3 ignore nulls) OVER (ORDER BY orderby) as col3,
last_value(col4 ignore nulls) OVER (ORDER BY orderby) as col4
from data_with_ordered_column
order by col4, id
Filling up the missing values in col3 and col4 requires a separate column to order by. Skip the data_with_ordered_column step and use that column instead if you have one in your table, because row_number() produces non-deterministic results.
| |
doc_1631
|
icecast.xml (DEFAUL)
<icecast>
<!-- location and admin are two arbitrary strings that are e.g. visible
on the server info page of the icecast web interface
(server_version.xsl). -->
<location>Earth</location>
<admin>icemaster@localhost</admin>
<!-- IMPORTANT!
Especially for inexperienced users:
Start out by ONLY changing all passwords and restarting Icecast.
For detailed setup instructions please refer to the documentation.
It's also available here: http://icecast.org/docs/
-->
<limits>
<clients>100</clients>
<sources>2</sources>
<queue-size>524288</queue-size>
<client-timeout>30</client-timeout>
<header-timeout>15</header-timeout>
<source-timeout>10</source-timeout>
<!-- If enabled, this will provide a burst of data when a client
first connects, thereby significantly reducing the startup
time for listeners that do substantial buffering. However,
it also significantly increases latency between the source
client and listening client. For low-latency setups, you
might want to disable this. -->
<burst-on-connect>1</burst-on-connect>
<!-- same as burst-on-connect, but this allows for being more
specific on how much to burst. Most people won't need to
change from the default 64k. Applies to all mountpoints -->
<burst-size>65535</burst-size>
</limits>
<authentication>
<!-- Sources log in with username 'source' -->
<source-password>hackme</source-password>
<!-- Relays log in with username 'relay' -->
<relay-password>hackme</relay-password>
<!-- Admin logs in with the username given below -->
<admin-user>admin</admin-user>
<admin-password>hackme</admin-password>
</authentication>
<!-- set the mountpoint for a shoutcast source to use, the default if not
specified is /stream but you can change it here if an alternative is
wanted or an extension is required
<shoutcast-mount>/live.nsv</shoutcast-mount>
-->
<!-- Uncomment this if you want directory listings -->
<!--
<directory>
<yp-url-timeout>15</yp-url-timeout>
<yp-url>http://dir.xiph.org/cgi-bin/yp-cgi</yp-url>
</directory>
-->
<!-- This is the hostname other people will use to connect to your server.
It affects mainly the urls generated by Icecast for playlists and yp
listings. You MUST configure it properly for YP listings to work!
-->
<hostname>localhost</hostname>
<!-- You may have multiple <listener> elements -->
<listen-socket>
<port>80</port>
<!-- <bind-address>127.0.0.1</bind-address> -->
<!-- <shoutcast-mount>/stream</shoutcast-mount> -->
</listen-socket>
<!--
<listen-socket>
<port>8080</port>
</listen-socket>
-->
<!--
<listen-socket>
<port>8443</port>
<ssl>1</ssl>
</listen-socket>
-->
<!-- Global header settings
Headers defined here will be returned for every HTTP request to Icecast.
The ACAO header makes Icecast public content/API by default
This will make streams easier embeddable (some HTML5 functionality needs it).
Also it allows direct access to e.g. /status-json.xsl from other sites.
If you don't want this, comment out the following line or read up on CORS.
-->
<http-headers>
<header name="Access-Control-Allow-Origin" value="*" />
</http-headers>
<!-- Relaying
You don't need this if you only have one server.
Please refer to the config for a detailed explanation.
-->
<!--<master-server>127.0.0.1</master-server>-->
<!--<master-server-port>8001</master-server-port>-->
<!--<master-update-interval>120</master-update-interval>-->
<!--<master-password>hackme</master-password>-->
<!-- setting this makes all relays on-demand unless overridden, this is
useful for master relays which do not have <relay> definitions here.
The default is 0 -->
<!--<relays-on-demand>1</relays-on-demand>-->
<!--
<relay>
<server>127.0.0.1</server>
<port>8080</port>
<mount>/example.ogg</mount>
<local-mount>/different.ogg</local-mount>
<on-demand>0</on-demand>
<relay-shoutcast-metadata>0</relay-shoutcast-metadata>
</relay>
-->
<!-- Mountpoints
Only define <mount> sections if you want to use advanced options,
like alternative usernames or passwords
-->
<!-- Default settings for all mounts that don't have a specific <mount type="normal">.
-->
<!--
<mount type="default">
<public>0</public>
<intro>/server-wide-intro.ogg</intro>
<max-listener-duration>3600</max-listener-duration>
<authentication type="url">
<option name="mount_add" value="http://auth.example.org/stream_start.php"/>
</authentication>
<http-headers>
<header name="foo" value="bar" />
</http-headers>
</mount>
-->
<!-- Normal mounts -->
<!--
<mount type="normal">
<mount-name>/example-complex.ogg</mount-name>
<username>othersource</username>
<password>hackmemore</password>
<max-listeners>1</max-listeners>
<dump-file>/tmp/dump-example1.ogg</dump-file>
<burst-size>65536</burst-size>
<fallback-mount>/example2.ogg</fallback-mount>
<fallback-override>1</fallback-override>
<fallback-when-full>1</fallback-when-full>
<intro>/example_intro.ogg</intro>
<hidden>1</hidden>
<public>1</public>
<authentication type="htpasswd">
<option name="filename" value="myauth"/>
<option name="allow_duplicate_users" value="0"/>
</authentication>
<http-headers>
<header name="Access-Control-Allow-Origin" value="http://webplayer.example.org" />
<header name="baz" value="quux" />
</http-headers>
<on-connect>/home/icecast/bin/stream-start</on-connect>
<on-disconnect>/home/icecast/bin/stream-stop</on-disconnect>
</mount>
-->
<!--
<mount type="normal">
<mount-name>/auth_example.ogg</mount-name>
<authentication type="url">
<option name="mount_add" value="http://myauthserver.net/notify_mount.php"/>
<option name="mount_remove" value="http://myauthserver.net/notify_mount.php"/>
<option name="listener_add" value="http://myauthserver.net/notify_listener.php"/>
<option name="listener_remove" value="http://myauthserver.net/notify_listener.php"/>
<option name="headers" value="x-pragma,x-token"/>
<option name="header_prefix" value="ClientHeader."/>
</authentication>
</mount>
-->
<fileserve>1</fileserve>
<paths>
<!-- basedir is only used if chroot is enabled -->
<basedir>/usr/share/icecast2</basedir>
<!-- Note that if <chroot> is turned on below, these paths must both
be relative to the new root, not the original root -->
<logdir>/var/log/icecast2</logdir>
<webroot>/usr/share/icecast2/web</webroot>
<adminroot>/usr/share/icecast2/admin</adminroot>
<!-- <pidfile>/usr/share/icecast2/icecast.pid</pidfile> -->
<!-- Aliases: treat requests for 'source' path as being for 'dest' path
May be made specific to a port or bound address using the "port"
and "bind-address" attributes.
-->
<!--
<alias source="/foo" destination="/bar"/>
-->
<!-- Aliases: can also be used for simple redirections as well,
this example will redirect all requests for http://server:port/ to
the status page
-->
<alias source="/" destination="/status.xsl"/>
<!-- The certificate file needs to contain both public and private part.
Both should be PEM encoded.
<ssl-certificate>/usr/share/icecast2/icecast.pem</ssl-certificate>
-->
</paths>
<logging>
<accesslog>access.log</accesslog>
<errorlog>error.log</errorlog>
<!-- <playlistlog>playlist.log</playlistlog> -->
<loglevel>3</loglevel> <!-- 4 Debug, 3 Info, 2 Warn, 1 Error -->
<logsize>10000</logsize> <!-- Max size of a logfile -->
<!-- If logarchive is enabled (1), then when logsize is reached
the logfile will be moved to [error|access|playlist].log.DATESTAMP,
otherwise it will be moved to [error|access|playlist].log.old.
Default is non-archive mode (i.e. overwrite)
-->
<!-- <logarchive>1</logarchive> -->
</logging>
<security>
<chroot>0</chroot>
<!--
<changeowner>
<user>nobody</user>
<group>nogroup</group>
</changeowner>
-->
</security>
</icecast>
And here is what I changed to attempt to make it work on port 80.
<icecast>
<!-- location and admin are two arbitrary strings that are e.g. visible
on the server info page of the icecast web interface
(server_version.xsl). -->
<location>Earth</location>
<admin>icemaster@localhost</admin>
<!-- IMPORTANT!
Especially for inexperienced users:
Start out by ONLY changing all passwords and restarting Icecast.
For detailed setup instructions please refer to the documentation.
It's also available here: http://icecast.org/docs/
-->
<limits>
<clients>100</clients>
<sources>2</sources>
<queue-size>524288</queue-size>
<client-timeout>30</client-timeout>
<header-timeout>15</header-timeout>
<source-timeout>10</source-timeout>
<!-- If enabled, this will provide a burst of data when a client
first connects, thereby significantly reducing the startup
time for listeners that do substantial buffering. However,
it also significantly increases latency between the source
client and listening client. For low-latency setups, you
might want to disable this. -->
<burst-on-connect>1</burst-on-connect>
<!-- same as burst-on-connect, but this allows for being more
specific on how much to burst. Most people won't need to
change from the default 64k. Applies to all mountpoints -->
<burst-size>65535</burst-size>
</limits>
<authentication>
<!-- Sources log in with username 'source' -->
<source-password>hackme</source-password>
<!-- Relays log in with username 'relay' -->
<relay-password>hackme</relay-password>
<!-- Admin logs in with the username given below -->
<admin-user>admin</admin-user>
<admin-password>hackme</admin-password>
</authentication>
<!-- set the mountpoint for a shoutcast source to use, the default if not
specified is /stream but you can change it here if an alternative is
wanted or an extension is required
<shoutcast-mount>/live.nsv</shoutcast-mount>
-->
<!-- Uncomment this if you want directory listings -->
<!--
<directory>
<yp-url-timeout>15</yp-url-timeout>
<yp-url>http://dir.xiph.org/cgi-bin/yp-cgi</yp-url>
</directory>
-->
<!-- This is the hostname other people will use to connect to your server.
It affects mainly the urls generated by Icecast for playlists and yp
listings. You MUST configure it properly for YP listings to work!
-->
<hostname>localhost</hostname>
<!-- You may have multiple <listener> elements -->
<listen-socket>
<port>8000</port>
<!-- <bind-address>127.0.0.1</bind-address> -->
<!-- <shoutcast-mount>/stream</shoutcast-mount> -->
</listen-socket>
<!--
<listen-socket>
<port>8080</port>
</listen-socket>
-->
<!--
<listen-socket>
<port>8443</port>
<ssl>1</ssl>
</listen-socket>
-->
<!-- Global header settings
Headers defined here will be returned for every HTTP request to Icecast.
The ACAO header makes Icecast public content/API by default
This will make streams easier embeddable (some HTML5 functionality needs it).
Also it allows direct access to e.g. /status-json.xsl from other sites.
If you don't want this, comment out the following line or read up on CORS.
-->
<http-headers>
<header name="Access-Control-Allow-Origin" value="*" />
</http-headers>
<!-- Relaying
You don't need this if you only have one server.
Please refer to the config for a detailed explanation.
-->
<!--<master-server>127.0.0.1</master-server>-->
<!--<master-server-port>8001</master-server-port>-->
<!--<master-update-interval>120</master-update-interval>-->
<!--<master-password>hackme</master-password>-->
<!-- setting this makes all relays on-demand unless overridden, this is
useful for master relays which do not have <relay> definitions here.
The default is 0 -->
<!--<relays-on-demand>1</relays-on-demand>-->
<!--
<relay>
<server>127.0.0.1</server>
<port>8080</port>
<mount>/example.ogg</mount>
<local-mount>/different.ogg</local-mount>
<on-demand>0</on-demand>
<relay-shoutcast-metadata>0</relay-shoutcast-metadata>
</relay>
-->
<!-- Mountpoints
Only define <mount> sections if you want to use advanced options,
like alternative usernames or passwords
-->
<!-- Default settings for all mounts that don't have a specific <mount type="normal">.
-->
<!--
<mount type="default">
<public>0</public>
<intro>/server-wide-intro.ogg</intro>
<max-listener-duration>3600</max-listener-duration>
<authentication type="url">
<option name="mount_add" value="http://auth.example.org/stream_start.php"/>
</authentication>
<http-headers>
<header name="foo" value="bar" />
</http-headers>
</mount>
-->
<!-- Normal mounts -->
<!--
<mount type="normal">
<mount-name>/example-complex.ogg</mount-name>
<username>othersource</username>
<password>hackmemore</password>
<max-listeners>1</max-listeners>
<dump-file>/tmp/dump-example1.ogg</dump-file>
<burst-size>65536</burst-size>
<fallback-mount>/example2.ogg</fallback-mount>
<fallback-override>1</fallback-override>
<fallback-when-full>1</fallback-when-full>
<intro>/example_intro.ogg</intro>
<hidden>1</hidden>
<public>1</public>
<authentication type="htpasswd">
<option name="filename" value="myauth"/>
<option name="allow_duplicate_users" value="0"/>
</authentication>
<http-headers>
<header name="Access-Control-Allow-Origin" value="http://webplayer.example.org" />
<header name="baz" value="quux" />
</http-headers>
<on-connect>/home/icecast/bin/stream-start</on-connect>
<on-disconnect>/home/icecast/bin/stream-stop</on-disconnect>
</mount>
-->
<!--
<mount type="normal">
<mount-name>/auth_example.ogg</mount-name>
<authentication type="url">
<option name="mount_add" value="http://myauthserver.net/notify_mount.php"/>
<option name="mount_remove" value="http://myauthserver.net/notify_mount.php"/>
<option name="listener_add" value="http://myauthserver.net/notify_listener.php"/>
<option name="listener_remove" value="http://myauthserver.net/notify_listener.php"/>
<option name="headers" value="x-pragma,x-token"/>
<option name="header_prefix" value="ClientHeader."/>
</authentication>
</mount>
-->
<fileserve>1</fileserve>
<paths>
<!-- basedir is only used if chroot is enabled -->
<basedir>/usr/share/icecast2</basedir>
<!-- Note that if <chroot> is turned on below, these paths must both
be relative to the new root, not the original root -->
<logdir>/var/log/icecast2</logdir>
<webroot>/usr/share/icecast2/web</webroot>
<adminroot>/usr/share/icecast2/admin</adminroot>
<!-- <pidfile>/usr/share/icecast2/icecast.pid</pidfile> -->
<!-- Aliases: treat requests for 'source' path as being for 'dest' path
May be made specific to a port or bound address using the "port"
and "bind-address" attributes.
-->
<!--
<alias source="/foo" destination="/bar"/>
-->
<!-- Aliases: can also be used for simple redirections as well,
this example will redirect all requests for http://server:port/ to
the status page
-->
<alias source="/" destination="/status.xsl"/>
<!-- The certificate file needs to contain both public and private part.
Both should be PEM encoded.
<ssl-certificate>/usr/share/icecast2/icecast.pem</ssl-certificate>
-->
</paths>
<logging>
<accesslog>access.log</accesslog>
<errorlog>error.log</errorlog>
<!-- <playlistlog>playlist.log</playlistlog> -->
<loglevel>3</loglevel> <!-- 4 Debug, 3 Info, 2 Warn, 1 Error -->
<logsize>10000</logsize> <!-- Max size of a logfile -->
<!-- If logarchive is enabled (1), then when logsize is reached
the logfile will be moved to [error|access|playlist].log.DATESTAMP,
otherwise it will be moved to [error|access|playlist].log.old.
Default is non-archive mode (i.e. overwrite)
-->
<!-- <logarchive>1</logarchive> -->
</logging>
<security>
<chroot>0</chroot>
<changeowner>
<user>root</user>
<group>root</group>
</changeowner>
</security>
</icecast>
Anything helps.
A: This is a moderately common use-case for Icecast and you are on the right path.
I've previously explained it e.g. here http://lists.xiph.org/pipermail/icecast/2015-February/013198.html
It boils down to (I'm assuming debian/ubuntu/… based on paths):
Edit two lines in /etc/default/icecast2:
USERID=root
GROUPID=root
Edit the following lines in /etc/icecast2/icecast.xml:
*
*this must be the first <listen-socket> entry:
<listen-socket>
<port>80</port>
<listen-socket>
*
*in the security section:
<changeowner>
<user>icecast2</user>
<group>icecast</group>
</changeowner>
*
*for yp listings, make sure <hostname> resolves to your Icecast server
(not your homepage!) and remove the <!-- --> around the <directory> section.
*
*start Icecast through its init script / systemd
| |
doc_1632
|
I precisely want the pdf to be shown in the browser, vs it being downloaded, but the browser are instead downloading.
I have disabled my browsers settings to download pdf files vs showing them, so that can't be the issue.
The relevant part of the code is simple:
if (isMobile) {
newTab.location = redirectUrl;
} else {
window.location = redirectUrl;
}
It works for mobile, but downloads it on desktop.
The url is a pdf that is stored on a AWS S3 cloud.
Is there a way to ensure the pdf is opened in the browser, vs downloading it?
| |
doc_1633
|
my object
[{id: "063f48d0-1452-4dad-8421-145820ddf0f8",
storeName: "birr",
cost: {
4fd5ee28-835d-42dc-85a6-699a37bc1948: "54",
f45827c8-1b1a-48c3-831b-56dab9bcaf3b: "543"
},
saved: true}]
I need to get cost of 54 somehow.
please help
A: Your GUIDs in cost need to be inside quotes.
var obj = [{id: "063f48d0-1452-4dad-8421-145820ddf0f8",
storeName: "birr",
cost: {
'4fd5ee28-835d-42dc-85a6-699a37bc1948': "54",
'f45827c8-1b1a-48c3-831b-56dab9bcaf3b': "543"
},
saved: true
}]
document.write(obj[0].cost['4fd5ee28-835d-42dc-85a6-699a37bc1948']);
That outputs the value 54.
A:
<script>
var arraylist = [{'id': "063f48d0-1452-4dad-8421-145820ddf0f8",
'storeName': "birr",
'cost': {
'4fd5ee28-835d-42dc-85a6-699a37bc1948': "54",
'f45827c8-1b1a-48c3-831b-56dab9bcaf3b': "543"
},
'saved': true}];
var costKey = '4fd5ee28-835d-42dc-85a6-699a37bc1948'
var selectedCost = arraylist[0]['cost'][costKey];
alert(selectedCost);
</script>
A: Make sure your keys are in quotes. Otherwise to retrieve the value it is simply a matter of accessing it like object[key] as the following code demonstrates.
var stores = [{id: "063f48d0-1452-4dad-8421-145820ddf0f8",
storeName: "birr",
cost: {
'4fd5ee28-835d-42dc-85a6-699a37bc1948': "54",
'f45827c8-1b1a-48c3-831b-56dab9bcaf3b': "543"
},
saved: true
}];
var store = stores[0];
var cost = store.cost;
var key = Object.keys(cost)[0];
var value = cost[key];
console.log(value);
| |
doc_1634
|
*
*Drop a cookie once the vote is complete (susceptible to multi browser gaming)
*Log IP address per vote (this will fail in proxy / corporate environments)
*Force logins
My site is not account based as such, although it aggregates Twitter data, so there is scope for using Twitter OAuth as a means of identification.
What existing systems exist and how do they do this?
A: One step towards a user auth system but not all of the complications:
Get the user to enter their email address and confirm their vote, you would not eradicate gaming but you would make it harder for gamers to register another email address and then vote etc.
Might be worth the extra step.
Let us know what you end up going for.
A: If you want to go with cookies after all, use an evercookie.
evercookie is a javascript API available that produces
extremely persistent cookies in a browser. Its goal
is to identify a client even after they've removed standard
cookies, Flash cookies (Local Shared Objects or LSOs), and
others.
evercookie accomplishes this by storing the cookie data in
several types of storage mechanisms that are available on
the local browser. Additionally, if evercookie has found the
user has removed any of the types of cookies in question, it
recreates them using each mechanism available.
Multi-browser cheating won't be affected, of course.
A: What type of gaming do you want to protect yourself against? Someone creating a couple of bots and bombing you with thousands (millions) of requests? Or someone with no better things to do and try to make 10-20 votes?
Yes, I know: both - but which one is your main concern in here?
Using CAPTCHA together with email based voting (send a link to the email to validate the vote) might work well against bots. But a human can more or less easily exploit the email system (as I comment in one answer and post here again)
I own a custom domain and I can have any email I want within it.
Another example: if your email is
myuser*@gmail.com*, you could use
"[email protected]"
[email protected], etc (the plus sign and the text after
it are ignored and it is delivered
to your account). You can also include
dots in your username ([email protected]). (This only
works on gmail addresses!)
To protect against humans, I don't know ever-cookie but it might be a good choice. Using OAuth integrated with twitter, FB and other networks might also work well.
Also, remember: requiring emails for someone to vote will scare many people off! You will get many less votes!
Another option is to limit the number of votes your system accepts from each ip per minute (or hour or anything else). To protect against distributed attacks, limit the total number of votes your system accepts within a timeframe.
A: The best thing would be to disallow anonymous voting. If the user is forced to log in you can save the userid with each vote and make sure that he/she only votes once.
The cookie approach is very fragile since cookies can be deleted easily. The IP address approach has the shortcoming you yourself describe.
A: Different approach, just to provide an alternative:
Assuming most people know how to behave or just can't be bothered to misbehave, just retroactively clean the votes. This would also keep voting unobtrusive for the voters.
So, set cookies, log every vote and afterwards (or on a time interval?) go through the results and remove duplicates based on the cookie values, IP/UserAgent combinations etc.
I'd assume that not actively blocking multiple votes from same person keeps the usage of highly technical circumvention methods to a minimum and the results are easy to clean.
As a down side, you can't probably show the actual vote counts live on the user interface, or eyebrows will be raised when bunch of votes just happen to go missing.
A: Although I probably wouldn't do this myself, but look at these cookies, they are pretty hard to get rid of:
http://samy.pl/evercookie/
A different way that I had to approach this problem and fight voting fraud, was to require an email address, then a person could still vote, but the votes wouldn't count until they clicked on a link in the email. This was easier than full on registration, but was still very effective in eliminating most of the fraudulent votes.
A: If you don't want force users to log, consider this evercookie, but force java script to enable logging!
This evercookie is trivial to block because it is java script based. The attacker would not likely use browser, with curl he could generate tousends of requests. Hovewer such tools have usually poor javascript support.
Mail is even easier to cheat. When you run your own server, you can accept all email addresses, so you will have practically unlimited pool of addresses to use.
| |
doc_1635
|
Currently the part of my code that deals with renaming is
$target = "$upload_dir/$_SESSION[myusername]Rejoin.$file[name]";
Would appreciate if someone could tell me the correct code to do so
A: You could change name in for/foreach loop -
$fdata = $_FILES['username'];
if(is_array($fdata['name']))
{
$uploads_dir = '/uploads';
for($i = 0; $i < count($fdata['name']); ++$i)
{
$name_of_file = $_FILES['username']['name'][$i]; //[$count];
$temp_name = $_FILES['username']['tmp_name'][$i]; //[$count];
move_uploaded_file($temp_name, "$uploads_dir/"."$name_of_file");
}
}
| |
doc_1636
|
Select AVG(EAX_T) AS EAX, AVG(EAI_T) AS EAI, H
FROM TABLENAME
WHERE SR = ? AND TO_DATE(DATEADD) = ?
GROUP BY H
ORDER BY H ASC
The Data can be Like this :
SR |H |EAX_T |EAI_T
45 |8 |-3 |0
45 |8 |-2 |0
98 |8 |8 |0
98 |8 |2 |0
106 |8 |0 |-1
106 |8 |0 |-9
I want sql Query for select row Group by H And SR if EAI_T OR EAX_T is Positive Number select Row With Highest And If EAI_T or EAX_T is negative Select The Lowest, If
45 |8 |-3 |0
45 |8 |-2 |0
SELECT ROW That Have -3
And If
98 |8 |8 |0
98 |8 |2 |0
SELECT Row That Have 8
Update :
I have 46 milion row The H is ref to Hour , so in one day i have 1000 devices and i need get avg of data in H and if it's Higher than 0 get Highest number in day and if lowest than 0 get Lowest rows to make my another table with this data , so SR ref to device Id and in my new table ill pick data that I found and make H1 , H2 , .... for devices
A: You can use MAX() window function:
select distinct t.*
from (
select t.sr, t.h,
sign(eax_t) * max(abs(eax_t)) over (partition by sr, h) eax_t,
sign(eai_t) * max(abs(eai_t)) over (partition by sr, h) eai_t
from tablename t
) t
order by t.sr, t.h
See the demo.
Results:
> SR | H | EAX_T | EAI_T
> --: | -: | ----: | ----:
> 45 | 8 | -3 | 0
> 98 | 8 | 8 | 0
> 106 | 8 | 0 | -9
A: Because the question owner using AVG in the code. I guess the owner want highest or lowest number according to the AVG(EAX_T) positive or negative group by SR and H.
Using CASE when AVG bigger than 0 get MAX , smaller than 0 get Min, equal 0 give 0.
select SR,H ,
case
when AVG(EAX_T) >0 then Max(EAX_T)
when AVG(EAX_T) <0 then Min(EAX_T) else 0 end as EAX,
case
when AVG(EAI_T) >0 then Max(EAI_T)
when AVG(EAI_T) <0 then Min(EAI_T) else 0 end as EAI from TABLENAME group by SR,H
I think the owner data just one sign in a group of SR and H. I also give @forpas upvote because I think his answer match the owner thought.
| |
doc_1637
|
I want the background image to respect / be inset by the padding (so that the padding is almost like a frame around the image).
.hero_image {
min-height: calc(100vh - 72px);
background-color: rgb(0, 97, 111);
box-sizing: border-box;
padding: 72px;
background-origin: padding-box;
background-image: url("https://s7.postimg.cc/6vtowr3u3/salters_hill_old_logo.jpg");
background-position: center center;
background-repeat: no-repeat;
background-size: contain;
}
<div class="hero_image"></div>
JS Fiddle
A: To get the result you are after you will need to change background-origin: padding-box; to background-origin: content-box;.
This is because the background is positioned relative to the padding box when you use background-origin: padding-box;, as you want to respect the padding you need to position it relative to the content box instead.
html, body {
padding: 0;
}
.hero_image {
min-height: calc(100vh - 72px);
background-color: rgb(0, 97, 111);
box-sizing: border-box;
padding: 72px;
background-origin: content-box;
background-image: url("https://s7.postimg.cc/6vtowr3u3/salters_hill_old_logo.jpg");
background-position: center center;
background-repeat: no-repeat;
background-size: contain;
}
<div class="hero_image"></div>
| |
doc_1638
|
I am able to do this with clearing the entire stage and redrawing new shapes (which resets their position), but I can't figure it out with the current shapes.
Q. What's the best way to approach making a change to a shapes color, during a Tween?
I was also curious if there's a better way to handling tweening the shapes width? Currently I am relying on ScaleX and ScaleY - but this also changes the stroke's size - which is not desired.
JS Fiddle
HTML
<button id="change">Click to Change Color</button>
<canvas id="demoCanvas" width="500" height="500"></canvas>
JS
var stage,
circle;
function init() {
stage = new createjs.Stage("demoCanvas");
createjs.Ticker.setFPS(60);
createjs.Ticker.addEventListener("tick", stage);
}
function createCircle(){
circle = new createjs.Shape().set({name:"circle"});
circle.graphics.setStrokeStyle(1).beginStroke("#000").beginFill( "#FFF" ).drawCircle(0, 0, 20);
circle.x = 100;
circle.y = 100;
stage.addChild(circle);
createjs.Tween.get(circle, {loop: true})
.to({x: 225, y: 225}, 1000, createjs.Ease.getPowInOut(1))
.to({x: 100, y: 100}, 1000, createjs.Ease.getPowInOut(1));
circle2 = new createjs.Shape().set({name:"circle"});
circle2.graphics.setStrokeStyle(1).beginStroke("#000").beginFill( "#FFF" ).drawCircle(0, 0, 20);
circle2.x = 400;
circle2.y = 400;
stage.addChild(circle2);
createjs.Tween.get(circle2, {loop: true})
.to({scaleX: 2, scaleY: 2, x: 425, y: 125}, 1000, createjs.Ease.getPowInOut(1))
.to({scaleX: 1, scaleY: 1, x: 400, y: 400}, 1000, createjs.Ease.getPowInOut(1));
stage.update();
}
$( "#change" ).click(function() {
// change color
});
$(document).ready(function() {
init();
createCircle();
});
A: There are a few questions in this post, so I will try to answer them all:
First, a solution to most of your issues is Graphic commands. Commands provide a simple way to store graphic instructions, and change them later. Here is a simple example:
var shape = new createjs.Shape();
var colorCmd = shape.graphics.beginFill("red").command;
var rectCmd = shape.graphics.drawRect(0,0,100,100).command;
// Later
colorCmd.style = "blue";
rectCmd.w = 200;
stage.update(); // Remember to update the stage after changing properties
You can read more about commands on the createjs blog. All commands and their properties are documented in the EaselJS docs.
*
*Change a color: I outlined this in the example above, but the short answer is to adjust the style property of a fill command. If you want to change it instantly, you can just set up a Tween.call:
Example:
createjs.Tween.get(circle, {loop: true})
.to({x: 225, y: 225}, 1000, createjs.Ease.getPowInOut(1))
.call(function(tween) {
colorCmd.style = "rgba(0, 0, 255, 0.5)"; // Change to 50% blue
})
.to({x: 100, y: 100}, 1000, createjs.Ease.getPowInOut(1));
If you want to tween the color, then you could check out the ColorPlugin, which is currently in a "Plugins" branch of TweenJS: https://github.com/CreateJS/TweenJS/tree/Plugins/extras/plugins
// Tween the color from its current value to blue.
// Note that only hex, short hex, HSL, and RGB formats are supported.
createjs.Tween.get(colorCmd).to({style:"#0000ff"});
*Change the size: The example above also shows how to modify the values of a drawRect call. You can do the same with any other draw command (including moveTo, lineTo, polyStar, etc).
Scaling also works, and if you want to not scale the stroke, just set the ignoreScale parameter on the stroke style.
shape.graphics.setStrokeStyle(1, null, null, null, true);
| |
doc_1639
|
https://www.tax.service.gov.uk/eat-out-to-help-out/find-a-restaurant/
When you input and search for a valid postcode it redirects to a URL with a parameter of 'results?postcode=RM7+0FT', for example. However, when I look in Chrome's Dev Tools under Network I can't see any API calls.
I'm fairly new to programming but not so new that I wish I could figure this out. I'd quite like to play around with this data if possible.
Many thanks all!
A: You can't see the API calls because the page is rendered server-side. You are redirected to a new page where all the data is fetched and populated on the server, so you only see the end result.
| |
doc_1640
|
Using jQuery and google maps v3, I am able to place a map marker and an event listener that opens an infobubble when the user clicks on the marker. What I'd like to do (but so far haven't been able to figure out) is add another event handler to the contents of the info bubble. For example, if the user clicks on the map marker open the info bubble (that part works), and then if they click on something inside the infobubble do something else. I have pasted my code below, thanks in advance for any help
function addMarker(data) {
var myLatlng = new google.maps.LatLng(data.Latitude, data.Longitude);
var title = data.title? data.title: "";
var icon = $('#siteUrl').val() + 'img/locate.png';
var bubbleContentString = "<span class=\"bubble-details-button\">Get Details about " + title+ "</span>";
myInfoBubble = new InfoBubble({
content: bubbleContentString,
hideCloseButton: true,
backgroundColor: '#004475',
borderColor: '#004475'
});
var myMarker = new google.maps.Marker({
position: myLatlng,
map: map,
title: title,
icon: icon
});
addListenerToMarker(myMarker, myInfoBubble);
markerSet.push(myMarker, myInfoBubble);
}
function addListenerToMarker(marker, bubble){
console.log($(bubble.getContent()).find('.bubble-details-button')[0]);
google.maps.event.addListener(marker, 'click', function() {
if (!bubble.isOpen()) {
google.maps.event.addListenerOnce(bubble, 'domready', function(){
console.log($(bubble.getContent()).find('.bubble-details-button')[0]);
google.maps.event.addDomListener($(bubble.getContent()).find('.bubble-details-button')[0], 'click', function(){
alert("hi");
});
});
bubble.open(map, marker);
}
});
}
A: You are trying to add "click" event on element ,which is not DOM Element. $('.bubble-details-button') is not DOM Element (it is a wrapper of DOM Element), but $('.bubble-details-button')[0] is.
On the other hand, when you are trying to add "click" event, the content is not created yet. You can work(e.g. add events) with content's elements ,only when they are already created. The InfoBubble will trigger "domready" event, when its content will be created.So you need to handle it:
if (!bubble.isOpen()) {
google.maps.event.addListenerOnce(bubble, 'domready', function(){
google.maps.event.addDomListener($(bubble.getContent()).find('.bubble-details-button')[0], 'click', function(){
alert("hi");
});
});
bubble.open(map, mymarker);
}
A: In scenarios where I have to do what you are describing, I include a JavaScript function call directly in the InfoBubble content. I often include hyperlinks within an InfoBubble, so in that case I do the following: 1 - Write a JavaScript function to handle a hyperlink click. 2 - Create the marker. 3 - Attach a click event handler to the marker that opens an InfoBubble. 4 - Define the content of the InfoBubble so that JavaScript embedded directly in the InfoBubble content is set to handle the click event by calling the JavaScript function that was defined in Step #1 - something like:
"<span>" +
"<a href='javascript:showDetail(" + param1 + "," + param2 + ");'>" +
displayTextContent + "</a>" +
"</span>"
| |
doc_1641
|
My question is: is there a way to enforce an update on activity B's input so that it gets the latest value of activity A's output?
| |
doc_1642
|
How to separate sandbox tokens and production tokens from db table? Your help is highly appreciated!! Thanks!
A: You should probably be keying your database table with some sort of UDID (you can create your own by hashing the bundle ID and the MAC address of the device) AND a second field that indicates whether the token is a "development" or a "production" token. The third field can be the actual token.
In your app delegate in the didRegisterForRemoteNotificationsWithDeviceToken delegate method you can add logic to determine whether your app is running in development vs. production mode and update your database with the device token based on the UDID and the "mode" the app is running in.
Your code might look something like the following:
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
// Update the device token record in our database
#if !defined (CONFIGURATION_Distribution)
// Update the database with our development device token
#endif
#if defined (CONFIGURATION_Distribution)
// Update the database with our production device token
#endif
}
To do this you need to go to your Project -> Build Settings. In the Preprocessor Macros section type CONFIGURATION_ and press Enter. This should create a preprocessor macro for each of your build configurations. In this case my build configurations are AdHoc, Debug, Distribution, and Release.
It creates CONFIGURATION_AdHoc, CONFIGURATION_Debug, CONFIGURATION_Distribution, and CONFIGURATION_Release for me.
| |
doc_1643
|
I usually do like below
RandomAccessFile raf = null;
try {
// do something ...
} catch (IOException e) {
// logger
} finally {
try {
if (null != raf) {
raf.close();
}
} catch (IOException e) {
// logger
}
}
Then I see I can do this in Java8
try (RandomAccessFile raf = ... ) {
// do something ...
} catch (IOException e) {
// logger
}
It seems a good way.
Looks like Java do the job to close IO.
edit 1
Personally, I like the 2nd way.
But is it good to use and has a high performance?
A: With Java 7 or higher, if the resource implements AutoCloseable, best practice is to use try-with-resources:
try (
RandomAccessFile raf = /*construct it */
) {
// Use it...
}
The resource will be closed automatically. (And yes, the catch and finally clauses are optional with try-with-resources.)
Regarding the code in your question:
*
*Re the main catch block: "log and forget" is generally not best practice. Either don't catch the exception (so the caller can deal with it) or deal with it correctly.
*In the catch block in your finally where you're closing, you're quite right not to allow that to throw (you could mask the main exception), but look at the way the spec defines try-with-resources and consider following that pattern, which includes any exception from close as a suppressed exception.
| |
doc_1644
|
If I remove the built-in authentication option, will the password data for non-integrated accounts be preserved or deleted? I want to be able to re-enable local auth and sign in as one of the headless accounts if ever needed, but am afraid of getting locked out of those accounts.
Please point me to some documentation if possible. I've had trouble finding any on this specific question.
| |
doc_1645
|
This is the method I want to call in a class called AddOrderPanel.
public void addLCheese(){
BigDecimal price = new BigDecimal("8.99");
CheesePizza largeCheese = new CheesePizza("Large Cheese/Tomato",price);
OrderItem laCheese = new OrderItem(largeCheese,1);
System.out.println(largeCheese.getDescription()+" "+largeCheese.getPrice()+" " +laCheese.testArray());
JPanel order = new JPanel();
order.setBackground(Color.blue);
order.setPreferredSize(new Dimension(800,50));
add(order,BorderLayout.CENTER);
revalidate();
}
And this is my listener code :
lCheese.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
AddOrderPanel orderPanel;
orderPanel.addLCheese();
}
});
When I try it it returns NullPointerException, ideas?
My Panel Object.
private JFrame myMainFrameObject;
AddOrderPanel(JFrame theMainFr){
myMainFrameObject = theMainFr;
this.setLayout(new FlowLayout(FlowLayout.RIGHT));
setBackground(Color.red);
setPreferredSize(new Dimension(800,0));
}
A: You're not assigning orderPanel to anything before calling orderPanel.addLCheese().
A: In your listener make this change to get the JFrame and then create a new instance of AddOrderPanel
lCheese.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
Component component = (Component) e.getSource();
JFrame frame = (JFrame) SwingUtilities.getRoot(component);
AddOrderPanel orderPanel = new AddOrderPanel(frame);
orderPanel.addLCheese();
}
});
| |
doc_1646
|
MyLib is mostly a Backbone collection which requires other submodules:
var _ = require('lodash');
var Backbone = require('backbone');
if (typeof window !== 'undefined') Backbone.$ = window.$;
var foo = require('foo'), bar = require('bar');
module.exports = Backbone.Collection.extend({ ... my library... });
Because Backbone and Underscore are bigger and more general, would like not to bundle them but treat them as external dependencies. So in package.json, am using browserify-shim to exclude them:
...
"browserify": {
"transform": [
"browserify-shim"
]
},
"browserify-shim": {
"lodash": "global:_",
"backbone": "global:Backbone"
}
The module loads fine in the browser, as _ gets defined as global variables:
<script src="/javascripts/underscore.js"></script>
<script src="/javascripts/mylib.js"></script>
<script type="text/javascript">
console.log(new MyLib()); // loads fine standalone or via require.js
</script>
But in Node.js, the browserify-bundled module looks for these external dependencies in an object called global
var _ = require("lodash");
var MyLib = require("./libs/mylib");
This fails with TypeError: Cannot call method 'isEqual' of undefined because _ is undefined. Inside mylib.js at the top I see the line:
var _ = (typeof window !== "undefined" ? window._ : typeof global !== "undefined" ? global._ : null)
However, I can get it to work by defining the dependencies globally like so:
var _ = GLOBAL.global._ = require("lodash");
var MyLib = require("./libs/mylib");
But this creates global variables, which many strongly discourage in this post: node.js global variables?
Is there a better way to include external dependencies for Browerify modules in Node.js?
How do I use Browserify with external dependencies?
| |
doc_1647
|
I just want to ask, if there are some configs or instructions that allows doctors (subscriber's users) to access the plan? (see the image below)
For example, I have "Silver package" plan that can manage 100 doctors with a specified amount. Question is, does the stripe has a config or documentation that gives those 100 doctors access with the silver package? or we just work this in our own database.
A: Unfortunately Stripe Subscriptions do not have the capability to provision your product themselves. Subscriptions automate and track your customer’s recurring payment. A Subscription's status can be used to determine if it is safe to provision your product to your customer[1]; it is up to you to implement the provisioning logic yourself.
[1] https://stripe.com/docs/billing/subscriptions/overview#subscription-statuses
| |
doc_1648
|
The requested operation could not be performed because OLE DB provider "Microsoft.ACE.OLEDB.16.0" for linked server "COMMON" does not support the required transaction interface.
if anybody knows the workaround that would be much appreciated.
| |
doc_1649
|
all_data = [];
//Get all documents in collection
function getAllDocuments() {
console.log('getAllDocuments() executed');
db.collection("All data").get().then((querySnapshot) => {
console.log('Getting documents from firestore...');
querySnapshot.forEach((doc) => {
//Creating object
data_t = new dbData;
all_data.push(data_t);
});
});
console.log('All data:', all_data.length);
}
//Display documents
function displayDocuments(data) {
console.log('displayDocuments() executed');
//Other lines of code
}
//Functions to run on page load
function pageLoad() {
getAllDocuments();
displayDocuments(all_data);
}
window.onload = pageLoad;
However, the functions are executed before data is retrieved from firebase. So, my website loads as an empty page. I have to execute the displayDocuments() again to display the data on the screen.
I understand the problem behind this. The webpage is not getting my documents from firebase on page load. Even though pageLoad() executes getAllDocuments(), it skips the db.collection.get() initially. This method is executed only after window.onload is executed, that is, after all my pageLoad() are executed. My console output looks like
getAllDocuments() executed
All data: 0
displayDocuments() executed
Getting documents from firestore...
Does anyone know why db.collection.get() is not executed in the defined order? How db.collection().get() gets executed at the end without getAllDocuments() being called?
A: You need to await the result of the first function since it performs an asynchronous action. You can do it by returning the promise directly. In this case, you don't need all_data global variable since you can return it from promise.
Something like that should work for you:
//Get all documents in collection
function getAllDocuments() {
console.log('getAllDocuments() executed');
return db.collection("All data").get().then((querySnapshot) => {
console.log('Getting documents from firestore...');
return querySnapshot.map((doc) => {
//Creating object using doc
// ....
return new dbData;
});
});
}
//Display documents
function displayDocuments(data) {
console.log('displayDocuments() executed');
//Other lines of code
}
//Functions to run on page load
function pageLoad() {
getAllDocuments().then(all_data => displayDocuments(all_data));
}
window.onload = pageLoad;
A: The reason why this is happening is because your getAllDocuments function finishes its execution before the promise could resolve.
What you can do is make getAllDocuments async and wait for promise to resolve using await, and call it from pageLoad() function using await. i.e
all_data = [];
async function getAllDocuments() {
console.log('getAllDocuments() executed');
const querySnapshot = await db.collection("All data").get();
querySnapshot.forEach((doc) => {
//Creating object
data_t = new dbData;
all_data.push(data_t);
});
console.log('All data:', all_data.length);
}
async function pageLoad() {
await getAllDocuments();
// displayDocuments(all_data);
}
| |
doc_1650
|
Error:Failed to resolve: com.google.android.gms:play-services-tasks:[11.0.4]
When i used android studio 2.3.2 version my project build successfully but after updated to android studio version to 2.3.3 and updated google play services i am getting this error please help.
There is no play-services-basement and play-services-tasks folder in my folder
when i comment this "compile 'com.google.android.gms:play-services-location:11.0.4'" line my project compiling fine if i uncomment then my project not compiling
Project Gradle file:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
}
}
allprojects {
buildDir = "C:/tmp/${rootProject.name}/${project.name}"
repositories {
jcenter()
}
}
ext {
compileSdkVersion = 25
buildToolsVersion = "25.0.2"
supportLibVersion = "25.3.1"
minSdkVersion = 14
targetSdkVersion = 25
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Module Gradle file:
apply plugin: 'com.android.application'
android {
compileSdkVersion rootProject.ext.compileSdkVersion
buildToolsVersion rootProject.ext.buildToolsVersion
useLibrary 'org.apache.http.legacy'
defaultConfig {
applicationId "package"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
debug {
debuggable true
}
}
lintOptions {
checkReleaseBuilds false
abortOnError false
}
}
repositories {
jcenter {
url "http://jcenter.bintray.com/"
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
compile "com.android.support:support-v4:${rootProject.ext.supportLibVersion}"
compile "com.android.support:design:${rootProject.ext.supportLibVersion}"
compile "com.android.support:recyclerview-v7:${rootProject.ext.supportLibVersion}"
compile 'com.google.android.gms:play-services-location:11.0.4'
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'de.hdodenhof:circleimageview:2.1.0'
compile 'com.github.beyka:androidtiffbitmapfactory:0.9.6.2'
debugCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
}
A: project gradle file:
buildscript {
repositories {
jcenter()
maven {
url 'https://maven.google.com'
}
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
}
}
allprojects {
buildDir = "C:/tmp/${rootProject.name}/${project.name}"
repositories {
jcenter()
maven {
url 'https://maven.google.com'
}
}
}
| |
doc_1651
|
I need to insert few element and I have to remove and read that removed element from queue.
If it is array I may have to modify the indexes every time I remove an element. Inserting and deleting may happen simultaneously also.
Which one is better from below case?
typedef struct{
mylist list;
struct mylistQ *next;
}mylistQ;
Array Code
static mylist myListQ[QUEUESIZE+1];
int qLast = 0;
void enqueue_element(mylist qItem)
{
myListQ[qLast] = qItem;
qLast++;
}
mylist dequeue_element()
{
retryq:
if(qLast >0) {
mylist qReturn = myListQ[0];
int i;
for (i = 0; i < qLast - 1; i++){
myListQ[i] = myListQ[i + 1];
}
qLast--;
return qReturn;
}
else {
goto retryq;
}
}
Linked List
int qLast = 0;
mylistQ *headElement = NULL;
mylistQ *tailElement = NULL;
void enqueue_element(mylist *List)
{
mylistQ *newnode;
newnode=(mylistQ*)av_malloc(sizeof(mylistQ));
newnode->next=NULL;
newnode->list=*List;
qLast++;
if(headElement==NULL && tailElement==NULL)
{
headElement=newnode;
tailElement=newnode;
}
else
{
tailElement->next=newnode;
tailElement=newnode;
}
}
mylist dequeue_element()
{
mylistQ *delnode; /* Node to be deleted */
mylist Dellist;
if(headElement==NULL && tailElement==NULL){
LOg( "Queue is empty to delete any element");
}
else
{
Log("In dequeue_picture queue is not empty");
delnode=headElement;
headElement=headElement->next;
if (!headElement){
tailElement=NULL;
}
Dellist = delnode->list;
av_free(delnode);
qLast--;
}
return Dellist;
}
A: It depends on how many operations you'll be performing and exactly how the array version is implemented.
If you're doing comparatively few operations, ie less than 1000 or so enqueue/dequeues in total, then an array would be faster because it is contiguous in memory. Maintain a pointer to the front and a pointer to the back, always add at the back and dequeue at the front.
On the other hand even if the list is no longer than 30 or so elems ever, if this has to persist of a long period you won't have any array resizing issues which is a potential problem with the array.
Linked list is guaranteed excellent performance, array you have to watch for resizing.
EDIT:
As mentioned by @Hans Passant, arrays are fast because they have CPU cache locality. As long as your array is small, your hardware will optimize performance such that the memory associated with storing the array will be kept in your L2. Indices likely in registers. This is REALLY fast. Judging by the fact that you won't need many elements, an array would be ideal in this case. And yes, you will have to modify indices when you move elements, but this is actually an extremely fast operation since if you build the code with optimization the indices will be stored in registrars.
Here's the catch though, you mention you may have to do both enqueue and dequeue at the same time, by this do you mean it's parallel ie multiple threads accessing the memory? If this is the case, arrays would still be faster, but you'll see something like a 800 fold decrease in performance. Why? because no longer can the processor buffer the memory associated with your queue on the die, but it must be stored in main memory. In addition, you're running the risk of creating a race condition between threads. Imagine if one thread tried to dequeue while another tried to enqueue and there was only one elem in the list, you could have disaster. Either way, if this application is very perfromance driven, be sure to compile (assuming gcc) with the NDEBUG and -O3 flags on.
Second Edit:
Looking at the code, and looking below at other answers, I'd suggest making your array code more efficient and turning it into a circular array since it sounds like you have an upper bound on the number of elements. As a side note, you're current array implementation is extremely inefficient, every time you remove you copy forward the rest of the Queue, this makes no sense, just increment a int pointer to the "first" index.
Pseudo Code:
int ciruclarArray[SIZE];
int front = 0;
int back = 0;
void enqueue(int elem)
{
circularArray[back] = elem;
if(back < (circularArray.length - 1))
back++;
else
back = 0;
return elem;
}
int dequeue()
{
int toReturn = circularArray[front];
//do same check for incrementing as enqueue
return toReturn;
}
just don't forget to do error checking for the normal stuff.
A: If there is an upper bound on the total number of elements you're going to store in the queue, use a circular array. This eliminates the need to resize an array, when continuously adding elements to its end.
A: Even if you have many elements, the array implementation is probably the fastest. For inspiration, I took a look at GCC's C++ dequeue. It stores the queue as an array of arrays. I am not sure if the iterators wrap around as in circular buffer. The array implementation also has fast random access, should you need it later.
| |
doc_1652
|
Our end testable product is web, wpf and windows forms.
The testing resources have introduced BDD and would like to learn and use Ruby and Cucumber to perform the testing. There has been some resistance from the developers, as we would prefer to stick with the same technology stack and use Specflow (or similar). The argument from the testers is that it is simpler to learn.
I want to be sure that the developers and testers are not being biased, and that it is worthwhile introducing another technology.
A: Both SpecFlow and Cucumber use the exact same business-person-readable language (gerkhin) to specify the features; the only difference is whether you'll write the step definitions in C# (using e.g. WatiN to drive browser-based tests) or Ruby (using e.g. Watir). So the tests will be structured in a very similar manner and will yield similar benefits no matter which one you choose.
I guess that the benefit of using SpecFlow over Cucumber is that the tests will be easily runnable from Visual Studio, as well as from e.g. TeamCity or other .NET-based continuous integration tools. On the other hand, when Cucumber tests are changed or new tests are added, you don't need to wait for recompilation (however, a change in the test code is often accompanied by a change in the production code, so this probably won't be a significant savings). When it comes to testing WPF-based or Windows Forms-based apps, I assume that it will be easier to control those applications from .NET (but it could be that there is some Ruby library for controlling other GUI applications...)
A: We have a similar setup, we have testers writing and implementing steps behind scenarios. Our testers are quite happy staying with .net and c#. I think that if you introduce another technology you would have developers not running the tests before they commit and not taking responsibility for the tests when they fail as it would be extremely hard to debug it. This would mean your build would be broke more than it's working.
It would probably be good to start for the testers to write the scenarios and passing them to development to be implemented by the developer that is going to introduce the feature into the application. They can then perhaps pair up with the developer and implement the scenarios together until they are comfortable doing it themselves.
A: I have been using SpecFlow and found it quite satisfactory up till this point. But it is the essence and the idea behind BDD that is more important than the tool. All these tools can do facilitate a common platform for the business and the development folks to develop a shared understanding of the system. Here is a very good post on BDD with SpecFlow
http://codingcraft.wordpress.com/2011/12/17/bdd-with-specflow
BDD can get you to do your TDD right too .
http://codingcraft.wordpress.com/2011/11/12/bdd-get-your-tdd-right/
| |
doc_1653
| ||
doc_1654
|
contains only a dummy component.
They are both stored into a db repository.
If I start the job from kitchen, everything runs fine:
./kitchen.sh -rep=spoon -user=<user> -pass=<pwd> -job A
Then I have written a simple java code:
JobMeta jobMeta = repository.loadJob(jobName, directory, null, null);
org.pentaho.di.job.Job job = new org.pentaho.di.job.Job(null, jobMeta);
job.getJobMeta().setInternalKettleVariables(job);
job.setLogLevel(LogLevel.ERROR);
job.setName(Thread.currentThread().getName());
job.start();
job.waitUntilFinished();
if (job.getResult() != null && job.getResult().getNrErrors() != 0) {
...
}
else {
...
}
Problem is that running the java program I always get the following error:
A - Unable to open transformation: null
A - java.lang.NullPointerException
at org.pentaho.di.job.entries.trans.JobEntryTrans.execute(JobEntryTrans.java:698)
at org.pentaho.di.job.Job.execute(Job.java:589)
at org.pentaho.di.job.Job.execute(Job.java:728)
at org.pentaho.di.job.Job.execute(Job.java:443)
at org.pentaho.di.job.Job.run(Job.java:363)
I have googled for this error without success and I am stucking there.
Any suggestion ?
A: The solution seems to be replacing the line inside kitchen
org.pentaho.di.job.Job job = new org.pentaho.di.job.Job(null, jobMeta);
with
org.pentaho.di.job.Job job = new org.pentaho.di.job.Job(repository, jobMeta);
Hoping that this helps someone else.
| |
doc_1655
|
Thanks
A: I don't think there's a way, unless you want to use single.php for it, and maybe move what you use single.php for somewhere else. You can read more about teamplate hierarchy here.
If you just don't want to replicate the code, you can always make a single-POST_TYPE.php for each one, and have those include a common template with the get_template_part function.
| |
doc_1656
|
protected void Page_Load(object sender, EventArgs e)
{
try
{
SAPSystemConnect sapCfg = new SAPSystemConnect();
RfcDestinationManager.RegisterDestinationConfiguration(sapCfg);
RfcDestination rfcDest = null;
rfcDest = RfcDestinationManager.GetDestination("Dev");
}
catch (Exception ex)
{
lbl.Text=ex.Message;
}
}
A: If the connection doesn't throw an exception, you'll know that the connection has been established. If there is a problem with the connection, the class will throw an appropriate exception.
| |
doc_1657
|
class Contact
{
// Read-only properties.
public string Name { get; }
public string Address { get; }
}
And I hope I can use object initializer syntax to create a Contact
Contact a = new Contact { Name = "John", Address = "23 Tennis RD" };
But I cannot. Any possible way to make use of the powerful object initializer syntax in this case?
A: The closest thing would be a constructor with optional parameters:
class Contact
{
public string Name { get; }
public string Address { get; }
public Contact(string name = null, string address = null) {
Name = name;
Address = address;
}
}
Then you can call it with parameter names:
new Contact(
name: "John",
address: "23 Tennis RD"
)
The syntax is slightly different from an object initializer, but it's just as readable; and IMO, the difference is a good thing, because constructor parameters tend to suggest immutable properties. And you can specify the parameters in any order, or leave some out, so it's just as powerful as object initializer syntax.
This does require some extra code (defining the constructor, assigning all the properties), so it's more work than object initializer syntax. But not too terrible, and the value of immutable objects is worth it.
(For what it's worth, C# 7 may get immutable "record types" that have much simpler syntax. These may or may not make it into the final release, but they sound pretty cool.)
A: This is dated now, but with the release of C# 9 you can use init to achieve the desired functionality.
So your example would become:
class Contract
{
// Read-only properties.
public string Name { get; init; }
public string Address { get; init; }
}
And then you could initialize with:
// success!
Contract a = new Contract { Name = "John", Address = "23 Tennis RD" };
But you would still be unable to modify the parameters after setting them (so effectively they are still readonly).
// error!
a.Name = "Uncle Bob";
Under the hood, when you use object initializer syntax prior to C# 9 the compiler would call the default constructor first, and then set the property values you've specified. Obviously if those properties are readonly (i.e. only a get method), it can't set them. The init only setter allows setting the value only on initialization, either via a constructor method or object initializer syntax.
More info is available here: https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9#init-only-setters
A: Nope, you cannot use it with readonly properties.
Here are the different property and field types in comparism.
public class sometype {
public int readonlyProp{
get;
}
public int normalProp {
get;
set;
}
public const int constField = 3;
public readonly int readonlyField = 3;
public int normalField = 3;
public void test() {
sometype test = new sometype() { readonlyProp = 3}; // Doesn't work -> Property or indexer is readonly
sometype test1 = new sometype() { normalProp = 3 }; // ok
sometype test2 = new sometype() { constField = 3 }; // Doesn't work -> Static field or property
sometype test3 = new sometype() { readonlyField = 3 }; // Doesn't work -> readonly field
sometype test4 = new sometype() { normalField = 3 }; // ok
}
}
It is important to understand that const fields are considered static and thus are not instance members. And since the object initializer is used for instance members this doesn't work.
A: Object initializer will first construct the object, then set property values.
It needs setters.
It's short hand for:
Contact a = new Contact();
a.Name = "John";
a.Address = "23 Tennis RD";
A readonly field can't have it's values set once the object has been constructed. To have that class immutable, you'll need to create a constructor to take those values:
class Contact // Immutable class
{
// Read-only properties.
public string Name { get; }
public string Address { get; }
public Contact(string name, string address)
{
this.Name = name;
this.Address = address;
}
}
| |
doc_1658
|
public class ClaimSearchCirtieria
{
public Guid? FinancialYear { get; set; }
public bool AllClaimants { get; set; }
public IList<Guid> ClaimantIds { get; set; }
public bool AllExpenseCategories { get; set; }
public IList<ExpenseCategoryAndTypeCriteria> EpenseCategoryAndTypes { get; set; }
}
And the ExpenseCategoryAndTypeCriteria
public class ExpenseCategoryAndTypeCriteria
{
public Guid ExpenseCategory { get; set; }
public bool AllTypesInCatgeory { get; set; }
public IList<Guid> ExpenseTypes { get; set; }
}
Searching on financial years and claimants needs to be an AND query, then I need the expense categories and expense types to be appended as an OR sub query.
In essence I'm trying to do:
select *
from claims
where <financial year> AND <Claimants> AND (expense type 1 OR expense type 2 or expense category X)
So far I've got this:
public PagedSearchResult<Claim> Search(ClaimSearchCirtieria searchCriteria, int page, int pageSize)
{
var query = All();
if (searchCriteria.FinancialYear.HasValue)
{
query = from claim in query
where claim.FinancialYearId == searchCriteria.FinancialYear
select claim;
}
if (!searchCriteria.AllClaimants)
{
query = from claim in query
where searchCriteria.ClaimantIds.Contains(claim.ClaimantId)
select claim;
}
if (!searchCriteria.AllExpenseCategories)
{
foreach (var item in searchCriteria.EpenseCategoryAndTypes)
{
if (item.AllTypesInCatgeory)
{
//Just search on the category
query = query.Where(claim =>
(from transaction in claim.ClaimTransactions
where item.ExpenseCategory == transaction.ExpenseType.ExpenseCategoryId
select transaction).Count() > 0
);
}
else
{
//Search for the specified types
query = query.Where(claim =>
(from transaction in claim.ClaimTransactions
where item.ExpenseTypes.Contains(transaction.ExpenseTypeId)
select transaction).Count() > 0
);
}
}
}
return PagedSearchResult<Claim>.Build(query, pageSize, page);
}
What I'm currently seeing is that the last expense category requested is the only expense category I get results for. Also, looking at the code, it looks like I would expect this to be building a series of AND queries, rather that the required OR.
Any pointers?
A: You can do this with LINQKit's PredicateBuilder. You need to use AsExpandable() when composing Entity Framework queries.
| |
doc_1659
|
Image:
Code:
import plotly.graph_objects as go
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
fig1 = go.Figure(data=[go.Sankey(
arrangement = "freeform",
node = dict(
pad = 80,
thickness = 10,
line = dict(color = "black", width = 0.5),
label = ["1131 articles identified through database search",
"3 additional articles identified",
"525 articles after duplicates removed",
"426 articles excluded based on title/abstract",
"98 full-text articles assessed for eligibility",
"50 full-text articles excluded",
"48 articles included in the literature overview"],
x = [0, 0, 0.4, 0.6, 0.5, 0.8, 0.7],
y = [0, 0, 0.5, 0.8, 0.15, 0.05, 0.4],
#color = ["darkblue","darkblue","darkblue","darkred","darkgreen","darkred","darkgreen"]
),
link = dict(
source = [0, 1, 2, 2, 4, 4], #corresponds to labels
target = [2, 2, 3, 4, 5, 6],
value = [1131, 3, 426, 98, 50, 48],
))])
fig1.update_layout(title = dict(text="Figure 1 - Review search and article screening"),
width=650,
height=450,
font_size=10,
margin=dict(l=0))```
| |
doc_1660
|
CREATE DATABASE IF NOT EXISTS dbwms DEFAULT CHARACTER SET `utf8`;
USE dbwms;
CREATE TABLE IF NOT EXISTS t_truck_types (
f_pk_ma_truck_type SMALLINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
f_sa_truck_type CHAR(4) NOT NULL UNIQUE, INDEX(f_sa_truck_type),
f_truck_length TINYINT
) ENGINE=InnoDB DEFAULT CHARACTER SET `utf8`;
CREATE TABLE IF NOT EXISTS t_truck_vendors (
f_pk_ma_truck_vendor_id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
f_sa_truck_vendor_id SMALLINT UNSIGNED NOT NULL UNIQUE, INDEX(f_sa_truck_vendor_id),
f_truck_vendor_nickname VARCHAR(12) NOT NULL UNIQUE, INDEX(f_truck_vendor_nickname)
) ENGINE=InnoDB DEFAULT CHARACTER SET `utf8`;
CREATE TABLE IF NOT EXISTS t_trucks (
f_pk_ma_truck_id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
f_truck_license_plate VARCHAR(15) NOT NULL UNIQUE, INDEX(f_truck_license_plate),
f_fk_ma_truck_type SMALLINT UNSIGNED NOT NULL,
f_fk_ma_truck_vendor_id SMALLINT UNSIGNED NOT NULL,
FOREIGN KEY (f_fk_ma_truck_type) REFERENCES t_truck_types(f_pk_ma_truck_type),
FOREIGN KEY (f_fk_ma_truck_vendor_id) REFERENCES t_truck_vendors(f_pk_ma_truck_vendor_id)
) ENGINE=InnoDB DEFAULT CHARACTER SET `utf8`;
Thanks in advance for your help.
sbeeht
A: That's because f_fk_ma_truck_type in t_trucks defined as an UNSIGNED. Both primary key and the foreign key should be of the same type. You may removed unsigned in t_trucks
CREATE TABLE IF NOT EXISTS t_trucks (
f_pk_ma_truck_id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
f_truck_license_plate VARCHAR(15) NOT NULL UNIQUE, INDEX(f_truck_license_plate),
f_fk_ma_truck_type SMALLINT NOT NULL,
f_fk_ma_truck_vendor_id SMALLINT UNSIGNED NOT NULL,
FOREIGN KEY (f_fk_ma_truck_type) REFERENCES t_truck_types(f_pk_ma_truck_type),
FOREIGN KEY (f_fk_ma_truck_vendor_id) REFERENCES t_truck_vendors(f_pk_ma_truck_vendor_id)
) ENGINE=InnoDB DEFAULT CHARACTER SET `utf8`;
or add it in the t_truck_types declaration
| |
doc_1661
|
INPUT_FILE_LIST=`/bin/ls -1 ${INPUT1_STAGING_DIR}` &&
SFTP_FILE_LIST=`/usr/bin/lftp -u username,password -e "set cmd:cls-default -1 && cls && bye" sftp://sftp.server.com` &&
while read name; do if `/bin/echo "$INPUT_FILE_LIST" | /bin/grep -q "^$name$"`; then OLD_FILES="$OLD_FILES $name"; fi; done < <(/bin/echo "$SFTP_FILE_LIST") &&
if [[ $OLD_FILES ]]; then /usr/bin/lftp -u username,password -e "rm ${OLD_FILES} && bye" sftp://sftp.server.com; fi
If I remove the line with the while it will run to completion (the ShellCommandActivity reaches FINISHED status) but if it's there the script "fails" in the sense that the ShellCommandActivity ends up in a WAITING_ON_DEPENDENCIES status.
Unfortunately the Data Pipeline service is not writing out any logs in this case, so I'm not sure why I'm having problems, and I am able to run the command successfully if I create an instance with the same image and instance type and run the command myself by logging in to the box.
As is perhaps already obvious from the code, the goal of all this is to remove files in an S3 bucket from an sftp server.
Notes:
*
*INPUT1_STAGING_DIR is an S3 bucket and that part is managed by the Data Pipeline and I've already confirmed that this part is working
*The script is actually all executed on a single line; the lines are broken up to make it easier to run but when deployed all 4 lines get concatenated with just a space between each, hence the && at the end of each line and all the ; in the 3rd line.
Here is the code with nicer formatting for convenience:
INPUT_FILE_LIST=`/bin/ls -1 ${INPUT1_STAGING_DIR}` &&
SFTP_FILE_LIST=`/usr/bin/lftp -u username,password -e "set cmd:cls-default -1 && cls && bye" sftp://sftp.server.com` &&
while read name; do
if `/bin/echo "$INPUT_FILE_LIST" | /bin/grep -q "^$name$"`; then
OLD_FILES="$OLD_FILES $name";
fi;
done < <(/bin/echo "$SFTP_FILE_LIST") &&
if [[ $OLD_FILES ]]; then
/usr/bin/lftp -u username,password -e "rm ${OLD_FILES} && bye" sftp://sftp.server.com;
fi
A: I was able to work around this problem by using s3cmd in my script instead of an S3 resource. I'm not sure why this worked but it did. I just changed the first line to:
INPUT_FILE_LIST=`/usr/bin/s3cmd ls s3://my-bucket/my-prefix`
and changed the grep pattern in the third line to $name$ and it started working. Note that this seems odd since the script completes as written above if I remove the while loop.
Either way, problem "solved", although I'd be happy to replace this solution with one that is able to use the S3 data pipeline resource.
A: this works for me
input=$(aws s3 ls $1 | awk '{print $4}')
echo "$input"
| |
doc_1662
|
I found the basic Code for accessing EWS here and it is working fine so far. However when I try to implement other operations that require attributes (like the FindFolder-operation) it fails.
Here is the code I'm using:
import urllib2
from suds.client import Client
from suds.sax.element import Element
from suds.transport.https import HttpTransport
class Transport(HttpTransport):
def __init__(self, **kwargs):
realm, uri = kwargs.pop('realm'), kwargs.pop('uri')
HttpTransport.__init__(self, **kwargs)
self.handler = urllib2.HTTPBasicAuthHandler()
self.handler.add_password(realm=realm,
user=self.options.username,
passwd=self.options.password,
uri=uri)
self.urlopener = urllib2.build_opener(self.handler)
transport = Transport(realm='owa10.123together.com',
uri='https://owa10.123together.com',
username='[email protected]',
password='demo123!')
client = Client("https://owa10.123together.com/EWS/Services.wsdl",
transport=transport)
ns = ('t', 'http://schemas.microsoft.com/exchange/services/2006/types')
soap_headers = Element('RequestServerVersion', ns=ns)
soap_headers.attributes.append('Version="Exchange2010_SP1"')
client.set_options(soapheaders=soap_headers)
address = client.factory.create('t:EmailAddress')
address.Address = '[email protected]'
traversal = client.factory.create('t:FolderQueryTraversalType')
#traversal.Traversal = 'Deep'
#print client.service.GetUserOofSettings(address)
test = client.service.FindFolder(traversal)
print test
When I run this code I get the following error:
suds.TypeNotFound: Type not found: 'Shallow'
I also used the logger in order to figure out the problem and it showes me the following:
DEBUG:suds.mx.literal:starting content:
(Content){
tag = "Shallow"
value = "Shallow"
type = None
}
Does anybody know here where's the problem? Is it my piece of code or is the .wsdl-file not ok?
Please note that I'm a bloody in Python and especially suds. If you need some more information or code just tell me.
Thank you very much in advance!
A: Same as How to fix unresolved types when importing Exchange Web Services (EWS) wsdl file?
Also see https://fedorahosted.org/suds/wiki/Documentation#FIXINGBROKENSCHEMAs
| |
doc_1663
|
1) Which approach is better to use in terms of response times,
fetching data from IMap using getAll
or
fetching data from IMap iterating over keys and using getAsync and then using future to store the retrieved data.
2) When does retrieval of data actually happen in case of getAsync? When future is invoked or when getAsync is called?
3) Which of the two should perform better when backoff is disabled?
A: As a general rule of thumb you need to minimize network trips in a distributed system. So getAll() is better which sends one operation per partition instead of get() which will send one operation over the network per each key.
2) It may or may not be executed before calling future.get(), but it will block and will get the result when you call it if the result is still not there.
| |
doc_1664
|
So there is a single canvas with a rectangle on it. When I hit 'up' the rectangle should move upwards, when I hit 'down' it should go downwards and so on.
But I don't want to have to always stay on the specific button. I want a loop to start whenever a key is pressed. And the loop should stop whenever another key is pressed - which will then start a new loop.
Till now I tried two different versions: one with a while loop and one with a setTimeout() function. Both don't work as I want them to. While() just puts the rectangle to the start of the y-axis and setTimeout() doesn't seem to call itself again. Where's my mistake?
window.onload = function() {
var canvas = document.getElementById("can");
var ctx = canvas.getContext("2d");
var x_coor = 230;
var y_coor = 230;
ctx.fillStyle = "darkgrey";
ctx.fillRect(0, 0, canvas.height, canvas.width);
ctx.fillStyle = "black";
ctx.fillRect(x_coor, y_coor, 20, 20);
var move = {
x_koor: 230,
y_koor: 230,
whichKey: function(event) {
var taste = event.keyCode;
if (taste == 38) { // up
this.up();
} else if (taste == 40) { // down
this.down();
} else if (taste == 37) { // left
x_koor = this.left();
} else if (taste == 39) { // right
x_koor = this.right();
}
},
up: function() {
while (this.y_koor > 0) {
this.y_koor -= 1;
ctx.fillStyle = "darkgrey";
ctx.fillRect(0, 0, canvas.height, canvas.width);
ctx.fillStyle = "black";
ctx.fillRect(this.x_koor, this.y_koor, 20, 20);
}
},
down: function() {
if (y_coor < canvas.height - 20) {
y_coor += 1;
x_coor = x_coor;
ctx.fillStyle = "darkgrey";
ctx.fillRect(0, 0, canvas.height, canvas.width);
ctx.fillStyle = "black";
ctx.fillRect(x_coor, y_coor, 20, 20);
window.setTimeout(this.down, 10);
}
},
// and so on...
window.addEventListener("keydown", move.whichKey.bind(move));
}
<canvas id="can" height="500" width="500"></canvas>
A: Typically, I find it easiest to have a single main game loop. Here, I'm simply keeping track of the last direction set, and handling it in the main game loop (in this case, the setInterval).
I hope this helps, and is what you were looking for.
window.onload = function() {
var canvas = document.getElementById("can");
var ctx = canvas.getContext("2d");
var x_coor = 58;
var y_coor = 58;
var size = 4;
var dirX = 0;
var dirY = 0;
ctx.fillStyle = "darkgrey";
ctx.fillRect(0, 0, canvas.height, canvas.width);
ctx.fillStyle = "black";
ctx.fillRect(x_coor, y_coor, size, size);
window.addEventListener("keydown", keyDown);
function keyDown(e) {
switch (e.keyCode) {
case 38:
dirX = 0;
dirY = -1;
break;
case 40:
dirX = 0;
dirY = 1;
break;
case 37:
dirX = -1;
dirY = 0;
break;
case 39:
dirX = 1;
dirY = 0;
break;
}
}
setInterval(function() {
x_coor += dirX * size;
y_coor += dirY * size;
coordLoop();
ctx.fillStyle = "darkgrey";
ctx.fillRect(0, 0, canvas.height, canvas.width);
ctx.fillStyle = "black";
ctx.fillRect(x_coor, y_coor, size, size);
}, 200);
function coordLoop() {
if (x_coor > canvas.width) {
x_coor = 0;
}
if (x_coor < 0) {
x_coor = canvas.width - size;
}
if (y_coor > canvas.height) {
y_coor = 0;
}
if (y_coor < 0) {
y_coor = canvas.height - size;
}
}
}
<canvas id="can" height="120" width="120"></canvas>
| |
doc_1665
|
["Alfa", "Beta", "Gamma", "Beta", "Alpha"]
I need to count the repetion of elements in this list and to put the result in a list of tuples in descending order.
If the count of two of the elements is the same, I need to sort them in reverse alphabetical order (Z->A)
This is the expected output
[('Beta', 2), ('Alfa', 1), ('Alpha', 1), ('Gamma', 1)]
My idea is to start splitting the string as following
def count_items(string):
wordlist = string.split(' ')
But I have no idea of how to continue.
Could you please help?
A: You can use Counter built module along most_common method
from collections import Counter
>>> l = ["Alfa", "Beta", "Gamma", "Beta", "Alpha"]
>>> Counter(l).most_common()
>>> [('Beta', 2), ('Alfa', 1), ('Alpha', 1), ('Gamma', 1)]
| |
doc_1666
|
init props
<Swiper
effect={"coverflow"}
grabCursor={true}
centeredSlides={true}
slidesPerView={"auto"}
coverflowEffect={{
rotate: 30,
stretch: 0,
depth: 200,
modifier: 1,
slideShadows: true,
}}
>
A: I have no way of proving why this is but pretty sure it's a bug with coverflowEffect.
I've just spent hours debugging this issue, and removing coverflowEffect fixes the slider. Once I reintroduce it, mobile swiping breaks again.
| |
doc_1667
|
The following code raises TypeError:
from django.db.models import Choices
class DataTypes(type, Choices):
CHAR = str, _('Short string')
INTEGER = int, _('Integer')
The error message:
dynamic_attributes = {k for c in enum_class.mro()
TypeError: descriptor 'mro' of 'type' object needs an argument
UPDATE:
When no mixin is used, then the error does not appear. But all the same, the values of the members are not converted correctly into the required data type.
class DataTypes(Choices):
CHAR = str, _('Short string')
INTEGER = int, _('Integer')
Test:
str in (DataTypes.CHAR, DataTypes.INTEGER) # False
A: I agree with Willem Van Onsem's opinion in the comments. I think it is impossible to use models.Choices for such data type as classes. So I tried to find a different approach with the ability to extend other classes.
Defining labels for choices (as Django Choices does) is also implemented.
def _is_dunder(name):
"""
Stolen liberally from 'aenum'.
Returns True if a __dunder__ name, False otherwise.
"""
return (len(name) > 4 and
name[:2] == name[-2:] == '__' and
name[2] != '_' and
name[-3] != '_')
class ChoicesMeta(type):
def __new__(mcs, cls, bases, attrs):
# ignore any keys listed in _ignore_
ignore = attrs.setdefault('_ignore_', [])
ignore.append('_ignore_')
# save constant names into list.
names = [k for k in attrs if not(_is_dunder(k) or k in ignore)]
# save constant labels into list.
labels = []
for k in names:
value = attrs[k]
if (
isinstance(value, (list, tuple)) and
len(value) > 1 and
isinstance(value[-1], (Promise, str))
):
value, label = value
else:
label = k.replace('_', ' ').title()
labels.append(label)
attrs[k] = value
new_cls = super().__new__(mcs, cls, bases, attrs)
new_cls.local_names = names
new_cls.local_labels = labels
return new_cls
@property
def names(cls):
names = []
for c in reversed(cls.__mro__):
names.extend(getattr(c, 'local_names', []))
return list(dict.fromkeys(names))
@property
def choices(cls):
empty = [(None, cls.__empty__)] if hasattr(cls, '__empty__') else []
return empty + [(getattr(cls, name), cls.labels[i]) for i, name in enumerate(cls.names)]
@property
def labels(cls):
labels = []
for c in reversed(cls.__mro__):
labels.extend(getattr(c, 'local_labels', []))
return list(dict.fromkeys(labels))
class Choices(metaclass=ChoicesMeta):
pass
Now you can create your Choices class and also subclass it:
class DataTypes(Choices):
CHAR = str, _('Short string')
INTEGER = int
class OtherTypes(DataTypes):
BOOLEAN = bool, _('Boolean (Either True or False)')
FLOAT = float, _('Floating point number')
Tests:
str in (DataTypes.CHAR, DataTypes.INTEGER) # True
bool in (OtherTypes.CHAR, OtherTypes.BOOLEAN) # True
DataTypes.choices # [(<class 'str'>, 'Short string'), (<class 'int'>, 'Integer')]
OtherTypes.choices # [(<class 'str'>, 'Short string'), (<class 'int'>, 'Integer'), (<class 'bool'>, 'Boolean (Either True or False)'), (<class 'float'>, 'Floating point number')]
| |
doc_1668
|
The text is centered and then there is an image to the right. I've tried plain CSS and I've tried flexbox but cannot get the header to look right.
How do you make the header look like this?
Please see the image for desired design (ignore the vertical line above the "L").
.header {
background: #43e895;
height: 10vh;
width: 100vw;
text-align: center;
}
.header-title {
font-family: 'Avenir Next Demi Bold', 'Arial';
font-size: 17px;
color: #ffffff;
padding-top: 10px;
}
.header-title {
font-family: 'Avenir Next Demi Bold', 'Arial';
font-size: 17px;
color: #ffffff;
padding-top: 10px;
}
.map-icon-container {
float: right;
}
.map-icon {
width: 35px;
}
<div class="header">
<div class="container">
<div class="header-title">Lunch Tyme</div>
<div class="map-icon-container"><img src="map_icon" class="map-icon" alt="Map Icon"/></div>
</div>
</div>
A: a few options :
*
*text-align + position
.header {
background:linear-gradient(to left, rgba(0,0,0,0.75) 50%, rgba(255,0,100,0.75) 50%) #43e895;
height: 10vh;
width: 100vw;
text-align: center;
}
.header-title {
font-family: 'Avenir Next Demi Bold', 'Arial';
font-size: 17px;
color: #ffffff;
padding-top:10px;
}
.map-icon-container {
position:absolute;
right:1em;
top:10px;
}
.map-icon {
width: 35px;
}
<div class="header">
<div class="container">
<div class="header-title">Lunch Tyme</div>
<div class="map-icon-container"><img src="map_icon" class="map-icon" alt="Map Icon"/></div>
</div>
</div>
*
*display + :before
*
*A) table
.header {
background: linear-gradient(to left, rgba(0, 0, 0, 0.75) 50%, rgba(255, 0, 100, 0.75) 50%) #43e895;
height: 10vh;
}
.container {
width: 100vw;
display: table;
table-layout: fixed;
}
.header-title {
font-family: 'Avenir Next Demi Bold', 'Arial';
font-size: 17px;
color: #ffffff;
padding-top: 10px;
text-align: center;
display: table-cell;
}
.container:before {
content: '';
}
.container:before,
.map-icon-container {
display: table-cell;
width: 35px;
}
.map-icon {
width: 35px;
}
<div class="header">
<div class="container">
<div class="header-title">Lunch Tyme</div>
<div class="map-icon-container"><img src="map_icon" class="map-icon" alt="Map Icon" /></div>
</div>
</div>
*
*
*
*B) flex https://css-tricks.com/snippets/css/a-guide-to-flexbox/
.header {
background: linear-gradient(to left, rgba(0, 0, 0, 0.75) 50%, rgba(255, 0, 100, 0.75) 50%) #43e895;
height: 10vh;
}
.container {
display: flex;
}
.header-title {
font-family: 'Avenir Next Demi Bold', 'Arial';
font-size: 17px;
color: #ffffff;
padding-top: 10px;
}
.container:before {
content: '';
}
.container:before,
.map-icon-container {
flex: 1;
text-align:right
}
.map-icon {
width: 35px;
}
<div class="header">
<div class="container">
<div class="header-title">Lunch Tyme</div>
<div class="map-icon-container"><img src="map_icon" class="map-icon" alt="Map Icon" /></div>
</div>
</div>
*
*
*
*C) grid https://css-tricks.com/snippets/css/complete-guide-grid/
.header {
background: linear-gradient(to left, rgba(0, 0, 0, 0.75) 50%, rgba(255, 0, 100, 0.75) 50%) #43e895;
height: 10vh;
}
.container {
display: grid;
grid-template-columns: 1fr auto 1fr;
}
.header-title {
font-family: 'Avenir Next Demi Bold', 'Arial';
font-size: 17px;
color: #ffffff;
padding-top: 10px;
}
.container:before {
content: '';
}
.map-icon-container {
margin: auto 0 auto auto;
}
.map-icon {
width: 35px;
}
<div class="header">
<div class="container">
<div class="header-title">Lunch Tyme</div>
<div class="map-icon-container"><img src="map_icon" class="map-icon" alt="Map Icon" /></div>
</div>
</div>
there is no one better than the other, the good one is the one that fits your needs and that you understand well enough to tune and reuse . Its up to you.
A: Converted to Bootstrap and it got it done correctly.
HTML:
<div class="row flex-nowrap justify-content-between align-items-center header fixed-top">
<div class="col-4 pt-1"></div>
<div class="col-4 text-center">
<div class="header-title">Lunch Tyme</div>
</div>
<div class="col-4 d-flex justify-content-end align-items-center">
<div class="map-icon-container"><img src="map_icon" class="map-icon" alt="Map Icon"/></div>
</div>
</div>
CSS:
.header {
background: #43e895;
height: 10vh;
width: 100vw;
margin-left: 0;
}
.header-title {
font-family: 'Avenir Next Demi Bold', 'Arial';
font-size: 17px;
color: #ffffff;
}
.header-title {
font-family: 'Avenir Next Demi Bold', 'Arial';
font-size: 17px;
color: #ffffff;
}
.map-icon {
width: 35px;
padding-top: 5px;
}
| |
doc_1669
|
A: Start regedit and delete the following two keys. And reboot your OS.
*
*HKEY_CURRENT_USER\SOFTWARE\Classes\.class
*HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.class
*
*Explorer initial state
*Set to open with notepad
*regedit HKEY_CURRENT_USER\SOFTWARE\Classes\.class
*remove key HKEY_CURRENT_USER\SOFTWARE\Classes\.class
*regedit HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.class
*remove key HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.class
*Explorer (sitill unchanged)
*Explorer (after restart windows)
| |
doc_1670
|
table 1
id | rel_id
123 | 456
789 | 321
so id column from table 1 = id from table 2 and will have catgy 180
rel_id column from table 1 = id from table 2 and will have catgy 181
table 2
id | catgy | spl_1 | spl_2 | spl_3 | spl 4
123 | 180 | 6 | 0 | 0 | 7
456 | 181 | 7 | 0 | 0 | 0
789 | 180 | 8 | 9 | 9 | 0
321 | 181 | 9 | 0 | 0 | 0
so i want to comapre spl_2, spl_3, spl_4 for id 123 with spl_1 for id 456 and if same then update id 123 spl's with null(in this case update spl_4 with null)
Thanks
A: You can just use a standard CASE expression for it:
Update YourTable
Set SPCLTY_2 = Case When SPCLTY_2 = SPCLTY_1 Then Null Else SPCLTY_2 End,
SPCLTY_3 = Case When SPCLTY_3 = SPCLTY_1 Then Null Else SPCLTY_3 End,
SPCLTY_4 = Case When SPCLTY_4 = SPCLTY_1 Then Null Else SPCLTY_4 End,
SPCLTY_5 = Case When SPCLTY_5 = SPCLTY_1 Then Null Else SPCLTY_5 End
A: When you need to update values in one table based on values from another table (or the same table, or the result of a join, etc. - from another relation* would be the most general formulation), it is often easiest to do it with the MERGE statement. This is a perfect example.
*Relation is a fancy term for a table or anything that resembles
one, such as the result of a join, an aggregate operation, or really
any kind of SELECT statement.
merge into table_2 t2
using
( select t1.id, s.spl_1
from table_1 t1 join table_2 s on t1.rel_id = s.id
) x
on ( x.id = t2.id )
when matched then update
set t2.spl_2 = case when t2.spl_2 = x.spl_1 then null else t2.spl_2 end,
t2.spl_3 = case when t2.spl_3 = x.spl_1 then null else t2.spl_3 end,
t2.spl_4 = case when t2.spl_4 = x.spl_1 then null else t2.spl_4 end
where x.spl_1 in (t2.spl_2, t2.spl_3, t2.spl_4)
-- WHERE clause so that you only update rows that need to be updated!
;
2 rows merged.
select * from table_2;
ID CATGY SPL_1 SPL_2 SPL_3 SPL_4
---------- ---------- ---------- ---------- ---------- ----------
123 180 6 0 0
456 181 7 0 0 0
789 180 8 0
321 181 9 0 0 0
| |
doc_1671
|
I don't know how to obtain the boolean value true/false and add the price to the amount value if it's true or remove the price if it's false. Does anyone have any suggestion?
<v-container grid-list-md text-xs-center>
<v-card class="">
<h2 class="headline mb-0">Extra ingredients:</h2>
<v-layout row wrap class="text-xs-center" v-for="ingredient in ingredients" :key="ingredient.id">
<v-layout column>
<v-flex xs6>
<v-checkbox name="checkbox" color="light-blue lighten-2" v-bind:label="`${ingredient.name}`" v-model="ingredient.checked" light></v-checkbox>
</v-flex>
</v-layout>
<v-layout column>
<v-flex xs6>
<v-subheader>{{ingredient.price}} €</v-subheader>
</v-flex>
</v-layout>
</v-layout>
<v-divider></v-divider>
<v-layout row wrap class="mb-3">
<v-flex xs6>
<h3 class="headline mb-0">Total price:</h3>
</v-flex>
</v-layout>
</v-card>
</v-layout>
<script>
export default {
data: () => ({
checked1: '',
ingredients: [{
id: 1,
name: "cheese",
price: 2,
checked: '',
}, {
id: 2,
name: "ham",
price: 2.0,
checked: '',
}, {
id: 3,
name: "Bacon",
price: 2.25,
checked: '',
}, {
id: 4,
name: "spinac",
price: 1.6,
checked: '',
}, {
id: 5,
name: "extracheese",
price: 2.5,
checked: '',
}, {
id: 6,
name: "pepper",
price: 2.75,
checked: '',
}],
}),
computed: {
total() {
var total = 0;
for (var i = 0; i < this.ingredients.length; i++) {
total += this.ingredients[i].price;
}
return total;
}
},
methods: {
addToCart(item){
amount = 0;
if(ingredient.checked == true){
amount += ingredient.price;
}
else {
amount -= ingredient.price;
}
}
}
}
</script>
A: Your boolean value is stored in ingredient.checked, and you can use it to control display of the price with either v-if or v-show:
<v-subheader v-if="ingredient.checked">{{ingredient.price}} €</v-subheader>
Then there's just one small change needed to calculate the total value (assuming you only want to add the price of checked items):
computed: {
total() {
var total = 0;
for (var i = 0; i < this.ingredients.length; i++) {
if (this.ingredients[i].checked) { // <-- this is new
total += this.ingredients[i].price;
}
}
return total;
}
},
...and display the computed value just like any other variable:
<h3 class="headline mb-0">Total price: {{total}}</h3>
| |
doc_1672
|
I already know about the Grown, Full, Ramped half-half (taken from "A Field Guide to Genetic Programming") and saw one new algorithm Two Fast Tree-Creation (haven't read the paper yet.).
A: Initial population plays an important role in heuristic algorithms such as GA as it help to decrease the time those algorithms need to achieve an acceptable result. Furthermore, it may influence the quality of the final answer given by evolutionary algorithms. (http://arxiv.org/pdf/1406.4518.pdf)
so as you know about Koza's different population methods, you must also remember that each algorithm that is used, isn't 100% random, nor can it be as an algorithm can be used. therefore you can predict what the next value will be.
another method you could potentially use is something called Uniform initialisation (refer to the free pdf : "a field guide to genetic programming"). the idea of this is that initially, when a population is created, within a few generations, due to crossing over and selection, the entire syntax tree could be lost within a few generations. Langdon (2000) came up with the idea of a ramped uniform distribution which effectively allows the user to specify the range of sizes a possible tree can have, and if a permutation of the tree is generated in the search space that doesn't fulfil the range of sizes, then the tree is automatically discarded, regardless of its fitness evaluation value. from here, the ramped uniform distribution will create an equal amount of trees depending on the range that you have used - all of which are random, unique permutations of the functions and terminal values you are using. (again, refer to "a field guide on genetic programming" for more detail)
this method can be quite useful in terms of sampling where the desired solutions are asymmetric rather than symmetric (which is what the ramped half and half deal with).
other recommeded readings for population initialisation:
http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.50.962&rep=rep1&type=pdf
A: I think that will depend on the problem that you want to solve. For example I'm working on a TSP and my initial population is generated using a simple greedy technique. Sometimes you need to create only feasible solutions so you have to create a mechanism for doing that. Usually you will find papers about your problem and how to create initial solutions. Hope this helps.
| |
doc_1673
|
public static void showStuff(Multimap<String, String> map) {
for (String key : map.keys()) {
System.out.println("The key, " + key
+ ", has the results: " + map.get(key));
}
}
This outputs:
The key, **one**, has the results: [a,b,c,d,d,e]
The key, **one**, has the results: [a,b,c,d,d,e]
The key, **one**, has the results: [a,b,c,d,d,e]
The key, **one**, has the results: [a,b,c,d,d,e]
The key, **one**, has the results: [a,b,c,d,d,e]
The key, **two**, has the results: [a,a,a,b,b,e]
The key, **two**, has the results: [a,a,a,b,b,e]
How would I have it only output unique keys. I want it to only printout the statement once rather than repeat it multiple times. I have a table with different rows with duplicate keys, hence I used the MultiMap to get all the values for a duplicated key. How will I now output only
The key, **one**, has the results: [a,b,c,d,d,e]
The key, **two**, has the results: [a,a,a,b,b,e]
Thank You!
A: You can use Multimap.keySet() to get just the distinct keys.
You can use Multimap.entries() to get the (key, values) pairs, rather than having to go back to the map to request the values associated with each key.
Alternatively, you can use Multimap.asMap() to convert it to a java.util.Map, and then work with that instead.
A: Use map.keySet() instead of map.keys()
| |
doc_1674
|
My template, the line that works correctly, looks thus:
strFilter = "@SQL=""urn:schemas:httpmail:subject"" like '%" & strSubject & "%'"
Set itmFiltered = fld.Items.Restrict(strFilter)
I've tried including the dates in various ways. Based on the help file, I thought something like this would work:
strFilter = "@SQL=""urn:schemas:httpmail:subject"" like '%" & strSubject & "%'"
If Len(strStart) <> 0 then
strfilter = strfilter & " AND ""urn:schemas:httpmail:Received:"" >='" & strStart & "'"
End If
set itmFiltered = fld.Items.Restrict(strfilter)
Error, every time.
I also tried setting it to just filter by the date, without including the subject line, like this:
strFilter = "@SQL=""urn:schemas:httpmail:Received: >=""'" & strStart & "'"
Again, no luck.
So, my questions:
What syntax do I need to use the Items.Restrict method to filter by date?
And what syntax do I need to use the Items.Restrict method to filter by multiple fields?
A: Firstly, you have an ":" at the end of""urn:schemas:httpmail:Received:"". Secondly, there is no such DASL name. Did you mean "datereceived"?
You need to use "urn:schemas:httpmail:datereceived" or "http://schemas.microsoft.com/mapi/proptag/0x0E060040". Use OutlookSpy (I am its author) to look up a DASL property name - click IMessage button, select the property, look at the DASL edit box.
| |
doc_1675
|
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.ACTION_TIMEZONE_CHANGED"/>
</intent-filter>
</receiver>
package com.broadcastreceiver;
import java.util.ArrayList;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class ExampleBroadCastReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
// TODO Auto-generated method stub
Log.d("ExmampleBroadcastReceiver", "intent=" + intent);
Intent intent1 = new Intent(context,Login.class);
context.startActivity(intent1);
}
}
I run this above code change the time zone in settings not calling other activity. Can anybody tell what the problem is?
A: I was having the same issue, and this thread helped me get TimeZone updates working, however I still wasn't getting notifications for Date/Time changes. I finally found that there's a difference in what you specify in your manifest file and what your broadcast receiver uses when filtering intents. While it IS documented in the Android Intent reference, it is very easy to overlook!
In your AndroidManifest.xml file, use the following:
<receiver android:name=".MyReceiver">
<intent-filter>
<!-- NOTE: action.TIME_SET maps to an Intent.TIME_CHANGED broadcast message -->
<action android:name="android.intent.action.TIME_SET" />
<action android:name="android.intent.action.TIMEZONE_CHANGED" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
And in your receiver class:
public class MyReceiver extends BroadcastReceiver {
private static final String TAG = "MyReceiver";
private static boolean DEBUG = true;
@Override
public void onReceive(Context context, Intent intent) {
final String PROC = "onReceive";
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
if (DEBUG) { Log.v(TAG, PROC + ": ACTION_BOOT_COMPLETED received"); }
}
// NOTE: this was triggered by action.TIME_SET in the manifest file!
else if (intent.getAction().equals(Intent.ACTION_TIME_CHANGED)) {
if (DEBUG) { Log.v(TAG, PROC + ": ACTION_TIME_CHANGED received"); }
}
else if (intent.getAction().equals(Intent.ACTION_TIMEZONE_CHANGED)) {
if (DEBUG) { Log.v(TAG, PROC + ": ACTION_TIMEZONE_CHANGED received"); }
}
}
}
A: It wasn't working because the intents are wrong. Replace the ones above with:
<intent-filter>
<action android:name="android.intent.action.TIMEZONE_CHANGED" />
<action android:name="android.intent.action.TIME" />
</intent-filter>
Then go to the Settings area and change the timezone.
A: I guess you didn't include the following lines in your AndroidManifext.xml, did you?
<receiver android:name=".ExampleBroadcastReceiver" android:enabled="false">
<intent-filter>
<action android:name="android.intent.ACTION_TIMEZONE_CHANGED" />
<action android:name="android.intent.ACTION_TIME" />
</intent-filter>
</receiver>
| |
doc_1676
|
My program objective
*
*Integral up/down counter GUI constructed using tkinter. (Python 3.4.2)
*Spinbox as user entry point - User either enters a "target" integer
or clicks on its up/down arrow.
*Show delayed updates on a label as the number on the label ramps up/
down to meet the "targeted" integer mentioned in (2)
*Updating automatically stops when the number displayed on the label equals the
targeted value
*A "Go" button to starts the ramp up/ down after the user entered the targeted value
*A "Stop" button to stop the update pause the ramp up/ down anytime
before reaching the targeted value
In this simplified implementation for debugging, you will see that I seemingly used the spinbox control variable unnecessarily. The actual (longer program) the control variable shall be used to trigger a validation routine for the user's input into the spinbox. And it is actually the control variable that is giving me some "curious error" during program start up
My simplified codes are as follows:
import tkinter as tk
import threading
import time
class controlPanel():
def __init__(self, master):
self.root = master
self.buildWidgets()
def buildWidgets(self):
self.labelVar = 0
self.ctrlVar = tk.StringVar()
self.ctrlVar.set(str(self.labelVar))
self.delay = 0.5
#+++++++++++++++++++++++++++++++++
self.labelName = tk.Label(self.root, text="Current Value: ", padx=3, pady=3)
self.labelName.grid(row=0, column=0)
self.labelValue = tk.Label(self.root, text=str(self.labelVar), padx=3, pady=3)
self.labelValue.grid(row=0, column=1)
#+++++++++++++++++++++++++++++++++
self.spinboxName = tk.Label(self.root, text="Target: ", padx=3, pady=3)
self.spinboxName.grid(row=1, column=0)
self.spinBoxA = tk.Spinbox(self.root, from_=0, to=1000,
textvariable=self.ctrlVar,
width=10, justify=tk.CENTER)
self.spinBoxA.grid(row=1, column=1)
#+++++++++++++++++++++++++++++++++
self.goButton = tk.Button(self.root, text="Go", width=12,
command=self.goButtonFunction,
padx=3, pady=3)
self.goButton.grid(row=2, column=1)
#+++++++++++++++++++++++++++++++++
self.stopButton = tk.Button(self.root, text="Stop", width=12,
command=self.stopButtonFunction,
padx=3, pady=3)
self.stopButton.grid(row=2, column=0)
#+++++++++++++++++++++++++++++++++
#self.labelValue.update()
#self.spinBoxA.update()
self.root.update()
def goButtonFunction(self):
print('GO button clicked')
self.flgRun = True
def stopButtonFunction(self):
print('STOP button clicked')
self.flgRun = False
class controlThread(controlPanel):
def __init__(self, master, name):
self.root = master
self.name = name
controlPanel.__init__(self, self.root)
self.flgRun = False
self.flgRunLock = threading.Lock()
self.pollPeriod = 100 # polling period, in ms
self.thread1 = threading.Thread(target = self.towardsTarget,
name=self.name)
self.thread1.daemon = False
self.thread1.start()
#time.sleep(5)
self.pollFlgRun()
#+++++++++++++++++++++++++++++++++
def pollFlgRun(self): # polls self.flgRun every self.pollPeriod
if self.flgRun:
print('<< Entering pollFlgRun >>')
time.sleep(0.01)
self.towardsTarget()
#self.flgRunLock.acquire() # lock thread to reset self.flgRun
self.flgRun = False # reset self.flgRun
#self.flgRunLock.release() # release thread
self.root.after(self.pollPeriod, self.pollFlgRun)
#+++++++++++++++++++++++++++++++++
def towardsTarget(self):
delay = 0.01 # delay in seconds
time.sleep(delay)
print('<< Entering towardsTarget >>')
#self.flgRunLock.acquire()
print('self.labelVar : ', str(self.labelVar))
# Problem 1: the following reference to self.ctrlVar gave error everytime the
# program starts. The error>> "RuntimeError: main thread is not in main loop"
# subsequent click on controlPanel.goButton will still give the program behavior
# specified above (i.e. no more error on subsequent clicks on the "Go" button)
#
# Problem 2: and when placed in a lock.acquire()/release() block, clicking the
# controlPanel.goButton will freeze up program
print('self.ctrlVar : ', self.ctrlVar.get())
#self.flgRunLock.release()
# test self.flgRun as well in case reset by controlPanel.stopButton
while( self.flgRun and str(self.labelVar) != self.ctrlVar.get() ):
print('WHILE loop')
if( self.labelVar < int(self.ctrlVar.get()) ):
self.labelVar +=1
print('self.labelVar before sleep> ', self.labelVar)
time.sleep(delay)
print('self.labelVar AFTER sleep> ', self.labelVar)
self.labelValue["text"] = str(self.labelVar)
self.labelValue.update()
else:
self.labelVar -=1
print('self.labelVar before sleep> ', self.labelVar)
time.sleep(delay)
print('self.labelVar AFTER sleep> ', self.labelVar)
self.labelValue["text"] = str(self.labelVar)
self.labelValue.update()
if __name__ == '__main__':
root = tk.Tk()
ctrl = controlThread(root, "X-thread")
Problem 1:
*
*Within class controlThread.towardsTarget() the print statement
referencing self.ctrlVar gave rise to error everytime the program
starts. The error being "RuntimeError: main thread is not in main
loop".
*Subsequent click on the "Go" button (controlPanel.goButton) will still give the program
behavior specified above (i.e. no more error on subsequent clicks on the "Go" button)
Problem 2:
*
*when the print statement mentioned in Problem 1 is placed in a
lock.acquire()/lock.release() block, clicking the "Go" button
(controlPanel.goButton) will freeze up program
I've read the following two pages and the links associated
*
*Threaded Tkinter script crashes when creating the second Toplevel widget
*RuntimeError: main thread is not in main loop
But the solutions mentioned in the two pages above did not make much sense to me as the error message "RuntimeError: main thread is not in main loop" does not appear at all if the mentioned print statement referencing self.ctrlVar was removed altogether.
My questions are
*
*What is causing this error in Problem 1?
*I was expecting the lock.acquire()/lock.release() block to solve
the problem but it ended up freezing the program instead. How can
the problem be avoided with the 'print' statement referencing
self.ctrlVar in place?
| |
doc_1677
|
<pre>
<form action='' method='POST'>
<input type='text' name='jml'>
<input type='submit' name='submit'>
</form>
<form action='' method='POST'>
<?php
if(isset($_POST['jml'])){
$jml = $_POST['jml'];
for($i=0;$i<$jml;++$i){
?>
Stuff Name <input type="text" name="name"> 
Stuff Price <input type='text' name='price'><br>
<br>
<?php
}
echo "<input type='submit' name='submit2'>";
echo "</form>";
}
if(isset($_POST['submit2'])){
$name[] = $_POST['name'];
$price[] = $_POST['price'];
global $jml;
for($i=0;$i<$jml;++$i){
echo $name.' '.$price.'<br>';
}
}
?>
</pre>
i was basic at C++ it's so easy to loop, but i'm still much to learn on this php so anyone can help me please?
A: What you need to do first is if you're expecting multiple row fields, put a [] in your name attribute in text fields. Example:
<input type="text" name="name[]">
This in turn will accept multiple text inputs under the same name turning it into an array.
Next, since you're reliant on the number of fields to be generated by $jml = $_POST['jml']; this will just be available on the first request. On the next submission this will be gone. Instead of using that with a global which doesn't make sense, just use the count of the submitted text fields.
$name = $_POST['name'];
$price = $_POST['price'];
$count = count($name); // get count
Take not that this is reliant to the forms all fields being complete.
After that, its just basic array pointing. echo $name[$i]:
Revised code:
<pre>
<form action='' method='POST'>
<input type='text' name='jml'>
<input type='submit' name='submit'>
</form>
<form action='' method='POST'>
<?php
if(isset($_POST['jml'])){
$jml = $_POST['jml'];
for($i=0;$i<$jml;++$i){
?>
Stuff Name <input type="text" name="name[]"> 
Stuff Price <input type='text' name='price[]'><br>
<br>
<?php
}
echo "<input type='submit' name='submit2'>";
echo "</form>";
}
if(isset($_POST['submit2'])){
$name = $_POST['name'];
$price = $_POST['price'];
$count = count($name);
for($i=0;$i<$count;++$i){
echo $name[$i].' '.$price[$i].'<br>';
}
}
?>
</pre>
A: Use foreach loop This is how you can easily loop through an array:
foreach($_POST as $key=>$value){
echo $value;
}
A: Check this
Working code here http://main.xfiddle.com/7ffb488b/stackoverflow/Loopanarraywithform.php
<pre>
<?php
if(isset($_POST['submit'])){
echo "<form action='' method='POST'>";
$jml = intval($_POST['jml']);
for($i=0;$i<$jml;++$i){
?>
Stuff Name <input type="text" name="name[]"> 
Stuff Price <input type='text' name='price[]'><br>
<br>
<?php
}
echo "<input type='submit' name='submit2'>";
echo "</form>";
}elseif(isset($_POST['submit2'])){
$name = $_POST['name'];
$price = $_POST['price'];
// global $jml;
$i=0;
foreach ($name as $key => $value) {
echo $value.' '.$price[$key].'<br/>';
$i++;
}
}else{?>
<form action='' method='POST'>
<input type='text' name='jml'>
<input type='submit' name='submit'>
</form>
<?php
}
?>
</pre>
| |
doc_1678
|
Visual FoxPro FAQs:
Q: Are there plans for Visual FoxPro to support 64-bit versions of the Windows operating system?
No. While Visual FoxPro will remain 32-bit and not natively use 64-bit addressing; it will run in 32-bit compatibility mode.
I tried to make one.
It is very much faster than ODBC, but there is only one problem: I cannot determine if a row is deleted or not.
In dBase when you delete a row it doesn't get really deleted, it only gets marked as deleted - how do I tell if a row is deleted?
A: The first byte of each record (not header or field description, but actual record data) will contain an asterisk ("*") if the record is deleted, or a blank space (" ") if not.
Here's something I found a while back on Wotsit.org that may help:
----------------------------------------------------------------------------
Genaral Format of .dbf files in Xbase languages 18-Nov-96
----------------------------------------------------------------------------
Applies for / supported by:
FS = FlagShip D3 = dBaseIII+
Fb = FoxBase D4 = dBaseIV
Fp = FoxPro D5 = dBaseV
CL = Clipper
1. DBF Structure
================
Byte Description
------+--------------------------------------
0..n .dbf header (see 2 for size, byte 8)
n+1 1st record of fixed length (see 2&3) \
2nd record (see 2 for size, byte 10) \ if dbf is
... / not empty
last record /
last optional: 0x1a (eof byte)
2. DBF Header (variable size, depending on field count)
=======================================================
Byte Size Contents Description Applies for (supported by)
----+----+--------+----------------------------+-----------------------------
00 1 0x03 plain .dbf FS, D3, D4, D5, Fb, Fp, CL
0x04 plain .dbf D4, D5 (FS)
0x05 plain .dbf D5, Fp (FS)
0x43 with .dbv memo var size FS
0xB3 with .dbv and .dbt memo FS
0x83 with .dbt memo FS, D3, D4, D5, Fb, Fp, CL
0x8B with .dbt memo in D4 format D4, D5
0x8E with SQL table D4, D5
0xF5 with .fmp memo Fp
01 3 YYMMDD Last update digits all
04 4 ulong Number of records in file all
08 2 ushort Header size in bytes all
10 2 ushort Record size in bytes all
12 2 0,0 Reserved all
14 1 0x01 Begin transaction D4, D5
0x00 End Transaction D4, D5
0x00 ignored FS, D3, Fb, Fp, CL
15 1 0x01 Encryptpted D4, D5
0x00 normal visible all
16 12 0 (1) multi-user environment use D4,D5
28 1 0x01 production index exists Fp, D4, D5
0x00 index upon demand all
29 1 n language driver ID D4, D5
0x01 codepage 437 DOS USA Fp
0x02 codepage 850 DOS Multi ling Fp
0x03 codepage 1251 Windows ANSI Fp
0xC8 codepage 1250 Windows EE Fp
0x00 ignored FS, D3, Fb, Fp, CL
30 2 0,0 reserved all
32 n*32 Field Descriptor, see (2a) all
+1 1 0x0D Header Record Terminator all
2a. Field descriptor array in dbf header (fix 32 bytes for each field)
========================================
Byte Size Contents Description Applies for (supported by)
----+----+--------+----------------------------+-----------------------------
0 11 ASCI field name, 0x00 termin. all
11 1 ASCI field type (see 2b) all
12 4 n,n,n,n fld address in memory D3
n,n,0,0 offset from record begin Fp
0,0,0,0 ignored FS, D4, D5, Fb, CL
16 1 byte Field length, bin (see 2b) all \ FS,CL: for C field type,
17 1 byte decimal count, bin all / both used for fld lng
18 2 0,0 reserved all
20 1 byte Work area ID D4, D5
0x00 unused FS, D3, Fb, Fp, CL
21 2 n,n multi-user dBase D3, D4, D5
0,0 ignored FS, Fb, Fp, CL
23 1 0x01 Set Fields D3, D4, D5
0x00 ignored FS, Fb, Fp, CL
24 7 0..0 reserved all
31 1 0x01 Field is in .mdx index D4, D5
0x00 ignored FS, D3, Fb, Fp, CL
2b. Field type and size in dbf header, field descriptor (1 byte)
=======================================================
Size Type Description/Storage Applies for (supported by)
------+---------+------------------------------+-----------------------------
C 1..n Char ASCII (OEM code page chars) all
rest= space, not \0 term.
n = 1..64kb (using deci count) FS
n = 1..32kb (using deci count) Fp, CL
n = 1..254 all
D 8 Date 8 Ascii digits (0..9) in the all
YYYYMMDD format
F 1..n Numeric Ascii digits (-.0123456789) FS, D4, D5, Fp
variable pos. of float.point
n = 1..20
N 1..n Numeric Ascii digits (-.0123456789) all
fix posit/no float.point
n = 1..20 FS, Fp, CL
n = 1..18 D3, D4, D5, Fb
L 1 Logical Ascii chars (YyNnTtFf space) FS, D3, Fb, Fp, CL
Ascii chars (YyNnTtFf ?) D4, D5 (FS)
M 10 Memo 10 digits repres. the start all
block posit. in .dbt file, or
10spaces if no entry in memo
V 10 Variable Variable, bin/asc data in .dbv FS
4bytes bin= start pos in memo
4bytes bin= block size
1byte = subtype
1byte = reserved (0x1a)
10spaces if no entry in .dbv
P 10 Picture binary data in .ftp Fp
structure like M
B 10 Binary binary data in .dbt D5
structure like M
G 10 General OLE objects D5, Fp
structure like M
2 2 short int binary int max +/- 32767 FS
4 4 long int binary int max +/- 2147483647 FS
8 8 double binary signed double IEEE FS
3. Each Dbf record (fix length)
==================
Byte Size Description Applies for (supported by)
------+----+--------------------------------------+--------------------------
0 1 deleted flag "*" or not deleted " " all
1..n 1.. x-times contents of fields, fixed all
length, unterminated.
For n, see (2) byte 10..11
| |
doc_1679
|
The process starts when I run from command line:
$ python3 input_process.py
But I get the exception:
sqlalchemy.exc.NoSuchColumnError: "Could not locate column in row for column 'fp_feed_types.id'"
Below is my code:
input_process.py
from feed_process.main_process import run
if __name__ == "__main__":
run()
feed_process/main_process.py
from multiprocessing import Pool
from feed_process.models import FeedIn
from feed_process.models.db import DBSession
def process_feed(feed_id):
session = DBSession()
feed_in = session.query(FeedIn).get(feed_id)
print(feed_in.feed_type)
def run(urls = None, feed_ids = None, num_workers = None):
DBSession().query(FeedId).get(26)
feed_ids = [1, 2, 3]
with Pool(processes = num_workers) as pool:
responses = [pool.apply_async(process_feed, (feed_id,)) for feed_id in feed_ids]
for response in responses:
response.get()
feed_process/models/db.py
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
connection_string = ""
engine = create_engine(connection_string)
Session = sessionmaker(bind=engine)
DBSession = scoped_session(Session)
feed_process/models/model.py
Base = declarative_base()
class FeedType(Base):
__tablename__ = "fp_feed_types"
id = Column(String, primary_key = True)
class FeedIn(Base):
__tablename__ = "fp_feeds_in"
id = Column("feedid", Integer, primary_key = True)
name = Column("feedname", String)
feed_type_id = Column(String, ForeignKey("fp_feed_types.id"))
feed_type = relationship("FeedType")
If I delete the line DBSession().query(FeedId).get(26) in run function The process works great :|. Note that 26 is a random number.
And yes, column 'fp_feed_types.id' exists.
What am I doing wrong?
| |
doc_1680
|
This is the current CSS:
.captcha-main-image {
width: 100%;
height: auto;
}
<img class ="captcha-main-image" id="captchaImage" src="">
I would like to change its width value.
This element is being generated by a different source and I can't ask the developer to change its value.
Any chance I can do that by using !important somehow?
A: You could add the class with max-width attribute to limit the width, e.g:
.captcha-main-image {
max-width: 100px;
}
A: Because of Angular's view isolation, you can override it only if you put the overrides in application's main style sheet.
In your application's styles.css, which is your application's main scss file - the one that is mentioned in agular.json, add the override:
.captcha-main-image {
width: <your-value>
}
Typically, the !important is not required. Use it only if required.
A: If you want to override class within component adding !important will help
Or if you want to override the css outside of that component use ::ng-deep .captcha-main-image can do.
| |
doc_1681
|
The file is returned from the server in the Response (binaries set as attachment), and I am letting the browser handle the file download from there on out.
Im doing the following on button click:
var fileUrl = 'mysite.com?id=12345';
document.location.href = fileUrl;
This will load the file, however, it can take a couple of seconds. I would like to show a preloader but then ofcourse I have to know when the file has been downloaded completed. Since I'm staying on the same page, is there a method or callback that tells if the 'new' location is loaded and thus I can hide the preloader?
Thanks!
A: Assuming you can download the file twice, you could load the file in a hidden iframe and detect when the iframe is done loading. Then, the file is already cached and should download quickly.
| |
doc_1682
|
Like in php:
$res = ($x > $y)? $x: $y;
What's its conversion in javascript?
A: var x = 2;
var y = 3;
var res = (x > y)? x: y;
Although perhaps the following would be better:
var res = Math.max(x, y);
A: It is the same in javascript:
res = (y < x) ? x : y; or res = (x > y) ? x : y;
A: The same. It is called ternary:
var x = 10, y = 50, res = 0;
res = (x > y) ? x : y;
alert(res);
A: It's the same in javascript :)
var res = (x > y) ? x : y;
A: Here you are: var res = x>y?x:y;
| |
doc_1683
|
have Dream Day
A: $("input").change(function(){
// do something
});
Click here for more information.
A: Try This code ,
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="../jquery-latest.js"></script>
<script>
$(document).ready(function(){
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("div").text(str);
})
.change();
});
</script>
<style>
div { color:red; }
</style>
</head>
<body>
<select name="sweets" multiple="multiple">
<option>Chocolate</option>
<option selected="selected">Candy</option>
<option>Taffy</option>
<option selected="selected">Carmel</option>
<option>Fudge</option>
<option>Cookie</option>
</select>
<div></div>
</body>
</html>
| |
doc_1684
|
However, when I navigate to access phpmyadmin or something else with the URL, http://127.0.0.1/home/index.php or http://127.0.0.1:8887/home/index.php, it's not able to connect.
The apache port is listening to 127.0.0.1:8887
A: UPDATE Feb 10th, 2014 Venkateshwaran Selvaraj solved the problem:
When I entered this URL directly
http://127.0.0.1:8887/modules/phpmyadmin3522x140127182138/
it takes me to phpmyadmin.
| |
doc_1685
|
My thought was to use the {if } approach within the pipe:
{if(input$diss=="Total")
dySeries("1", label = "All") else
dySeries("man", label = "Male") %>%
dySeries("woman", label = "Female")
}
This step comes after dygraph() is called. My idea was to say "if there is no disaggregation, use dySeries("1", label = "All"), otherwise use dySeries("man", label = "Male") %>% dySeries("woman", label = "Female").
But I get an error:
$ operator is invalid for atomic vectors
Am I on the right track, or is there a better way to create conditional plot parameters for dygraph based on inputs?
---
title: "test"
output:
flexdashboard::flex_dashboard:
theme: bootstrap
runtime: shiny
---
```{r setup, include=FALSE}
library(flexdashboard)
library(tidyverse)
library(tibbletime)
library(dygraphs)
library(magrittr)
library(xts)
```
```{r global, include=FALSE}
# generate data
set.seed(1)
dat <- data.frame(date = seq(as.Date("2018-01-01"),
as.Date("2018-06-30"),
"days"),
sex = sample(c("male", "female"), 181, replace=TRUE),
lang = sample(c("english", "spanish"), 181, replace=TRUE),
age = sample(20:35, 181, replace=TRUE))
dat <- dplyr::sample_n(dat, 80)
```
Sidebar {.sidebar}
=====================================
```{r}
radioButtons("diss", label = "Disaggregation",
choices = list("All" = "Total",
"By Sex" = "sex",
"By Language" = "lang"),
selected = "Total")
```
Page 1
=====================================
```{r plot}
renderDygraph({
grp_col <- rlang::sym(input$diss)
dat %>%
mutate(Total = 1) %>%
mutate(my_group = !!grp_col) %>%
group_by(date = lubridate::floor_date(date, "1 week"), my_group) %>%
count() %>% spread(my_group, n) %>% ungroup() %>%
padr::pad() %>% replace(is.na(.), 0) %>%
xts::xts(order.by = .$date) %>%
dygraph() %>%
dyRangeSelector() %>%
{if(input$diss=="Total")
dySeries("1", label = "All") else
dySeries("male", label = "Male") %>%
dySeries("female", label = "Female")
} %>%
dyOptions(
useDataTimezone = FALSE,
stepPlot = TRUE,
drawGrid = FALSE,
fillGraph = TRUE,
colors = ifelse(input$diss=="Total",
"blue",
c("purple", "orange"))
)
})
```
A: Eric!
I had a similar problem and this aproach solved it for me:
Inside the {if} you have to specify axactly where the element that comes through the pipe is going to fit in the dySeries, you do that by placing a dot (.) in the dySeries function.
Instead of the if you used, you could try the following:
{if(input$diss=="Total")
dySeries(., "1", label = "All") else
dySeries(., "man", label = "Male")
}%>%
{if(input$diss=="Total")
.
else
dySeries(., "woman", label = "Female")
}
I divided the {if} into two conditional evaluations, I don't know if it's going to work, but it's worth the try. You shouldn't get the error mentioned in the question when you use the dot. I had a question about conditional evaluation by using pipes and was able to solve it in a similar way, if you want to take a look.
| |
doc_1686
|
public class MediaContent
{
public MediaContent()
{
this.Sequences = new List<MediaSequence>();
this.Items = new List<MediaItem>();
}
public List<MediaSequence> Sequences
{
get;
set;
}
public List<MediaItem> Items
{
get;
set;
}
}
public class MediaSequence
{
public MediaSequence()
{
this.Sequences = new List<MediaSequence>();
this.Items = new List<MediaItem>();
}
public List<MediaSequence> Sequences
{
get;
set;
}
public List<MediaItem> Items
{
get;
set;
}
}
public class MediaItem
{
public string Filename
{
get;
set;
}
}
The difficulty comes because each node can contain 2 lists, and the lists are recursive. Example data is show below.
var uberNestedSequence = new MediaSequence();
uberNestedSequence.Items.Add(new MediaItem { Filename = "video1.mp4" });
uberNestedSequence.Items.Add(new MediaItem { Filename = "video2.avi" });
var nestedSequence = new MediaSequence();
nestedSequence.Sequences.Add(uberNestedSequence);
var nestedSequence2 = new MediaSequence();
this.Media.Sequences.Add(nestedSequence);
this.Media.Sequences.Add(nestedSequence2);
So, how do I display this data in a WPF Tree view?
<TreeView Margin="5" VerticalAlignment="Top" Grid.Row="1" ItemsSource="{Binding Media}">
I have tried the below but apparently you cannot specify 2 different templates for the same data type.
<HierarchicalDataTemplate DataType="{x:Type local:MediaSequence}" ItemsSource="{Binding Sequences}">
<TextBlock Text="sequence" />
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:MediaSequence}" ItemsSource="{Binding Items}">
<TextBlock Text="item" />
</HierarchicalDataTemplate>
Any help appreciated, thanks
A: Okay lets tackle this in terms of the simplest things first, and it should help to clear out your thinking. It might not look like it but you've not really got anything more complicated than the normal, folders and files heirachy that we usually see.
So if we start with the ends of the trees first, we can define
<DataTemplate DataType="{x:Type local:MediaItem}">
<TextBlock Text="item" />
</DataTemplate>
We don't any subitems so its just a normal template.
Moving deeper into the tree we now have nodes of MediaSequences which have both items and sequences on them. If only we could treat them as one thing?
Well if we stick to the file system analogy, you find that DotNet defines FileInfos and DirectoryInfos as derivations of the a base FileSystemInfo. All we need to do is the same.
public interface IMedia
{
// Actually they have nothing in common
}
public class MediaItem : IMedia
{
...
}
public class MediaSequence : IMedia
{
public IEnumerable<IMedia> Children
{
get
{
// This one collection can now expose both types
// but can be anything behind the scenes
return Sequences.Concat(Items);
}
}
}
Which then allows us to define the other template
<HierarchicalDataTemplate DataType="{x:Type local:MediaSequence}" ItemsSource="{Binding Children}">
<TextBlock Text="sequence" />
</HierarchicalDataTemplate>
And if you really need to you can define your root as something different too, but its really just a sequence.
public class MediaContent : MediaSequence
{
...
}
| |
doc_1687
|
Pyodc v- 4.0.31
ibmiacccess 1..1.0.15-1.0
('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'IBM i Access ODBC Driver 64-bit' : file not found (0) (SQLDriverConnect)")
None
avail = pyodbc.drivers()
print (avail)
drivers = [item for item in pyodbc.drivers()]
driver = drivers[-1]
sys = 'xxxxxxxxx'
uname = 'dbuser'
pas ='xxxxxx'
try:
connection = pyodbc.connect(
DRIVER= {driver} ,
system= {sys},
uid= {uname},
pwd={pas},
autocommit=True)
cursor = connection.cursor()
cursor.execute(query)
x = cursor.fetchall()
except Exception as e:
print(e)
x = None
finally:
exit
I am able to connect to isql -v
#isql -v dbuser
+---------------------------------------+
| Connected! |
| |
| sql-statement |
| help [tablename] |
| quit |
| |
+---------------------------------------+
configured odbcinist.ini and odbc.ini follows :
[ODBC Data Sources]
dbuser = IBM i Access ODBC Driver 64-bit
Default = IBM i Access ODBC Driver 64-bit
[dbuser]
Description = IBM i Access ODBC Driver 64-bit
Driver = IBM i Access ODBC Driver 64-bit
System = xxxxxxx
UserID = xxxx
Password = xxxx
Naming = 0
DefaultLibraries = QGPL
Database =
ConnectionType = 0
CommitMode = 2
ExtendedDynamic = 1
DefaultPkgLibrary = QGPL
DefaultPackage = A/DEFAULT(IBM),2,0,1,0,512
AllowDataCompression = 1
MaxFieldLength = 32
BlockFetch = 1
BlockSizeKB = 128
ExtendedColInfo = 0
LibraryView = ENU
AllowUnsupportedChar = 0
ForceTranslation = 0
Trace = 0
-----------------------------------
[IBM i Access ODBC Driver]
Description=IBM i Access for Linux ODBC Driver
Driver=/opt/ibm/iaccess/lib/libcwbodbc.so
Setup=/opt/ibm/iaccess/lib/libcwbodbcs.so
Driver64=/opt/ibm/iaccess/lib64/libcwbodbc.so
Setup64=/opt/ibm/iaccess/lib64/libcwbodbcs.so
Threading=0
DontDLClose=1
UsageCount=1
[IBM i Access ODBC Driver 64-bit]
Description=IBM i Access for Linux 64-bit ODBC Driver
Driver=/opt/ibm/iaccess/lib64/libcwbodbc.so
Setup=/opt/ibm/iaccess/lib64/libcwbodbcs.so
Threading=0
DontDLClose=1
UsageCount=1
also linked
any help is great thank you in advance !!!
A: Not familiar with your setup, but if I get a "File not found" while connecting to the driver, the file not found in question is usually an .so file. In the simplest case the driver is just missing and not installed. More obscure cases I encountered were 32Bit / 64Bit mismatch, or a dependency of the driver missing (as in an .so file not installed on the system). Using the ldd shows you all the dynamic libraries your driver depends on.
| |
doc_1688
|
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
RewriteCond %{HTTP_HOST} ^www\.samajamonline\.com$
RewriteRule ^/?$ "http\:\/\/samajamonline\.com\/" [R=301,L]
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType text/css "access plus 1 year"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 1 month"
</IfModule>
<IfModule mod_headers.c>
<FilesMatch "\.(js|css|xml|gz)$">
Header append Vary: Accept-Encoding
</FilesMatch>
</IfModule>
<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>
Only after refreshing items are showing on my shopping cart and also destroy cart function is also not working
| |
doc_1689
|
Thank you @n.m
P.S. - few of the array's are not needed for this problem but I put them nevertheless.
#include <stdio.h>
#include <stdlib.h>
#define MAX 1000
int time=0;
int smallest_component = 100000;
int count=0;
//these are the value that will be used to mark vertices
enum
{
white, gray, black
}color;
// A structure to represent an adjacency list node
typedef struct _Node
{
int dest;
int color;
struct _Node* next;
}Node;
/* This is the structure of the adjacency list
* It simply has an array of Nodes
*/
typedef struct _Adj
{
Node *list; // pointer to head node of list
}Adj;
int D[MAX];
int F[MAX];
int Color[MAX];
// Prototypes
void printGraph(Adj *list, int vertices);
void addEdge(Adj *list, int start, int end);
void DFS(Adj* list, int vertex);
int main(int argc, char **argv)
{
FILE *in = NULL;
int vertex1=0, vertex2=0;
int vertex_count=0;
Node *head = NULL;
int v=1;
int u=1;
int connected_components = 0;
//make sure enough arguments are supplied
if(argc!=2)
{
printf("hw1 <vertices-file>\n");
return 1;
}
//open the file
in = fopen(argv[1], "r");
//check to see if the file was opened
if(in == NULL)
{
printf("The file could not be opened");
return 2;
}
//START THE INSERTION OF THE VERTICES
//grab the first number. It is the number of vertices
fscanf(in, "%d", &vertex_count);
int vertices = vertex_count + 1;
//Create the struct pointer and call the function to create the Graph
Adj* list = (Adj*)malloc(sizeof(Adj)*vertices);
for(v=1; v<vertices; v++){
Color[v] = white;
}
//run through each pair of numbers
while(fscanf(in, "%d %d", &vertex1, &vertex2)!=EOF)
{
// create the first list
addEdge(list, vertex1, vertex2);
}
printf("\n\n");
Node *temp;
//run through the graph's nodes
for (v = 1; v < vertices; v++)
{
count = 0;
if(Color[v] == white){
DFS(list, v);
connected_components++;
if(smallest_component>count)
smallest_component=count;
}
}
printf("The number of connected components is %d\n", connected_components);
printf("The smallest component has %d vertices\n", smallest_component);
free(list);
//printGraph(myGraph);
return 0;
}
//Run a DFS given the Adjacency list and vertex in the list
void DFS(Adj* list, int vertex)
{
count++;
//printf("\nI am in DFS with node %d \n", vertex);
Color[vertex] = gray;
time = time + 1;
D[vertex] = time;
Node *temp;
for(temp = list[vertex].list; temp != NULL; temp = temp->next)
{
if(Color[temp->dest] == white)
DFS(list, temp->dest);
}
//get the new time, color, and end time
time = time+1;
F[vertex] = time;
//this means that we backtracked and now the node is black
Color[vertex] = black;
}
/*
* This function creates the edge between the two vertices.
* Since we have an UNDIRECTED graph, when I create the edges, I create them for both vertex and destination
*/
void addEdge(Adj* list, int v, int dest)
{
//create the edge between vertex and destination
Node* temp = (Node*)malloc(sizeof(Node));
temp->next = list[v].list;
temp->dest = dest;
list[v].list = temp;
//create the edge between dest and vertex
Node* temp2 = (Node*)malloc(sizeof(Node));
temp2->next = list[dest].list;
temp2->dest = v;
list[dest].list = temp2;
}
A: Your data structure represents an directed graph, and the DFS connected components count algorithm only works for undirected graphs. The results will not be correct.
You need to adapt your data structure to represent an undirected graph. The easiest way to do that is to add, for each original edge (a, b), an opposite edge (b, a). Just add another call to addEdge.
| |
doc_1690
|
and here is the error which im getting in browser console
image of error in browser console
UserService.js
`
import axios from "axios";
import { myAxios } from "./Constant";
export const saveUser = (user) => {
return myAxios.post("/user/register-user",user).then((response) => response.data);
}
`
SignUp.js
`
const submitForm = async (event)=>{
// stopping default behavior of submit
event.preventDefault()
//console.log('data submitted')
console.log(signUpData)
// validate form data
// call server api to submit form data
saveUser(signUpData)
.then((resp) => {
console.log(resp);
console.log("success log");
}).catch((error) => {
console.log(error);
//console.log("Error log");
})
`
Springboot REST API Code
backend code
CORS configuration
backend code
from postman api is working fine this
{
"userName":"ram",
"userEmail":"[email protected]",
"password":"pwd5",
"about":"ram is a react developer working in xyz"
}
| |
doc_1691
|
hosts=(usa1 london2)
for i in ${hosts[@]}; do
echo ---${i}---
ssh ttoleung@${i} ls /apps | awk '{ printf("%s:%s\n", "hostname", $0) }'
done
Current output, based on code fragment above:
---usa01---
hostname:E2.gui
hostname:E1.server
---london2---
hostname:E1.gui
Desired output:
---usa01---
usa01:E2.gui
usa01:E1.server
---london2---
london2:E1.gui
A: As an intro note, it is not a safe expand array names without double quotes unless for obvious reasons because doing so would split quoted strings in array that themselves have spaces
So change
for i in ${hosts[@]};
to
for i in "${hosts[@]}"; # Note the quoted array
Now, coming to your problem, you can pass bash variables to awk using its -v parameter. So change
ssh ttoleung@${i} ls /apps | awk '{ printf("%s:%s\n", "hostname", $0) }'
to
ssh ttoleung@${i} ls /apps | awk -v hname="${i}" '{ printf("%s:%s\n", hname, $0) }'
Here we pass shell parameter ${i} to awk variable hname.
Side Note: Don't parse ls output for the reasons mentioned [ here ]. In your case though, it doesn't make much of a difference.
A: Replace:
awk '{ printf("%s:%s\n", "hostname", $0) }'
With:
awk -v h="$i" '{ printf("%s:%s\n", h, $0) }'
-v h="$i" tells awk to create an awk variable h and assign to it the value of the shell variable $i.
Aside: we used h="$i" rather than h=$i because it is good practice to put shell variables inside double-quotes unless you want the shell to perform word-splitting and pathname expansion.
| |
doc_1692
|
HTML:
<button class="mobile-menu-btn mobile-menu-btn-films" onclick="toggleMenuFilms()">
<div id="btn-films"></div>
</button>
<div id="mobile-menu-sub-div-films">
<ul>
<li>
Item 1
</li>
<li>
Item 2
</li>
<li>
Item 3
</li>
</ul>
</div>
JS:
function toggleMenuFilms() {
var x = document.getElementById("mobile-menu-sub-div-films");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
I want to add something that says "if (x.style-display === "block") { rotate.btn-films } else { do nothing }" but I don't know how. Any help is appreciated.
A: In this example I change the class name of the parent element. By controlling the class name I can change the appearance of both the button and the menu.
function toggleMenuFilms(event) {
var menu = event.target.closest('div.menu');
menu.classList.toggle('open');
}
div#mobile-menu-sub-div-films {
display: none;
}
div#btn-films::before {
content: 'arrow';
}
div.menu.open #btn-films {
transform: rotate(180deg);
}
div.menu.open #mobile-menu-sub-div-films {
display: block;
}
<div class="menu">
<button class="mobile-menu-btn mobile-menu-btn-films" onclick="toggleMenuFilms(event)">
<div id="btn-films"></div>
</button>
<div id="mobile-menu-sub-div-films">
<ul>
<li>
Item 1
</li>
<li>
Item 2
</li>
<li>
Item 3
</li>
</ul>
</div>
</div>
| |
doc_1693
|
var blob = new Blob([uint8Array], { type: "image/png" });
$rootScope.blobVal = URL.createObjectURL(blob);
I used above code for converting Canvas DataUrl to Blob Object from above snippet am getting blobval as URL like
blob:http%3A//xyz.xyz.x.yz%3A8100/
4fa503b3-2e1d-4d38-b112-1f417c670b93
but i need only
4fa503b3-2e1d-4d38-b112-1f417c670b93
Thanks in Advance!!
A: var blob = new Blob([uint8Array], { type: "image/png" });
var objectUrl = URL.createObjectURL(blob);
str_arr = objectUrl.split("/");
$rootScope.blobVal = str_arr[str_arr.length - 1];
$rootScope.blobVal contains 4fa503b3-2e1d-4d38-b112-1f417c670b93
| |
doc_1694
|
SOLVED: See answer below and how to serve files from an embedded HTTP server.
UPDATE: The videos which fail to display if embedded in the res/raw folder play just fine if they are hosted online. See below for example:
// This works
mMediaPlayer.setDataSource("http://someserver.com/test.mp4");
//This does not work. The file is the same as the one above but placed in res/raw.
String vidpath = "android.resource://" + getActivity().getPackageName() + "/" + R.raw.test;
mMediaPlayer.setDataSource(getActivity(), Uri.parse(vidpath));
We need a texture view so we can apply some effects to it. The TextureView is used to display a video from the MediaPlayer. The application works on Android 4.1, 4.3 and 4.4 (on many devices including the old Nexus S up to the Nexus 10 and Note 3) but on 4.2.2 the TextureView becomes black. There are no errors or exceptions reported by the MediaPlayer and the reported video sizes are correct. Testing a SurfaceView on this particular device displays the video, but then we can't manipulate the view the way we need to.
One interesting bit is that a TextureView works on that device if playing the Nasa Live Streaming Video feed and some other streaming m3u8 files (http://www.nasa.gov/multimedia/nasatv/NTV-Public-IPS.m3u8) but we need to play embedded videos from the raw folder. We noticed however that at the very top of the TextureView, there's a 4x1 pixel line which keeps blinking some colors very rapidly. I wonder if the media player is rendering the video on that hairline or maybe it is an encoding problem or a hardware issue (this particular 4.2.2 device is a mimic of the iPad mini called... the haiPad >.< (which of course is the client's target device - hate you Murphy)).
Here's the info I could gather about the video which is failing to play:
MPEG-4 (Base Media / Version 2): 375 KiB, 5s 568ms
1 Video stream: AVC
1 Audio stream: AAC
Overall bit rate mode: Variable
Overall bit rate: 551 Kbps
Encoded date: UTC 2010-03-20 21:29:11
Tagged date: UTC 2010-03-20 21:29:12
Writing application: HandBrake 0.9.4 2009112300
Video: 466 Kbps, 560*320 (16:9), at 30.000 fps, AVC ([email protected]) (2 ref Frames)
Anyone has any pointers?
A: For anyone facing similar issues, this is what worked for us.
We are still not sure why playing embedded videos with the app does not work. We tried res/raw, assets and copying to the internal storage and sd card.
Since it was able to play videos from an HTTP server, we ended up embedding a light weight HTTP server within the app to serve the files directly from the assets directory. Here I'm using nanohttpd as an embedded server.
For it to work, I just need to place the video in the assets folder. For example assets/animation/animation1.mp4. When referencing the file, you pass "animation/animation1.mp4" as a path and the server will serve the file from the assets directory.
Application class starting the http server and registering it as a service.
public class MyApplication extends Application {
private NanoServer mNanoServer;
@Override
public void onCreate() {
super.onCreate();
mNanoServer = new NanoServer(0, getApplicationContext());
try {
mNanoServer.start();
} catch (IOException e) {
Log.e("Unable to start embeded video file server. Animations will be disabled.",
"MyApplication", e);
}
}
@Override
public void onTerminate() {
mNanoServer.stop();
super.onTerminate();
}
@Override
public Object getSystemService(String name) {
if (name.equals(NanoServer.SYSTEM_SERVICE_NAME)) {
// TODO Maybe we should check if the server is alive and create a new one if it is not.
// How often can the server crash?
return mNanoServer;
}
return super.getSystemService(name);
}
}
The NanoServer class
/*
* TODO Document this.
*/
public class NanoServer extends NanoHTTPD {
public static final String SYSTEM_SERVICE_NAME = "NANO_EMBEDDED_SYSTEM_HTTP_SERVER";
private Context mContext;
public NanoServer(int port, Context context) {
super(port);
this.mContext = context;
}
public NanoServer(String hostname, int port) {
super(hostname, port);
}
@Override
public Response serve(IHTTPSession session) {
try {
Uri uri = Uri.parse(session.getUri());
String fileToServe = normalizePath(uri.getPath());
return new Response(Status.OK, "video/mp4", (InputStream) mContext.getAssets().open(fileToServe));
} catch (IOException e) {
return new Response(Status.INTERNAL_ERROR, "", "");
}
}
private String normalizePath(String path) {
return path.replaceAll("^/+", "");
}
public String getUrlFor(String filePath) {
return String.format(Locale.ENGLISH, "http://localhost:%d/%s", getListeningPort(), filePath);
}
}
Using it in a Fragment
if (fileToPlay != null) {
mTextureView = (TextureView) inflatedView.findViewById(R.id.backgroundAnimation);
mTextureView.setSurfaceTextureListener(new VideoTextureListener());
}
...
private final class VideoTextureListener implements SurfaceTextureListener {
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
mMediaPlayer.release();
mMediaPlayer = null;
return true;
}
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
Surface s = new Surface(surface);
try {
NanoServer server =
(NanoServer) getActivity().getApplication().getSystemService(NanoServer.SYSTEM_SERVICE_NAME);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setSurface(s);
mMediaPlayer.setDataSource(server.getUrlFor(mHotspotTemplate.animation));
mMediaPlayer.prepareAsync();
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setVolume(0, 0);
mMediaPlayer.setOnErrorListener(new OnErrorListener() {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
mMediaPlayer.release();
mTextureView.setVisibility(View.INVISIBLE);
return true;
}
});
mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mMediaPlayer.start();
}
});
mMediaPlayer.setLooping(true);
mMediaPlayer.setVolume(0, 0);
} catch (Throwable e) {
if (mMediaPlayer != null) {
mMediaPlayer.release();
}
mTextureView.setVisibility(View.INVISIBLE);
}
}
}
| |
doc_1695
|
$myContent ="<h1>This word should not be replaced: TEST</h1>. But this one should be replaced: test";
$dom = new DOMDocument;
$dom->loadHTML(strtolower($myContent));
$xPath = new DOMXPath($dom);
foreach($xPath->query("//text()[contains(.,'test') and not(ancestor::h1)]") as $node)
{
/*need to do a replace on each occurrence of the word "test"
in $node->textContent here so that it becomes <b>test</b>. How? */
}
echo $dom->saveHTML should yield:
<h1>This word should not be replaced: TEST</h1>.
But this one should be replaced: <b>test</b>"
A: Edit: As @LarsH has noticed, I hadn't paid attention to the requirement that the replacement should be in bold.
There are two easy ways to correct this:
.1. In the transformation replace:
<xsl:value-of select="$pRep"/>
with
<b><xsl:value-of select="$pRep"/></b>
.2. Pass as the value of the pReplacement parameter not just "ABC" but <b>ABC</b>
This XSLT 1.0 transformation:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:param name="pTarget" select="'test'"/>
<xsl:param name="pReplacement" select="'ABC'"/>
<xsl:variable name="vCaps" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'"/>
<xsl:variable name="vLowecase" select="'abcdefghijklmnopqrstuvwxyz'"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="text()[not(ancestor::h1)]">
<xsl:call-template name="replaceCI">
<xsl:with-param name="pText" select="."/>
</xsl:call-template>
</xsl:template>
<xsl:template name="replaceCI">
<xsl:param name="pText"/>
<xsl:param name="pTargetText" select="$pTarget"/>
<xsl:param name="pRep" select="$pReplacement"/>
<xsl:variable name="vLowerText"
select="translate($pText, $vCaps, $vLowecase)"/>
<xsl:choose>
<xsl:when test=
"not(contains($vLowerText, $pTargetText))">
<xsl:value-of select="$pText"/>
</xsl:when>
<xsl:otherwise>
<xsl:variable name="vOffset" select=
"string-length(substring-before($vLowerText, $pTargetText))"/>
<xsl:value-of select="substring($pText,1,$vOffset)"/>
<xsl:value-of select="$pRep"/>
<xsl:call-template name="replaceCI">
<xsl:with-param name="pText" select=
"substring($pText, $vOffset + string-length($pTargetText)+1)"/>
<xsl:with-param name="pTargetText" select="$pTargetText"/>
<xsl:with-param name="pRep" select="$pRep"/>
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
when applied on the provided XML document (corrected to be well-formed):
<html>
<h1>This word should not be replaced: TEST</h1>.
But this one should be replaced: test
</html>
produces the wanted result:
<html>
<h1>This word should not be replaced: TEST</h1>.
But this one should be replaced: ABC
</html>
Do note:
*
*This is a generic transformation that accepts as parameters the target and the replacement text.
*The replacement is case-incensitive, but we suppose that the target parameter is provided in lowercase.
*It is even much easier to solve this with XSLT 2.0.
| |
doc_1696
|
Basic Code Examples:
Page 1 ----
<body>
<div class="content">
<div class="sliderBackground" id="sliderContainer" style="background: black; height: 40px; width: 100%;">
<div id="left">random left</div>
<div id="center">random center</div>
<div id="right">random Right</div>
</div>
</div>
</body>
Page 2
<body>
<div class="content">
<form id="search">
<input type="search" id="searcher" placeholder="Search" style="width: 95%;">
</form>
</div>
</body>
necessary imports (jquery etc)
<script type="text/javascript">
$("#search").submit(function(event) {
event.preventDefault(); // does not do anything (push.js... reloads page)
});
</script>
to reiterate my problem, the user clicks on a link (not shown in basic code) to use push.js to goto page 2. in page 2, they sure, where the page reloads when it should not (I am using ajax to utilize the search query etc). When the user goes back, the left, center, right css no longe works.
A: What if you try the following (finish with return false):
<script type="text/javascript">
$("#search").submit(function(event) {
event.preventDefault(); // does not do anything (push.js... reloads page)
// your logic here
return false;
});
</script>
A: This is probably a bit late but I think your problem is that script tags on pages loaded by push don't get run.
I.e. your code on page 2 isn't being run at all.
| |
doc_1697
|
*
*_mm_storeu_si128: Store 128-bits of integer data from a into memory. mem_addr does not need to be aligned on any particular boundary.
*_mm_loadu_si128: Load 128-bits of integer data from memory into dst. mem_addr does not need to be aligned on any particular boundary.
All the difference is on the word store or load but the difference is not clear to me.
A: In C terms:
*
*load = read data pointed to by a pointer.
*store = write through a pointer.
For a simple type like int, load and store functions would look like this:
int load(int *p) { return *p; }
void store(int *p, int val) { *p = val; }
__m128i load/store functions mostly exist to communicate aligned vs. unaligned to the compiler, vs. dereferencing __m128i* directly. Or for float / double, they also avoid casts because _mm_loadu_ps takes a const float* arg.
In asm terms, a load reads data from memory into a register (or as a source operand for an ALU instruction). A store writes data to memory.
C local variables are normally kept in registers, but of course your compiler is free to optimize intrinsic loads/stores the same way it can optimize dereferences of an int *. e.g. it might optimize away a store/reload so the asm wouldn't contain an instruction to do that.
| |
doc_1698
|
The problem I have is displaying the information that I've received from the sensors, which changes every 25 milliseconds, in my graphical interface.
I've established that the data is being passed from one thread to the other successfully (as an integer).
In my GUI I have dialog boxes dedicated to displaying this information, my current tactic is using the SetDlgItemInt() function in the main message loop. This is what the while loop looks like at the moment;
while (GetMessage(&msg, NULL, 0, 0))
{
SetDlgItemInt(hWnd, IDC_DISPBOX1, *Value, True);
if (!TranslateAccelerator(msg.hWnd, hAccelTable, &SMSFs))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
This displays the infomation, but it flashes constantly as it updates, and I was wondering if there is a better way to do this.
I'm new to win32 gui programming, and GUI programming in general, and I couldn't find an example of how to approach this way of displaying information, so this is what I've improvised using what I know of programming in this environment.
| |
doc_1699
|
AlarmManager[] alarmManager=new AlarmManager[24];
for(f=0;f<arr2.length;f++)
{
Intent intent = new Intent(AlarmR.this, Riciving.class);
pi=PendingIntent.getBroadcast(AlarmR.this, 0,intent, 0);
alarmManager[f] = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager[f].set(AlarmManager.RTC_WAKEUP,arr2[f] ,pi);
}
Thanks in Advance
A: On your pendingIntent you need to set the second requestCode to a unique number. I usually run the array through a for loop and set the request code dynamically for each item in the array. Without the requestCode the alarms are overwriting each other.
AlarmManager[] alarmManager=new AlarmManager[24];
intentArray = new ArrayList<PendingIntent>();
for(f=0;f<arr2.length;f++){
Intent intent = new Intent(AlarmR.this, Riciving.class);
pi=PendingIntent.getBroadcast(AlarmR.this, f,intent, 0);
alarmManager[f] = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager[f].set(AlarmManager.RTC_WAKEUP,arr2[f] ,pi);
intentArray.add(pi);
}
Basically, you just want to change requestCode to a dynamic number. By setting it to f you are giving it a new unique id for every item in the array. Keep in mind, if you want to cancel the alarms you will need to use another for loop and cancel each one individually. I personally add all my alarms to their own array so I can handle them separately.
Then if you need to cancel them:
private void cancelAlarms(){
if(intentArray.size()>0){
for(int i=0; i<intentArray.size(); i++){
alarmmanager.cancel(intentArray.get(i));
}
intentArray.clear();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.