id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23538500
|
DemoApplication.java => Right click => run as => java application. Here is what I am getting : -
Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/boot/SpringApplication
at com.sample.DemoApplication.main(DemoApplication.java:10)
Caused by: java.lang.ClassNotFoundException: org.springframework.boot.SpringApplication
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more
Here is my POM.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sample</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<configuration>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
</plugins>
</build>
</project>
========================================================================
I've set the JAVA_HOME variable and Maven path (till bin) in the path environment variable.
| |
doc_23538501
|
In mcu, the code must be specific to hardware i cannot use raspberry pi code on arduino. However since the fpga chip looks at the verilog or vhdl code and creates the circuit we have designed, Can the same vhdl or verilog code be used on different fpga boards(by only editing the clockspeed or pin names accordingly) if there is enough gate source?
I have basys2 board and there are more tutorials on different boards if same code and logic would work then i will not buy another board and learn on basys2 by using different board sources.
A: Yes both of them will work well. If it is plain code(without any library as in VHDL) it will work.
| |
doc_23538502
|
$(document).ready(function () {
'use strict';
var myData = [
{ id: "1", invdate: "2007-10-01", name: "test", note: "note", amount: "200.00", tax: "10.00", closed: true, ship_via: "TN", total: "210.00" },
{ id: "2", invdate: "2007-10-02", name: "test2", note: "note2", amount: "300.00", tax: "20.00", closed: false, ship_via: "FE", total: "320.00" },
{ id: "3", invdate: "2011-07-30", name: "test3", note: "note3", amount: "400.00", tax: "30.00", closed: false, ship_via: "FE", total: "430.00" },
{ id: "4", invdate: "2007-10-04", name: "test4", note: "note4", amount: "200.00", tax: "10.00", closed: true, ship_via: "TN", total: "210.00" },
{ id: "5", invdate: "2007-10-31", name: "test5", note: "note5", amount: "300.00", tax: "20.00", closed: false, ship_via: "FE", total: "320.00" },
{ id: "6", invdate: "2007-09-06", name: "test6", note: "note6", amount: "400.00", tax: "30.00", closed: false, ship_via: "FE", total: "430.00" },
{ id: "7", invdate: "2011-07-30", name: "test7", note: "note7", amount: "200.00", tax: "10.00", closed: true, ship_via: "TN", total: "210.00" },
{ id: "8", invdate: "2007-10-03", name: "test8", note: "note8", amount: "300.00", tax: "20.00", closed: false, ship_via: "FE", total: "320.00" },
{ id: "9", invdate: "2007-09-01", name: "test9", note: "note9", amount: "400.00", tax: "30.00", closed: false, ship_via: "TN", total: "430.00" },
{ id: "10", invdate: "2007-09-08", name: "test10", note: "note10", amount: "500.00", tax: "30.00", closed: true, ship_via: "TN", total: "530.00" },
{ id: "11", invdate: "2007-09-08", name: "test11", note: "note11", amount: "500.00", tax: "30.00", closed: false, ship_via: "FE", total: "530.00" },
{ id: "12", invdate: "2007-09-10", name: "test12", note: "note12", amount: "500.00", tax: "30.00", closed: false, ship_via: "FE", total: "530.00" }
],
myGrid = $("#list"),
lastSel = -1,
inEdit;
myGrid.jqGrid({
datatype: 'local',
data: myData,
colNames: ['Inv No', 'Date', 'Client', 'Amount', 'Tax', 'Total', 'Closed', 'Shipped via', 'Notes'],
colModel: [
{ name: 'id', index: 'id', width: 70, align: 'center', sorttype: 'int', formatter: 'int', editable: true,
editoptions: {
//readonly: 'readonly',
disabled: 'disabled',
dataInit: function (elem) {
if (!inEdit) {
$(elem).val($.jgrid.randId());
}
}
}
},
{ name: 'invdate', index: 'invdate', width: 75, align: 'center', sorttype: 'date',
formatter: 'date', formatoptions: { newformat: 'd-M-Y' }, datefmt: 'd-M-Y',
editable: true
},
{ name: 'name', index: 'name', width: 65, editable: true },
{ name: 'amount', index: 'amount', width: 75, sorttype: 'int', formatter: 'int', editable: true,
editoptions: {
dataInit: function (elem) {
$(elem).mask("99:99");
}
}
},
{ name: 'tax', index: 'tax', width: 52, sorttype: 'int', formatter: 'int', editable: true },
{ name: 'total', index: 'total', width: 60, sorttype: 'int', formatter: 'int', editable: true },
{ name: 'closed', index: 'closed', width: 67, align: 'center', formatter: 'checkbox', editable: true,
edittype: 'checkbox', editoptions: { value: 'Yes:No', defaultValue: 'Yes' }
},
{ name: 'ship_via', index: 'ship_via', width: 95, align: 'center', formatter: 'select', editable: true,
edittype: 'select', editoptions: { value: 'FE:FedEx;TN:TNT;IN:Intim', defaultValue: 'Intime' }
},
{ name: 'note', index: 'note', width: 60, sortable: false, editable: true,
editoptions: {
dataInit: function (elem) {
$(elem).val(inEdit ? "in Edit" : "in Add");
}
}
}
],
rowNum: 10,
rowList: [5, 10, 20],
pager: '#pager',
gridview: true,
ignoreCase: true,
rownumbers: true,
sortname: 'invdate',
viewrecords: true,
cellsubmit: 'clientArray',
sortorder: 'desc',
caption: 'Combining Advanced Searching and Toolbar Searching in one grid',
height: 'auto'
});
myGrid.jqGrid('navGrid', '#pager',
{ del: false, search: false },
{ // Edit
recreateForm: true,
beforeInitData: function () {
inEdit = true;
}
},
{ // Add
recreateForm: true,
beforeInitData: function () {
inEdit = false;
}
});
});
A: What you try to do is to use form editing to edit local data which is not supported by jqGrid currently. Nevertheless, how I described here, one do can implement this.
I get the demo from the answer and modified a little to use the current version of jqGrid. The corresponding demo. The demo do more as you need, for example context menu. You can remove features which you don't need.
| |
doc_23538503
|
Here are the images:
A: I faced the same problem. In my case the issue was not with firebase. Just clearing the cache was the solution.
A: Firebase hosting not showing up app?
There might be two reasons for this problem
1st step:
Make sure your public folder (define in your firebase.json) 'dist' containing the index.html hasn't been modified by firebase init command, if yes replace it with your original project index.html
for reference (dist is standard but your may different)
{
"hosting": {
"public": "dist"
}
}
2nd step:
Make sure to configure your base href in project's index.html
as
< base href="https://["YOUR FIREBASE PROJECT NAME"].firebaseapp.com/">
and other bundle files as
< script type="text/javascript" src="https://["YOUR FIREBASE PROJECT NAME"].firebaseapp.com/runtime.a66f828dca56eeb90e02.js"></script>
< script type="text/javascript" src="https://["YOUR FIREBASE PROJECT NAME"].firebaseapp.com/polyfills.14fc14f3e029a8cfd046.js"></script>
< script type="text/javascript" src="https://["YOUR FIREBASE PROJECT NAME"].firebaseapp.com/main.2eb2046276073df361f7.js"></script>
3rd step
run the command firebase deploy
enjoy ! ;)
A: I had ran to this issue and
If anybody had encounters the same after using firebase init command,
check your index.html file in your public folder (for react).
it might have been overridden by firebase.
in order to tell firebase not to override your existing index.html file,
type 'N' when firebase asks if you want to override the existing index.html file
A: If someone is here because of a
it seems like some domains ending with web.app are blocked from ISP providers, for some countries, I used a private VPN and access my site until it was fixed.
A: The step to deploy are as following
STEP 1:
ng build --prod
STEP 2:
firebase init
*Are you ready to proceed?* Yes
*What do you want to use as your public directory?* dist/{your-application-name}
*Configure as a single-page app (rewrite all urls to /index.html)?(y/N)* Yes
*File dist/{your-application-name}/index.html already exists. Overwrite?(y/N)* No
STEP 3:
firebase deploy --only hosting
And if still you are getting the same page just press 'CTRL + F5' it will clean the cached.
A: It's because the index.html has modified itself when you selected "Y" while initializing the firebase. It has basically replaced your own index file to this one. Check and replace the index file and next time, do not overwrite index.html file. It would work.
A: If you're seeing what's in this screenshot, there's another index.html file generated by Firebase, and it points to this one instead of your own. Here's how to fix:
*
*Delete the Firebase-generated index.html and keep your own.
*Re-deploy using firebase deploy
A: For myself, the problem was I given an absolute path to my app location, firebase init seem's only take a relative path.
A: Since Angular v6 CLI projects are making it easier to have multiple apps with shared codebases. Hence the new folder within dist.
Quoting dotGitignore answer:
I found that the ng build --prod will create a dist and an another
subfolder under this where the project location is.
Check how to fix it here https://stackoverflow.com/a/50360478/11652243
A: Only solution is firebase deploy file is index.tml but we need build file so replace your
{
"hosting": {
"public": "build",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}
Just replace your firebase.json file with this and you will se the magic
A: The fix that worked for me was using the second link that firebase provides instead of the first one:
USE: your-project-id.firebaseapp.com (instead of: your-project-id.web.app)
A: There are a few instances where nothing is really needed. Move all your static files into the public folder you chose. use command
firebase deploy
and just clear the cache by hitting ctrl+f5.
that did it for me.
A: I faced similar issue when deploying a website in firebase.
Firebase usually creates two default domains, web.app and firebaseapp.com.
If one doesn't work out, use another.
This solved my problem. Try it!
Make sure that you uploading your files to firebase.
Else, use firebase deploy --only hosting to deploy to files from the public directory to firebase.
A: Follow these steps for the usual deployment. https://alligator.io/angular/deploying-angular-app-to-firebase/
You have to check whether index.html inside the dist folder is regenerated by Firebase.
If so, all you need to do is just delete that html file which is modified by Firebase and create a new index.html file then enforcedly update the content with index.html which is actually created via $ ng build --prod. Now enter $ firebase deploy --only hosting.
So keep an eye of your index.html file contents and its location. if its location is not dist folder. you should give proper location accordingly for public field from firebase.json file.
A: I have same issue. Follow below steps:
firebase init
*Are you ready to proceed?* Yes
Make a public folder and Copy your all files into it
*What do you want to use as your public directory?*(public) -->only press enter
*Configure as a single-page app (rewrite all urls to /index.html)?(y/N)* N
*File public/index.html already exists. Overwrite?(y/N)* No
Thats it your app will host...
A: @arslan's answer helped me here & worked for me, went from a blank webpage to being able to see my app.
My solution: I edited my firebase.json file and then npm run build and then re-ran my command firebase emulators:start. Changed the file from
{
"functions": {
"source": "functions"
},
"hosting": {
"public": "public",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}
to...
{
"hosting": {
"public": "build",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}
A: Figured it out myself, What solved my issue:
*
*ran build (npm run build)
*add manually firebase.json and .firebasesrc files to root folder
*make sure firebase.json hosting->public is set to "build
*run firebase deploy
A: I had the same issue, I realised for some wierd reason, the firebase.json wasnt in my repo. I created it with config from the above examples, and then I did firebase init again, after it run it found my firebase.json and modified it, it worked
A: I ran into this same issue and resolved with below steps:
HACK Solution
Step:1 Go to your build folder and replace index.html with your index.html(public folder).
Step:2 Run command: npm run build
Step:3 Select NO => File dist/{your-application-name}/index.html already exists. Overwrite? (y/N) No
Step:4 Then go to the link and press Ctrl+f5. your app will be in front of you. :)
A: after command firebase init, go to public or dist folder and select all files (not folders) except firebase related files and copy into dist or public folder. After this execute command firebase deploy and wait for a while. After finish go to mentioned url there you will find your working app.
A: When you ran firebase init Firebase creates a file structure in your project folder and depending on the selections you made it created a /public folder (or another name if you specified) for your public files. Within that /public folder it also creates a index.html file containing the welcome message you are seeing. You need to take your app files (web pages, etc) and move them into that public folder and replace that index.html file along with them. After doing this run the command "firebase deploy" and it will update and you should see your app.
A: Before deploying ensure your files are in the newly created directory e.g y or public folders
A: in my case after building with ng build i told firebase the source directory is dist, but actually it was dist/my-project...
(there was a firebase index.html in dist. angular index.html was in dist/my-project...)
A: Sometimes when this happen you need to logout firebase logout on your CLI,
then login again firebase login.
Then repeat all the procedures for hosting
And make sure you initialized Firebase Firebase.initializeApp() on your main method if you are using flutter.
This worked for me.
A: During initialization of the firebase directory you need to choose build as public directory.
The run
1.npm run build
2.firbase deploy
If this doesn't work try clearing the cache of your browser.
A: Here I found an answer to the question
Step1: Initialize the firebase first.
$firebase init
Step2: Create a production build now.
$ng build --prod
Step:3 It's time to deploy your app.
$firebase deploy
| |
doc_23538504
|
This code works perfectly:
QDomElement new_item = doc.createElement(name);
new_item.setAttribute("type", value.typeName());
new_item.setAttribute("value", value.toString());
doc.elementsByTagName(section).at(0).appendChild(new_item);
But if I would create QDomElement myself (without calling createElement method), then it doesn't get inserted into the document. Something like this doesn't work:
QDomElement new_item;
new_item.setTagName(name);
new_item.setAttribute("type", value.typeName());
new_item.setAttribute("value", value.toString());
doc.elementsByTagName(section).at(0).appendChild(new_item);
Can anyone explain to me why I need to use createElement method ?
Thank you :)
A: Basically DomElement creation needs information that QDomDocument has. From Qt 4.7 documentation
Since elements, text nodes, comments, processing instructions, etc., cannot exist outside the context of a document, the document class also contains the factory functions needed to create these objects. The node objects created have an ownerDocument() function which associates them with the document within whose context they were created.
http://doc.qt.io/archives/qt-4.7/qdomdocument.html#details (third paragraph)
| |
doc_23538505
|
I'm trying this out by attempting to fetch an image over http and store it to the blobstore:
file_name = files.blobstore.create(mime_type='image/jpeg')
image = urllib2.urlopen(url)
with files.open(file_name, 'a') as f:
f.write(image) # LINE 142
files.finalize(file_name)
blob_key = files.blobstore.get_blob_key(file_name)
This code is throwing the error:
File "/Users/willmerydith/repos/spam/admin.py", line 142, in post
f.write(image)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/api/files/file.py", line 364, in write
self._make_rpc_call_with_retry('Append', request, response)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/api/files/file.py", line 472, in _make_rpc_call_with_retry
_make_call(method, request, response)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/api/files/file.py", line 229, in _make_call
rpc.check_success()
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/api/apiproxy_stub_map.py", line 558, in check_success
self.__rpc.CheckSuccess()
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/api/apiproxy_rpc.py", line 156, in _WaitImpl
self.request, self.response)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/api/apiproxy_stub.py", line 80, in MakeSyncCall
if request.ByteSize() > self.__max_request_size:
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/api/files/file_service_pb.py", line 1923, in ByteSize
n += self.lengthString(len(self.data_))
AttributeError: addinfourl instance has no attribute '__len__'
I suspect it is breaking because I am exceeding a size limit. Is that due to the way I am writing the image to the blobstore? The size limit for Blobstores is 2 GB, and the images I am testing are less than 200-300 KB.
A: urllib2.urlopen returns a urllib2.addinourl object, rather than a string. You can't write this object directly to your file object.
Try f.write(image.read()) on line 142.
A: This is not working anymore as the files API has been disabled in September 2015.
| |
doc_23538506
|
A: To change this in a custom package/theme, copy the layout file checkout.xml from $MAGENTO/app/design/frontend/base/default/layout/checkout.xml to $MAGENTO/app/design/$PACKAGE/$THEME/layout/checkout.xml
Then find the following lines:
*
*<action method="addCartLink"></action>
*<action method="addCheckoutLink"></action>
in that file.
Then just comment those lines out (put <!-- at the beginning of each line and put --> at the end of each line).
In terms of CSS selectors, this would be: layout > default > referance[name='top.links'] > block > action
A: The best way is to not touch the core layout files, instead your best bet is to create custom theme with only one layout file local.xml like described here To remove the links from the top menu you would need to add these lines in your local.xml file:
<default>
<reference name="top.links">
<remove name="checkout_cart_link" />
</reference>
</default>
I believe this will remove the checkout and my cart links from the top menu. If this doesn't work, try changing top.links with topLinks since in page.xml it is declared as="topLinks"
<reference name="topLinks">
<remove name="checkout_cart_link" />
</reference>
A: In order to do BOTH the Checkout link and the Top Cart you'll need to put these within the <default> </default> of your local.xml in your layout folder (app/design/frontend/THEME/THEMENAME/layout/)
// Checkout Link
<reference name="topLinks">
<remove name="checkout_cart_link" />
</reference>
// Top Cart Link
<reference name="header">
<action method="unsetChild"><alias>topCart</alias></action>
</reference>
| |
doc_23538507
|
an example of the problem with the code, http://jsfiddle.net/zVrq8/
I don't understand what's going on here.
A: I made it for the first two items. For the rest it's the same: link
What I did, added a float: left to the li:
div#lasteventimg ul li{
float:left;
}
this way li will go next to the previous li, as long as there is space in the ul
Second thing I changed is in the HTML, added to a single li both the image and the input, also a <br /> to make the input below the image. There are other ways to do this, but this seemed the easiest here.
| |
doc_23538508
|
Let's say i m writing a shared library which will be used by other applications and i want to use alarm, setitimer functions and trap SIGALRM signal to do some processing at specific time.
I see some problems with it:
1) If application code (which i have no control of) also uses SIGALRM and i install my own signal handler for it, this may overwrite the application's signal handler and thus disable it's functionality. Of course i can make sure to call previous signal handler (retrieved by signal() function) from my own signal handler, but then there is still a reverse problem when application code can overwrite my signal handler and thus disable the functionality in my library.
2) Even worse than that, application developer may link with another shared library from another vendor which also uses SIGALRM, and thus nor me nor application developer would have any control over it.
3) Calling alarm() or setitimer() will overwrite the previous timer used by the process, so application could overwrite the timer i set in the library or vice versa.
I m kinda a novice at this, so i m wondering if there is already some convention for handling this? (For example, if every code is super nice, it would call previous signal handler from their own signal handler and also structure the alarm code to honor previous timers before overwriting them with their own timer)
Or should i avoid using signal handlers and alarm()s in a library alltogether?
A:
Or should i avoid using signal handlers and alarm()s in a library alltogether?
Yes. For the reasons you've identified, you can't depend on signal disposition for anything, unless you control all code in the application.
You could document that your library requires that the application not use SIGALRM, nor call alarm, but the application developer may not have any control over that anyway, and so it's in your best interest to avoid placing such restrictions in the first place.
If your library can work without SIGALRM (perhaps with reduced functionality), you can also make this feature optional, perhaps controlled by some environment variable. Then, if it is discovered that there is some code that interferes with your signal handling, you can tell the end-user to set your environment variable to disable that part of your library (which beats having to rebuild and supply a new version of it).
P.S. Your question and this answer applies to any library, whether shared or archive.
| |
doc_23538509
|
i go to set the itemcommand event or any event for the matter, when i go to click on the command or do something that should cause to trigger the event, nothing ends up firing. So i was wondering what exactly i am doing wrong with my declaration on my item command.
You will find my code below:
private void createRadGrid()
{
//create radgrid
RadGrid rg = new RadGrid();
rg.ID = "RadGridView";
//setting the datasource and itemcommand event handler.
rg.DataSourceID = "MachineDataSet";
rg.ItemCommand += new GridCommandEventHandler(RadGridView_ItemCommand);
rg.Width = 862;
rg.CellSpacing = 2;
rg.CellPadding = 4;
rg.BorderWidth = 3;
rg.BackColor = System.Drawing.Color.Transparent;
rg.BorderColor = System.Drawing.Color.DarkGray;
rg.ForeColor = System.Drawing.Color.Black;
rg.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
rg.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
rg.BorderStyle = BorderStyle.Ridge;
rg.ShowStatusBar = true;
rg.AllowPaging = true;
rg.PageSize = 5;
rg.PagerStyle.Mode = GridPagerMode.NextPrevAndNumeric;
rg.AutoGenerateColumns = false;
rg.MasterTableView.PageSize = 5;
rg.MasterTableView.DataKeyNames = new string[] { "ID" };
rg.MasterTableView.ClientDataKeyNames = new string[] { "ID" };
rg.MasterTableView.AutoGenerateColumns = false;
rg.ClientSettings.Resizing.AllowColumnResize = true;
rg.ClientSettings.Resizing.EnableRealTimeResize = true;
rg.ClientSettings.Resizing.ResizeGridOnColumnResize = true;
GridBoundColumn boundColumn = new GridBoundColumn();
boundColumn.DataField = "ID";
boundColumn.HeaderText = "ID";
boundColumn.UniqueName = "MachineID";
boundColumn.Visible = false;
rg.MasterTableView.Columns.Add(boundColumn);
GridBoundColumn boundColumn1 = new GridBoundColumn();
boundColumn1.DataField = "SiteName";
boundColumn1.HeaderText ="Site Name";
boundColumn1.Resizable = true;
boundColumn1.ReadOnly = true;
rg.MasterTableView.Columns.Add(boundColumn1);
GridBoundColumn boundColumn2 = new GridBoundColumn();
boundColumn2.DataField = "Name";
boundColumn2.HeaderText = "Machine Name";
boundColumn2.Resizable = true;
boundColumn2.ReadOnly = true;
rg.MasterTableView.Columns.Add(boundColumn2);
GridBoundColumn boundColumn3 = new GridBoundColumn();
boundColumn3.DataField = "MachineType";
boundColumn3.HeaderText = "Machine Type";
boundColumn3.Resizable = true;
boundColumn3.ReadOnly = true;
rg.MasterTableView.Columns.Add(boundColumn3);
GridBoundColumn boundColumn4 = new GridBoundColumn();
boundColumn4.DataField = "MachineModel";
boundColumn4.HeaderText = "Machine Model";
boundColumn4.Resizable = true;
boundColumn4.ReadOnly = true;
rg.MasterTableView.Columns.Add(boundColumn4);
GridButtonColumn buttonColumn = new GridButtonColumn();
buttonColumn.ButtonType = GridButtonColumnType.PushButton;
buttonColumn.CommandName = "AssignNewValues";
buttonColumn.Resizable = true;
buttonColumn.Text = "Assign New Values";
rg.MasterTableView.Columns.Add(buttonColumn);
PlaceHolder_RadGridView.Controls.Add(rg);
}
The problem area seems to be in this line
rg.ItemCommand += new GridCommandEventHandler(RadGridView_ItemCommand);
Any help or suggestions are greatly appreciated.
A: Try placing the createRadGrid() either in the page_init or page_load event. if you are setting the event after, that could be the reason of it no firing.
Hope this is of any help.
Cheers.
A: Try moving this line:
PlaceHolder_RadGridView.Controls.Add(rg);
Right to after this line:
RadGrid rg = new RadGrid();
rg.ID = "RadGridView";
And see if that makes a difference.
| |
doc_23538510
|
All the scripts of adding a css file to WordPress plugin that I found are referring to including a css file in the plugin output page on the website itself. - wp_enqueue_scripts
the solution i created is to use this piece of code in my plugin page:
echo '<style type="text/css">';
include( '/css/style.css' );
echo '</style>';
But if feels to me like an unprofessional solution so I wanted to ask if anyone knows a better solution
A: You can use wp_enqueue_style() yourself, with plugins_url():
function my_styles(){
$css_path = plugins_url('/css/style.css', __FILE__);
wp_enqueue_style('my_stylesheet', $css_path);
}
add_action( 'admin_init', 'my_styles' );
| |
doc_23538511
|
Thanks in advance...
A: The entries in META-INF are generated with jarsigner tool. The format of this file is specified. Thus, even if you add some entries to this file, it seems that the verification process will not pass.
| |
doc_23538512
|
Thank you in advance.
A: This is a library linking issue. Try the following, as it may need re-installing, or updated:
pip install pyhull
If that doesn't work, you may have to recompile python, and any additional libraries or utilities (coreutils, binutils, glibc, even gcc).
If you have the Oracle C compiler, you can try that by using cc, or gcc if that is easier. The Oracle C compiler would be specific to your Solaris installation and may work better.
If you do not want to do that, you might want to try a packaged version of python for your version of SunOS / Solaris and then install pyhull or qhull using pip.
| |
doc_23538513
|
My columns look like this:
School_Assigned Will_You_Enroll_There
Anderson Yes
Williams No
Anderson NaN
Anderson Yes
Anderson Maybe
Based on this, the NaN value should contain Yes since the number of Yes's (for Anderson) are greater than the number of no's and maybe's. School_Assigned and Will_You_Enroll_There are columns 10 and 11 respectively. My data frame is called gt_Exam.
Here is my code:
enroll_categories = ["Yes", "No", "Maybe"]
count1 = 0
count2 = 0
count3 = 0
for i in range(len(gt_Exam)):
if pd.isna(gt_Exam.iloc[i, 11]) == True:
value = gt_Exam.iloc[i, 10]
for j in range(len(gt_Exam)):
if (gt_Exam.iloc[j, 10] == value) & (gt_Exam.iloc[j, 11] == enroll_categories[0]):
count1 += 1
elif (gt_Exam.iloc[j, 10] == value) & (gt_Exam.iloc[j, 11] == enroll_categories[1]):
count2 += 1
elif (gt_Exam.iloc[j, 10] == value) & (gt_Exam.iloc[j, 11] == enroll_categories[2]):
count3 += 1
maximum_categories = max(count1, count2, count3)
if maximum_categories == count1:
gt_Exam.iloc[i, 11] = enroll_categories[0]
elif maximum_categories == count2:
gt_Exam.iloc[i, 11] = enroll_categories[1]
else:
gt_Exam.iloc[i, 11] = enroll_categories[2]
A: We can try fillna with the first mode per group (groupby transform):
gt_Exam['Will_You_Enroll_There'] = gt_Exam['Will_You_Enroll_There'].fillna(
gt_Exam.groupby('School_Assigned')['Will_You_Enroll_There']
.transform(lambda s: pd.Series.mode(s)[0])
)
Series.get can be used if it is possible a group is all NaN and, thus, produces no mode. This will prevent a key error and also (optionally) allow a default value to be specified:
gt_Exam['Will_You_Enroll_There'] = gt_Exam['Will_You_Enroll_There'].fillna(
gt_Exam.groupby('School_Assigned')['Will_You_Enroll_There']
.transform(lambda s: pd.Series.mode(s).get(0))
)
gt_Exam:
School_Assigned Will_You_Enroll_There
0 Anderson Yes
1 Williams No
2 Anderson Yes
3 Anderson Yes
4 Anderson Maybe
DataFrame:
import numpy as np
import pandas as pd
gt_Exam = pd.DataFrame({
'School_Assigned': {0: 'Anderson', 1: 'Williams', 2: 'Anderson',
3: 'Anderson', 4: 'Anderson'},
'Will_You_Enroll_There': {0: 'Yes', 1: 'No', 2: np.nan, 3: 'Yes',
4: 'Maybe'}
})
| |
doc_23538514
|
*
*name
*family
*address
and i have a 2 user's:
*
*User A
*User B
i want to when User B insert new record into the table,show in User A gridView.
i use this solution:
User A web browser has a this code:
<script type="text/javascript">
$(document).ready(function () {
setTimeout("RefreshPage()", 5000);
});
function RefreshPage() {
/* var url = "GetOrder.aspx";
$(location).attr("href", url);
*/
location.reload();
};
</script><br/>
that code refresh User A webpage every 5 second and in page load event i write a simple code to run select query and show in gridview.
this method very crazy solution to do this.
can i use other solution and how?
A: Your code Refresh whole page. Use below code, it will refresh only contain. :)
<asp:ScriptManager ID="scp1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="up1" runat="server">
<ContentTemplate>
<asp:GridView ID="yourGrid" runat="server"></asp:GridView>
<asp:Button id="btnAutoRefresh" runat="server" style="display:none"
onclick="btnAutoRefresh_Click" />
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript">
$(document).ready(function () {
setInterval("RefreshPage()", 5000);
});
function RefreshPage() {
$("#<%=btnAutoRefresh.ClientID %>").trigger("click");
};
</script>
// code behind
protected void btnAutoRefresh_Click(object sender, EventArgs e)
{
// code for Bind Grid
}
A: You need to use client notification technique, for example SignalR. You can read more about it here
| |
doc_23538515
|
The latest Emmet can only accept HTML syntax on custom snippets
These snippets my seems odd, since these are my custom tag which will be convert into php code in Template Engine, so the code aren't HTML syntax.
For instance, when I type p1 and press tab, I want it give me <!--{if }-->:
{
"config": {
// Configure snippets/options for HTML syntax only.
// For a list of supported syntaxes, check out keys of `syntax_scopes`
// dictionary of `Emmet.sublime-settings`
"html": {
"snippets": {
"p1": "<!--{if }-->",
"l1": "<!--{/if}-->",
"p2": "<!--{loop }-->",
"l2": "<!--{/loop}-->",
"p3": "<!--{eval }-->",
"p4": "<!--{block }-->",
"l4": "<!--{/block}-->",
"else": "<!--{else}-->",
"elif": "<!--{elseif }-->"
}
}
}
}
A: New Emmet accepts snippet values as Emmet abbreviations (yep, a recursion) and plays better with native ST snippets. Thus, you should either add your snippets as native in ST, or if you still want to use Emmet for such snippets, you should write them as valid Emmet abbreviation. To output arbitrary text in Emmet abbreviation, you should write it as text node, e.g. wrap with { and }.
So, your snippet should look like this:
"p1": "{<!--{if }-->}"
| |
doc_23538516
|
I have looked at multiple examples on multiple sites but I can't find anything that shows two items being animated independently of each other. The closest thing I have found is the example on the link provided labeled Multi-State which is located at the bottom of the list.
A: No. MotionLayout has a single value "progress" which moves from 0 to 1.
You can have 2 motionlayouts in another layout and each is a slider.
| |
doc_23538517
|
"AttributeError: type object 'todo.task' has no attribute 'do_toggle_done'"
what maiming by attribute and how can add it for both buttons
THE ERROR IT'S OCCUR WITH BOTH BUTTONS
(# -*- coding: utf-8 -*-
from odoo import models, fields, api
class TodoTask(models.Model):
_name = 'todo.task'
_description = 'To-do Task'
name = fields.Char('Description', required=True)
is_done = fields.Boolean('Done?')
active = fields.Boolean('Active?', default=True)
@api.multi
def do_toggle_done(self):
for task in self:
task.is_done = not task.is_done
return True
@api.model
def do_clear_done(self):
dones = self.search([('is_done', '=', True)])
dones.write({'active': False})
return True
)
THIS IS THE XML CODE
<?xml version="1.0"?>
<odoo>
<!-- To-Do Task Form view -->
<record id="view_form_todo_task" model="ir.ui.view">
<field name="name">To-do Task Form</field>
<field name="model">todo.task</field>
<field name="arch" type="xml">
<form>
<header>
<button name="do_toggle_done" type="object"
string="Toggle Done" class="oe_highlight"/>
<button name="do_clear_done" type="object"
string="Clear All Done" />
</header>
<sheet>
<group name="group_top">
<group name="group_left">
<field name="name"/>
</group>
<group name="group_right">
<field name="is_done"/>
<field name="active" readonly="1"/>
</group>
</group>
</sheet>
</form>
</field>
</record>
<!-- To-Do Task List view -->
<record id="view_tree_todo_task" model="ir.ui.view">
<field name="name">To-do Task Tree</field>
<field name="model">todo.task</field>
<field name="arch" type="xml">
<tree colors="decoration-muted: is_done==True">
<field name="name"/>
<field name="is_done"/>
</tree>
</field>
</record>
<!-- To-Do Task Search view -->
<!--<record id="view_filter_todo_task" model="ir.ui.view">-->
<!--<field name="name">To-do Task Filter</field>-->
<!--<field name="model">todo.task</field>-->
<!--<field name="arch" type="xml">-->
<!--<search>-->
<!--<field name="name"/>-->
<!--<filter string="Not Done" domain="[('is_done','=',False)]"/>-->
<!--<filter string="Done" domain="[('is_done','!=',False)]"/>-->
<!--</search>-->
<!--</field>-->
<!--</record>-->
</odoo>
this is the error massage
Odoo Server Error
Traceback (most recent call last):
File "/odoo/odoo-server/odoo/http.py", line 654, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "/odoo/odoo-server/odoo/http.py", line 312, in _handle_exception
raise pycompat.reraise(type(exception), exception, sys.exc_info()[2])
File "/odoo/odoo-server/odoo/tools/pycompat.py", line 87, in reraise
raise value
File "/odoo/odoo-server/odoo/http.py", line 696, in dispatch
result = self._call_function(**self.params)
File "/odoo/odoo-server/odoo/http.py", line 344, in _call_function
return checked_call(self.db, *args, **kwargs)
File "/odoo/odoo-server/odoo/service/model.py", line 97, in wrapper
return f(dbname, *args, **kwargs)
File "/odoo/odoo-server/odoo/http.py", line 337, in checked_call
result = self.endpoint(*a, **kw)
File "/odoo/odoo-server/odoo/http.py", line 939, in __call__
return self.method(*args, **kw)
File "/odoo/odoo-server/odoo/http.py", line 517, in response_wrap
response = f(*args, **kw)
File "/odoo/odoo-server/addons/web/controllers/main.py", line 966, in call_button
action = self._call_kw(model, method, args, {})
File "/odoo/odoo-server/addons/web/controllers/main.py", line 954, in _call_kw
return call_kw(request.env[model], method, args, kwargs)
File "/odoo/odoo-server/odoo/api.py", line 742, in call_kw
method = getattr(type(model), name)
AttributeError: type object 'todo.task' has no attribute 'do_toggle_done'
A: Try to restart odoo and update the module, it worked for me.
A: Button call is directly related to current active model and recordset. You need to use @api.multi to work with object type button. Change you button methods with @api.multi decorators. Everything else seems good with your code. Should work perfectly.
| |
doc_23538518
|
There used to be 20 + exceptions. However, I was able to research and figure out what practices were not being followed that were causing the errors. However, I cannot seem to find these lased three errors. Is there a list somewhere of possible causes of this exception? I would show the code, however, these errors could be across 22 classes.
Thank you in advance.
EDIT
Here is the error below. The code is executed from a command line runner, so please refer the the "Caused by:" exception. There really is a gratuitous amount of code to comb through and it would not be practical to post here. That is why I am asking for a reference list of possible triggers for this exception. Does such a list exist?
java.lang.IllegalStateException: Failed to execute CommandLineRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:735) [spring-boot-1.5.12.RELEASE.jar:1.5.12.RELEASE]
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:716) [spring-boot-1.5.12.RELEASE.jar:1.5.12.RELEASE]
at org.springframework.boot.SpringApplication.afterRefresh(SpringApplication.java:703) [spring-boot-1.5.12.RELEASE.jar:1.5.12.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:304) [spring-boot-1.5.12.RELEASE.jar:1.5.12.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.12.RELEASE.jar:1.5.12.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.12.RELEASE.jar:1.5.12.RELEASE]
at com.xdome.XdomeApplication.main(XdomeApplication.java:14) [classes/:na]
Caused by: com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 3 counts of IllegalAnnotationExceptions
at com.sun.xml.bind.v2.runtime.IllegalAnnotationsException$Builder.check(IllegalAnnotationsException.java:106) ~[jaxb-impl-2.2.3-1.jar:2.2.3]
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getTypeInfoSet(JAXBContextImpl.java:489) ~[jaxb-impl-2.2.3-1.jar:2.2.3]
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:319) ~[jaxb-impl-2.2.3-1.jar:2.2.3]
at com.sun.xml.bind.v2.runtime.JAXBContextImpl$JAXBContextBuilder.build(JAXBContextImpl.java:1170) ~[jaxb-impl-2.2.3-1.jar:2.2.3]
at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:145) ~[jaxb-impl-2.2.3-1.jar:2.2.3]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_144]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_144]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_144]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_144]
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:247) ~[na:1.8.0_144]
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:234) ~[na:1.8.0_144]
at javax.xml.bind.ContextFinder.find(ContextFinder.java:441) ~[na:1.8.0_144]
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:641) ~[na:1.8.0_144]
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:584) ~[na:1.8.0_144]
at com.xdome.XMLGenerator.run(XMLGenerator.java:27) ~[classes/:na]
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:732) [spring-boot-1.5.12.RELEASE.jar:1.5.12.RELEASE]
... 6 common frames omitted
A: After working on this issue, I thought I would come bask and leave a few quick thoughts. Unfortunately, it looks like this is a general error. From what I can tell there is no collective list of errors for this exceptions because this is meant to be a catch-all exception when all else fails. However, here are a few item I came across when working on my project:
When working with JAXB, be sure all desired classes that you hope to marshall have a default, empty argument constructor. I assume JAXB just needs to do some basic POJO operations and without a no args constructor, it wouldn't be possible.
public class A {
public A(){}
}
Another issue I came across involved inheritance. Many of the previous objects were inheriting from an abstract class that contained common fields. This abstract class was not directly part of the XML hierarchy, however. The inclusion of the abstract class as a superclass seemed to throw the IllegalAnnotationsException. So, where class B is part of the XML structure, DO NOT do the following:
public abstract class A {
...
}
public class B extends A {
}
And finally, the IllegalAnnotationsException can be thrown for misusing JAXB annotation. When getting the aforementioned exception, double check to make sure you are annotating the intended fields and classes. As I am new to JAXB myself, I came across this issues. You can find JAXB documentation on Oracle's website: https://docs.oracle.com/javase/8/docs/technotes/guides/xml/jaxb/index.html
I hope this information helps at least a couple people. At the very least it's one last stack overflow question without an answer.
| |
doc_23538519
|
public:
int info;
NodeType* link;
};
I came across this when learning about linked list, and as a beginner, at line 4, pointer link is an object of class NodeType, this interpretation is definitely wrong, so can somebody please explain what does this line mean? I don't recall learning this when I am interacting with the concept of OOP.
struct NodeType
{
int info;
struct NodeType* link;
};
I take that this structure declaration here is of the same as the class declared above, so my second question is, why is there a second struct keyword at line 4? Can the keyword be removed? Is this the phenomenon called nested struct?
A: Yes, the two snippets are the same.
why is there a second struct keyword at line 4?
It's called an elaborated type specifier (a type with struct prepended to it, or class/union/enum; the definition class NodeType {} doesn't count as one).
It's useless here and can be removed. It's only useful when a struct is mentioned for the first time, so the compiler doesn't know it's a struct yet.
In this regard C++ is different from C, where you must prepend struct every time to refer to a struct.
[is] pointer link is an object of class NodeType?
No, an object of class NodeType would be NodeType link;, but then it wouldn't be a pointer.
You could say that link is an object of type NodeType * (a pointer to NodeType).
| |
doc_23538520
|
My table structure is as follows:
equip_items
--------------
id (pk)
equip_type_id (fk to equip_types)
site_id (fk to sites)
equip_status_id (fk to equip_status)
name
(equip_type_id, site_id, name) is a composite unique key constraint in the db. I have implemented a callback on the name field that deals with grocery_CRUD validation of the unique constraint - taking into account either editing existing or adding new equip_items.
function unique_equip_item_check($str, $edited_equip_item_id){
$var = $this->Equip_Item_model->is_unique_except($edited_equip_item_id,$this->input->post('site_id'),$this->input->post('equip_type_id'),$this->input->post('name'));
if ($var == FALSE) {
$s = 'You already have an equipment item of this type with this name.';
$this->form_validation->set_message('unique_equip_item_check', $s);
return FALSE;
} else {
return TRUE;
}
}
I have the site_id and equip_type_id set as hidden fields as I do not want the user to change these - no problem.
$crud->field_type('site_id', 'hidden', $site_id);
$crud->field_type('equip_status_id', 'hidden', iQS_EqStatus_InUse);
When users add an equip_item I want them to be able to select the equip_type from a list of types - No problem, this is default grocery_CRUD behaviour.
$crud->add_fields('equip_status_id', 'site_id', 'equip_type_id', 'name');
When users edit an equip_item I don't want the user to be able to edit the equip_type. I figured no problem I can just set the edit_fields to exclude equip_type_id:
$crud->edit_fields('equip_status_id', 'site_id', 'name', 'barcode_no');
BUT this plays havoc with my validation callback because the value of the equip_type_id field is nowhere on the edit form and it is obviously needed by my validation routine.
So I need to have the equip_type_id field visible and acting normal when adding a new record but hidden when editing a record.
I've tried this hack of all hacks :
if ($this->uri->segment(4)!= FALSE){$crud->field_type('equip_type_id', 'hidden');}
My theory was that "$this->uri->segment(4)" only give a false result if adding a new record, but it does not work.
I have also tried:
$crud->callback_edit_field('equip_type_id', array($this,'edit_equip_type_field_callback'));
with
function edit_equip_type_field_callback($value = '', $primary_key = null){
return '<input type="hidden" value="'.$value.'" name="equip_type_id"';
}
But that doesn't work it just screws up the layout of the form fields - the 'Type' label etc is still visible.
Any suggestions?
A: I think the problem is that you have to add the field equip_status_id to the edit fields.
So in your case this will simply solve your problem:
$crud->edit_fields('equip_status_id', 'site_id',
'name', 'barcode_no','equip_status_id');
or
$crud->fields('equip_status_id', 'site_id', 'name',
'barcode_no','equip_status_id'); //for both add and edit form
of course you have to also use your hack:
if ($this->uri->segment(4)!= FALSE) {
$crud->field_type('equip_type_id', 'hidden');
}
or you can do it with a more proper way:
$crud = new grocery_CRUD();
if ($crud->getState() == 'edit') {
$crud->field_type('equip_type_id', 'hidden');
}
...
With this way you will also remember why you did this hacking to the code.
| |
doc_23538521
|
import React, {useState } from 'react';
function App() {
const [seconds, setSeconds] = useState(10);
const startTimer = () => {
const interval = setInterval(() => {
setSeconds(seconds => seconds - 1);
// Logs 10 every time
console.log(seconds)
// Never meets this condition
if (seconds === 0) {
clearInterval(interval)
}
}, 1000);
}
return (
<div>
<button onClick={() => startTimer()}></button>
// updates with current seconds
<p>{seconds}</p>
</div>
)
}
export default App;
A: That is because the setSeconds updates the state with a new variable on every tick but the initial reference (seconds === 10) still points to the initial set variable. That is why it stays at 10 => The initial reference.
To get the current value, you have to check it in the setSeconds variable (passed as seconds) like this:
const startTimer = () => {
const interval = setInterval(() => {
setSeconds(seconds => {
if(seconds < 1) {
clearInterval(interval);
return 10;
}
return seconds - 1;
});
}, 1000);
}
Here is a working sandbox
You should also rename the variable to not have the same name (seconds) twice in a single funtion.
| |
doc_23538522
|
For example I have an instance, c, of class Car. How do I call c.honk() from within a migrations file, or access c.colour ?
P.S.
I know that I can 'import' models within the migrations file using ModelName = apps.get_model('appname', 'ModelName') , and I know that I can call class-based functions by doing import('appname').pythonfile.functionname . In other words I know how to do things like call Car.get_components() from within a migrations file.
P.P.S. I'm not sure whether "instance-based functions" and "class-based functions" is the right terminology, but I hope you understand what I mean.
A: As per Django documentation you can't access arbitrary code (custom methods, __init__, save etc.) in migrations, however you can use custom managers if they have use_in_migrations = True attribute.
| |
doc_23538523
|
ActiveRecord::RecordNotFound in RecipesController#show
Couldn't find recipe with id=index
Extracted source (around line #8)
def show
@recipe = Recipe.find(params[:id]) # This line is highlighted in pink
end
I believe this has to do with my routes. The url to my index page is localhost:3000/games/index (I'm calling the index action on my recipes controller. I created that action through resources :recipe creating seven restful routes including index.) However, when I access it, ROR thinks I'm accessing a game with id of index, through the show route. The truth is I would like to set my index page to localhost:3000/recipes. I don't want the index at the end.
Here is my RecipesController
class RecipesController < ApplicationController
def index
@recipe = Recipe.all
end
def show
@recipe = recipe.find(params[:id])
end
def new
@recipe = Recipe.new
end
def create
@recipe = Recipe.new(params[:id])
if @recipe.save
redirect_to @recipe
else
render 'new'
end
end
def edit
end
def update
end
def destroy
end
end
As you can see, I defined the 7 common RESTful routes and have finished 4 of them.
Here is my routes.rb file
Recipes::Application.routes.draw do
resources :recipes
end
By declaring resources :recipes, I created 7 routes without having to declare them on multiple lines.
Here is the result of rake routes
Prefix Verb URI Pattern Controller#Action
recipes GET /recipes(.:format) recipes#index
POST /recipes(.:format) recipes#create
new_recipe GET /recipes/new(.:format) recipes#new
edit_recipe GET /recipes/:id/edit(.:format) recipes#edit
recipe GET /recipes/:id(.:format) recipes#show
PATCH /recipes/:id(.:format) recipes#update
PUT /recipes/:id(.:format) recipes#update
DELETE /recipes/:id(.:format) recipes#destroy
Here is my index.html.erb file located in apps/views/recipes directory
<h1>Here is a list of recipes</h1>
<table>
<thead>
<tr>
<th>Recipe</th>
<th>Cook Time</th>
<th>Prep Time</th>
<th>Difficulty</th>
</tr>
</thead>
<tbody>
<% @recipes.each do |recipe| %>
<tr>
<td><%= recipe.recipe %></td>
<td><%= recipe.cooktime %></td>
<td><%= recipe.preptime %></td>
<td><%= recipe.difficulty %></td>
</tr>
<% end %>
</tbody>
</table>
Here is my migrations file
class CreateRecipes < ActiveRecord::Migration
def change
create_table :recipes do |t|
t.string :recipe
t.string :cooktime
t.string :preptime
t.integer :difficulty
t.timestamps
end
end
end
Here is my application.html.erb file used as a template for every webpage
<!DOCTYPE html>
<html>
<head>
<title>Recipes</title>
<%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %>
<%= javascript_include_tag "application", "data-turbolinks-track" => true %>
<%= csrf_meta_tags %>
</head>
<body>
<%= yield %>
<%= link_to "Home", recipes_path %>
<%= link_to "Edit", edit_recipe_path(:id) %>
<%= link_to "New", new_recupe_path %>
<%= link_to "Delete" %>
</body>
</html>
I tried creating ActiveRecord objects through rails console and had them saved. So ActiveRecord objects do exist with IDs. I don't know where I went wrong here.
If you need any more information, please let me know.
I appreciate any help. Thank you for your time.
A: what gives you this error? I could imagine calling /games/index would. Basically index is parsed as a parameter to the /games/:id route.
EDIT:
this is because of the <%= link_to "Edit", edit_game_path(:id) %> call in the layout template. Which is misplaced. You cannot edit if you are viewing /games because no :id is present.
| |
doc_23538524
|
https://codepen.io/arman311/pen/XobKBL
Edit: I tried @Elliot-Robson's fix, now I get this error:
The page at 'https://codepen.io/arman311/pen/XobKBL' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint '.../fonts/Roboto-Regular.ttf'. This request has been blocked; the content must be served over HTTPS.
A: As the actual issue is a CORS problem (and your server appears to use Apache) please try creating a .htaccess file in the same folder as your fonts.
Inside this file add the following:
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET"
This will allow any origin to access anything in that file.
CORS is designed to stop users browsing a different website from being able to load data from your website (as cookies are attached, if they are logged in - they will get the same data as if they were logged in). This is most often exploited by making POST requests (but not always) on a users behalf.
As it should only affect the fonts folder this should be relatively safe to achieve, just make sure to remove the htaccess file when the challenge is over to avoid people using your fonts without CORS for free.
| |
doc_23538525
|
//Create camera view
session = AVCaptureSession()
var layer = self.cameraView.layer
vidLayer = AVCaptureVideoPreviewLayer.layerWithSession(session) as AVCaptureVideoPreviewLayer
vidLayer.frame = self.cameraView.bounds
vidLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
var device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
var error:NSError? = nil
var input:AVCaptureDeviceInput? = AVCaptureDeviceInput.deviceInputWithDevice(device, error: &error) as? AVCaptureDeviceInput
var output = AVCaptureMetadataOutput();
session.addOutput(output)
output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
output.metadataObjectTypes = [AVMetadataObjectTypeUPCECode, AVMetadataObjectTypeCode39Code, AVMetadataObjectTypeCode39Mod43Code, AVMetadataObjectTypeCode93Code, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code, AVMetadataObjectTypePDF417Code, AVMetadataObjectTypeQRCode, AVMetadataObjectTypeAztecCode]
if(input != nil){
println("ADDED")
session.addInput(input)
}
layer.addSublayer(vidLayer)
session.startRunning()
2014-10-07 15:25:09.279 WegmannMobile[457:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[AVCaptureMetadataOutput setMetadataObjectTypes:] - unsupported type found. Use -availableMetadataObjectTypes.'
*** First throw call stack:
(0x2d7edf83 0x38068ccf 0x2c72bc29 0x618f0 0x62060 0x300256df 0x3019b43f 0x300b8d63 0x300b8b6d 0x300b8b05 0x3000ad59 0x2fc8862b 0x2fc83e3b 0x2fc83ccd 0x2fc836df 0x2fc834ef 0x2fc7d21d 0x2d7b9255 0x2d7b6bf9 0x2d7b6f3b 0x2d721ebf 0x2d721ca3 0x3267b663 0x3006e14d 0x9eff4 0x9f030 0x38575ab7)
libc++abi.dylib: terminating with uncaught exception of type NSException
A: Try adding both the input and output to the session before setting the metadata object types.
When you don't have the camera attached to the session yet, availableMetadataObjectTypes will be empty.
A: This is one of those rare cases where the error message is very useful.
Call [output availableMetadataObjectTypes] and make sure what you're trying to set is in there. If not, then don't try to set that value.
| |
doc_23538526
|
To understand how that algorithm sorts numbers in an array I decided to go through my code step for step in the Eclipse debugger window.
Now there was one step that I can not comprehend even after going through it what felt like hundreds of times.
My initial array is [10, 5, 3, 22, 11, 2]
When I go through the code the program starts by swapping 10 and 2, then 5 and 3 and then 2 and 2. At that point the value for i is 1 and the value for j is -1.
Now the way I see it is that there are three conditions
*
*while(i<=j) Which returns false, because i = 1 and j = -1
*if(left < j) Which returns false, because left = 0 and j = -1
*if(i < right) Which also returns false, because i = 1 and right = 1
But to my surprise when the program gets to the last bracket right before public static void display the program skips back to line 40 if(i < right)
but suddenly the values for right, i, j and pivot have changed from to 5, 2, -1, and 3 respectively.
I would be very grateful if someone could explain why the values get changed.
I have also added two pictures which show what I see on my Eclipse window step I don't understand
public class QSort {
public static void quickSort(int[] arr, int left, int right){
int i = left;
int j = right;
int temp;
int pivot = arr[(left+right)/2];
System.out.println("\n\nleft = " + left + "\tright = " + right);
System.out.println("Pivot is: " + pivot + "(" + (left+right)/2 + ")");
while(i <= j){
while(arr[i] < pivot){
System.out.println("i is: " + arr[i] + "(" + i + ")");
i++;
System.out.println("i is: " + arr[i] + "(" + i + ")");
}
while(arr[j] > pivot){
System.out.println("j is: "+ arr[j] + "(" + j + ")");
j--;
System.out.println("j is: "+ arr[j] + "(" + j + ")");
}
if(i <= j){
System.out.println("i is: " + arr[i] + "(" + i + ")");
System.out.println("j is: "+ arr[j] + "(" + j + ")");
System.out.println("Swapped " + arr[i] + "(" + i + ")"+ " with " + arr[j] + "(" + j + ")");
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
System.out.println("i is: (" + i + ")");
System.out.println("j is: (" + j + ")");
System.out.println("Pivot is: " + pivot + "(" + (left+right)/2 + ")");
}
}
if(left < j){
System.out.println("j is: (" + j + ")");
quickSort(arr, left, j);
}
if(i < right){
System.out.println("i is: (" + i + ")");
quickSort(arr, i, right);
}
}
public static void display(int[] arr){
if(arr.length > 0){
System.out.print(arr[0]);
}
for(int i = 1; i < arr.length; i++){
System.out.print(", " + arr[i]);
}
}
public static void main(String[] args) {
int[] data = new int[]{10,5,3,22,11,2};
System.out.println("Before: ");
display(data);
quickSort(data, 0, data.length-1);
System.out.println("\nAfter: ");
display(data);
}
}
Thanks a lot!
A: I think your problem is that you don't fully understand recursion. At least that's what it sounds like from your desription of the question.
Anyway, I've tried to simply follow your program by keeping a trace of all variables. Hope this helps:
arr left right i j pivot
----------------- ------- -------- ------- ----- ----------
[10,5,3,22,11,2] 0 5
0 5 arr[2] = 3
[2,5,3,22,11,10] 1 4
3
2
[2,3,5,22,11,10] 2 1
The while loop has finished because i<=j is now false (2 > 1).
The first condition left < j (0 < 1) is true, so you call quicksort again recursively: quicksort(arr, 0, 1) - which means you now sort the array [2,3] which is already sorted, so nothing will happen:
arr left right i j pivot
----------------- ------- -------- ------- ----- ----------
[2,3,5,22,11,10] 0 1
0 1 arr[0] = 2
0
[2,3,5,22,11,10] 1 -1
The while loop condition is now false. The first condition left < j is false as well (because 0 > -1) and the second condition i < right is also false (because 1 == 1) So this call is finished and you return to where you were. Were was that? The first condition of the table above. The state of variables and parameters is now:
arr left right i j pivot
----------------- ------- -------- ------- ----- ----------
[10,5,3,22,11,2] 0 5 2 1 3
The second condition is checked (as it is the next line executed). Its value is also true since the condition is i < right (2 < 5). So you now do quicksort again recursively: quicksort(arr, 2, 5) - which means you now sort the array [3,22,11,10]:
arr left right i j pivot
----------------- ------- -------- ------- ----- ----------
[2,3,5,22,11,10] 2 5
2 5 arr[3] = 22
3
[2,3,5,10,11,22] 4 4
5
i > j now so we exit the while loop.
The first condition left < j (2 < 4) is true, so we call quicksort(arr, 2, 4) in order to sort [5,10,11] which is already sorted. I'll skip this part as it does not change the array at all.
When the recursive call is done, we return to where we were and now the second condition will be checked. i < right (5 < 5) is false And so we're done.
The original quicksort call has finished and the array is sorted.
A: The first picture you have shows the debugger is inside two recursive invocations of quicksort: quicksort is called from main, and then on line 38 calls quicksort again (this is the principle of quicksort, it's a recursive strategy). So you see you're on line 40 of the inner call, then when you step from there, you go back to the previous invocation of quicksort (the debugger shows you a stack of two lines instead of three in the top left window), and you're back to the previous values of pivot, etc. The array is passed as is to all recursive invocations so it's shared, but the integer variables aren't.
I think here it's the recursion that makes it hard to understand, check your call stack.
A: Your efforts of studying a sorting algorithms using print statements and a debugger are commendable! But your current implementation of Quicksort is rather difficult to understand, at least initially, because it has got both iteration and recursion going on (i.e. you use loops and at the same time, you have a procedure quicksort calling itself).
Let's take a rather different approach (purely recursive approach) to see how Quicksort works and why it works. Converting this recursive procedure to an iterative one (somewhat like you have written) is, luckily, a matter of technique (in this case)! I propose we do this here because that way we might control the complexity better. Again, the reason I am doing this is to better understand what is going on.
When Sir Tony Hoare proposed the algorithm and proved its correctness, it was something like this:
public static void qsort(int[] ints, int fi, int li) {
/* the recursive procedure */
if (fi < li) {
int p = partition(ints, fi, li); // key routine -- see below
qsort(ints, fi, p - 1);
qsort(ints, p + 1, li);
}
}
That's it! Isn't beautiful? Well, it is. All you do is:
*
*Partition the given array. In my eyes, partitioning is an elegant procedure to solve a tricky problem well. The problem is simple: Given an array of numbers, rearrange the array such that there is a number in it, all the numbers to the left of which are smaller or equal to it and all the numbers to the right of which are larger than or equal to it -- return the index of such an element in the array. I urge you to try to solve this problem on your own. Both the procedures (Lomuto and Hoare) given on Wikipedia work well.
*Once you are sure that your partitioning works as expected, you recursively sort the two partitions using the same qsort procedure (the order of recursive calls does not matter) and you are done!
I tried to implement the partition procedure myself:
/**
Implements partitioning of array a from a[p] to a[r], leaves all the other elements of the array intact.
@param a the given int array
@param p int first index of the part of array to be partitioned
@param r int the second index of the part of array to be partitioned
*/
public static int partition(int[] a, int p, int r) {
//this is something I have written
int pivot = a[p];
int i = p + 1;
int j = i - 1;
while (i <= r) {
if (a[i] < pivot) {
a[j] = a[i];
a[i] = a[j+1];
j++;
}
i++;
}
a[j] = pivot;
return j;
}
private static void swap(int[] ints, int i1, int i2) {
int tmp = ints[i2];
ints[i2] = ints[i1];
ints[i1] = tmp;
}
Now, I haven't yet proved the correctness of this procedure, but we can do that separately. You can even reimplement the Lomuto procedure and see that it works to your satisfaction.
And that's it. If you now want to debug this with a debugger, you are more than equipped to do it. Here's the entire implementation.
Now, the question of converting this recursive procedure to an iterative one is very interesting and this document: (shameless plug: I wrote it) http://bit.ly/recurse-iterate should give you some clues. Actual conversion of the above Quicksort procedure to an iterative one is left as an exercise to the reader :-).
| |
doc_23538527
|
[[0 0 0 0 0 0 0 0 1 1]
[0 0 0 1 0 1 0 0 0 1]
[1 0 1 0 0 0 1 0 0 1]
[1 0 0 0 0 0 0 0 1 0]
[0 1 0 0 0 1 0 1 1 0]
[0 0 0 1 1 0 0 0 0 0]
[0 1 1 1 1 1 0 0 0 0]
[1 0 0 0 1 0 1 0 0 0]
[0 0 0 0 0 0 0 1 0 0]
[0 1 0 0 0 0 0 0 0 0]]
We can think of it as a map that is viewed from above.
I'll pick a random cell, let's say line 3 column 4 (start counting at 0). If the cell contains a 1, there is no problem. If the cell is a 0, I need to find the index of the nearest 1.
Here, line 3 column 4 is a 0, I want a way to find the nearest 1 which is line 4 column 5.
*
*If two cells containing 1 are at the same distance, I don't care which one I get.
*Borders are not inter-connected, i.e. the nearest 1 for the cell line 7 column 9 is not the 1 line 7 column 0
Of course it is a simplified example of my problem, my actual np arrays do not contain zeros and ones but rather Nones and floats
A: This is a simple "path-finding" problem. Prepare an empty queue of coordinates and push a starting position to the queue. Then, pop the first element from the queue and check location and if it's 1 return the coordinates, otherwise push all neighbours to the queue and repeat.
ADJACENT = [(0, 1), (1, 0), (0, -1), (-1, 0)]
def find(data: np.array, start: tuple):
queue = deque()
deque.append(start)
while queue:
pos = queue.popleft()
if data[pos[0], pos[1]]:
return position
else:
for dxy in ADJACENT:
(x, y) = (pos[0] + dxy[0], pos[1], dxy[1])
if x >= 0 and x < data.size[0] and y >= and y < data.size[1]:
queue.append((x,y))
return None
| |
doc_23538528
|
example would be as follows
<video id="videoOne"
controls src="videoOne.mp4"
</video>
<video id="videoTwo"
controls src="videoTwo.mp4"
</video>
I am able to play track which events are firing by changing the 0 to 1 to reference the appropriate video I just need to be able to do it via jquery but am unsure exactly how to accomplish this
var current_source = $('video')[0].currentSrc;
in the following jquery
var PodcastAnalytics = PodcastAnalytics || {};
// Wait for the video element to be parsed before attempting this.
$(document).ready(function(){
// Wait until the video metadata has been loaded before we try to determine the current video source.
$('video').on('loadedmetadata', function(){
// Simple function to chop off the file extension for the current source of the video.
PodcastAnalytics.audio_url = (function(){
var current_source = $('video')[0].currentSrc;
return current_source.slice(0, -4);
}());
// function that sends the actual tracking beacon
PodcastAnalytics.gaq_track = function(action) {
// All events will be in the Video category
var tracking_params = ['podcast','audio']
// append the event action after the event method and the event category
tracking_params.push(action);
// append the video url as the event label
tracking_params.push(PodcastAnalytics.audio_url);
// Replace this console.log with something like this if you are using Google Analytics:
// _gaq.push(tracking_params);
console.log(tracking_params);
}
$('video').on('play', function(){
PodcastAnalytics.gaq_track('Play');
});
$('video').on('pause', function(){
PodcastAnalytics.gaq_track('Pause');
});
$('video').on('seeked', function(){
PodcastAnalytics.gaq_track('Seeked');
});
$('video').on('ended', function(){
PodcastAnalytics.gaq_track('Ended');
});
});
});
A: I might be way off, and if I am, please let me know and I'll delete my answer.
But here's what I would try:
*
*inside the outer bind event, grab a reference to the video object.
*use that to find your current_src
*continue using it to perform the additional event bindings.
Just a thought.
var PodcastAnalytics = PodcastAnalytics || {};
// Wait for the video element to be parsed before attempting this.
$(document).ready(function(){
// Wait until the video metadata has been loaded before we try to determine the current video source.
$('video').on('loadedmetadata', function(){
// should 'this' refer to the video object?
var $video = $(this);
// Simple function to chop off the file extension for the current source of the video.
PodcastAnalytics.audio_url = (function(){
var current_source = $video.attr('currentSrc');
// var current_source = $('video')[0].currentSrc;
return current_source.slice(0, -4);
}());
// function that sends the actual tracking beacon
PodcastAnalytics.gaq_track = function(action) {
// All events will be in the Video category
var tracking_params = ['podcast','audio']
// append the event action after the event method and the event category
tracking_params.push(action);
// append the video url as the event label
tracking_params.push(PodcastAnalytics.audio_url);
// Replace this console.log with something like this if you are using Google Analytics:
// _gaq.push(tracking_params);
console.log(tracking_params);
}
$video.on('play', function(){
PodcastAnalytics.gaq_track('Play');
});
$video.on('pause', function(){
PodcastAnalytics.gaq_track('Pause');
});
$video.on('seeked', function(){
PodcastAnalytics.gaq_track('Seeked');
});
$video.on('ended', function(){
PodcastAnalytics.gaq_track('Ended');
});
});
});
A: I used the following jquery to get the correct <video id=""/> but would still like to know if it's possible and how to go about getting the currentSrc from e.target.id
$(document).ready(function($){
$('video').on('loadedmetadata', function() {
tracking = function(action,id, source) {
var items = ['podcast','audio',action,id, source];
console.log(items);
};
});
$('video').off('play').on('play', function(e) {
var idx = $(this).index();
var currentSource = $('video')[idx].currentSrc;
tracking('Play', e.target.id, currentSource);
});
$('video').off('pause').on('pause', function(e) {
tracking('Pause', e.target.id);
});
$('video').off('seeked').on('seeked', function(e) {
tracking('Seeked', e.target.id);
});
$('video').off('ended').on('ended', function(e) {
tracking('Ended', e.target.id);
});
});
| |
doc_23538529
|
<div data-role="fieldcontain">
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Term:</legend>
<label for="txtSDate">
</label>
<input id="txtSDate" name="txtSDate" value="<%=sdate%>" placeholder="Enter start date" type="date" data-inline="true"
maxlength="12" />
<label for="txtEDate">
</label>
<input id="txtEDate" name="txtEDate" value="<%=edate%>" type="date" maxlength="12" placeholder="Enter end date" />
</fieldset>
</div>
A: maybe you missed the fieldcontian?
please try below:
<div data-role="fieldcontain">
<label for="txtSDate"></label>
<input id="txtSDate" name="txtSDate" value="<%=sdate%>" placeholder="Enter start date" type="date" data-inline="true" maxlength="12" />
</div>
| |
doc_23538530
|
Employee
Id Name salary DeptId
1 john 100 1
2 Nicolas 200 1
3 Chris 300 2
4 jonny 400 3
5 leo 500 5
6 jim 600 4
7 bryan 700 4
Dept
DeptID DeptName
1 HR
2 MGR
3 Support
4 Admin
5 Staff
I've tried query as:
select d.deptname,CONCAT(e.name,'') from emp e inner join dept d on e.deptid=d.deptid group by d.deptname,e.name
Output: How Can I get this Output ?
DeptName EmpNames(list of Names)
HR john,Nicolas
MGR Chris
Support jonny
Admin jim,bryan
Staff leo
| |
doc_23538531
|
Object o = new Object();
session.save(o)
and
session.save(new Object());
I ask because I am finding sometimes the objects are mixed up in my implementation. The discrepancy is found in production database. So it is hard to test.
Here is the edited code:
pubic class Product {
Logger logger = Logger.getRootLogger();
private String globalId;
public void service() {
this.gobalId = getVariable("GLOBALID"); //from Asterisk
Transaction tran = null;
try {
Session session = HibernateUtil.getCurrentSession();
int charge=0;
//set charge
Transaction tran = session.beginTransaction();
session.save(new Packet(globalId, charge));
tran.commit();
} catch (Exception e) {
if (tran != null) tran.rollback();
logger.error("Error", e);
} finally {
HibernateUtil.closeCurrentSession();
}
}
}
At run time, I see in the Packet table duplicate globalId rows with different values for the charge column. The globalId is supposed to be unique, even though it is not the primary key in the table. There could be a couple of explanations:
*
*Asterisk is sending a wrong value for globalId in the getVariable() method
*The service method needs to be synchrnozied (the Asterisk Java API says the Product class is implemented like a Servlet)
I don't see any errors in the logs. So no exceptions are thrown in the code.
Any help is appreciated.
Thanks
| |
doc_23538532
|
import java.net.HttpURLConnection;`
import java.net.URL;
import java.net.URLEncoder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;
import org.xml.sax.SAXException;
public class GeocodingSample {
// URL prefix to the geocoder
private static final String GEOCODER_REQUEST_PREFIX_FOR_XML =
"http://maps.google.com/maps/api/geocode/xml";
public static final void main (String[] argv) throws IOException,
XPathExpressionException, ParserConfigurationException, SAXException {
// query address
String address = "1600 Amphitheatre Parkway, Mountain View, CA";
// prepare a URL to the geocoder
URL url = new URL(GEOCODER_REQUEST_PREFIX_FOR_XML + "?address=" +
URLEncoder.encode(address, "UTF-8") + "&sensor=false");
// prepare an HTTP connection to the geocoder
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
Document geocoderResultDocument = null;
try {
// open the connection and get results as InputSource.
conn.connect();
InputSource geocoderResultInputSource = new
InputSource(conn.getInputStream());
// read result and parse into XML Document
geocoderResultDocument =
DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(geocoderResultInputSource);
} finally {
conn.disconnect();
}
// prepare XPath
XPath xpath = XPathFactory.newInstance().newXPath();
// extract the result
NodeList resultNodeList = null;
// a) obtain the formatted_address field for every result
resultNodeList = (NodeList)
xpath.evaluate("/GeocodeResponse/result/formatted_address",
geocoderResultDocument, XPathConstants.NODESET);
for(int i=0; i<resultNodeList.getLength(); ++i) {
System.out.println(resultNodeList.item(i).getTextContent());
}
// b) extract the locality for the first result
resultNodeList = (NodeList)
xpath.evaluate("/GeocodeResponse/result[1]/
address_component[type/text()='locality']/long_name",
geocoderResultDocument, XPathConstants.NODESET);
for(int i=0; i<resultNodeList.getLength(); ++i) {
System.out.println(resultNodeList.item(i).getTextContent());
}
// c) extract the coordinates of the first result
resultNodeList = (NodeList)
xpath.evaluate("/GeocodeResponse/result[1]/geometry/location/*",
geocoderResultDocument, XPathConstants.NODESET);
float lat = Float.NaN;
float lng = Float.NaN;
for(int i=0; i<resultNodeList.getLength(); ++i) {
Node node = resultNodeList.item(i);
if("lat".equals(node.getNodeName())) lat =
Float.parseFloat(node.getTextContent());
if("lng".equals(node.getNodeName())) lng =
Float.parseFloat(node.getTextContent());
}
System.out.println("lat/lng=" + lat + "," + lng);
// c) extract the coordinates of the first result
resultNodeList = (NodeList)
xpath.evaluate("/GeocodeResponse/result[1]/address_component[type/text()
= 'administrative_area_level_1']/country[short_name/text() = 'US']/*",
geocoderResultDocument, XPathConstants.NODESET);
float lat = Float.NaN;
float lng = Float.NaN;
for(int i=0; i<resultNodeList.getLength(); ++i) {
Node node = resultNodeList.item(i);
if("lat".equals(node.getNodeName())) lat =
Float.parseFloat(node.getTextContent());
if("lng".equals(node.getNodeName())) lng =
Float.parseFloat(node.getTextContent());
}
System.out.println("lat/lng=" + lat + "," + lng);
}
}
A: You want to get the altitude for a specific point, I found this page that provide this facility, a code is provided in the page http://www.daftlogic.com/sandbox-google-maps-find-altitude.htm
I hope it will answer the question.
A: thanks for contributing ...
i got the solution for converting the latitude and longitude to 3d coordinates(x,y,z)...that is
suppose that the model of earth has radius r then
LAT=latitude*pi/180
LON=longitude*pi/180
x=r*cos(LAT)*cos(LON)
y=r*sin(LAT)
z=r*cos(LAT)*sin(LON)..
| |
doc_23538533
|
Any help would be extremely appreciated!
| |
doc_23538534
|
select top (20)percent o.BillEmail,SUM(o.total) as TotalSpent,
count(o.OrderID) as TotalOrders
from dbo.tblOrder o with (nolock)
where o.DomainProjectID=13
and o.BillEmail not like ''
and o.OrderDate >= '2010-01-01'
and o.OrderDate < '2011-01-01'
group by o.BillEmail
order by TotalSpent desc
From this, I need to find the retention rate of those top 20% spenders over the next two years.
Meaning, which of the top 20% in 2010 stuck around and are on top in 2011, and then in 2012 as well? Note: I'd need a count of how many were in 2010, then in 2011, then also in 2012.
I know it'd be much easier if I could create another table or pull from an excel sheet with only the top buyers listed. However, I don't have write access to our database so I have to do it all in nested queries, or whatever y'all have to suggest. I'm still a beginner so I don't know the best methods.
Thank you!
A: You have an interesting question. Fundamentally, it is about migration in spending quintiles from one year to the next. I would solve this by looking at all quintiles for the three years, to see where people move.
This starts with a summary of the data by year and email. The key function is ntile(). To be honest, I often do the calculation myself using row_number() and count(), which is why those are in the CTE (but not used subsequently):
with YearSummary as (
select year(OrderDate) as yr, o.BillEmail, SUM(o.total) as TotalSpent,
count(o.OrderID) as TotalOrders,
row_number() over (partition by year(OrderDate) order by sum(o.Total) desc) as seqnum,
count(*) over (partition by year(OrderDate)) as NumInYear,
ntile(5) over (partition by year(OrderDate) order by sum(o.Total) desc) as Quintile
from dbo.tblOrder o with (nolock)
where o.DomainProjectID=13 and o.BillEmail not like ''
group by o.BillEmail, year(OrderDate)
)
select q2010, q2011, q2012,
count(*) as NumEmails,
min(BillEmail), max(BillEmail)
from (select BillEmail,
max(case when yr = 2010 then Quintile end) as q2010,
max(case when yr = 2011 then Quintile end) as q2011,
max(case when yr = 2012 then Quintile end) as q2012
from YearSummary
group by BillEmail
) ys
group by q2010, q2011, q2012
order by 1, 2, 3;
The final step is to take the multiple rows for each email and to combine them into counts. Do note that some emails will not have any spending in certain years, so their corresponding Quintile will be NULL (this should actually produce more like 180 row - 5*6*6 - rather than 125 rows - 5*5*5
I also include sample emails in the final results (the min()and max()), which allow you to see samples for each group.
Note: For the retention rate, calculate the ratio between (1, 1, 1) -- top tile in all years -- and the total in the top quintile in 2010.
A: Try this:
;WITH top_2010 AS
(
select top (20)percent o.BillEmail,SUM(o.total) as TotalSpent,
count(o.OrderID) as TotalOrders
from dbo.tblOrder o with (nolock)
where o.DomainProjectID=13
and o.BillEmail not like ''
and o.OrderDate >= '2010-01-01'
and o.OrderDate < '2011-01-01'
group by o.BillEmail
),
top_2011 AS
(
select top (20)percent o.BillEmail,SUM(o.total) as TotalSpent,
count(o.OrderID) as TotalOrders
from dbo.tblOrder o with (nolock)
where o.DomainProjectID=13
and o.BillEmail not like ''
and o.OrderDate >= '2011-01-01'
and o.OrderDate < '2012-01-01'
group by o.BillEmail
),
top_2012 AS
(
select top (20)percent o.BillEmail,SUM(o.total) as TotalSpent,
count(o.OrderID) as TotalOrders
from dbo.tblOrder o with (nolock)
where o.DomainProjectID=13
and o.BillEmail not like ''
and o.OrderDate >= '2012-01-01'
and o.OrderDate < '2013-01-01'
group by o.BillEmail
)
SELECT top_2010.*,
ISNULL(top_2011.TotalSpent, 0) AS [TotalSpent_2011],ISNULL(top_2011.TotalOrders, 0) AS [TotalOrders_2011] ,
ISNULL(top_2012.TotalSpent, 0) AS [TotalSpent_2012],ISNULL(top_2012.TotalOrders, 0) AS [TotalOrders_2012]
FROM top_2010
LEFT JOIN top_2011 ON top_2010.BillEmail = top_2011.BillEmail
LEFT JOIN top_2012 ON top_2010.BillEmail = top_2012.BillEmail
WHERE top_2011.BillEmail IS NOT NULL OR top_2012.BillEmail IS NOT NULL
order by top_2010.TotalSpent desc
please note that I'm using LEFT JOIN so you can see all those that were in the top 2011 or 2012
if you need those that were in 2011 AND 2012 you can change to INNER JOIN
A: You can use common table expressions to accomplish this. Create a top 20% listing for each year, and then inner join them to find which companies are in the top quintile for all three years. Because you want only records which are present in all three years, you should not use left joins.
WITH Top2010 AS (
select top (20)percent o.BillEmail,SUM(o.total) as TotalSpent,
count(o.OrderID) as TotalOrders
from dbo.tblOrder o with (nolock)
where o.DomainProjectID=13
and o.BillEmail not like ''
and o.OrderDate >= '2010-01-01'
and o.OrderDate < '2011-01-01'
group by o.BillEmail
order by TotalSpent desc
),
Top2011 AS (
select top (20)percent o.BillEmail,SUM(o.total) as TotalSpent,
count(o.OrderID) as TotalOrders
from dbo.tblOrder o with (nolock)
where o.DomainProjectID=13
and o.BillEmail not like ''
and o.OrderDate >= '2011-01-01'
and o.OrderDate < '2012-01-01'
group by o.BillEmail
order by TotalSpent desc
),
Top2012 AS (
select top (20)percent o.BillEmail,SUM(o.total) as TotalSpent,
count(o.OrderID) as TotalOrders
from dbo.tblOrder o with (nolock)
where o.DomainProjectID=13
and o.BillEmail not like ''
and o.OrderDate >= '2012-01-01'
and o.OrderDate < '2013-01-01'
group by o.BillEmail
order by TotalSpent desc
)
SELECT Top2010.BillEmail -- plus whatever other columns you want
FROM Top2010
INNER JOIN Top2011 ON Top2010.BillEmail = Top2011.BillEmail
INNER JOIN Top2012 ON Top2012.BillEmail = Top2011.BillEmail
A: Personally I'd use a couple of CTEs; one per year. I'd also name things a little more generically (rather than embedding the year name everywhere). Once we've got our resultsets we can use EXISTS to check who was around in all 3 periods.
-- Get the 1st Jan in the current year
DECLARE @current_year date = DateAdd(yy, DateDiff(yy, 0, Current_Timestamp), 0);
; WITH highest_spenders_2_years_ago AS (
<your_query>
WHERE o.orderDate >= DateAdd(yy, -2, @current_year)
AND o.orderDate < DateAdd(yy, -1, @current_year)
)
, highest_spenders_last_year AS (
<your_query>
WHERE o.orderDate >= DateAdd(yy, -1, @current_year)
AND o.orderDate < DateAdd(yy, 0, @current_year)
)
, highest_spenders_this_year AS (
<your_query>
WHERE o.orderDate >= DateAdd(yy, 0, @current_year)
AND o.orderDate < DateAdd(yy, 1, @current_year)
)
SELECT *
FROM highest_spenders_this_year
WHERE EXISTS (
SELECT *
FROM highest_spenders_last_year
WHERE BillEmail = highest_spenders_this_year.BillEmail
)
AND EXISTS (
SELECT *
FROM highest_spenders_2_years_ago
WHERE BillEmail = highest_spenders_this_year.BillEmail
)
A: SELECT Base2010.BillEmail,
CASE WHEN retention2011.BillEmail = '' THEN 'Not retained' ELSE 'Retained' END AS retained2011,
CASE WHEN retention2012.BillEmail = '' THEN 'Not retained' ELSE 'Retained' END AS retained2012
FROM
(select top (20)percent o.BillEmail,SUM(o.total) as TotalSpent,
count(o.OrderID) as TotalOrders, BillEmail
from dbo.tblOrder o with (nolock)
where o.DomainProjectID=13
and o.BillEmail not like ''
and o.OrderDate >= '2010-01-01'
and o.OrderDate < '2011-01-01'
group by o.BillEmail
) AS Base2010
LEFT JOIN
(select top (20)percent o.BillEmail,SUM(o.total) as TotalSpent,
count(o.OrderID) as TotalOrders, BillEmail
from dbo.tblOrder o with (nolock)
where o.DomainProjectID=13
and o.BillEmail not like ''
and o.OrderDate >= '2011-01-01'
and o.OrderDate < '2012-01-01'
group by o.BillEmail
) AS retention2011
ON Base2010.BillEmail = retention2011.BillEmail
LEFT JOIN
(select top (20)percent o.BillEmail,SUM(o.total) as TotalSpent,
count(o.OrderID) as TotalOrders, BillEmail
from dbo.tblOrder o with (nolock)
where o.DomainProjectID=13
and o.BillEmail not like ''
and o.OrderDate >= '2012-01-01'
and o.OrderDate < '2013-01-01'
group by o.BillEmail
) AS retention2012
ON Base2010.BillEmail = retention2012.BillEmail
| |
doc_23538535
|
Note : im currently storing the token and refresh token in a JSON file
| |
doc_23538536
|
But when i run my code it shows Unfortunately,Lister has been stopped.
My code in onCreate method is:-
PackageManager pm=this.getPackageManager();
List<ApplicationInfo> list=pm.getInstalledApplications(0);
ListView lv=(ListView)findViewById(R.id.listView1);
ArrayList<String> al=new ArrayList<String>();
for(ApplicationInfo app:list)
{
String appN=pm.getApplicationLabel(app).toString();
al.add(appN);
}
ArrayAdapter<String> arr=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,android.R.id.text1,al);
lv.setAdapter(arr);
setContentView(R.layout.activity_sec);
and my activity_sec.xml code is:-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="top"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.gestureview.Sec" >
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="40dp" >
</ListView>
</RelativeLayout>
My Log Cat is:-
06-19 04:33:53.234: E/AndroidRuntime(1205): FATAL EXCEPTION: main
06-19 04:33:53.234: E/AndroidRuntime(1205): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.gestureview/com.example.gestureview.Sec}: java.lang.NullPointerException
06-19 04:33:53.234: E/AndroidRuntime(1205): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
06-19 04:33:53.234: E/AndroidRuntime(1205): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
06-19 04:33:53.234: E/AndroidRuntime(1205): at android.app.ActivityThread.access$600(ActivityThread.java:141)
06-19 04:33:53.234: E/AndroidRuntime(1205): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
06-19 04:33:53.234: E/AndroidRuntime(1205): at android.os.Handler.dispatchMessage(Handler.java:99)
06-19 04:33:53.234: E/AndroidRuntime(1205): at android.os.Looper.loop(Looper.java:137)
06-19 04:33:53.234: E/AndroidRuntime(1205): at android.app.ActivityThread.main(ActivityThread.java:5041)
06-19 04:33:53.234: E/AndroidRuntime(1205): at java.lang.reflect.Method.invokeNative(Native Method)
06-19 04:33:53.234: E/AndroidRuntime(1205): at java.lang.reflect.Method.invoke(Method.java:511)
06-19 04:33:53.234: E/AndroidRuntime(1205): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-19 04:33:53.234: E/AndroidRuntime(1205): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-19 04:33:53.234: E/AndroidRuntime(1205): at dalvik.system.NativeStart.main(Native Method)
06-19 04:33:53.234: E/AndroidRuntime(1205): Caused by: java.lang.NullPointerException
06-19 04:33:53.234: E/AndroidRuntime(1205): at com.example.gestureview.Sec.onCreate(Sec.java:33)
06-19 04:33:53.234: E/AndroidRuntime(1205): at android.app.Activity.performCreate(Activity.java:5104)
06-19 04:33:53.234: E/AndroidRuntime(1205): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
06-19 04:33:53.234: E/AndroidRuntime(1205): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
06-19 04:33:53.234: E/AndroidRuntime(1205): ... 11 more
It seems that there must be a problem with creating ListView.
A: You should First set Content than call the ListView
PackageManager pm=this.getPackageManager();
List<ApplicationInfo> list=pm.getInstalledApplications(0);
setContentView(R.layout.activity_sec); ///call this Line here
ListView lv=(ListView)findViewById(R.id.listView1);
ArrayList<String> al=new ArrayList<String>();
for(ApplicationInfo app:list)
{
String appN=pm.getApplicationLabel(app).toString();
al.add(appN);
}
ArrayAdapter<String> arr=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,android.R.id.text1,al);
lv.setAdapter(arr);
A: This is working too
final PackageManager pm = mParentActivity.getPackageManager();
List<ApplicationInfo> packages = pm.getInstalledApplications(0);
for (ApplicationInfo packageInfo : packages) {
// get the UID for the selected app
int UID = packageInfo.uid;
String package_name = packageInfo.packageName;
ApplicationInfo app = null;
try {
app = pm.getApplicationInfo(package_name, 0);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String name = (String) pm.getApplicationLabel(app);
Drawable icon = pm.getApplicationIcon(app);
final SmsDetailsPojo dataItem = new SmsDetailsPojo();
dataItem.setContactNum(name);
dataItem.setDrawable(icon);
if((app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) == 1) {
// updated system apps
} else if ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 1) {
// system apps
} else {
arrayUserInstalledApps.add(dataItem);
}
| |
doc_23538537
|
A: You'd need some server-side application anyway, even if that application were SQL Server :)
Something like rsh might do - have your local SQL instance invoke xp_cmdshell with an rsh command (or a batch file), connecting to the remote server and executing the command.
If you have SQL on the remote machine, it'd be far easier; call a stored procedure on that machine from the local machine, and let that stored procedure do the work (might need fiddling with proxies and "execute as").
A third option would be to create a .NET stored procedure, and do your socket programming or remote invocation from there - it runs in-process, so you get similar same performance and security benefits you'd get from writing it in T-SQL rather than hopping out to a cmdshell with all the mess that entails.
| |
doc_23538538
|
{
"name" : "Ravi Tamada",
"email" : "[email protected]",
"phone" :
{
"home" : "08947 000000",
"mobile" : "9999999999"
}
}
Here is my JsonObjectRequest:
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, APITEST,null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
Gson gson = new Gson();
People people;
people = gson.fromJson(jsonObject.toString(),People.class);
tv_city.setText(""+people.email);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
}
});
It's ok with tv_city.setText(""+people.email())...
Here is my javabean class:
public class People {
public String name ;
public String email;
public class Phone{
public String home;
public String mobile;
}
}
Now I want to get "home" number,how?
A: 1- You have to update your bean class as follows :-
public class People implements Serializable {
private String name ;
private String email;
private Phone phone;
public Phone getPhone () {
return phone;
}
public void setPhone (Phone phone) {
this.phone = phone;
}
public String getName () {
return name;
}
public void setName (String name) {
this.name = name;
}
public String getEmail () {
return email;
}
public void setEmail (String email) {
this.email = email;
}}
2- Create a new bean class Phone.java :-
public class Phone implements Serializable{
private String home;
public String getMobile () {
return mobile;
}
public void setMobile (String mobile) {
this.mobile = mobile;
}
public String getHome () {
return home;
}
public void setHome (String home) {
this.home = home;
}
private String mobile;}
3- Now update your code as follows:-
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, APITEST,null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
Gson gson = new Gson();
People people;
people = gson.fromJson(jsonObject.toString(),People.class);
tv_city.setText(""+people.email);
//for getting Home & Mobile number
String home=people.getPhone.getHome();
String mobile=people.getPhone.getMobile();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
}
});
Note:- My above bean is as per expected api response in your question. But if you have nested objects then you have to choose either List<Phone> or ArrayList<Phone> inside in your People bean and then create its getters and setters.
Hope this will help you !!!
A: you can also get the data directly from the json object like this
if(JsonObject!=null){
String email=JsonObject.getString("email");
}
OR
To make it work write getters() and setters() in your model object(person object) you can auto generate it too .
once you do that get the data like this
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, APITEST,null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
Gson gson = new Gson();
People people;
people = gson.fromJson(jsonObject.toString(),People.class);
tv_city.setText(""+people.getEmail());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
}
});
A: Replace your JavaBean class with
public class People {
@SerializedName("name")
@Expose
private String name;
@SerializedName("email")
@Expose
private String email;
@SerializedName("phone")
@Expose
private Phone phone;
/**
*
* @return
* The name
*/
public String getName() {
return name;
}
/**
*
* @param name
* The name
*/
public void setName(String name) {
this.name = name;
}
/**
*
* @return
* The email
*/
public String getEmail() {
return email;
}
/**
*
* @param email
* The email
*/
public void setEmail(String email) {
this.email = email;
}
/**
*
* @return
* The phone
*/
public Phone getPhone() {
return phone;
}
/**
*
* @param phone
* The phone
*/
public void setPhone(Phone phone) {
this.phone = phone;
}
}
And
public class Phone {
@SerializedName("home")
@Expose
private String home;
@SerializedName("mobile")
@Expose
private String mobile;
/**
*
* @return
* The home
*/
public String getHome() {
return home;
}
/**
*
* @param home
* The home
*/
public void setHome(String home) {
this.home = home;
}
/**
*
* @return
* The mobile
*/
public String getMobile() {
return mobile;
}
/**
*
* @param mobile
* The mobile
*/
public void setMobile(String mobile) {
this.mobile = mobile;
}
}
and then you can make call in your JsonResponse like
JSONObject phone=jsonObject.getJSONObject("phone");
String home=phone.getHome();
will return you the home Number.
Hope it helps :)
A: JSONObject phone=jsonObject.getJSONObject("phone");
String home=phone.getString("home");
Now you have Home Phone number in home string.
| |
doc_23538539
|
So for example, I'm trying to do a fetch on a store's listings:
fetch('https://openapi.etsy.com/v2/shops/[shopId]/listings/active?api_key=[apiKey]')
But that violates the browser's CORS policy. No problem, says the documentation on Etsy. You can always use their proxy: beta-api.etsy.com. So I add that to my package.json file:
"proxy": "https://beta-api.etsy.com/"
And then I change my fetch line:
fetch('/v2/shops/[shopId]/listings/active?api_key=[apiKey]')
But CORS is still being violated in the browser.
Access to fetch at 'https://www.etsy.com/shop/beta-api/v2/shops/[shopId]/listings/active?api_key=[apiKey]' (redirected from 'http://localhost:3000/v2/shops/[shopId]/listings/active?api_key=[apiKey]') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I don't want an opaque response, either, so doing "no-cors" really doesn't help. Does anyone have any recommendations on how I can at least get a local website up and running?
A: You are getting that error because your server has set Access-Control-Allow-Origin to restrict cross-domain traffic. You are sending your request from your localhost so that is considered cross-domain.
If you are able to change your server settings to set Access-Control-Allow-Origin: * then you can make those requests without a CORS error but I don't suggest doing this.
The best solution would probably be a proxy server. You can use cors-anywhere heroku app to easily do this.
Excerpt from Medium Article on this issue
The cors-anywhere server is a proxy that adds CORS headers to a
request. A proxy acts as an intermediary between a client and server.
In this case, the cors-anywhere proxy server operates in between the
frontend web app making the request, and the server that responds with
data.
Similar to the Allow-control-allow-origin plugin, it adds the
more open Access-Control-Allow-Origin: * header to the response.
Say your frontend is trying to make a GET request to:
https://joke-api-strict-cors.appspot.com/jokes/random
But this api does not have a Access-Control-Allow-Origin value
in place that permits the web application domain to access it.
So instead, send your GET request to:
https://cors-anywhere.herokuapp.com/https://joke-api-strict-cors.appspot.com/jokes/random
The proxy server receives the
https://joke-api-strict-cors.appspot.com/jokes/random
from the url above. Then it makes the request to get that server’s
response. And finally, the proxy applies the Access-Control-Allow-
Origin: * to that original response.
| |
doc_23538540
|
A: If you read the docs or any information starting from edgware you would see that we've removed that support. You should use native zipkin rabbit / kafka dependencies. Everything is there in the docs.
| |
doc_23538541
|
error[E0502]: cannot borrow `*x` as immutable because it is also borrowed as mutable
--> src\main.rs:17:23
|
17 | *x.get_a_mut() += x.get_a(); //B DOESN'T COMPILE
| ------------------^--------
| || |
| || immutable borrow occurs here
| |mutable borrow occurs here
| mutable borrow later used here
If it is a problem to use a mutable and an immutable reference to a in the same expression, why does C and D compile?
struct X {
a: i64,
}
impl X {
pub fn get_a_mut(&mut self) -> &mut i64 {
return &mut self.a;
}
pub fn get_a(&self) -> &i64 {
return &self.a;
}
}
fn my_fn(x: &mut X) {
*x.get_a_mut() += 5; //A
*x.get_a_mut() += x.get_a(); //B DOESN'T COMPILE
*x.get_a_mut() += 2 * x.get_a(); //C
*x.get_a_mut() = x.get_a() + x.get_a(); //D
}
fn main() {
let mut x = X { a: 50 };
my_fn(&mut x);
}
A: According to += documentation, you are calling something like add_assign(lhs: &mut i64, rhs: &i64) in case B and something like add_assign(lhs: &mut i64, rhs: i64) in cases A, C and D.
In case A, rhs is a constant, different from x.a; no problem.
In case C, rhs is a temporary (the result of 2 * x.get_a()) and does not need to keep a reference on x.a to exist; no problem.
In case D, rhs is a temporary (the result of x.get_a() + x.get_a()) and does not need to keep a reference on x.a to exist; no problem.
But when it comes to case B, rhs is a reference on x.a; then this call uses both a mutable (lhs) and immutable (rhs) reference on the same data (x.a) at the same time, which is forbidden.
You could eventually clone rhs: *x.get_a_mut() += x.get_a().clone().
| |
doc_23538542
|
Most of the schema is set out for the actual creation of the emails but i'm still not sure on one design element
Where to store the archive of sent emails?
Should i store them in sql database as nvarchar(max)
or actually store them as files within the file system itself (.htm files for example) and then just have a link to the file stored in the database
very much in the same way as i store photos currently.
A: I would advocate using the file system.
I built an email engine years ago that in its' day delivered a million messages per hour (it was a pretty big deal then). While there is value in having traceability through database logging, etc., I found working with file system is significantly easier to manage day to day.
I built out a semi-RESTful structure like so:
*
*Client (A)
*
*Year
*
*Month
*
*Day
*
*Email Subject
*
*message.html
*message.txt
*
*Images
*Etc.
In addition to being a simple file structure, it also makes managing other file dependencies easier. Emails often include images, file attachments, etc. and keeping a those files bundled within the same email resource folder reduced complexity.
My emails table still needed a reference to the path of the email but that was easily calculated based on the [scheduled] email delivery date.
To specifically address your SQL Server suggestion I can say I tried storing emails exactly as you suggested as well. In the end, and for my particular technology stack, I need to write my files to disk for an "online version" anyway. When you've got dynamic emails being written like this:
Dear [John Smith],
Thank you for your interest in [XYZ].
Handling variable substitution is drastically easier when the file is available to be served by your backend (.NET, Java, Rails, etc.) by simply providing an ID.
http://myclient.emailserver.com/2013/10/29/the-most-brilliant-subject-line-ever?id=1234
Last but certainly not least you must weight the additional cost of keeping those emails in your database. SQL Server is a beautiful piece of software - personally, I think it's the best thing Microsoft ever built - but these emails are archive material and they're just adding bulk to your system. I don't know the scale of the system you're attempting to build but if even with a hundred million emails (which isn't that hard to produce) you're talking about a lot of girth.
Hope this helps.
Cheers!
A: SMTP servers usually already store them as files, in .eml format. You can chose to keep them that way and use your database to catalog and index them, or you can store everything in the database, but personally I think its dangerous to do that for some reasons:
*
*You database would rapidly increase in size, as a single message can have more then 10MB, and NVARCHAR uses UNICODE, so that would be actually 20MB. Storage-wise it's a highly inefficient solution;
*No database server handle variable length data very well, you may have performance issues and database files that continuously grow in size even if you delete stuff;
*Afaik each table has a limit of 8TB, this may be small depeding on your case;
*A typical backup would generate monstrous files of possibly many terabytes. You would have to create a custom backup solution to manage that;
*When storing large amounts of data, hard disk errors are to be taken in consideration. If some sector gets corrupted you can lose a random email file, and thats usually okay. If the database file get corrupted it will be a catastrophic problem. A smaller database covers less space in disk and runs less risk of having a sector corrupted.
A: One of the reasons you don't want to store lots of blobs in sql is that the backups take longer and longer and cannot as easily be split to a seperate file server (or servers) that can run concurrently with your SQL server backup -- this factor alone causes lots of grief when you use SQL as a file store
| |
doc_23538543
|
I would like to know why the Upload File button only shows for a SuperUser and not a registered user?
Which code must I add?
A: we have implemented something like below for our use
<label class="file-upload">
<span><strong>Select file</strong></span>
<asp:FileUpload CssClass="fileuploadcss" ClientIDMode="Static" ID="POdDOc" runat="server" />
</label>
<style type="text/css">
.file-upload
{
overflow: hidden;
display: inline-block;
position: relative;
vertical-align: middle;
text-align: center; / Cosmetics /
border: 1px solid #cfcfcf;
background: #e2e2e2; / Nice if your browser can do it /
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
cursor: pointer;
}
.file-upload:hover
{
background: #e9e9e9;
}
.file-upload.focus
{
outline: 1px solid yellow;
}
.file-upload input
{
position: absolute;
top: 0;
left: 0;
margin: 0;
font-size: 10pt; / Loses tab index in webkit if width is set to 0 /
opacity: 0;
filter: alpha(opacity=0);
}
.file-upload strong
{
padding-top: 5px;
font-size: 9pt;
font-weight: normal;
}
.file-upload span
{
position: absolute;
top: 0;
left: 0;
z-index: 100;
display: inline-block; / Adjust button text vertical alignment /
padding-top: 5px;
}
/ Adjust the button size /
.file-upload
{
height: 22px;
}
.file-upload, .file-upload span
{
width: 75px;
}
a.dellink
{
color: #e60000;
font-weight: bold;
text-decoration: none;
}
a.dellink:hover
{
color: #ff8040;
font-weight: bold;
text-decoration: none;
}
.customcssspan
{
/*color: #20b5dc;*/
color: Red;
}
.clsHidden
{
display: none;
}
| |
doc_23538544
|
For this to happen, I have to briefly return something else than the MaterialApp from the build method in my app state.
class _RestartWidgetState extends State<RestartWidget> {
Key key = new UniqueKey();
static bool isRestarting = false;
void restartApp() {
this.setState(() {
isRestarting = true;
key = new UniqueKey();
});
Timer(Duration(milliseconds: 500), (){
this.setState(() {
isRestarting = false;
key = new UniqueKey();
});
});
}
@override
Widget build(BuildContext context) {
return new Container(
key: key,
child: widget.child,
);
}
}
class MyAppState extends State<MyApp>{
@override
Widget build(BuildContext context) {
if( _RestartWidgetState.isRestarting ) {
return Container( ... );
}
else{
return ScopedModel<MyModel>(
model: myModel,
child: MaterialApp(
home: MainScreen(),
...
)
);
}
}
}
Is there another/better way of doing this? It feels kind of sketchy.
| |
doc_23538545
|
order deny,allow
deny from all
allow from xxx.xxx.xxx.xxx
Everything worked fine and I was able to access from xxx.xxx.xxx.xxx, while others could not access and got a 403 error.
A few days ago, though, I started getting the 403 error when accessing via my laptop from xxx.xxx.xxx.xxx. The strange thing is that when I access from my mobile phone, using the same IP, everything works fine.
If I delete the contents of .htaccess, then my laptop can access the website, but add the contents again and then it can't.
I am pretty sure the code in .htaccess is correct, since it worked before.
I get the ip I am using by googling "what is my ip". Is there another IP I should be using?
I had some problems with FileZilla that same day and may have made some changes related to that... but I can't remember doing anything that I didn't undo.
Any suggestions would be much appreciated.
A: Sometimes a client accesses a server through IPv6, which is the most recent Internet protocol and successor to IPv4.
IPv6 has a different kind of IP addresses, and therefore Apache doesn't recognize your laptop anymore.
To enable your laptop via IPv6 as well, you may give an appropriate IPv6 address to Allow, e.g.
Allow from 2001:db8::a00:20ff:fea7:ccea
This may be given in addition to the IPv4 address, so you may connect either way.
| |
doc_23538546
|
Player one moves around with ASWD and second player with HUJK.
These are the two events and they are declared in the constructor as so this.move(); and this.moveBug();
private move() {
window.addEventListener('keypress', (e: KeyboardEvent) => {
switch (e.keyCode) {
case 97:
this._player.move(-10, 0);
break;
case 119:
this._player.move(0, -10);
break;
case 100:
this._player.move(+10, 0);
break;
case 115:
this._player.move(0, +10);
break;
}
this.update();
});
}
private moveBug() {
window.addEventListener('keypress', (e: KeyboardEvent) => {
switch (e.keyCode) {
case 104:
this._bugPlayer.moveBug(-10, 0);
break;
case 117:
this._bugPlayer.moveBug(0, -10);
break;
case 107:
this._bugPlayer.moveBug(+10, 0);
break;
case 106:
this._bugPlayer.moveBug(0, +10);
break;
}
this.update();
});
}
However both images move turn based, I can't move them both at the same time.
I want this game to be playable on 1 keyboard.
Is there a way this can be achieved?
A: I would define the move function once and call it based on the pressed key. Here is a rough skeleton of the approach.
class Movement {
move(target, x, y) {
// handle move code...
}
constructor() {
const move = this.move;
window.addEventListener('keypress', (e: KeyboardEvent) => {
let charCode = e.which || e.keyCode;
switch (charCode) {
case 97:
move('player', -10, 0);
break;
case 119:
move('player', 0, -10);
break;
case 100:
move('player', +10, 0);
break;
case 115:
move('player', 0, +10);
break;
case 104:
move('bug', -10, 0);
break;
case 117:
move('bug', 0, -10);
break;
case 107:
move('bug', +10, 0);
break;
case 106:
move('bug', 0, +10);
break;
}
});
}
}
const m = new Movement();
https://jsfiddle.net/zp3vj7ma/
| |
doc_23538547
|
descr = df.loc[:, 'desc']
arr = []
pat = re.compile("(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)")
for i in descr:
test = pat.findall(i)
arr.append(test)
df["IPA"] = arr
It gives IP address output, but I want the output as 10.35.50.4 etc
[(10, 35, 50, 4)] and [(10, 35, 50, 3)].
A: You need to transform your groups (Anything inside a parentheses) into non-capturing groups. You can do that by adding a "?:" right after opening the parentheses.
pat = re.compile("(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)")
The reason is written on the definition of the function "findall":
Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result.
Therefore it was returning all the groups, numbers inside your address, separately.
| |
doc_23538548
|
Knowing, based on other questions I've seen, that I can get the same number from System.Environment.TickCount property (or something else), how can I infer the DateTime object that corresponds to the TickCount I received?
A: You can't, without more information (and even then it can be ambiguous). Environment.TickCount returns:
A 32-bit signed integer containing the amount of time in milliseconds that has passed since the last time the computer was started.
... so unless you can find out the time the computer was started from somewhere, you're out of luck. There may well be registry entries or system calls you can make to find out the last boot time, but I don't know them off the top of my head. Of course, you can get an approximate value by taking Environment.TickCount yourself and DateTime.UtcNow as soon after (or before) that as possible, and finding the difference between the two:
public static DateTime UnreliableDateTimeFromTickCount(int tickCount)
{
DateTime now = DateTime.UtcNow;
DateTime boot = now - TimeSpan.FromMilliseconds(Environment.TickCount);
return boot + TimeSpan.FromMilliseconds(tickCount);
}
However, even with that, the value will cycle round every 24.9 days, so if the computer has been on for longer than that, the count is ambiguous.
I'd suggest avoiding using Environment.TickCount if possible, basically - is this under your control at all?
A: I recognize that this is a very old question, but since it was the first hit from Google when I was searching, I felt others may land here.
All of the points in @JonSkeet's answer are valid and be sure to read them and fully understand where it applies to you. For my specific situation, I knew that the tick count value I needed to convert would be within the last few days, however there was a risk that the value captured was before TickCount overflowed, and the conversion would occur after. Below is the method I wrote which should handle the case of TickCount overflowing and will convert the given tick count into a DateTime, as long as it is within the last 49 days.
To elaborate a little more on how Environment.TickCount works: When the computer turns on, it starts at 0 and increments each millisecond. After 24.9 days from booting, the capacity of a Int32 is reached and TickCount rolls over from Int32.MaxValue to Int32.MinValue. After the initial wrap, it will continue to overflow every 49.7 days.
/// <summary>
/// Converts the given tick count into a DateTime. Since TickCount rolls over after 24.9 days,
/// then every 49.7 days, it is assumed that the given tickCount occurrs in the past and is
/// within the last 49.7 days.
/// </summary>
/// <param name="tickCount">A tick count that has occurred in the past 49.7 days</param>
/// <returns>The DateTime the given tick count occurred</returns>
private DateTime ConvertTickToDateTime(int tickCount)
{
// Get a reference point for the current time
int nowTick = Environment.TickCount;
DateTime currTime = DateTime.Now;
Int64 mSecElapsed = 0;
// Check for overflow condition
if( tickCount < nowTick) // Then no overflow has occurred since the recorded tick
{
// MIN|--------------TC---------------0------------Now-------------|MAX
mSecElapsed = nowTick - tickCount;
}
else // tickCount >= currTick; Some overflow has occurred since the recorded tick
{
// MIN|--------------Now---------------0------------TC-------------|MAX
mSecElapsed = Convert.ToInt64((int.MaxValue - tickCount) + (nowTick + Math.Abs(Convert.ToDouble(int.MinValue)))); // Time BEFORE overflow + time since the overflow
}
DateTime tickCountAsDateTime = currTime - TimeSpan.FromMilliseconds(mSecElapsed);
return tickCountAsDateTime;
}
To test the method, I used the following code:
static void Main(string[] args)
{
Console.WriteLine("Test Start Time: {0}", DateTime.Now);
// 10 seconds ago
int tc0 = CalculateTC(TimeSpan.FromSeconds(10));
Console.WriteLine("Expect 10 seconds ago: {0}", ConvertTickToDateTime(tc0));
// 10 minutes ago
int tc1 = CalculateTC(TimeSpan.FromMinutes(10));
Console.WriteLine("Expect 10 minutes ago: {0}", ConvertTickToDateTime(tc1));
// 10 hours ago
int tc2 = CalculateTC(TimeSpan.FromHours(10));
Console.WriteLine("Expect 10 hours ago: {0}", ConvertTickToDateTime(tc2));
// 1 Day ago
int tc3 = CalculateTC(TimeSpan.FromDays(1));
Console.WriteLine("Expect 1 Day ago: {0}", ConvertTickToDateTime(tc3));
// 10 Day ago
int tc4 = CalculateTC(TimeSpan.FromDays(10));
Console.WriteLine("Expect 10 Days ago: {0}", ConvertTickToDateTime(tc4));
// 30 Day ago
int tc5 = CalculateTC(TimeSpan.FromDays(30));
Console.WriteLine("Expect 30 Days ago: {0}", ConvertTickToDateTime(tc5));
// 48 Day ago
int tc6 = CalculateTC(TimeSpan.FromDays(48));
Console.WriteLine("Expect 48 Days ago: {0}", ConvertTickToDateTime(tc6));
// 50 Day ago (Should read as a more recent time because of the Environment.TickCount wrapping limit - within a day or two)
int tc7 = CalculateTC(TimeSpan.FromDays(50));
Console.WriteLine("Expect to not see 50 Days ago: {0}", ConvertTickToDateTime(tc7));
// 10 Seconds ahead (Should read as a very old date - around 50 days ago)
int tc8 = Convert.ToInt32(Environment.TickCount + TimeSpan.FromSeconds(10).TotalMilliseconds);
Console.WriteLine("Expect to not see 10 seconds from now: {0}", ConvertTickToDateTime(tc8));
}
private static int CalculateTC(TimeSpan timespan)
{
int nowTick = Environment.TickCount;
double mSecToGoBack = timespan.TotalMilliseconds;
int tc;
if (Math.Abs(nowTick - int.MinValue) >= mSecToGoBack) // Then we don't have to deal with an overflow
{
tc = Convert.ToInt32(nowTick - mSecToGoBack);
}
else // Deal with the overflow wrapping
{
double remainingTime = nowTick + Math.Abs(Convert.ToDouble(int.MinValue));
remainingTime = mSecToGoBack - remainingTime;
tc = Convert.ToInt32(int.MaxValue - remainingTime);
}
return tc;
}
The following is the output from the test application:
Test Start Time: 5/3/2019 4:30:05 PM
Expect 10 seconds ago: 5/3/2019 4:29:55 PM
Expect 10 minutes ago: 5/3/2019 4:20:05 PM
Expect 10 hours ago: 5/3/2019 6:30:05 AM
Expect 1 Day ago: 5/2/2019 4:30:05 PM
Expect 10 Days ago: 4/23/2019 4:30:05 PM
Expect 30 Days ago: 4/3/2019 4:30:05 PM
Expect 48 Days ago: 3/16/2019 4:30:05 PM
Expect to not see 50 Days ago: 5/3/2019 9:32:53 AM
Expect to not see 10 seconds from now: 3/14/2019 11:27:28 PM
I hope this helps someone who may be in a similar situation as me.
A: Instead of a tick-count as int
It seems like you would prefer different datatypes:
*
*system up-time as TimeSpan
*system start-time as DateTime
(However I am not 100% sure based on the wording of your question)
Below is a code example that uses Windows Management Instrumentation to get those properties.
using System;
using Microsoft.Management.Infrastructure;
using Microsoft.Management.Infrastructure.Options;
using System.Linq;
namespace MachineTimeStamps
{
class Program
{
/// <summary>
/// Print the system Uptime and Last Bootup Time (using Win32_OperatingSystem LocalDateTime & LastBootUpTime properties).
/// </summary>
public static void Main(string[] args)
{
var uptime = GetSystemUptime("COMPUTER_NAME");
if (!uptime.HasValue)
{
throw new NullReferenceException("GetSystemUptime() response was null.");
}
var lastBootUpTime = GetSystemLastBootUpTime("COMPUTER_NAME");
if (!lastBootUpTime.HasValue)
{
throw new NullReferenceException("GetSystemLastBootUpTime() response was null.");
}
Console.WriteLine($"Uptime: {uptime}");
Console.WriteLine($"BootupTime: {lastBootUpTime}");
Console.ReadKey();
}
/// <summary>
/// Retrieves the duration (TimeSpan) since the system was last started.
/// Note: can be used on a local or a remote machine.
/// </summary>
/// <param name="computerName">Name of computer on network to retrieve uptime for</param>
/// <returns>WMI Win32_OperatingSystem LocalDateTime - LastBootUpTime</returns>
private static TimeSpan? GetSystemUptime(string computerName)
{
string namespaceName = @"root\cimv2";
string queryDialect = "WQL";
DComSessionOptions SessionOptions = new DComSessionOptions();
SessionOptions.Impersonation = ImpersonationType.Impersonate;
CimSession session = CimSession.Create(computerName, SessionOptions);
string query = "SELECT * FROM Win32_OperatingSystem";
var cimInstances = session.QueryInstances(namespaceName, queryDialect, query);
if (cimInstances.Any())
{
var cimInstance = cimInstances.First();
var lastBootUpTime = Convert.ToDateTime(cimInstance.CimInstanceProperties["LastBootUpTime"].Value);
var localDateTime = Convert.ToDateTime(cimInstance.CimInstanceProperties["LocalDateTime"].Value);
var uptime = localDateTime - lastBootUpTime;
return uptime;
}
return null;
}
/// <summary>
/// Retrieves the last boot up time from a system.
/// Note: can be used on a local or a remote machine.
/// </summary>
/// <param name="computerName">Name of computer on network to retrieve last bootup time from</param>
/// <returns>WMI Win32_OperatingSystem LastBootUpTime</returns>
private static DateTime? GetSystemLastBootUpTime(string computerName)
{
string namespaceName = @"root\cimv2";
string queryDialect = "WQL";
DComSessionOptions SessionOptions = new DComSessionOptions();
SessionOptions.Impersonation = ImpersonationType.Impersonate;
CimSession session = CimSession.Create(computerName, SessionOptions);
string query = "SELECT * FROM Win32_OperatingSystem";
var cimInstances = session.QueryInstances(namespaceName, queryDialect, query);
if (cimInstances.Any())
{
var lastBootUpTime = Convert.ToDateTime(cimInstances.First().CimInstanceProperties["LastBootUpTime"].Value);
return lastBootUpTime;
}
return null;
}
}
}
A: I seemed to get the wrong results from Jerren's solution; this might be a fudge/incorrect - where the complexity of overflows is concerned, but this got me close to the right results for my tests, an attempt at approximating the result:
// TimeSpan result
var approxUpTime = TryApproximateUpTime();
private static TimeSpan? TryApproximateUpTime()
{
TimeSpan? retVal;
var envTickCountInMs =
Environment.TickCount;
try
{
retVal =
envTickCountInMs > 0
?
new DateTime()
.AddMilliseconds(Environment.TickCount) -
DateTime.MinValue
:
new TimeSpan(
new DateTime(
((long)int.MaxValue + (envTickCountInMs & int.MaxValue)) * 10 * 1000).Ticks);
}
catch (Exception)
{
// IGNORE
retVal = null;
}
return retVal;
}
| |
doc_23538549
|
For example, I have code:
variable=value
My cursor is on "equals" sign and I want to add spaces around it. Can I do it without regex?
A: There's no ready-to-use command that does exactly that but you can do whatever you want with the basic building blocks at your disposal:
:nnoremap <key> s <C-r>" <Esc><Left>
now press <key> on any character.
I'm sure there are many other ways…
I wouldn't create a mapping for that, though, s<Space>=<Space><Esc> is good enough in my opinion.
A: Add this line to your .vimrc:
nnoremap <leader>w a<Space><Esc><Left><Left>a<Space><Esc><Right>
This is a simulation of sequence action you do:
*
*a: go to insert mode, place cursor after current position.
*<Space>: add a space.
*<Esc>: back to normal mode.
*<Left><Left>: go back 2 characters.
*a<Space><Esc>: repeat adding space action.
*<Right>: move cursor back to begin character.
Restart vim to make changes. Then you can place cursor at =, press \w. You can change \w to whatever key you want.
| |
doc_23538550
|
Example:
table employees
-----------------------------------
employee_one | employee_two |
-----------------------------------
JOHN SMITH | JACK STEVENS |
MASON LEWIS | JOHN WALKER |
ANDREA YOUNG | MARTINA ROBINSON|
JACK STEVENS | JOHN SMITH |
JOHN WALKER | MASON LEWIS |
MARTINA ROBINSON| ANDREA YOUNG |
and the results I want is:
-----------------------------------
employee_one | employee_two |
-----------------------------------
JOHN SMITH | JACK STEVENS |
MASON LEWIS | JOHN WALKER |
ANDREA YOUNG | MARTINA ROBINSON|
or
-----------------------------------
employee_one | employee_two |
-----------------------------------
JACK STEVENS | JOHN SMITH |
JOHN WALKER | MASON LEWIS |
MARTINA ROBINSON| ANDREA YOUNG |
My problem is that my query always find all the results and I get the same table. I tried:
SELECT DISTINCT t1.*
FROM employees
AS t1 LEFT JOIN employees AS t2 ON (t1.employee_one = t2.employee_two AND t1.employee_two = t2.employee_one)
OR (t1.employee_one = t2.employee_one AND t1.employee_two = t2.employee_two)
But I get the same results
A: Every pair of names will show up twice, so use a where clause to limit the output to just those where employee_one < employee_two:
select t1.*
from employees t1
where employee_one < employee_two
and exists (
select *
from employees t2
where t2.employee_two = t1.employee_one
and t2.employee_one = t1.employee_two)
Caveat: this assumes that there are no rows where employee_one = employee_two.
| |
doc_23538551
|
I have a good amount of business logic and application logic as well with the asterisk.
I wanted to know how would be the performance with EC2 instance? is it recommended to use EC2 instance with asterisk?
Thanks
A: amazon ec2 is bad idea for voip.
It have NAT and not perfect timing. Also it not so hi perfomance.
100 calls require instance like c1.xlarge/ m1.xlarge/c3.large - ECU 8+.
On c1.medium asterisk usualy can handle 50-80 calls depend of dialplan and your skill.
Also note, that bandwidth on ec2 is VERY costly.
I not recomend use ec2 instances for asterisk, unless you need have any of following:
*
*on demand application with failover setup.
*payed per minute/scalable application(for example planned conference service)
*need posibility launch instance on crash and/or other infrastructure already on EC2.
In all other cases much better get 2 dedicated servers and setup failover for thoose servers. You will get much more perfomance for similar cost.
A: A successful deployment of Asterisk on Amazon EC2 requires that you enable three critical ports on EC2's firewall. Without them, Asterisk will not work. Thus, the following ports are key to passing RTP packets (for voice) and SIP signaling (for devices, DTMF codes, etc.):
5060 (UDP)
4569 (UDP)
10000-20000 (UDP)
22 (TCP) (You'll need this for SSH access)
Use Eric Hammond's Ubuntu AMI (Amazon Machine Image), ami-ce44a1a7, and the 1000HZ AKI, aki-9b00e5f2. This AKI is important because it is specifically compiled for VoIP applications such as Asterisk. Any AKI (Amazon Kernel Image) other than one set at 1000HZ will produce undesirable results in voice quality and functionality.
TIP: Asterisk 1.4.21.1 is an older, but stable version. Supplement the version number with a newer one if you prefer
| |
doc_23538552
|
"The user or group name 'domain\ServerName ' is not recognized.
(rsUnknownUserName)".
I want now to change the log in into ssrs using the logged in domain\username on my intranet network for each user, instead of application servername.
My qustion is:Is it a good solution? How can I do that?Thanks
| |
doc_23538553
|
MyClass callee() {
MyClass a;
/* RVO is disabled */
return a;
}
void caller() {
/* RVO is disabled */
MyClass b = no_rvo();
}
What does the stack look like in this case? Does caller() and callee() separately allocate space for a and b on the stack, then a is copied to b? If so, does the RET statement at the end of the callee() fully decrement the stack pointer to what it was before, or is the stack memory for a freed after the copy operation?
A: It depends on the calling convention. But all x86 32 and 64-bit calling conventions make the same choice, and pass a pointer to the return value as a "hidden" first arg.
callee can still optimize away a (unless something else stops that from happening) and just store directly into that return-value pointer.
non-trivially-copyable types may need to run the copy-constructor at some point, and a destructor for a.
But re: your actual question, with optimization enabled the caller would pass &b as the return-value pointer.
With optimization disabled, I think I've seen some compilers create space for a separate return-value temporary and then copy from there, which is hilariously redundant for trivially-copyable types.
In theory the return-value pointer could point somewhere other than stack memory, e.g. if assigning to an element of static MyClass arr[10].
But it must not point to anything that callee could access any other way, because in the C++ abstract machine the return value is a separate object that nothing can be pointing to before the function returns.
| |
doc_23538554
|
A: Data frames
A data frame is a table, where each column can have different types of values. Its purpose is similar to spreadsheets, or SQL tables. An example can make things clearer.
Example
Suppose, for example, you have data about people: name, age, and whether they are employed. We can have these data in vectors, for example:
names <- c('John', 'Sylvia', 'Arthemis')
age <- c(32, 16, 21)
employed <- c(TRUE, FALSE, TRUE)
A data frame allows us to have all the data related to a person in one row. To create it, we just pass the vectors as arguments to data.frame():
> df <- data.frame(Name=names, Age=age, Working=employed)
> df
Name Age Working
1 John 32 TRUE
2 Sylvia 16 FALSE
3 Arthemis 21 TRUE
Note how clearer the data format is now. With data frames, many operations become easier. For example, filtering:
> df[df$Age>20,]
Name Age Working
1 John 32 TRUE
3 Arthemis 21 TRUE
This is just one example of many. Filtering, aggregating, plotting, etc. became much more straightforward with data frames.
Tibbles
Tibbles are just a new kind of data frame. It is part of the very popular tidyverse set of packages and subtly differs from data frames in a few points.
Differences from data frames
One notable difference is that the tibble format contains more information:
> t <- tibble(Name=names, Age=age, Working=employed)
> t
# A tibble: 3 × 3
Name Age Working
<chr> <dbl> <lgl>
1 John 32 TRUE
2 Sylvia 16 FALSE
3 Arthemis 21 TRUE
More important, though, is that tibbles do not have some confusing features that data frames have.
For example, you can get a column from the data frame by giving only the beginning of the column name:
> df$N
[1] "John" "Sylvia" "Arthemis"
It may look practical, but if you find this line in your source code, it can be hard to understand. It can also lead to bugs if multiple columns start with the same prefix.
If you do that to tibbles, it will return NULL and print a warning:
> t$N
NULL
Warning message:
Unknown or uninitialised column: `N`.
This is just one example. More differences can be found on this page, although most of them are more relevant to older, more experienced coders.
The tribble() function
We created tibble objects with the function tibble() so far. tribble() is just another way of creating tibble objects. The difference is that, while tibble() receives vectors very much like data.frame(), tribble() expects as arguments:
*
*the name of the columns in the so-called "tilde syntax"; and then
*each row
without having to create any vector.
How to use tribble()
To understand what it means and why it is useful, an example will make it clear:
> t2 <- tribble(
+ ~Name, ~Age, ~`Employment status`,
+ "John", 32, TRUE,
+ "Sylvia", 16, FALSE,
+ "Arthemis", 21, TRUE
+ )
Note that you can see the table format when inputting the data. It is great for examples in code! But don't be mistaken: the return object is equivalent to the same thing created by tibble():
> t2
# A tibble: 3 × 3
Name Age `Employment status`
<chr> <dbl> <lgl>
1 John 32 TRUE
2 Sylvia 16 FALSE
3 Arthemis 21 TRUE
Which one to use?
You can use whatever you prefer! All of them work well. Yet some can be more fit to one context or another.
*
*If you are not using tidyverse, you'd probably use traditional data frames.
*Now, if you are using tidyverse, you'd probably prefer tibbles, since they are a cornerstone of those packages. You may also prefer tibble to avoid confusing data frame behaviors.
Supposing you're going to create tibbles, which function should you use?
*
*If you are reading data from files, or from vectors, you will probably prefer to use tibble().
*If you are going to add hardcoded values to your tibble, then the tribble() function may be more practical.
Addendum: mixing tibble() and tribble() up
tibble() and tribble() return the same kind of object, but they have very different signatures. Yet, their names are really similar, so people often confuse them. Pay attention to that!
If you call tibble() passing tribble() arguments, you'll get an error similar to this:
> tibble(
+ ~Name, ~Age, ~`Employment status`,
+ "John", 32, TRUE
+ )
Error:
! All columns in a tibble must be vectors.
✖ Column `~Name` is a `formula` object.
Run `rlang::last_error()` to see where the error occurred.
If you call tribble() passing tibble() arguments, this is the error you will get:
> t <- tribble(Name=names, Age=age, Working=employed)
Error:
! Must specify at least one column using the `~name` syntax.
Run `rlang::last_error()` to see where the error occurred.
If you are having problems with error messages similar to those ones, verify you're using the right signature in your call.
(I'm posting this addendum so people googling for these errors can find this Q&A. I spent an hour trying to understand why I was getting that error. This is a surprisingly ungoogleable topic!)
| |
doc_23538555
|
Also, have placed onError function in ReactPlayer which gives 150 as an error in it's argument.
A: I checked with multiple ppl having different versions of IE 11and the video is payable on IE too. Most probably, an issue with FlashPlayer.
| |
doc_23538556
|
I've tried connecting in both Postman and in a VB program as follows:
Imports System.Net
Imports System.IO
Module Main
Sub Main()
Dim result As String = RunQuery("", "https://ec2.amazonaws.com/?Action=DescribeInstances")
Console.WriteLine(result)
Console.ReadLine()
End Sub
Public Function RunQuery(creds As String, url As String, Optional data As String = Nothing) As String
Dim request As HttpWebRequest = TryCast(WebRequest.Create(url), HttpWebRequest)
request.ContentType = "application/json"
request.Method = "GET"
If data IsNot Nothing Then
Using writer As StreamWriter = New StreamWriter(request.GetRequestStream())
writer.Write(data)
End Using
End If
Dim d As Date = Date.UtcNow
Dim t As String = Format(d, "yyyyMMdd") & "T" & Format(d, "HHmmss") & "Z"
request.Headers.Add("X-Amz-Date", t)
request.Headers.Add("Authorization", "AWS4-HMAC-SHA256 Credential=***MYAPIKEY***/20201216/us-east-2/ec2/aws4_request, SignedHeaders=host;x-amz-date, Signature=***MYAPISECRET***")
Dim response As HttpWebResponse = TryCast(request.GetResponse(), HttpWebResponse)
Dim result As String = String.Empty
Using reader As StreamReader = New StreamReader(response.GetResponseStream())
result = reader.ReadToEnd()
End Using
Return result
End Function
End Module
The output from postman was
<?xml version="1.0" encoding="UTF-8"?>
<Response><Errors><Error><Code>AuthFailure</Code><Message>AWS was not able to validate the provided access credentials</Message></Error></Errors><RequestID>37153d9f-c042-4ae3-8a13-06dc3b052afc</RequestID></Response>
I wrote the vb based on postmans code:
var client = new RestClient("https://ec2.amazonaws.com/?Action=DescribeInstances");
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("X-Amz-Date", "20201216T092737Z");
request.AddHeader("Authorization", "AWS4-HMAC-SHA256 Credential=MYAPIKEY/20201216/us-east-2/ec2/aws4_request, SignedHeaders=host;x-amz-date, Signature=MYAPISIGNATURE");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
Similar questions have been asked many times before but the only answers I can see are that the PC clock was wrong, so I've corrected mine such that its within 0.2 seconds of the true internet time.
Also I could not find another similarly simple VB or C# program that successfully connects to EC2, so this thread may help others in future.
I'm wondering if the signature has to be encoded with base64 or some other algorithm ? Otherwise how can I get this working either in postman or in vb/c# ? TIA
A: So there were a couple of issues
*
*Wrong URL, the correct one was https://ec2.us-east-2.amazonaws.com/?Action=DescribeInstances&Version=2016-11-15
*I assumed that the secret was the signature, it is not.
Here's a complete VB.NET console application that successfully connects to AWS. Sorry its not commented but the code is reasonably obvious and not too long.
Option Explicit On
Option Compare Text
Option Strict On
Imports System.Net.Http
Imports System.Security.Cryptography
Imports System.Text
Public Module Program
Public Sub Main(ByVal args As String())
If args.Length <> 5 Then
Throw New Exception("AWS Integration requires 5 parameters: url accessKey secretKey awsRegion awsServiceName")
End If
Dim url As String = args(0) ' "https://ec2.us-east-2.amazonaws.com/?Action=DescribeInstances&Version=2016-11-15"
Dim accessKey As String = args(1) ' api key
Dim secretkey As String = args(2) ' api secret
Dim awsRegion As String = args(3) ' = "us-east-2"
Dim awsServiceName As String = args(4) '= "ec2"
Dim msg As HttpRequestMessage = New HttpRequestMessage(HttpMethod.[Get], url)
msg.Headers.Host = msg.RequestUri.Host
Dim utcNowSaved As DateTimeOffset = DateTimeOffset.UtcNow
Dim amzLongDate As String = utcNowSaved.ToString("yyyyMMddTHHmmssZ")
Dim amzShortDate As String = utcNowSaved.ToString("yyyyMMdd")
msg.Headers.Add("x-amz-date", amzLongDate)
Dim canonicalRequest As New StringBuilder
canonicalRequest.Append(msg.Method.ToString & vbLf)
canonicalRequest.Append(String.Join("/", msg.RequestUri.AbsolutePath.Split("/"c).Select(AddressOf Uri.EscapeDataString)) & vbLf)
canonicalRequest.Append(GetCanonicalQueryParams(msg) & vbLf)
Dim headersToBeSigned As New List(Of String)
For Each header In msg.Headers.OrderBy(Function(a) a.Key.ToLowerInvariant, StringComparer.OrdinalIgnoreCase)
canonicalRequest.Append(header.Key.ToLowerInvariant)
canonicalRequest.Append(":")
canonicalRequest.Append(String.Join(",", header.Value.[Select](Function(s) s.Trim)))
canonicalRequest.Append(vbLf)
headersToBeSigned.Add(header.Key.ToLowerInvariant)
Next
canonicalRequest.Append(vbLf)
Dim signedHeaders As String = String.Join(";", headersToBeSigned)
canonicalRequest.Append(signedHeaders & vbLf)
canonicalRequest.Append("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
Dim stringToSign As String = "AWS4-HMAC-SHA256" & vbLf & amzLongDate & vbLf & amzShortDate & "/" & awsRegion & "/" & awsServiceName & "/aws4_request" & vbLf & Hash(Encoding.UTF8.GetBytes(canonicalRequest.ToString))
Dim dateKey() As Byte = HmacSha256(Encoding.UTF8.GetBytes("AWS4" & secretkey), amzShortDate)
Dim dateRegionKey() As Byte = HmacSha256(dateKey, awsRegion)
Dim dateRegionServiceKey() As Byte = HmacSha256(dateRegionKey, awsServiceName)
Dim signingKey() As Byte = HmacSha256(dateRegionServiceKey, "aws4_request")
Dim signature As String = ToHexString(HmacSha256(signingKey, stringToSign.ToString))
Dim credentialScope As String = amzShortDate & "/" & awsRegion & "/" & awsServiceName & "/aws4_request"
msg.Headers.TryAddWithoutValidation("Authorization", "AWS4-HMAC-SHA256 Credential=" & accessKey & "/" & credentialScope & ", SignedHeaders=" & signedHeaders & ", Signature=" & signature)
Dim client As HttpClient = New HttpClient
Dim result As HttpResponseMessage = client.SendAsync(msg).Result
If result.IsSuccessStatusCode Then
'Console.WriteLine(result.Headers)
Dim s As String = result.Content.ReadAsStringAsync().Result
Console.WriteLine(s)
Else
Console.WriteLine(result.StatusCode & vbCrLf & result.ToString.Replace(vbCr, "").Replace(vbLf, ""))
End If
End Sub
Private Function GetCanonicalQueryParams(ByVal request As HttpRequestMessage) As String
Dim values = New SortedDictionary(Of String, String)
Dim querystring = System.Web.HttpUtility.ParseQueryString(request.RequestUri.Query)
For Each key In querystring.AllKeys
If key Is Nothing Then
values.Add(Uri.EscapeDataString(querystring(key)), $"{Uri.EscapeDataString(querystring(key))}=")
Else
values.Add(Uri.EscapeDataString(key), $"{Uri.EscapeDataString(key)}={Uri.EscapeDataString(querystring(key))}")
End If
Next
Dim queryParams = values.Select(Function(a) a.Value)
Return String.Join("&", queryParams)
End Function
Public Function Hash(ByVal bytesToHash() As Byte) As String
Return ToHexString(SHA256.Create.ComputeHash(bytesToHash))
End Function
Private Function ToHexString(ByVal array As IReadOnlyCollection(Of Byte)) As String
Dim hex = New StringBuilder(array.Count * 2)
For Each b In array
hex.AppendFormat("{0:x2}", b)
Next
Return hex.ToString
End Function
Private Function HmacSha256(ByVal key() As Byte, ByVal data As String) As Byte()
Return New HMACSHA256(key).ComputeHash(Encoding.UTF8.GetBytes(data))
End Function
End Module
HTH someone :)
| |
doc_23538557
|
I have compare the configuration with other working device its is lenovo 7000 (version 5.1) i found that its Android System WebView is an older version.even in updating this its still not working my js code is include
(function() {
window.UserApi = {
url: URL + '/api/login.php',
user_id: 0,
user_name: '',
file_upload_url: URL + '/upload.php',
init: function() {},
onSuccess: function(reponse) {
UserApi.function1();
},
function1: function() {},
function2: function() {},
functionN: function() {}
};
UserApi.init();
})();
Is there any issue with the js code .This is working in almost all devices.
If any have any idea please share
| |
doc_23538558
|
CNN Model:
inputs = tf.keras.layers.Input(shape=(50,3))
x = tf.keras.layers.Conv1D(filters=12, kernel_size=2, strides=1, padding='valid', activation='relu')(inputs)
x = tf.keras.layers.MaxPooling1D()(x)
x = tf.keras.layers.Conv1D(filters=12, kernel_size=2, strides=1, padding='valid', activation='relu')(x)
x = tf.keras.layers.MaxPooling1D()(x)
x = tf.keras.layers.Conv1D(filters=12, kernel_size=2, strides=1, padding='valid', activation='relu')(x)
x = tf.keras.layers.Flatten()(x)
predictions = tf.keras.layers.Dense(3, activation='softmax')(x)
Dense Model:
inputs = tf.keras.layers.Input(shape=(50,3))
x = tf.keras.layers.Dense(64, activation='relu')(inputs)
x = tf.keras.layers.Dense(64, activation='relu')(x)
x = tf.keras.layers.Dense(64, activation='relu')(x)
x = tf.keras.layers.Dense(32, activation='relu')(x)
x = tf.keras.layers.Flatten()(x)
predictions = tf.keras.layers.Dense(3, activation='softmax')(x)
When trying to send a prediction request to the CNN model with TF Serving, I get the correct response, but the same request being sent to the Dense model returns a 400 Bad Request error.
reading = np.random.uniform(0, 1, (50, 3))
r = requests.post('http://localhost:8501/v1/models/my_model:predict', data=json.dumps({'instances': reading.tolist()}))
CNN Model returns correctly:
{"predictions": [[1.78464702e-20, 4.44278494e-33, 4.32330665e-07]]}
Dense Model returns:
{"error": "indices[0] = 2 is not in [0, 2)\\n\\t [[{{node model/dense/Tensordot/GatherV2_1}}]]"}
Any ideas whats happening here?
A: Looking closely, the Dense model expected input as (-1,50,3).
A simple np.reshape(-1,50,3) solved the problem for me.
| |
doc_23538559
|
I importet a OSM file and now im working on a function which you can input a point in WGS84 format and a POI and then the function finds the shortest path to the POI.
So for finding the nearest Geometries to my WGS84 Point I use
Coordinate co = new Coordinate(12.9639158,56.070904);
List<SpatialDatabaseRecord> results2 = GeoPipeline
.startNearestNeighborLatLonSearch(layer, co, 1)
.toSpatialDatabaseRecordList();
but then my problems start because i don't really understand how the OSM file is built up
Is there a function so that i can get my POI Node by name?
I get an index from the OSM file
SpatialDatabaseService spatialService = new SpatialDatabaseService(database);
Layer layer = spatialService.getLayer(osm);
LayerIndexReader spatialIndex = layer.getIndex();
Can I use it to search Nodes by properties?
And for finding the shortest Way between the points I found a dijkstra Algorithm
PathFinder<WeightedPath> finder = GraphAlgoFactory.dijkstra(
Traversal.expanderForTypes( ExampleTypes.MY_TYPE, Direction.BOTH ), "cost" );
WeightedPath path = finder.findSinglePath( nodeA, nodeB );
The question now is what are my RelationshipTypes??? I think it shoud be NEXT but how do I include this in the code? Do I have to create an Enum with NEXT???
Can someone give me some feedback if im on the right way and give me some help please?
Okay finally found out how to find Nodes by id :D not too difficult but i searched for a long time :D
Thank you
A: I can make a few comments:
*
*We currently do not add names or tags to lucene indexes in the OSM importer, but it is a good idea.
*What is done is adding all geometries (poi, streets, polygons, etc.) to the RTree index. This is the index you got back when you called layer.getIndex(). This index can be used to find things within regions, and can also perform a filter by properties of the geometry (name or tags) while searching the index. This is probably your best bet for finding something by name. See below for two options for this.
*Route finding in the OSM model is not trivial, because the current model is designed for OSM completeness with all osm-nodes represented as real nodes in one huge connected network including all geometries (not just roads). The graph is complex, and a traverser would need to know how to traverse it to achieve route finding. It is not as simple as following NEXT relationships. See for example slides 13 and 15 at http://www.slideshare.net/craigtaverner/neo4j-spatial-backing-a-gis-with-a-true-graph-database. Each line segment does have a length, but what you really want is a simpler graph that has nodes only for points of intersection, and single relationships for the total drive distance between these points. This graph is not there, but could be added by the OSM importer.
Finally, two suggestions for finding POI by name. Either:
- dynamic layers
- or geopipes
For Dynamic layers you can use either CQL syntax or key,value pairs (for tags). For examples of each see lines 81 and 84 of https://github.com/neo4j/spatial/blob/master/src/test/java/org/neo4j/gis/spatial/TestDynamicLayers.java. This approach allows the test for name to be done during the traversal in a callback from the RTree.
For GeoPipes, you define a stream, and each object returned by the RTree will be passed to the next filter. This should have the same performance as the dynamic layers, and also be a bit more intuitive to use. See for example the 'filter_by_osm_attribute' and 'filter_by_property' tests on lines 99 and 112 of https://github.com/neo4j/spatial/blob/master/src/test/java/org/neo4j/gis/spatial/pipes/GeoPipesTest.java. These both search for streets by name.
| |
doc_23538560
|
To send the request and get all the data together I though I will user Observable.forkJoin and to repeat it every time i put it inside a setInterval.
Something like below.
setInterval(function () {
console.log("INSIDE SET INTERVAL")
return Observable.forkJoin(
self.http.get(url1, { headers: headers, method: 'GET' }).map((res: Response) => res.json()),
self.http.get(url2, { headers: headers, method: 'GET' }).map((res: Response) => res.json()),
self.http.get(url3, { headers: headers, method: 'GET' }).map((res: Response) => res.json()),
self.http.get(url4, { headers: headers, method: 'GET' }).map((res: Response) => res.json()),
self.http.get(url5, { headers: headers, method: 'GET' }).map((res: Response) => res.json()),
);
}, 60000);
But when i try to subscribe to this function it says
Property 'subscribe' does not exists on type 'void'.
i have implemented the same using Observable.timer(60000) but then each request resides in different files and it becomes difficult to track.
is there a better way to implement it?
Please guide.
Thanks
A: There is better way to do the same,
Instead of setInterval, You should use Observable.interval
let url = 'https://jsonplaceholder.typicode.com/users/';
let response = Observable.interval(60000).switchMap(() =>
Observable.forkJoin(
this.http.get(`${url}1`).map((res: Response) => res.json()),
this.http.get(`${url}2`).map((res: Response) => res.json())
)
);
response.subscribe(([data1, data2]) => {
// your code
});
WORKING DEMO (You can check the console log)
And I think , you can't return value from setInterval directly , as you have used in your code , for more read
| |
doc_23538561
|
$ myprog -i value_a -o value_b
I am not sure how to use Pytest to test the output of this program. Given values of value_a and value_b, I expect a certain output that I want to test.
The Pytest examples that I see all refer to testing functions, for instance if there is a function such as:
import pytest
def add_nums(x,y):
return x + y
def test_add_nums():
ret = add_nums(2,2)
assert ret == 4
But I am not sure how to call my program using Pytest and not just test individual functions? Do I need to use os.system() and then call my program that way?
In my program I am using argparse module.
A: The solution is based on monkeypatch fixture. In below example myprog reads number from the file myprog_input.txt adds 2 to it and stores result in myprog_output.txt
*
*Program under test
cat myprog.py
#!/usr/bin/python3.9
import argparse
import hashlib
def main():
parser = argparse.ArgumentParser(description='myprog')
parser.add_argument('-i')
parser.add_argument('-o')
args = parser.parse_args()
with open(args.i) as f:
input_data=int(f.read())
output_data=input_data+2
f.close()
with open(args.o,"w") as fo:
fo.write(str(output_data) + '\n')
fo.close()
with open(args.o) as fot:
bytes = fot.read().encode() # read entire file as bytes
fot.close()
readable_hash = hashlib.sha256(bytes).hexdigest();
return readable_hash
if __name__ == '__main__':
print(main())
*Test
cat test_myprog.py
#!/usr/bin/python3.9
import sys
import myprog
def test_myprog(monkeypatch):
with monkeypatch.context() as m:
m.setattr(sys, 'argv', ['myprog', '-i', 'myprog_input.txt', '-o', 'myprog_output.txt'])
assert myprog.main() == 'f0b5c2c2211c8d67ed15e75e656c7862d086e9245420892a7de62cd9ec582a06'
*Input file
cat myprog_input.txt
3
*Running the program
myprog.py -i myprog_input.txt -o myprog_output.txt
f0b5c2c2211c8d67ed15e75e656c7862d086e9245420892a7de62cd9ec582a06
*Testing the program
pytest test_myprog.py
============================================= test session starts =============================================
platform linux -- Python 3.9.5, pytest-6.2.5, py-1.10.0, pluggy-1.0.0
rootdir: /home/<username>/py
plugins: hypothesis-6.23.1
collected 1 item
test_myprog.py . [100%]
============================================== 1 passed in 0.04s ==============================================
| |
doc_23538562
|
And if that is possible how it is possible?
A: I'm not sure what you mean. You can both access and set state in a callback from addEventListener:
class Example extends React.Component {
state = {
clickCount: 0,
}
componentDidMount() {
document.addEventListener('click', () => {
console.log('old clicks', this.state.clickCount);
this.setState(prev => ({
clickCount: prev.clickCount + 1,
}));
});
}
// ...
}
| |
doc_23538563
|
Apologies if this has been answered elsewhere, I've had a good look around!
A: I tried the onNavigated to method as explained in the link below. This worked just fine
http://msdn.microsoft.com/en-us/library/system.windows.controls.page.onnavigatedto%28v=vs.95%29.aspx
| |
doc_23538564
|
I think the right way to do this is having two implementations of an interface, one for production and one for development. This way the rest of the application doesn't need to know about the production/development and can be tested just the same. All I need to do is to find a way to inject the right instance for each environment. And BTW, I prefer not to include the development version in the production code at all!
Does anyone know how to do this?
[UPDATE]
I've using Angular cli to kick off my project so I'm using Webpack (I think!). I prefer not to use an external mock server because I prefer to keep the test/development environment isolated from external dependencies. That way all I need to work on my frontend project is itself. Also, even though my question is focused on rest client, but of course this question can be generalized to any other singleton injectable.
I'm asking this question because in other DI frameworks that I worked with (namely Spring) doing so is part of the framework. So I was expecting to see the same here as well.
At this point, I know I can leverage the environment.production to check and see if it's in production mode or not. But first of all, this is a runtime variable but I think I'm looking for a compile-time one (I'm not sure though). Also, even though we have that variable but the following code leads to a compile error:
if (environment.production) {
import { RestClientService } from './rest-client.service';
}
else {
import { MockRestClientService as RestClientService } from './mock-rest-client.service';
}
ERROR in ... Duplicate identifier 'RestClientService'.
ERROR in ... An import declaration can only be used in a namespace or module.
A: Use factory provider for this:
export function restClientFactory(http: HttpClient): RestClientService {
if (environment.production) {
return new RestClientService(http);
} else {
return new MockRestClientService();
}
}
@NgModule({
providers: [
{ provide: RestClientService, useFactory: restClientFactory, deps: [ HttpClient ] },
],
})
class AppModule {}
The approach with conditional import statements doesn't work, because static import statements are allowed only at the top level of the file. They can not be nested inside if/else statement. You can use dynamic import() to overcome this, but this will also lead to both implementations being included in your bundle.
Unfortunately there is no technical possibility to do a compile-time configuration of the DI like in Spring.
The main problem with runtime check is that both implementations will be included in your production bundle. You can rely on tree-shaking, which is part of the production build, to ensure that your mock client is not included in the production bundle.
Since environment.production variable never changes you can expect that one branch of the if/else is never reachable and therefore can be dropped from bundle by tree-shaking process. The problem is that tool doing tree-shaking can not understand it, because variable is not declared as a const, but as a property of an object.
If you add export const production = true to environment.prod.ts and export const production = false to environment.ts and use this variable in the if/else statement one of the branches should be successfully tree shaken from the production bundle.
Note that this approach relies on the implementation detail of the Angular CLI. Nevertheless I successfully used it in one of my project for more than a year now.
| |
doc_23538565
|
Someone that can point me in the right direction?
This is the parent component of Podcast:
import React, { Component } from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import NavLinks from './components/NavLinks';
import Home from './components/Home';
import Podcast from './components/Podcast';
import './App.css';
class App extends Component {
render() {
return (
<Router>
<div className="App">
<NavLinks />
<Route exact path='/' component={Home} />
<Route path='/podcast/:podID' component={Podcast} />
</div>
</Router>
);
}
}
export default App;
This is my main Component (Podcast):
import React, { Component } from 'react';
import PodcastList from './PodcastList';
class Podcast extends Component {
constructor(props) {
super(props);
this.state = {
podcast: []
};
}
// Fetches podID from props.match
fetchPodcast () {
const podID = this.props.match.params.podID
fetch(`https://itunes.apple.com/search?term=podcast&country=${podID}&media=podcast&entity=podcast&limit=20`)
.then(response => response.json())
.then(data => this.setState({ podcast: data.results }));
}
componentDidMount () {
this.fetchPodcast()
}
// Check if new props is not the same as prevProps
componentDidUpdate (prevProps) {
// respond to parameter change
let oldId = prevProps.match.params.podID
let newId = this.props.match.params.podID
if (newId !== oldId)
this.fetchPodcast()
}
render() {
return (
<div>
<PodcastList />
</div>
)
}
}
export default Podcast;
This is the component thats list's all podcasts:
import React, { Component } from 'react';
class PodcastList extends Component {
render() {
return (
<div>
<h2>Country ({this.props.match.params.podID}) </h2>
<ul>
{this.state.podcast.map(podcast =>
<li key={podcast.collectionId}>
<a
href={podcast.collectionId}>
{podcast.collectionName}</a>
</li>
)}
</ul>
</div>
)
}
}
export default PodcastList;
A: Where does the error comes from? Podcast or PodcastList ? Maybe because you're not passing the props down to PodcastList ?
Try:
<PodcastList {...this.props} {...this.state} />
Also, in the child component (PodcastList) use this.props and not this.state
A: I guess you are using react-router. To have match prop of the React Router you have to decorate it by withRouter decorator of the module
import React, { Component } from 'react';
import { withRouter } from 'react-router';
class PodcastList extends Component {
render() {
return (
<div>
<h2>Country ({this.props.match.params.podID}) </h2>
<ul>
{this.state.podcast.map(podcast =>
<li key={podcast.collectionId}>
<a
href={podcast.collectionId}>
{podcast.collectionName}</a>
</li>
)}
</ul>
</div>
)
}
}
export default withRouter(PodcastList);
UPDATE:
One of the ways how to handle podcast prop in the PodcastList. The solutions fits all React recommendations and best practices.
import React, { PureComponent } from 'react';
import PodcastItem from './PodcastItem';
class Podcast extends PureComponent { // PureComponent is preferred here instead of Component
constructor(props) {
super(props);
this.state = {
podcast: []
};
}
// Fetches podID from props.match
fetchPodcast () {
const podID = this.props.match.params.podID
fetch(`https://itunes.apple.com/search?term=podcast&country=${podID}&media=podcast&entity=podcast&limit=20`)
.then(response => response.json())
.then(data => this.setState({ podcast: data.results }));
}
componentDidMount () {
this.fetchPodcast()
}
// Check if new props is not the same as prevProps
componentDidUpdate (prevProps) {
// respond to parameter change
let oldId = prevProps.match.params.podID
let newId = this.props.match.params.podID
if (newId !== oldId)
this.fetchPodcast()
}
render() {
return (
<div>
<h2>Country ({this.props.match.params.podID}) </h2>
<ul>
{this.state.podcast.map(podcast => (
<PodcastItem key={podcast.collectionId}> podcast={podcast} />
))}
</ul>
</div>
)
}
}
export default Podcast;
import React from 'react';
// Here Stateless function is enough
const PodcastItem = ({ podcast }) => (
<li key={podcast.collectionId}>
<a href={podcast.collectionId}>{podcast.collectionName}</a>
</li>
);
export default PodcastItem;
| |
doc_23538566
|
Redux is a predictable state container
Can explain to me what "predictable" word meaning in this context?
A: Redux is a "state container" because it holds all the state of your application. It doesn't let you change that state directly, but instead forces you to describe changes as plain objects called "actions". Actions can be recorded and replayed later, so this makes state management predictable. With the same actions in the same order, you're going to end up in the same state.
By
Dan Abramov
A: You first have to understand how Redux works. There are few key principles:
*
*State is a immutable object
*You never mutate application state, you always return a new, modified one
*All state changes are initiated through actions (they contain desired changes details)
*Reducers take current state, action and produce a new state ((state, action) => state)
So you can see that this is all unidirectional (changes flow one way only):
state -> action -> reducer -> state -> action -> reducer -> state ...
Redux is heavily inspired by Elm architecture and encourages functional programming principles, one of them being pure functions (they produce no side effects (like http calls, disk reads) and their output is always the same for the same input).
Every single state change in reducers has to be taken care by developers explicitly. Also all reducers are supposed to be pure. That's where the predictability comes from.
So to summarize, predictable in this context means, that using Redux you'll know what every single action in application will do and how state will change.
A: After some while, I understood the point:
First all, my question come from C++/Java/C# event driven (Redux have implementation not only for JS).
So I wonder what so bad with old pattern fashion Event-driving environment like Winform and all like? They all work with DataTable or collection of plain classes (Structures). The visual component hold state of Edit state or another Widget state, but not logic at all. (I not refer here to big words like MVC or MVVW or all other slogan. But all convince the same truth: we must seperate the View from Logic in some way).
Refer to Evaldas Buinauskas answer, have 4 principle. Let me explain why those principles is not the piont:
1> For what reason I need immutable? (Automatic changing awareness can be done with Aspect-Oriented Programming Or even is not so badly call re-render manually after each action)
2> Same of above (I still guess we not want clone hole store for each action without delete the previous one. For most app is not necessary or not possible due the lake of RAM).
3> All event driven I knew implement it.
4> Some of above. Immutable not necessary and new state as result of Action implement well with all known event driver patterns.
So, I think the main answer of Evaldas Buinauskas from my view point is:
Redux is heavily inspired by Elm architecture and encourages functional programming principles, one of them being pure functions (they produce no side effects (like http calls, disk reads) and their output is always the same for the same input).
With pure function that not change anything outside of Store, we get more clear and testable code (I guess that mean of words "Predicated").
A: You need to understand how changes are made in Reux and what is action and reducer in it.
*
*An action is an object which has a type property and it describes the changes in the state of the application.
*A reducer actually carries out the state transition depending on the action.
This way reducer carries out a definite state transition based on a definite action out of multiple possible actions. So every time a specific action causes a specific change in a state and makes Redux predictable.
| |
doc_23538567
|
XML looking something like this:
<Type type_id="4218">
<Title>English Premier League</Title>
<Event start_time="2011-12-18 16:10:00" ev_id="2893772">
<Description>Manchester City v Arsenal</Description>
<Market mkt_typ="Win/Draw/Win">
<Occurrence bet_id="42455761" decimal="1.6666666666667">
<Description>Manchester City</Description>
</Occurrence>
<Occurrence bet_id="42455762" decimal="3.6">
<Description>Draw</Description>
</Occurrence>
<Occurrence bet_id="42455764" decimal="5">
<Description>Arsenal</Description>
</Occurrence>
</Market>
</Event>
</Type>
output should be:
id:4218
title:English Premier League
ev_id:2893772
date of match:Sun Dec 18 16:10:00 CET 2011
description:Manchester City v Arsenal
one:1.6666666666667
draw:3.6
two:5
My code looks something like this:
XMLInputFactory factory = XMLInputFactory.newInstance();
try {
XMLStreamReader streamReader = factory.createXMLStreamReader(new URL("http://cubs.bluesq.com/cubs/cubs.php?action=getpage&thepage=385.xml").openStream());
while (streamReader.hasNext()) {
int event = streamReader.next();
if(event == XMLStreamConstants.START_ELEMENT){
if(streamReader.getLocalName().equals("Type")){
long id = Integer.parseInt(streamReader.getAttributeValue(null, "type_id"));
if( id == 4218){
System.out.println("id:"+id);
streamReader.nextTag();
System.out.println("title:"+streamReader.getElementText());
streamReader.nextTag();
int ev_id = Integer.parseInt(streamReader.getAttributeValue(null, "ev_id"));
System.out.println("ev_id:"+ev_id);
DateFormat formater = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
formater.setTimeZone(TimeZone.getTimeZone("CET"));
String tempDatum = streamReader.getAttributeValue(null,"start_time");
Date dateOfMatch = formater.parse(tempDatum);
System.out.println("date of match:"+dateOfMatch);
streamReader.nextTag();
String description = streamReader.getElementText();
System.out.println("description:"+ description);
streamReader.nextTag();
String market = streamReader.getAttributeValue(null, "mkt_typ");
if(market.equals("Win/Draw/Win")){
streamReader.nextTag();
double one = Double.parseDouble(streamReader.getAttributeValue(null, "decimal"));
System.out.println("one:"+ one);
double draw = Double.parseDouble(streamReader.getAttributeValue(null, "decimal"));
System.out.println("draw:"+draw);
double two = Double.parseDouble(streamReader.getAttributeValue(null, "decimal"));
System.out.println("two:"+two);
}
}
}
}
}
This code produce output:
id:4218
title:English Premier League
ev_id:2893772
date of match:Sun Dec 18 16:10:00 CET 2011
description:Manchester City v Arsenal
one:1.6666666666667
draw:1.6666666666667
two:1.6666666666667
how do I get others value from atribute "decimal" in elements "Occurrence"???
A:
if(market.equals("Win/Draw/Win")){
streamReader.nextTag();
I only had a quick look, but I would say you probably are staying at the first Occurence element since you're calling streamReader.nextTag() only once, but streamReader.getAttributeValue three times.
A: private String xmlFile = "file location";
private String desiredAttribute;
...
ClassLoader classLoader = this.getClass().getClassLoader();
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
InputStream inputStream = classLoader.getResourceAsStream(xmlFile);
XMLEventReader xmlEventReader = inputFactory.createXMLEventReader(inputStream);
try {
while (xmlEventReader.hasNext()) {
XMLEvent event = xmlEventReader.nextEvent();
if (event.isStartElement()) {
StartElement startElement = event.asStartElement();
QName qname = startElement.getName();
String elementName = qname.toString();
if (elementName.equals("My Element")) {
Iterator attributes = startElement.getAttributes();
while (attributes.hasNext()) {
Attribute attribute = (javax.xml.stream.events.Attribute) (attributes.next());
String attribute= attribute.getValue();
desiredAttribute = attribute;
}
...
You can also check for attribute name while iterating
| |
doc_23538568
|
public class ToDoAdapter extends ArrayAdapter<ToDo> {
private FirebaseAuth mAuth;
FirebaseUser user;
FirebaseFirestore db;
private Context context;
private int resource;
private List<ToDo> list;
private LayoutInflater inflater;
CheckBox checkBox;
ToDo toDo;
public ToDoAdapter(@NonNull Context context, int resource, @NonNull List<ToDo> objects,
LayoutInflater inflater) {
super(context, resource, objects);
this.context=context;
this.resource=resource;
this.list=objects;
this.inflater=inflater;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View view = inflater.inflate(resource,parent, false);
mAuth = FirebaseAuth.getInstance();
user = mAuth.getCurrentUser();
db = FirebaseFirestore.getInstance();
view.setClickable(true);
view.setFocusable(true);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bundle bundle = new Bundle();
bundle.putSerializable("todoID",position);
bundle.putSerializable("item", ToDoFragment.arrayAdapterToDo.getItem(position)
.getDetalii());
bundle.putSerializable("deadline", ToDoFragment.arrayAdapterToDo.getItem(position)
.getDeadline().toString());
ToDoFragment.getInstance().newFragment(bundle);
}
});
toDo = list.get(position);
if(toDo!=null){
addData(view, toDo.getDeadline());
addDetalii(view, toDo.getDetalii());
check(view, toDo.isEsteEfectuat());
}
checkBox = view.findViewById(R.id.checkbox);
checkBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(checkBox.isChecked()) {
*****
checkBox.setChecked(true);
toDo.setEsteEfectuat(true);
updateCheckBox();
view.setBackgroundColor(Color.parseColor("#008000"));
} else {
checkBox.setChecked(false);
toDo.setEsteEfectuat(false);
updateCheckBox();
view.setBackgroundColor(Color.parseColor("#FF0000"));
}
}
});
return view;
}
}
How can i gen the right position, i mean the right item to check/uncheck
If i put a toast instead of ****, i gen the first item of the list
A: With the @blackapps's help, try this:
CheckBox checkBox = view.findViewById(R.id.checkbox);
checkBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
toDo = ToDoFragment.arrayAdapterToDo.getItem(position);
if(checkBox.isChecked()) {
checkBox.setChecked(true);
toDo = ToDoFragment.arrayAdapterToDo.getItem(position);
toDo.setEsteEfectuat(true);
updateCheckBox();
view.setBackgroundColor(Color.parseColor("#008000"));
} else {
checkBox.setChecked(false);
toDo = ToDoFragment.arrayAdapterToDo.getItem(position);
toDo.setEsteEfectuat(false);
updateCheckBox();
view.setBackgroundColor(Color.parseColor("#FF0000"));
}
}
});
| |
doc_23538569
|
text/xml" so it is an example of an "Application" file, but any file is an "Application" file.
What about Text resource data? It is generic and probably enlightens the main purpose.
A: XML is a very flexible, and very low-level, format, so it's hard to describe its "data type" outside of a concrete usage.
For instance, in different contexts, you could describe XML data as (these aren't mutually exclusive):
*
*marked up text, per the "M" in XML; e.g. XHTML, DocBook
*serialized application data; e.g in SOAP or RESTful web services
*metadata describing another resource; e.g. RSS/Atom feeds, project manifests and configuration files
*hierarchical object data; e.g. SVG
*self-referential data definitions; e.g. XML Schema
Or you could define it by the purpose of the data - if a JPEG file is a "raster image", then an SVG file is a "vector image", a DocBook file is a "documentation file", etc - with XML simply being a detail of the format used, just as "sequence of big-endian 16-bit words" would be.
A: I chose the term TextResource, since it is what it should be used for within the project scope: Documents, Configuration files, etc.
| |
doc_23538570
|
How do I tell emacs to assume that the background is either dark or light?
A: I think the best approach to use is to use ColorTheme. Other options to customize the frame colors you can find here. I can't think about a single command, however you can start emacs with --reverse-video.
A: M-x set-variable <RET> frame-background-mode <RET> dark
see also the bottom of https://www.gnu.org/software/emacs/manual/html_node/elisp/Defining-Faces.html
A: Write this at the end of your ~/.emacs file :
;; dark mode
(when (display-graphic-p)
(invert-face 'default)
)
(set-variable 'frame-background-mode 'dark)
Note: The "when" sentence is there to avoid to invert colors in no-window mode (I presume your terminal has already a black background).
A: I've used the invert-face function in the past:
(invert-face 'default)
Or:
M-x invert-face <RET> default
A: The alect-themes package for Emacs 24 provides light, dark, and black themes, and can be installed either manually or using MELPA.
To install alect-themes using MELPA and select alect-dark (from ~/emacs.d/init.d):
(when (>= emacs-major-version 24)
(require 'package)
(add-to-list 'package-archives
'("melpa-stable" . "http://melpa-stable.milkbox.net/packages/"))
(package-initialize)
(load-theme 'alect-dark)
)
There are quite a few color theme packages in MELPA, so if alect-themes doesn't meet your needs, experiment with some of the others.
| |
doc_23538571
|
| KEY 4759839 | asljhk | 35049 | | sklahksdjf|
| KEY 359 | skj | 487 |y| 2985789 |
The above data in my file would originally look like this in column A:
KEY 4759839
asljhk
35049
sklahksdjf
KEY 359
skj
487
y
2985789
Considerations:
*
*Blank cells need to be transposed as well, so the macro cant stop based on emptyCell
*The number of cells between KEY's is not constant so it actually needs to read the cell to know if it should create a new row
*It can either stop based on say 20 empty cells in a row or prompt for a max row number
*(Optional) It would be nice if there was some sort of visual indicator for the last item in a row so that its possible to tell if the last item(s) were blank cells
I searched around and found a macro that had the same general theme but it went based on every 6 lines and I did not know enough to try to modify it for my case. But in case it helps here it is:
Sub kTest()
Dim a, w(), i As Long, j As Long, c As Integer
a = Range([a1], [a500000].End(xlUp))
ReDim w(1 To UBound(a, 1), 1 To 6)
j = 1
For i = 1 To UBound(a, 1)
c = 1 + (i - 1) Mod 6: w(j, c) = a(i, 1)
If c = 6 Then j = j + 1
Next i
[c1].Resize(j, 6) = w
End Sub
I would greatly appreciate any help you can give me!
A: This works with the sample data you provided in your question - it outputs the result in a table starting in B1. It runs in less than one second for 500k rows on my machine.
Sub kTest()
Dim originalData As Variant
Dim result As Variant
Dim i As Long
Dim j As Long
Dim k As Long
Dim countKeys As Long
Dim countColumns As Long
Dim maxColumns As Long
originalData = Range([a1], [a500000].End(xlUp))
countKeys = 0
maxColumns = 0
'Calculate the number of lines and columns that will be required
For i = LBound(originalData, 1) To UBound(originalData, 1)
If Left(originalData(i, 1), 3) = "KEY" Then
countKeys = countKeys + 1
maxColumns = IIf(countColumns > maxColumns, countColumns, maxColumns)
countColumns = 1
Else
countColumns = countColumns + 1
End If
Next i
'Create the resulting array
ReDim result(1 To countKeys, 1 To maxColumns) As Variant
j = 0
k = 1
For i = LBound(originalData, 1) To UBound(originalData, 1)
If Left(originalData(i, 1), 3) = "KEY" Then
j = j + 1
k = 1
Else
k = k + 1
End If
result(j, k) = originalData(i, 1)
Next i
With ActiveSheet
.Cells(1, 2).Resize(UBound(result, 1), UBound(result, 2)) = result
End With
End Sub
A: Tested and works:
Sub test()
Row = 0
col = 1
'Find the last not empty cell by selecting the bottom cell and moving up
Max = Range("A650000").End(xlUp).Row 'Or whatever the last allowed row number is
'loop through the data
For i = 1 To Max
'Check if the left 3 characters of the cell are "KEY" and start a new row if they are
If (Left(Range("A" & i).Value, 3) = "KEY") Then
Row = Row + 1
col = 1
End If
Cells(Row, col).Value = Range("A" & i).Value
If (i > Row) Then
Range("A" & i).Value = ""
End If
col = col + 1
Next i
End Sub
| |
doc_23538572
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entity;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Entity;
import javax.persistence.FetchType;
@Entity
@Table(name = "Presentation")
public class Presentation implements Serializable
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "start_time")
private Timestamp startTime;
@Column(name = "end_time")
private Timestamp endTime;
@ManyToOne(targetEntity = Location.class, fetch = FetchType.LAZY)
private Location location;
@ManyToMany
private List<User> users;
@ManyToMany(mappedBy = "presentations")
private List<Planning> plannings;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Timestamp getEndTime() {
return endTime;
}
public void setEndTime(Timestamp endTime) {
this.endTime = endTime;
}
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public List<Planning> getPlannings() {
return plannings;
}
public void setPlannings(List<Planning> plannings) {
this.plannings = plannings;
}
public Timestamp getStartTime() {
return startTime;
}
public void setStartTime(Timestamp startTime) {
this.startTime = startTime;
}
}
Now i can fetch these with the following query:
Query q = session.createQuery("SELECT p FROM " + Presentation.class.getSimpleName() + " p");
to get a List.
Now i need to pass something to a library that i use for showing presentations on a timeline. I would like to somehow edit this structure directly after i fetched it to match with the library api.
public PresentationModified(JaretDate date, int h, int m, double durH, String text) {
JaretDate begin = date.copy().setTime(h, m, 0);
setRealBegin(begin);
JaretDate end = begin.copy().advanceHours(durH);
setRealEnd(end);
_text = text;
checkSpanMultiple();
changed();
}
I can't find a good way to fetch the query and create the corresponding objects directly afterwards.
| |
doc_23538573
|
START TRANSACTION;
INSERT INTO address_tbl (address_ln_1, address_ln_2, address_town, address_county, address_postcode) VALUES ('place', '', 'Town', 'county', 'postcode');
SELECT LAST_INSERT_ID();
COMMIT;
using the js:
var query= function (sql){
return new Promise(resolve => {
con.query(sql, (err, result) => {
if(err) throw err;
resolve(result);
});
});
}
error:
C:\node_modules\mysql\lib\protocol\Parser.js:437
throw err; // Rethrow non-MySQL errors
^
Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'INSERT INTO address_tbl (address_ln_1, address_ln_2, address_town, address_count' at line 1
at Query.Sequence._packetToError (C:\node_modules\mysql\lib\protocol\sequences\Sequence.js:47:14)
at Query.ErrorPacket (C:\node_modules\mysql\lib\protocol\sequences\Query.js:77:18)
at Protocol._parsePacket (C:\node_modules\mysql\lib\protocol\Protocol.js:291:23)
at Parser._parsePacket (C:\node_modules\mysql\lib\protocol\Parser.js:433:10)
at Parser.write (C:\node_modules\mysql\lib\protocol\Parser.js:43:10)
at Protocol.write (C:\node_modules\mysql\lib\protocol\Protocol.js:38:16)
at Socket.<anonymous> (C:\node_modules\mysql\lib\Connection.js:91:28)
at Socket.<anonymous> (C:\node_modules\mysql\lib\Connection.js:525:10)
at Socket.emit (events.js:198:13)
at addChunk (_stream_readable.js:288:12)
--------------------
at Protocol._enqueue (C:\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Connection.query (C:\node_modules\mysql\lib\Connection.js:201:25)
at resolve (C:\db.js:18:13)
at new Promise (<anonymous>)
at Object.query (C:\db.js:17:12)
at insert (C:\utl\order_model.js:16:8)
at Order.insert (C:\utl\order_model.js:99:9)
at utill.calculate_cart (C:\routes\orderRouter.js:65:15)
at pm.getProducts.productlist (C:\utl\utill.js:22:9)
at Object.getProducts (C:\utl\products_model.js:27:9)
[nodemon] app crashed - waiting for file changes before starting...
A: So just reading the error message and comparing to the (working) query above:
Working: INSERT INTO address_tbl (address_ln_1, address_ln_2, address_town, address_county, address_postcode) VALUES ('place', '', 'Town', 'county', 'postcode');
Error Message: 'INSERT INTO address_tbl (address_ln_1, address_ln_2, address_town, address_count'
You're missing some of the parameters for your Table Insert. I'd look at why that is.
| |
doc_23538574
|
Basically, I am trying to connect to my Ally Invest account using Python and requests. I have signed up for the API and have gotten the consumer key, secret, oauth token, and secret. I am currently trying to display my balances, with this as the first part of my code:
url = 'https://devapi.invest.ally.com/v1/accounts/{}/balances.json'.format(acct)
authorize = OAuth1(cKey, cSecret, oToken, oSecret)
my_acct = requests.get(url, auth = authorize)
my_acct.status_code
Everything looks fine and my_acct.status_code returns 200 but then I try running the following
data = my_acct.json()
data
and I get the following error:
JSONDecodeError Traceback (most recent call last)
<ipython-input-29-2c5022dcbfa5> in <module>
----> 1 data = my_acct.json()
2 data
/usr/lib/python3/dist-packages/requests/models.py in json(self, **kwargs)
895 # used.
896 pass
--> 897 return complexjson.loads(self.text, **kwargs)
898
899 @property
/usr/lib/python3/dist-packages/simplejson/__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, use_decimal, **kw)
516 parse_constant is None and object_pairs_hook is None
517 and not use_decimal and not kw):
--> 518 return _default_decoder.decode(s)
519 if cls is None:
520 cls = JSONDecoder
/usr/lib/python3/dist-packages/simplejson/decoder.py in decode(self, s, _w, _PY3)
368 if _PY3 and isinstance(s, bytes):
369 s = str(s, self.encoding)
--> 370 obj, end = self.raw_decode(s)
371 end = _w(s, end).end()
372 if end != len(s):
/usr/lib/python3/dist-packages/simplejson/decoder.py in raw_decode(self, s, idx, _w, _PY3)
398 elif ord0 == 0xef and s[idx:idx + 3] == '\xef\xbb\xbf':
399 idx += 3
--> 400 return self.scan_once(s, idx=_w(s, idx).end())
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Here is the output when I run print(my_acct.text)
'<!DOCTYPE html>\n<!--[if IE]><html class="ie"><![endif]-->\n<!--[if !IE]><!-->\n<html>\n <!--<![endif]-->\n\n <head>\n <meta charset="UTF-8" />\n <meta\n name="viewport"\n content="width=device-width, initial-scale=1, minimum-scale=1"\n />\n <meta\n name="ROBOTS"\n content="NOINDEX, NOFOLLOW"\n />\n <meta\n http-equiv="X-UA-Compatible"\n content="IE=edge"\n />\n <link\n href="https://www.ally.com/failover/InvestSplash/faviconnewsplash.ico"\n rel="shortcut icon"\n type="image/x-icon"\n />\n <meta\n name="format-detection"\n content="telephone=no"\n />\n <title>We\'re sorry | Ally Bank</title>\n <link\n href="https://www.ally.com/failover/InvestSplash/core.buildnewsplash.css"\n media="screen"\n rel="stylesheet"\n type="text/css"\n />\n <script\n language="javascript"\n type="text/javascript"\n src="https://www.ally.com/failover/InvestSplash/jquery-1.4.2.js"\n ></script>\n\n\n <style type="text/css">\n @font-face {\n font-family: allycons;\n src: url(\'https://www.ally.com/failover/InvestSplash/allyconsEOTnewsplash.eot\');\n src: url(\'https://www.ally.com/failover/InvestSplash/allyconsEOTiefixnewsplash.eot\') format(\'embedded-opentype\'), url(\'https://www.ally.com/failover/InvestSplash/allyconsTTFnewsplash.ttf\') format(\'truetype\'), url(\'https://www.ally.com/failover/InvestSplash/allyconsWOFFnewsplash.woff\') format(\'woff\'), url(\'https://www.ally.com/failover/InvestSplash/allyconsSVGnewsplash.svg\') format(\'svg\');\n font-weight: 400;\n font-style: normal\n }\n\n [class*=" icon-"],\n [class^=icon-] {\n font-family: allycons !important;\n speak: none;\n font-style: normal;\n font-weight: 400;\n font-variant: normal;\n text-transform: none;\n line-height: 1;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: ... </body>\n\n</html>\n'
(Note: I've had to shorten it a bit, but this is the top part.)
The weird thing is, when I ran the above code block last night, it was working fine; showing a JSON of my balances. I tried looking up the error but have not found anything that seems to work.
Any help is very much appreciated. Thanks.
| |
doc_23538575
|
@Slf4j
@Repository
public class UserJdbcRepository {
private final SQLQueryFactory queryFactory;
@Autowired
public UserJdbcRepository(DataSource dataSource) {
Configuration configuration = new Configuration(new OracleTemplates());
configuration.setExceptionTranslator(new SpringExceptionTranslator());
this.queryFactory = new SQLQueryFactory(configuration, dataSource);
}
public Page<User> findAll(BooleanExpression predicate, Pageable pageable) {
QUser u = new QUser("u");
SQLQuery<Tuple> sql = queryFactory
.select(u.userId, // omitted)
.from(u)
.where(predicate);
long count = sql.fetchCount();
List<Tuple> results = sql.fetch();
// Conversion List<Tuple> to List<User> omitted
return new PageImpl<>(users, pageable, count);
}
}
fetchCount() is executed correctly, but fetch() is throwing NullPointerException:
java.lang.NullPointerException: null
at com.querydsl.sql.AbstractSQLQuery.fetch(AbstractSQLQuery.java:502) ~[querydsl-sql-4.4.0.jar:na]
From debug I found that root cause is in com.querydsl.sql.AbstractSQLQuery:
java.sql.SQLException: Connection is closed
If I create second (the same as first one) query sql2, then it is working (of course):
SQLQuery<Tuple> sql2 = queryFactory
.select(... // same as first one)
long count = sql.fetchCount();
List<Tuple> results = sql2.fetch();
My question is if connection should be really closed after fetchCount() is called? Or do I have some misconfiguration?
I have SpringBoot 2.4.5; spring-data-commons 2.5.0; Oracle driver ojdbc8 21.1.0.0; QueryDSL 4.4.0
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-sql</artifactId>
<version>${querydsl.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-sql-spring</artifactId>
<version>${querydsl.version}</version>
<scope>compile</scope>
</dependency>
<plugin>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-maven-plugin</artifactId>
<version>${querydsl.version}</version>
<executions>
<execution>
<goals>
<goal>export</goal>
</goals>
</execution>
</executions>
<configuration>
<jdbcDriver>oracle.jdbc.OracleDriver</jdbcDriver>
<jdbcUrl>jdbc:oracle:thin:@//localhost:1521/XE</jdbcUrl>
<jdbcUser>user</jdbcUser>
<jdbcPassword>password</jdbcPassword>
<sourceFolder>${project.basedir}/src/main/java</sourceFolder>
<targetFolder>${project.basedir}/src/main/java</targetFolder>
<packageName>org.project.backend.repository.querydsl</packageName>
<schemaToPackage>true</schemaToPackage>
<schemaPattern>project</schemaPattern>
<tableNamePattern>
// omitted
</tableNamePattern>
</configuration>
<plugin>
A: Issue is caused by missconfiguration. QueryDSL doc contains Spring integration section, where is mentioned that SpringConnectionProvider must be used. So I changed my constructor and it is working now as expected:
@Autowired
public UserJdbcRepository(DataSource dataSource) {
Configuration configuration = new Configuration(new OracleTemplates());
configuration.setExceptionTranslator(new SpringExceptionTranslator());
// wrong: this.queryFactory = new SQLQueryFactory(configuration, dataSource);
Provider<Connection> provider = new SpringConnectionProvider(dataSource);
this.queryFactory = new SQLQueryFactory(configuration, provider);
}
I also found there is useful method fetchResults() containing count for pagination purpose (so not needed to explicitly call fetchCount()):
public Page<User> findAll(BooleanExpression predicate, Pageable pageable) {
QUser u = new QUser("u");
SQLQuery<Tuple> sql = queryFactory
.select(u.userId, // omitted)
.from(u)
.where(predicate);
sql.offset(pageable.getOffset());
sql.limit(pageable.getPageSize());
QueryResults<Tuple> queryResults = sql.fetchResults();
long count = queryResults.getTotal();
List<Tuple> results = queryResults.getResults();
// Conversion List<Tuple> to List<User> omitted
return new PageImpl<>(users, pageable, count);
}
| |
doc_23538576
|
Spinner1,Spinner2,Spinner3 value is retrieved from one table "LABELS".
All three spinner value is inserted in to another table "LABELS2" while clicking the save button.
Requirement: Spinner2 should load contents based on comparision between table "Labels" and "Labels2".
Idea behind is to avoid duplication in the data insert and to know how many records is left after saving the data.
Example: Table "Labels" is having three record
1.("A1”,”EXTRA1”,”MORE1");
2,("A1”,”EXTRA2”,”MORE2");
3,("A1”,”EXTRA2”,”MORE2");
MainActivity
public class MainActivity extends AppCompatActivity {
DatabaseHandler mDH;
Spinner mSpinner1,mSpinner2,mSpinner3;
Cursor mSpinner1Csr,mSpinner2Csr,mSpinner3Csr;
SimpleCursorAdapter mSpinner1Adapter,mSpinner2Adapter,mSpinner3Adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSpinner1 = this.findViewById(R.id.spinner1);
mSpinner2 = this.findViewById(R.id.spinner2);
mSpinner3 = this.findViewById(R.id.spinner3);
mDH = new DatabaseHandler(this);
addSomeTestingData(); // ADD testing data if none
manageSpinner1(); // Manages spinner1 not that spinner 1 invokes manage spinner2 and spinnr manages spinner3
}
private void addSomeTestingData() {
if(DatabaseUtils.queryNumEntries(mDH.getWritableDatabase(),DatabaseHandler.TABLE_LABELS) > 0) return;
// Data for LABELS2 table (spinner 1 (note 1st column listed in spinner))
mDH.insertLabel("A1”,”EXTRA1”,”MORE1");
mDH.insertLabel("A1”,”EXTRA2”,”MORE2");
mDH.insertLabel("A1”,”EXTRA3”,”MORE5");
mDH.insertLabel1("A1EXTRA1");
mDH.insertLabel1("A1EXTRA2");
mDH.insertLabel1("B1EXTRA1");
mDH.insertLabel1("B1EXTRA2");
mDH.insertLabel1("L1EXTRA1");
mDH.insertLabel1("L1EXTRA2");
// Data for LABELS table (spinner 1,2,3)
mDH.insertlabel("A1”,”EXTRA1”,”MORE1");
mDH.insertlabel("A1”,”EXTRA2”,”MORE2");
mDH.insertlabel("A1”,”EXTRA3”,”MORE5");
}
private void manageSpinner1() {
mSpinner1Csr = mDH.getAllLabelsForSpinner1AsCursor();
if (mSpinner1Adapter == null) {
mSpinner1Adapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_1,
mSpinner1Csr,
new String[]{DatabaseHandler.KEY_NAME},
new int[]{android.R.id.text1},
0
);
mSpinner1.setAdapter(mSpinner1Adapter);
mSpinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
manageSpinner2(mSpinner1Csr.getString(mSpinner1Csr.getColumnIndex(DatabaseHandler.ROUTE)));
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} else {
mSpinner1Adapter.swapCursor(mSpinner1Csr);
}
}
private void manageSpinner2(String keyFromSpinner1) {
mSpinner2Csr = mDH.getAllLabelsForSpinner2AsCursor(keyFromSpinner1);
if (mSpinner2Adapter == null) {
mSpinner2Adapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_1,
mSpinner2Csr,
new String[]{DatabaseHandler.ROUTE},
new int[]{android.R.id.text1},
0
);
mSpinner2.setAdapter(mSpinner2Adapter);
mSpinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
manageSpinner3(mSpinner2Csr.getString(mSpinner2Csr.getColumnIndex(DatabaseHandler.ROUTE)));
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} else {
mSpinner2Adapter.swapCursor(mSpinner2Csr);
}
}
private void manageSpinner3(String keyForSpinner3) {
mSpinner3Csr = mDH.getAllLabelsForSpinner3AsCursor(keyForSpinner3);
if (mSpinner3Adapter == null) {
mSpinner3Adapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_1,
mSpinner3Csr,
new String[]{DatabaseHandler.KEY_ID},
new int[]{android.R.id.text1},
0
);
mSpinner3.setAdapter(mSpinner3Adapter);
} else {
mSpinner3Adapter.swapCursor(mSpinner3Csr);
}
}
}
DatabaseHandler
public class DatabaseHandler extends SQLiteOpenHelper {
// Database Version
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "spinnerExample";
private final Context myContext;
private SQLiteDatabase myDataBase;
// Database Name
// Labels table name
public static final String TABLE_LABELS = "labels"; //<<<< Made public
public static final String TABLE_LABELS1= "labels1";
public static final String TABLE_LABELS2= "labels2";
// Labels Table Columns names
public static final String KEY_ID4 = "input_label";
public static final String KEY_ID12 = "id2"; //<<<< Made public
public static final String KEY_ID = "id";
public static final String KEY_99 = "sno"; //<<<< Made public//<<<< Made public
public static final String KEY_NAME = "name"; //<<<< made public
public static final String KEY_ID1 = "id1"; //<<<< Made public
public static final String KEY_NAME1 = "name1";
public static final String KEY_1 = "number"; //<<<< Made public
public static final String KEY_2 = "outletname"; //<<<< made public
public static final String KEY_3 = "sunday"; //<<<< Made public
public static final String KEY_4 = "monday";
public static final String KEY_5 = "tuesday";
public static final String KEY_6 = "wednesday";
public static final String KEY_7 = "thursday";
public static final String KEY_8 = "saturday";
public static final String KEY_9 = "closed";
public static final String KEY_10 = "calling";
public static final String KEY_11 = "id3";
public static final String ROUTE= "route";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
myDataBase = this.getWritableDatabase();
this.myContext = context;
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
//boolean dbExist = checkDataBase();
// Category table create query
String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("+ KEY_99 + " INTEGER,"
+ ROUTE + " TEXT," + KEY_ID + " TEXT," + KEY_NAME + " TEXT)";
String CREATE_CATEGORIES_TABLE1 = "CREATE TABLE " + TABLE_LABELS1 + "("
+ KEY_ID1+ " TEXT," + KEY_NAME1+ " TEXT)";
String CREATE_CATEGORIES_TABLE2 = "CREATE TABLE " + TABLE_LABELS2 + "("
+ KEY_11+ " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_1+ " TEXT," + KEY_2+ " TEXT," + KEY_3+ " TEXT)";
db.execSQL(CREATE_CATEGORIES_TABLE);
db.execSQL(CREATE_CATEGORIES_TABLE1);
db.execSQL(CREATE_CATEGORIES_TABLE2);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS1);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS2);
// Create tables again
onCreate(db);
}
/**
* Inserting new lable into lables table
* */
public void insertlabel(String text,String id9,String id, String label) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(KEY_99,text);
cv.put(ROUTE,id9);
cv.put(KEY_ID,id);
cv.put(KEY_NAME,label);
db.insert(TABLE_LABELS,null,cv);
db.close();
}
public void insertLabel(String message1, String message2,String message3){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_1, message1);
values.put(KEY_2, message2);
values.put(KEY_3,message3);
// Inserting Row
db.insert(TABLE_LABELS2, null, values);
//db.close(); // Closing database connection
}
public void insertLabel1(String label){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME1, label);
db.insert(TABLE_LABELS1, null, values);
//db.close(); // Closing database connection
}
public void insertLabel2(String label){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, label);
db.insert(TABLE_LABELS, null, values);
db.close(); // Closing database connection
}
public Cursor getAllLabelsForSpinner1AsCursor() {
String[] columns = new String[]{"rowid AS _id, *"}; // Need _id column for SimpleCursorAdapter
return this.getWritableDatabase().query(TABLE_LABELS,columns,null,null,null,null,null);
}
public Cursor getAllLabelsForSpinner2AsCursor(String keyFromSinner1) {
String[] columns = new String[]{"rowid AS _id, *"}; // Need _id column for SimpleCursorAdapter
return this.getWritableDatabase().query(
TABLE_LABELS,columns,
DatabaseHandler.ROUTE + " LIKE ?",
new String[]{keyFromSinner1+"%"},
null,null,null
);
}
public Cursor getAllLabelsForSpinner3AsCursor(String keyFromSpinner2) {
String[] columns = new String[]{"rowid AS _id, *"}; // Need _id column for SimpleCursorAdapter
return this.getWritableDatabase().query(
TABLE_LABELS,columns,
DatabaseHandler.ROUTE + " LIKE ?",
new String[]{keyFromSpinner2 + "%"},
null,null,null);
}
}
Simulation:
As you can below selection of the first spinner "P1" shows his relevant information
now second spinner display the information based on first spinner selection.
we save the information on each selection.
Requirement is spinner 2 information should reduce upon data saving information.
example : if you select "9001234" then save information with "9001234" and next automatically should come "9003562" and so on as per saving the information.
Looking forward to any help.
A: How about this ?
public Cursor getRoutes(long name) {
SQLiteDatabase db = this.getReadableDatabase();
String whereclause = KEY_NAME + "=?";
String[] whereargs = new String[]{String.valueOf(name)};
String sql = "SELECT customer_name,labels5.number,labels.id,customer._id,labels.route FROM customer left join labels ON customer._id = labels._id LEFT JOIN labels5 ON labels5.number = labels.route WHERE number IS NULL";
return db.query(sql,null,whereclause,whereargs,null,null,ROUTE);
}
A: Second way
public Cursor getRoutes(long name) {
SQLiteDatabase db = this.getReadableDatabase();
String whereclause = KEY_NAME + "=?";
String[] whereargs = new String[]{String.valueOf(name)};
String[] tableColumns = new String[]{"customer_name, labels5.number,labels.id,customer._id,labels.route FROM customer left join labels ON customer._id = labels._id LEFT JOIN labels5 ON labels5.number = labels.route where number is NULL "};
//String orderBy = "ROUTE";
// String tableColumns = SELECT customer_name, labels5.number,labels.id,customer._id,labels.route FROM customer left join labels ON customer._id = labels._id LEFT JOIN labels5 ON labels5.number = labels.route where number is NULL" ;
return db.query(TABLE_LABELS,tableColumns,whereclause,whereargs,null,null,ROUTE);
}
| |
doc_23538577
|
onRestoreInstanceState(Bundle savedInstanceState)
is not geting called, I am pasting my code below. Actually I want to redraw all the points that are saved when my activity went in background.
package com.geniteam.mytest;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;
public class Tutorial2D extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(new Panel(this));
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Panel panel = new Panel(this);
outState.putSerializable("test", panel._graphics);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Panel panel = new Panel(this);
panel.set_graphics((ArrayList<GraphicObject>) savedInstanceState.getSerializable("test"));
}
class Panel extends SurfaceView implements SurfaceHolder.Callback {
private TutorialThread _thread;
private ArrayList<GraphicObject> _graphics = new ArrayList<GraphicObject>();
public ArrayList<GraphicObject> get_graphics() {
return _graphics;
}
public void set_graphics(ArrayList<GraphicObject> graphics) {
_graphics = graphics;
}
public Panel(Context context) {
super(context);
getHolder().addCallback(this);
_thread = new TutorialThread(getHolder(), this);
setFocusable(true);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
synchronized (_thread.getSurfaceHolder()) {
// if (event.getAction() == MotionEvent.ACTION_DOWN) {
GraphicObject graphic = new GraphicObject(BitmapFactory.decodeResource(getResources(), R.drawable.icon));
graphic.getCoordinates().setX((int) event.getX() - graphic.getGraphic().getWidth() / 2);
graphic.getCoordinates().setY((int) event.getY() - graphic.getGraphic().getHeight() / 2);
_graphics.add(graphic);
//}
return true;
}
}
@Override
public void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
Bitmap bitmap;
GraphicObject.Coordinates coords;
for (GraphicObject graphic : _graphics) {
bitmap = graphic.getGraphic();
coords = graphic.getCoordinates();
canvas.drawBitmap(bitmap, coords.getX(), coords.getY(), null);
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// TODO Auto-generated method stub
}
public void surfaceCreated(SurfaceHolder holder) {
try{
_thread.setRunning(true);
_thread.start();
}catch(Exception ex){
_thread = new TutorialThread(getHolder(), this);
_thread.start();
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// simply copied from sample application LunarLander:
// we have to tell thread to shut down & wait for it to finish, or else
// it might touch the Surface after we return and explode
boolean retry = true;
_thread.setRunning(false);
while (retry) {
try {
_thread.join();
retry = false;
} catch (InterruptedException e) {
// we will try it again and again...
}
}
}
}
class TutorialThread extends Thread {
private SurfaceHolder _surfaceHolder;
private Panel _panel;
private boolean _run = false;
public TutorialThread(SurfaceHolder surfaceHolder, Panel panel) {
_surfaceHolder = surfaceHolder;
_panel = panel;
}
public void setRunning(boolean run) {
_run = run;
}
public SurfaceHolder getSurfaceHolder() {
return _surfaceHolder;
}
@Override
public void run() {
Canvas c;
while (_run) {
c = null;
try {
c = _surfaceHolder.lockCanvas(null);
synchronized (_surfaceHolder) {
_panel.onDraw(c);
}
} finally {
// do this in a finally so that if an exception is thrown
// during the above, we don't leave the Surface in an
// inconsistent state
if (c != null) {
_surfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
}
class GraphicObject {
/**
* Contains the coordinates of the graphic.
*/
public class Coordinates {
private int _x = 100;
private int _y = 0;
public int getX() {
return _x + _bitmap.getWidth() / 2;
}
public void setX(int value) {
_x = value - _bitmap.getWidth() / 2;
}
public int getY() {
return _y + _bitmap.getHeight() / 2;
}
public void setY(int value) {
_y = value - _bitmap.getHeight() / 2;
}
public String toString() {
return "Coordinates: (" + _x + "/" + _y + ")";
}
}
private Bitmap _bitmap;
private Coordinates _coordinates;
public GraphicObject(Bitmap bitmap) {
_bitmap = bitmap;
_coordinates = new Coordinates();
}
public Bitmap getGraphic() {
return _bitmap;
}
public Coordinates getCoordinates() {
return _coordinates;
}
}
}
A: onRestoreInstanceState only gets called if the app is destroyed and re-created. Putting the app in the background then bringing it up again will call onResume, but not onRestoreInstanceState.
| |
doc_23538578
|
User dynamically select the folder for download excel
I tried with
<input id="input-folder-1" type="file" webkitdirectory>
but upload the files inside the folder.
but I want to select folder.
Thanks Advance !!!
| |
doc_23538579
|
I'm able to discover the name in the Discovery Browser and dns-sd tool but it doesn't show any information.
I've also tried to use my Cordova app to discover the service and this just shows the service as having been "Added" but it never gets to the "Resolved" state.
When running the same service on my MacOS machine, everything works as it should. The service is resolved and I'm able to get information on the service. It also works in the iOS app.
If anyone has any ideas or input, I would be forever grateful! This problem has had be bogged down for 3 days now.
A: Ah, thank goodness. I've solved my own problem. Turns out this iOS/MacOSx required me to specify the hostname as well as the service name. This wasn't in the documentation.
After adding a "host" field to my published service everything worked as it should!
| |
doc_23538580
|
<Command Name="searchCommand">
<Example>Search for UWP on Bing </Example>
<ListenFor RequireAppName="BeforeOrAfterPhrase"> search for {search} on {service} </ListenFor>
<Feedback>Searching for {search} on {service}</Feedback>
<Navigate />
</Command>
I added these phrases (where the service is dynamically updated in code, this all works fine):
<PhraseList Label="service">
<!-- Dynamic -->
</PhraseList>
<PhraseTopic Label="search" Scenario="Search">
<!-- Dynamic -->
</PhraseTopic>
Now when I use this command, the API only seems to recognize the last phrase. So if I use 3 phrases, only the last will be recognized.
Command: 'Search for UWP on Bing'
Shows up as: 'Searching for {search} on Bing'
TextSpoken value: 'Search for UWP on Bing' (so the voice to text is working correctly)
When I use 'Search for {search}' in the ListenFor, it correctly returns the right result. But for this feature I am implementing I need 2 (or even 3) phrases in a single command.
It seems that UWP only recognizes the last phrase. Am I correct or should it be possible to use multiple phrases inside a ListenFor element?
Update June 13, 2016:
I have created a repro:
A: Geert, it looks like you're using Windows Insider build 14342. The issue you're seeing is due to a bug introduced in build 14341 which should be fixed in builds >= 14371.
Hope that helps.
A: No UWP recognizes multiple phrase inside a ListenFor
I guess you need to more than one ListenFor
<Command Name="searchCommand">
<Example>Search for UWP on Bing </Example>
<ListenFor RequireAppName="BeforeOrAfterPhrase"> search for {search} on {service} </ListenFor>
<ListenFor RequireAppName="BeforeOrAfterPhrase">search for {search}</ListenFor>
<ListenFor RequireAppName="BeforeOrAfterPhrase">search for on {service}</ListenFor>
<Feedback>Searching for {search} on {service}</Feedback>
<Navigate />
</Command>
In this way you can cover all the combination. I guess Cortana is getting confused because of only one ListenFor.
| |
doc_23538581
|
Error:A problem occurred configuring project ':app'.
> Could not download hamcrest-core.jar (org.hamcrest:hamcrest-core:1.3)
> Could not get resource 'https://jcenter.bintray.com/org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3.jar'.
> Could not GET 'https://jcenter.bintray.com/org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3.jar'.
> jcenter.bintray.com
A: the error is not because of hamcrest-core-1.3.jar file. it seems gradle cannot connect to jcenter and download the junit.jar . So, make sure of your internet connection and rebuild your project. normally gradle downloads all necessary jars. if it dosent try to update your build tools.
A: Try this on your build.gradle Module:app
configurations.all {
resolutionStrategy {
force 'org.hamcrest:hamcrest-core:1.3'
}}
Reference: https://docs.gradle.org/current/dsl/org.gradle.api.artifacts.ResolutionStrategy.html
A: Remove the following lines from build.gradle Module:app under dependencies
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.1', {
exclude group: 'com.android.support', module: 'support-annotations'
})
A: In my experience, When I created a new project I encountered this issue.
To fix it I removed the dependency below from build.gradle Module:app.
testCompile 'junit:junit:4.12'
After that and rebuild project the problem never happened.
A: I had the same issue before, the gradle could not access jar repositories in my case.
You probably need to:
*
*first make sure you are connected to internet
*setup the proxy settings in Android Studio (especially if you are using it from your work environment/network) OR connect to an open network
A: Go to gradle.properties and comment all systemProp proxys and resync
its work for me
*
*Android 2.3.3
A: Disable Gradle offline mode under
File > Settings > Build, Execution , Deployment >
Global Gradle settings
Disable offline work
| |
doc_23538582
|
For example:
interface TestProps {
foo: string;
}
const TestComponent extends React.Component<TestProps, {}> {
render() { return null; }
}
// now I need to create a type using conditional types so that
// I can pass either the component or the props and always get the
// TProps type back
type ExtractProps<TComponentOrTProps> = /* ?? how to do it? */
type a = ExtractProps<TestComponent> // type a should be TestProps
type b = ExtractProps<TestProps> // type b should also be TestProps
Is this possible, and can anybody provide a solution?
A: It's a pretty straight forward application of conditional types and their inference behavior (using the infer keyword)
interface TestProps {
foo: string;
}
class TestComponent extends React.Component<TestProps, {}> {
render() { return null; }
}
type ExtractProps<TComponentOrTProps> = TComponentOrTProps extends React.Component<infer TProps, any> ? TProps : TComponentOrTProps;
type a = ExtractProps<TestComponent> // type a is TestProps
type b = ExtractProps<TestProps> // type b is TestProps
A: There's a built-in helper for that
type AnyCompProps = React.ComponentProps<typeof AnyComp>
And it also works for native DOM elements:
type DivProps = React.ComponentProps<"div">
https://stackoverflow.com/a/55005902/82609
A: I'd suggest to use React.ComponentType, because it will also include functional components:
type ExtractProps<TComponentOrTProps> =
TComponentOrTProps extends React.ComponentType<infer TProps>
? TProps
: TComponentOrTProps;
| |
doc_23538583
|
After maybe 2 weeks, stickers stopped work on my iPhone as well as iPhone of my brother. I have to delete it, and install it again.
Is there any time limit of the provisioning profile, how long it works without dev account?
A: The free provisioning expires in 7 days (previously it was 90 days), you can see the expiration date in Xcode selecting the i icon near the provisioning profile like in this image:
| |
doc_23538584
|
When I press Start debugging all the possibly windows (watch 1 - 4), data sources, properties, registers (to be honest I have not even ever seen these windows before) appear in front of the code window and stay there after I stop the debugger.
Anyone has an idea what could be causing this ? (I am using CodeRush and Refactor for quite a while now)
When I close and restart visual studio all the windows are where they should be.
PS: Previously I have seen normal switching from normal to debug mode and back with some repositioning changes. That is the way it used to work. Now it is not. It has suddenly gone mad and when going to the debug mode it sometimes shows all possible IDE windows and sometimes not. When it does it no longer returns to the previous state. I cannot find this in the options anywhere.
A: Visual Studio remembers 2 sets of window layouts, normal mode and debugging mode. My solution is to arrange my normal windows exactly like I want them, then start debugging an application and once again arrange all of the windows the way I want, usually making it as similar to my normal layout as possible, then stopping the debugger and doing a File Exit so that VS saves my settings.
After doing that, it recalls my 2 different layouts each time.
A: I'm experiencing the same thing - whenever the debugger is running, switching focus back to the IDE immediately caused the debug panel to expand.
I ended up just pinning the debug panel so that it always appears when debugging, and just changing its height as needed.
A: To add to palehorse, another tip is Full Screen mode.
| |
doc_23538585
|
Please if there is anyone who has a clear and simple example of the integration (form submit and saving in DB) I will be extremely thankful!
If you could put the simple project in a ZIP and upload it (with its jars it will be great)
Thank you!
A: I guess this one using gwt 2.5.0-rc1, Spring 3.1.2.RELEASE and Hibernate 4 will be helpful. This project is using maven, so install maven which will take care of required dependencies. git clone it, command-line build with $ mvn clean install and dive into.
The basic gwt server-shared-client architecture is
Entity
@Entity
@Table(name = "TBL_BOOK")
public class Book implements Serializable {
private static final long serialVersionUID = -687874117917352477L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID")
private Long id;
@Column(name = "TITLE", nullable = false)
private String title;
@Column(name = "SUBTITLE")
private String subtitle;
@Column(name = "AUTOR", nullable = false)
private String autor;
@Column(name = "DESCRIPTION")
private String description;
@Column(name = "ISBN")
private String isbn;
@Column(name = "GENRE")
private String genre;
@Temporal(TemporalType.DATE)
@Column(name = "PUBLISHED_DATE")
private Date publishedDate;
@Column(name = "PUBLISHER")
private String publisher;
public Book() {
}
public Book(Long id, String title, String subtitle, String autor,
String description, String isbn, String genre, Date publishedDate,
String publisher) {
this.id = id;
this.title = title;
this.subtitle = subtitle;
this.autor = autor;
this.description = description;
this.isbn = isbn;
this.genre = genre;
this.publishedDate = publishedDate;
this.publisher = publisher;
}
public Book(Book bookDTO) {
this.id = bookDTO.getId();
this.title = bookDTO.getTitle();
this.subtitle = bookDTO.getSubtitle();
this.autor = bookDTO.getAutor();
this.description = bookDTO.getDescription();
this.isbn = bookDTO.getIsbn();
this.genre = bookDTO.getGenre();
this.publishedDate = bookDTO.getPublishedDate();
this.publisher = bookDTO.getPublisher();
}
//getters and setters
@Override
public String toString() {
return "Book [id=" + id + ", title=" + title + ", subtitle=" + subtitle
+ ", author=" + autor + ", description=" + description
+ ", isbn=" + isbn + ", genre=" + genre + ", publishedDate="
+ publishedDate + ", publisher=" + publisher + "]";
}
}
web configuration
<!-- SpringGwt remote service servlet -->
<servlet>
<servlet-name>springGwtRemoteServiceServlet</servlet-name>
<servlet-class>org.spring4gwt.server.SpringGwtRemoteServiceServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>springGwtRemoteServiceServlet</servlet-name>
<url-pattern>/GwtSpringHibernate/springGwtServices/*</url-pattern>
</servlet-mapping>
Client side stub for RPC
/**
* The client side stub for the RPC service.
*/
@RemoteServiceRelativePath("springGwtServices/bookService")
public interface BookService extends RemoteService {
public void saveOrUpdate(Book book) throws Exception;
public void delete(Book book) throws Exception;
public Book find(long id);
public List<Book> findAllEntries();
}
Server
@Service("bookService")
public class BookServiceImpl extends RemoteServiceServlet implements BookService {
private static final long serialVersionUID = -6547737229424190373L;
private static final Log LOG = LogFactory.getLog(BookServiceImpl.class);
@Autowired
private BookDAO bookDAO;
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void saveOrUpdate(Book book) throws Exception {
//
}
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void delete(Book book) throws Exception {
//
}
public Book find(long id) {
return bookDAO.findById(id);
}
public List<Book> findAllEntries() {
//
}
}
Client View
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class GwtSpringHibernate implements EntryPoint {
/**
* The message displayed to the user when the server cannot be reached or
* returns an error.
*/
private static final String SERVER_ERROR = "An error occurred while "
+ "attempting to contact the server. Please check your network "
+ "connection and try again.";
/**
* Create a remote service proxy to talk to the server-side Book service.
*/
private final BookServiceAsync bookService = GWT.create(BookService.class);
/**
* This is the entry point method.
*/
public void onModuleLoad() {
DateBox.DefaultFormat defaultFormatter = new DateBox.DefaultFormat(DateTimeFormat.getFormat("dd.MM.yyyy"));
// Add new Book Area
final TextBox titleField = new TextBox();
titleField.setFocus(true);
final TextBox subtitleField = new TextBox();
final TextBox autorField = new TextBox();
final TextBox descriptionField = new TextBox();
final TextBox isbnField = new TextBox();
final TextBox genreField = new TextBox();
final DateBox publishedDateField = new DateBox();
publishedDateField.setFormat(defaultFormatter);
final TextBox publisherField = new TextBox();
final Button saveButton = new Button("Save");
saveButton.addStyleName("button");
final Button retrieveButton = new Button("Retrieve");
retrieveButton.addStyleName("button");
final Label errorLabel = new Label();
// Add fields to the Rootpanel
RootPanel.get("title").add(titleField);
RootPanel.get("subtitle").add(subtitleField);
RootPanel.get("autor").add(autorField);
RootPanel.get("description").add(descriptionField);
RootPanel.get("isbn").add(isbnField);
RootPanel.get("genre").add(genreField);
RootPanel.get("publishedDate").add(publishedDateField);
RootPanel.get("publisher").add(publisherField);
RootPanel.get("btnSave").add(saveButton);
RootPanel.get("btnRetrieveAllEntries").add(retrieveButton);
RootPanel.get("errorLabelContainer").add(errorLabel);
// Create the popup dialog box
final DialogBox dialogBox = new DialogBox();
dialogBox.setText("Remote Procedure Call");
dialogBox.setAnimationEnabled(true);
final Button closeButton = new Button("Close");
// We can set the id of a widget by accessing its Element
closeButton.getElement().setId("closeButton");
final Label textToServerLabel = new Label();
final HTML serverResponseLabel = new HTML();
VerticalPanel dialogVPanel = new VerticalPanel();
dialogVPanel.addStyleName("dialogVPanel");
dialogVPanel.add(new HTML("<b>Sending request to the server:</b>"));
dialogVPanel.add(textToServerLabel);
dialogVPanel.add(new HTML("<b>Server replies:</b>"));
dialogVPanel.add(serverResponseLabel);
dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
dialogVPanel.add(closeButton);
dialogBox.setWidget(dialogVPanel);
// Add a handler to close the DialogBox
closeButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
dialogBox.hide();
saveButton.setEnabled(true);
saveButton.setFocus(true);
retrieveButton.setEnabled(true);
}
});
class SaveBookHandler implements ClickHandler, KeyUpHandler {
public void onKeyUp(KeyUpEvent event) {
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
saveBook();
}
}
public void onClick(ClickEvent arg0) {
saveBook();
}
private void saveBook() {
errorLabel.setText("");
String _title = titleField.getText();
String _subtitle = subtitleField.getText();
String _autor = autorField.getText();
String _desc = descriptionField.getText();
String _isbn = isbnField.getText();
String _genre = genreField.getText();
Date _publishedDate = publishedDateField.getValue();
String _publisher = publisherField.getText();
// First, we validate the input.
if (Validator.isBlank(_title) || Validator.isBlank(_autor)) {
String errorMessage = "Please enter at least the Title and the Autor of the book";
errorLabel.setText(errorMessage);
return;
}
Book bookDTO = new Book(null, _title, _subtitle, _autor, _desc, _isbn, _genre, _publishedDate, _publisher);
saveButton.setEnabled(false);
serverResponseLabel.setText("");
textToServerLabel.setText(bookDTO.toString());
bookService.saveOrUpdate(bookDTO, new AsyncCallback<Void>() {
public void onFailure(Throwable caught) {
dialogBox.setText("Remote Procedure Call - Failure");
serverResponseLabel.addStyleName("serverResponseLabelError");
serverResponseLabel.setHTML(SERVER_ERROR + caught.toString());
dialogBox.center();
closeButton.setFocus(true);
}
public void onSuccess(Void noAnswer) {
dialogBox.setText("Remote Procedure Call");
serverResponseLabel.removeStyleName("serverResponseLabelError");
serverResponseLabel.setHTML("OK");
dialogBox.center();
closeButton.setFocus(true);
}
});
}
}
// Add a handler to send the book info to the server
SaveBookHandler saveBookHandler = new SaveBookHandler();
saveButton.addClickHandler(saveBookHandler);
publisherField.addKeyUpHandler(saveBookHandler);
// Create a handler for the retrieveButton
class RetrieveAllEntriesHandler implements ClickHandler {
/**
* Fired when the user clicks on the retrieveButton.
*/
public void onClick(ClickEvent event) {
retrieveAllEntries();
}
private void retrieveAllEntries() {
// Nothing to validate here
// Then, we send the input to the server.
retrieveButton.setEnabled(false);
errorLabel.setText("");
textToServerLabel.setText("");
serverResponseLabel.setText("");
bookService.findAllEntries(
new AsyncCallback<List<Book>>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
dialogBox.setText("Remote Procedure Call - Failure");
serverResponseLabel.addStyleName("serverResponseLabelError");
serverResponseLabel.setHTML(SERVER_ERROR + caught.toString());
dialogBox.center();
closeButton.setFocus(true);
}
public void onSuccess(List<Book> data) {
dialogBox.setText("Remote Procedure Call");
serverResponseLabel.removeStyleName("serverResponseLabelError");
if(data != null && !data.isEmpty()){
StringBuffer buffer = new StringBuffer();
for (Book book : data) {
buffer.append(book.toString());
buffer.append("<br /><br />");
}
serverResponseLabel.setHTML(buffer.toString());
} else {
serverResponseLabel.setHTML("No book information store in the database.");
}
dialogBox.center();
closeButton.setFocus(true);
}
});
}
}
// Add a handler
RetrieveAllEntriesHandler retrieveAllEntriesHandler = new RetrieveAllEntriesHandler();
retrieveButton.addClickHandler(retrieveAllEntriesHandler);
}
}
For more widgets, go through official widget library, UiBinder.
A: 1) Download the zip file cited above from https://github.com/chieukam/gwt-spring-hibernate-tutorial/archive/master.zip and extract it somewhere
2) In Eclipse, create a new Maven project. Since there is no .project file provided in the above zip, you will need to confiugre all this manually.
3) Import "File System" from the place where you unzipped this project into your new Maven project.
At this point, I have some errors:
*
*BookServiceAsync appears to be nonexistent, resulting in 6 compile errors.
*"Plugin execution not covered by lifecycle configuration: org.apache.maven.plugins:maven-war-plugin:2.1.1:exploded (execution: default, phase: compile)" in pom.xml, lines 162 and 185
This example seems to be somewhat incomplete. Am I missing something??
| |
doc_23538586
|
The following function is located in the controller class of the project.
public void callSearch(){
Stage supplyStage = new Stage();
Parent root = null;
try {
root = FXMLLoader.load(getClass().getResource("supplyResult.fxml"));
supplyStage.setTitle("Supply Result Set");
supplyStage.setScene(new Scene(root, 1400, 900));
supplyStage.show();
} catch (IOException e) {
e.printStackTrace();
}
try {
typeColumn.setCellValueFactory(new PropertyValueFactory<Supply, String>("type"));
nameColumn.setCellValueFactory(new PropertyValueFactory<Supply, String>("name"));
dateColumn.setCellValueFactory(new PropertyValueFactory<Supply, String>("order_date"));
pricePerUnitColumn.setCellValueFactory(new PropertyValueFactory<>("pricePerUnit"));
quantityColumn.setCellValueFactory(new PropertyValueFactory<>("quantity"));
}
catch (NullPointerException npe){
System.out.println("Null...");
}
searchSupplyStartDate = java.sql.Date.valueOf(startDateDatePicker.getValue());
searchSupplyEndDate = java.sql.Date.valueOf(endDateDatePicker.getValue());
tableOutput.setItems(myMain.getSupplies(searchSupplyStartDate,searchSupplyEndDate,null,null));
}
My problem is that I get a NullPointerException in the line typeColumn.setCellValueFactory(new PropertyValueFactory<Supply, String>("type"));
In previous version of the application I had the columns in the same window as the rest of the scene. Now I try to add a second window when displaying the same stuff, to make the first scene a bit more beautiful. (the code was working when I had one scene).
In fact, to make things clear, i want with the press of a button, the function callSearch() to be called. Then a window appears, with a table of 5 columns attached: typeColumn, nameColumn, dateColumn, pricePerUnitColumn, quantityColumn. Those 5 columns are declared in the (only) controller of the project, so i thought that they are visible in any fxml file in the project, but that's not the case.
Does anybody know what am I missing? the typeColumn is visible from the SupplyResult.fxml in scene builder, but does not seem to execute the code it has to...
| |
doc_23538587
|
1.
"""
SELECT a.id, a.body, a.owner_user_id
FROM `bigquery-public-data.stackoverflow.posts_questions` AS q
INNER JOIN `bigquery-public-data.stackoverflow.posts_answers` AS a
ON q.id = a.parent_id
WHERE q.tags LIKE '%bigquery%'
"""
*
"""
SELECT a.id, a.body, a.owner_user_id
FROM `bigquery-public-data.stackoverflow.posts_answers` AS a
INNER JOIN `bigquery-public-data.stackoverflow.posts_questions` as q
ON q.id = a.parent_id
WHERE q.tags LIKE "%bigquery%"
"""
I know that the second one is way more expensive. I want to know why this is the case.
My guess - In 1 post_questions is retrieved first, and we need to loop over only the question ids, but in 2 we need to loop over the answer parent ids. Since there are way more answers than questions, second one turns out be more expensive.
Am I right? Also, am I right in assuming that the end result of the two queries would be the same?
A: The two queries are syntactically equivalent (so they do produce the same results). I don’t know what makes you think that one is more expensive than the other, but it is surely not the case.
SQL is a descriptive language, as opposed to a procedural language. You tell the database the results you want, and let it decide how to proceed. The query planner parses the query and produces the execution plan it thinks is best. It will happily "start" from one table or the other, regardless of the order in which they appear in the query.
A: The two should have exactly the same cost in BigQuery. I am assuming that you are using "on-demand" pricing, because the question would not be appropriate for a flat-rate pricing model.
BigQuery charges on the number of bytes that are read to process the query, not on the complexity of the query. In fact, multiple references to the same table do not affect the price. However, the number of columns referenced does affect the price.
Both queries are referring to the same tables and columns, so the cost should be the same.
You can review how BigQuery calculates prices in the documentation.
| |
doc_23538588
|
"Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying await operation. "
| |
doc_23538589
|
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
if current_user
self.current_user = current_user
logger.add_tags current_user.name
end
end
end
end
gives me
There was an exception - NoMethodError(undefined method `name' for nil:NilClass)
Equivalent to the ApplicationController I included the SessionHelper in channels/application_cable/connection.rb
module ApplicationCable
class Connection < ActionCable::Connection::Base
include SessionsHelper
identified_by :current_user
# (..)
end
end
but doesn't work.
A: As you can see in the notesof the official documentation the cable can not access the session. In this article, cited in the notes, you can find a way to use cookies for managing athentication
| |
doc_23538590
|
I have successfully implemented this with a visual search before with ${whatever} == 0 ||${whatever2} == 0 || but can the same theory be applied to multiple verifyelementnotpresent?
the formulas I have in uivision for the visual verify are:
{
"Command": "visualVerify",
"Target": "status2_dpi_96.png@1",
"Value": "",
"Description": ""
},
{
"Command": "store",
"Target": "1",
"Value": "!timeout_wait",
"Description": ""
},
{
"Command": "visualSearch",
"Target": "registration_dpi_96.png@1",
"Value": "registration",
"Description": ""
},
{
"Command": "visualSearch",
"Target": "submission_dpi_96.png@1",
"Value": "submission",
"Description": ""
},
{
"Command": "visualSearch",
"Target": "debt_dpi_96.png@1",
"Value": "debt",
"Description": ""
},
{
"Command": "visualSearch",
"Target": "[email protected]",
"Value": "documents",
"Description": ""
},
{
"Command": "if_v2",
"Target": "${registration} == 0 || ${submission} == 0 || ${debt} == 0 || ${documents} == 0",
"Value": "",
"Description": ""
},
but now instead of visual search, I want a ifelementnotpresent with the elements xpath and a name:
{
"Command": "verifyElementNotPresent",
"Target": "/html/body/div[2]/form/div/div[1]/div[2]/div[1]/div[3]/div[${!times}]/div[3]/div[2]/div/div[2]/div/a",
"Value": "others",
"Description": "reconcile"
},
{
"Command": "verifyElementNotPresent",
"Target": "/html/body/div[2]/form/div/div[1]/div[2]/div[1]/div[3]/div[${!times}]/div[3]/div[4]/div[1]/label",
"Value": "suggestion",
"Description": "reconcile2"
},
{
"Command": "if_v2",
"Target": "${!LastCommandOk} == false",
"Value": "if no potential others",
"Description": ""
},
so in the above, I would prefer it check if element 1 or element 2 are not there, and both these are true, then press a different element, but nowhere in uivision/selenium do I see it keep record/count of an element like it does with the visual aspects, and no I cannot use a visual element here as it is duplicated up to 10 times and these elements have to be referenced in a specific order.
| |
doc_23538591
|
It's quite obvious that Yesod currently supports a lot more features than Snap. However, I can't stand the syntax Yesod uses for its HTML, CSS and Javascript.
So, I'd like to understand what I'd be missing if I went with Snap instead. For example, doesn't look like database support is there. How about sessions? Other features?
A: Give hamlet a try- you might end up liking it. A negative reaction at a superficial level is not uncommon. However, nobody that has actually used hamlet complains.
Also, why not use Happstack? Just because they aren't "in the news" doesn't mean they don't have a solid framework.
A: Full disclosure: I'm one of the lead developers of Snap.
First of all, let's talk about what Snap is. Right now the Snap team maintains five different projects on hackage: snap-core, snap-server, heist, snap, and xmlhtml. snap-server is a web server that exposes the API defined by snap-core. heist is a templating system. xmlhtml is an XML/HTML parsing and rendering library used by heist. snap is an umbrella project that glues them all together and provides the powerful snaplets API that makes web apps composable and modular.
Yesod has a host of projects on hackage. Most (all?) of them are listed in the Yesod category. Some of the notable ones are yesod-core, warp, persistent, and hamlet.
The reality of Haskell web development is that it's much less of an exclusive-or choice than seems to be perceived. In general the projects are very loosely coupled and fairly interchangeable. You could build a website using warp (the Yesod team's web server), heist (the Snap team's template system), and acid-state (the Happstack project's persistence system). You could also use snap-server with hamlet or persistent.
That said, the two projects definitely have some differences. The biggest difference I can point out objectively is that Yesod projects typically make heavy use of Template Haskell and quasiquoting to create concise DSLs, while Snap projects stick to building combinator libraries that favor composability. Just about any other differences I can think of will be subjectively biased towards Snap. The umbrella packages named after both projects are obviously going to make specific choices for the above mentioned components, and these choices will be reflected in the project dependencies. But that still doesn't mean that you can't pull in something different and use it as well.
Snap does have sessions and authentication, interfaces to several databases, and nice form handling (here and here) using digestive-functors that includes prepackaged support for arbitrarily nested dynamically sizable lists. These are just some of the growing ecosystem of pluggable snaplets. The sessions and authentication snaplets are written in a way that is back-end agnostic. So with a small amount of glue code you should be able to use it with just about any persistence system you can think of. In the future, Snap will stick with this policy as often as possible.
For the most part I think the choice of Snap vs Yesod vs Happstack is less an issue of features and more one of personal taste. Whenever someone says that one of the frameworks doesn't have something that another one has, most of the time it will be pretty easy to pull in the missing functionality from the other framework by importing the necessary package.
EDIT: For a more detailed comparison of the big three Haskell web frameworks check out my recent blog post. For a rougher (but possibly more useful) comparison using some broader generalizations, see my Haskell Web Framework Comparison Matrix
A: Fair warning: I'm the lead developer of Yesod.
I'm not sure what you don't like about the Javascript syntax: it is plain javascript with variable interpolation. As for CSS Yesod now has Lucius which allows you to also use plain CSS. For HTML, you can easily use any other library you want, including Heist (what Snap uses). That said, it's a bit of a funny thing to skip Yesod over CSS/Javascript syntax, when Snap doesn't even have a syntax for it. You are certainly welcome to their solution of just static files.
Yesod comes with seamless support for authentication/authorization, type-safe URLs, widgets, email, and a bunch of little things all over the place (breadcrumbs, messages, ultimate destination). Plus, Yesod has a fairly rich set of add-on packages for things like comments and markdown, and a few large real-world code bases to pick at for examples. If any of these are attractive to you, you might want to check if your alternatives supports them.
A: You probably referring to old version of yesod. Latest yesod versions have plain syntax for html, javascript and css.
The html syntax of yesod's template library hamlet is plain html with complete opening and closing tags and all normal html attributes. Yes you can omit closing tags and use shortcuts for id and class attributes. But you do not have to. You can continue to write plain html.
Not only that but html templates can reside in separate files, just like in Snap's template library Heist.
Java script templates (julius) are plain javascript files, also residing in separate files.
The css template does indeed have a different syntax, but recent version of yesod now provides also plain css syntax.
If you go with Heist you will not have type safe urls.
In Heist html templates are read from harddrive everytime. Yesod compiles all templates directly into the executable. No file is read from harddrive. Thus the response is much faster. You can see the benchmarks yourself.
In Yesod you can create widgets that cooperate nicely. Snap does not deal with widgets at all. You will have to roll your own.
| |
doc_23538592
|
Traceback (most recent call last):
File "/Users/sebpole/Documents/EvalPrimePallindrome.py", line 43, in <module>
if GPF(c) == c:
File "/Users/sebpole/Documents/EvalPrimePallindrome.py", line 37, in GPF
la = fac(int(la))
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
Which I believe means at some point in my program an integer is being turned into not-an-integer and then plugged into a function that needs an integer? Not really sure where that's happening though...Here's the code:
#Find the largest prime palindrome less than 1000
primePalis = []
def isolate(x, y):
x = str(x)
r = x[len(x)-y]
return int(r)
def palcheck(x):
i=1
while i < len(str(x)):
if isolate(x, i) != isolate(x, len(str(x))-i+1):
return 0
i = i+1
return 1
def fac(x):
a = 2
while a <= x:
if a**2 > x:
return 0
break
elif x%a == 0:
return x/a
break
if a!=2:
a = a+2
elif a == 2:
a = a+1
def GPF(x):
la = fac(x)
lb = la
if la == 0:
return x
while la != 0:
lb = la
la = fac(la)
return lb
c = 1
while c <= 1000:
if palcheck(c) == 1:
if GPF(c) == c:
primePalis.append(c)
c = c+1
print(max(primePalis))
Any ideas what's going on?
Side note: Is there an easier way to get the website to recognize my code as code that's not manually hitting the space bar four times before every line of my code?
A: The function fac() doesn't doesn't explicitly return anything if control reaches the end, so it returns None.
A simple fix is to add return a at the end:
def fac(x):
a = 2
#...
if a!=2:
a = a+2
elif a == 2:
a = a+1
return a
A: The la = fac(int(la)) error line doesn't really seem to be preset in the code you posted, but the problem probably is that fac(1) doesn't return anything, which means its return value is None.
| |
doc_23538593
|
The UI is basic. On the main view, a label will read On in green (if the switch is on) and Off in red (if the switch is off.) There is a setting button in the top right that will segue (settingsSegue) to the settings UITableViewController, where the UISwitch is located.
The problem is loading up the NSUserDefault once the app loads. In viewDidLoad, I check to see if there's a value saved for the switch key. If there is, load it up. If not, set it to false (in the storyboard, the switch is set to false as default.) The Switch Status loads up as Off every time. Even if the default value is On. This shouldn't be happening.
ViewController.swift:
import UIKit
var nsDefaults = NSUserDefaults.standardUserDefaults()
class ViewController: UIViewController, SettingsViewControllerDelegate {
var onFromMain = Bool()
@IBOutlet weak var switchStateLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
if let mySavedKey = nsDefaults.objectForKey("savedSwitchSettingDefault") {
// A value exists. Load it up.
nsDefaults.objectForKey("savedSwitchSettingDefault")
print("The switch is set! \(mySavedKey)")
checkSwitchState()
}
else {
// Nothing stored in NSUserDefaults yet. Set switch to False.
nsDefaults.setBool(false, forKey: "savedSwitchSettingDefault")
checkSwitchState()
}
}
func myVCDidFinish(controller: SettingsViewController, switchState: Bool) {
onFromMain = switchState.boolValue
checkSwitchState()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "settingsSegue" {
let nav = segue.destinationViewController as! UINavigationController
let secondVC = nav.topViewController as! SettingsViewController
secondVC.delegate = self
}
}
func checkSwitchState() {
if onFromMain {
switchStateLabel.text = "On"
switchStateLabel.textColor = UIColor.greenColor()
}
else {
switchStateLabel.text = "Off"
switchStateLabel.textColor = UIColor.redColor()
}
}
}
SettingsViewController.swift:
import UIKit
protocol SettingsViewControllerDelegate {
func myVCDidFinish(controller: SettingsViewController, switchState: Bool)
}
class SettingsViewController: UITableViewController {
var delegate: SettingsViewControllerDelegate? = nil
@IBOutlet weak var switchOutlet: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
switchOutlet.on = nsDefaults.boolForKey("savedSwitchSettingDefault")
}
@IBAction func closeSettingsPageBarButtonItemPressed(sender: UIBarButtonItem) {
if (delegate != nil) {
delegate!.myVCDidFinish(self, switchState: switchOutlet.on)
self.dismissViewControllerAnimated(true, completion: nil)
}
}
@IBAction func switchPressed(sender: UISwitch) {
// Tap the switch to change the setting.
nsDefaults.setBool(switchOutlet.on, forKey: "savedSwitchSettingDefault")
}
}
I believe my problem lies somewhere in loading up the default key for "savedSwitchSettingDefault". Is this correct? Or does the issue lie elsewhere in the code?
A: You can tidy things up quite a bit by relying on the fact that the default you want is false and that boolForKey gives you false when the key isn't present.
Also, by accessing the setting in viewWillAppear you can avoid the need for the delegate callback.
ViewController.swift
import UIKit
class ViewController: UIViewController {
let nsDefaults = NSUserDefaults.standardUserDefaults()
var onFromMain = false
@IBOutlet weak var switchStateLabel: UILabel!
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.onFromMain = self.nsDefaults.boolForKey("savedSwitchSettingDefault")
self.checkSwitchState()
}
func checkSwitchState() {
if self.onFromMain {
switchStateLabel.text = "On"
switchStateLabel.textColor = UIColor.greenColor()
}
else {
switchStateLabel.text = "Off"
switchStateLabel.textColor = UIColor.redColor()
}
}
}
SettingsViewController.swift:
import UIKit
class SettingsViewController: UITableViewController {
let nsDefaults = NSUserDefaults.standardUserDefaults()
@IBOutlet weak var switchOutlet: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.switchOutlet.on = self.nsDefaults.boolForKey("savedSwitchSettingDefault")
}
@IBAction func closeSettingsPageBarButtonItemPressed(sender: UIBarButtonItem) {
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func switchPressed(sender: UISwitch) {
// Tap the switch to change the setting.
self.nsDefaults.setBool(self.switchOutlet.on, forKey: "savedSwitchSettingDefault")
}
}
A: When retrieving the bool value from User Defaults, boolForKey will return false if the value doesn't exist. So in this case there's no need for unwrapping. From the documentation:
If a boolean value is associated with defaultName in the user defaults, that value is returned. Otherwise, false is returned.
If the value is getting set (you are sure of it), and the behavior of the app is not working correctly your problem might lie elsewhere.
I would recommend using another approach, declare your "onFromMain" as an optional boolean, then unwrap it when you need it.
var onFromMain: Bool?
...
func checkSwitchState() {
//- This will unwrap your optional or set false if its nil
let switchSate = onFromMain ?? false
//- Then you can set the values based on the value (or the default false)
switchStateLabel.text = switchState ? "On" : "Off"
switchStateLabel.textColor = switchState ? UIColor.greenColor() : UIColor.redColor()
}
Then attach the debugger with a breakpoint and see if the value is being unwrapped or if its defaulting to false.
Also, you are setting your delegate only when the segue is called, depends of the scenario, and if i understand you correctly, you migt not get the value until you have actually navigated to the settings view. So when opening the app (without navigating to the settings view) the onFromMain will never get populated.
Alternatively you can fetch the value on the view did load method to get it straight away when you load the app.
| |
doc_23538594
|
The permissions granted to user are insufficient for performing this operation (rsAccessDenied)
Then I changed the internet explorer local intranet settings (user authentication --> logon) but didn't get the reports.
Kindly help me solve this issue.
A: You need to grant access rights to user you're accessing the reports server.
There are MSDN tutorials for that: 1, 2, but short steps are:
*
*Open reports portal.
*Go to Settings page -> Security tab, and add your domain\user to the list of users as administrator.
*Go to reports page again.
*Click Manage folder, on opened page open Security tab.
*Add your domain\user to the list of users with all available premissions.
If you can't open reports portal in Chrome, try to access it in IE, and if it's not working, try to run IE as administrator.
| |
doc_23538595
|
var pageviews = [
[1, 0]
];
$.get("http://bla..bla",
function(res){
pageviews.push([2, res.value]);
}, "json");
I've checked the pageviews variable but the array is not updated. I can see the "res.value" on my console. So what is the problem?
A: Its most likely, that you check the pageviews array at the wrong spot. Liky any Ajax operation, .get() works asynchronously by default, which means you can't just check that array after the .get() call and expect the data was already updated.
Infact, its not, because it takes a while for the browser and your network to complete the data transfer. If you immediately check your array, after your .push() call, I promise the array was updated as expected.
$.get( /* ... */ );
console.log( pageviews ); // wrong result, the array was not even touched at this point
You might find jQuerys implicit promise objects helpful, you might use it like
$.get( /* ... */ ).done(function( res ) {
pageviews.push([2, res.value]);
console.log(pageviews);
});
That is pretty much the exact same like you already do, but its syntax is probably in a more convenient fashion. The "done()" thing should make it pretty much clear.
Of course, you can also mixup those things (for whatever reason), like
$.get("http://bla..bla", function(res){
pageviews.push([2, res.value]);
}, "json").done(function() {
console.log( pageviews );
});
A: If you are checking pageviews straight after calling $.get, it will 99% of the time not have any change. This is because the request is asynchronous (as opposed to synchronous) meaning that it occurs in the background and lets the main thread of Javascript to keep executing.
Try console.log inside here:
$.get("http://bla..bla",
function(res){
pageviews.push([2, res.value]);
console.log(pageviews); //<-- This will log the updated value to the console
}, "json");
| |
doc_23538596
|
I was thinking about keeping them in a map<pair<k,v>> and to find the pair with minimal v each time I inset a new pair (the amount of additions is very small...).
Each time I will update the v I will compare it the "minimal" pair, and if it is smaller I will update the "minimal" pair.
I there a better solution to this?
A: Your solution only takes into account the situation where a new value becomes lower than the older minimum value.
It will fail if the older minimum value increases, and you have to find the new minimum.
Well I would keep 2 maps:
map<k,v> kKeyMap;
multimap<v,&k> vValueMap;
Use the multimap to get the lowest value (because it can handle multiple k's with the same v).
Like regular map, it's sorted, so acquiring the lowest is just a matter of getting the first item in the map O(1).
On each change, you look up the k with the first map (kKeyMap), and change the value O(logn).
Use the old v value to remove the old (v,k) value from the multimap, then add then new (v,k) value. O(logn)
So, you have O(1) query for lowest, and O(logn) for insert. Assuming n = #k
| |
doc_23538597
|
Currently we're using Kafka but we would like to replace it with Firehose for different reasons (maintenance, cost, etc). I configured API Gateway with Firehose and without any coding I was able to store my requests in S3 in parquet files.
Now comes cost estimation. From Amazon example 500 records/second will cost 216 $ / month. The record size is rounded up to 5Kb. In our case 10K requests/second will cost 20 times more.
Our record size is 1.5k. So it makes sense to package multiple records into one. I did not find an example of how to do it easily. I don't want to implement this application by myself because there are many edge cases to be managed. And for me it seems to be pretty common case which should be already implemented.
Is there a standard way (AWS service, github project, etc) which can be used to package records?
Or is there a better solution to my problem?
| |
doc_23538598
|
So, my problem is this:
I need to split an "&" delimited to string into a list of objects, but I need to account for the values containing the ampersand as well.
Please let me know if you can provide any help.
var subjectA = 'myTestKey=this is my test data & such&myOtherKey=this is the other value';
Update:
Alright, to begin with, thanks for the awesome, thoughtful responses. To give a little background on why I'm doing this, it's to create a cookie utility in JavaScript that is a little more intelligent and supports keys ala ASP.
With that being said, I'm finding that the following RegExp /([^&=\s]+)=(([^&]*)(&[^&=\s]*)*)(&|$)/g does 99% of what I need it to. I changed the RegExp suggested by the contributors below to also ignore empty spaces. This allowed me to turn the string above into the following collection:
[
[myTestKey, this is my test data & such],
[myOtherKey, this is the other value]]
]
It even works in some more extreme examples, allowing me to turn a string like:
var subjectB = 'thisstuff===myv=alue me==& other things=&thatstuff=my other value too';
Into:
[
[thisstuff, ==myv=alue me==& other things=],
[thatstuff, my other value too]
]
However, when you take a string like:
var subjectC = 'me===regexs are hard for &me&you=&you=nah, not really you\'re just a n00b';
Everything gets out of whack again. I understand why this is happening as a result of the regular expression above (kudos for a very awesome explanation), but I'm (obviously) not comfortable enough with regular expressions to figure out a work around.
As far as importance goes, I need this cookie utility to be able to read and write cookies that can be understood by ASP and ASP.NET & vice versa. From playing with the example above, I'm thinking that we've taken it as far as we can, but if I'm wrong, any additional input would be greatly appreciated.
tl;dr - Almost there, but is it possible to account for outliers like subjectC?
var subjectC = 'me===regexs are hard for &me&you=&you=nah, not really you\'re just a n00b';
Actual ouput:
[
[me, ==regexs are hard for &me],
[you, ],
[you, nah, not really you\'re just a n00b]
]
Versus expected output:
[
[me, ==regexs are hard for &me&you=],
[you, nah, not really you\'re just a n00b]
]
Thanks again for all of your help. Also, I'm actually getting better with RegExp... Crazy.
A: If your keys cannot contain ampersands, then it's possible:
var myregexp = /([^&=]+)=(.*?)(?=&[^&=]+=|$)/g;
var match = myregexp.exec(subject);
while (match != null) {
key = match[1];
value = match[2];
// Do something with key and value
match = myregexp.exec(subject);
}
Explanation:
( # Match and capture in group number 1:
[^&=]+ # One or more characters except ampersands or equals signs
) # End of group 1
= # Match an equals sign
( # Match and capture in group number 2:
.*? # Any number of characters (as few as possible)
) # End of group 2
(?= # Assert that the following can be matched here:
& # Either an ampersand,
[^&=]+ # followed by a key (as above),
= # followed by an equals sign
| # or
$ # the end of the string.
) # End of lookahead.
This may not be the most efficient way to do this (because of the lookahead assertion that needs to be checked several times during each match), but it's rather straightforward.
A:
I need to split an "&" delimited to string into a list of objects, but I need to account for the values containing the ampersand as well.
You can't.
Any data format that allows a character to appear both as a special character and as data needs a rule (usually a different way to express the character as data) to allow the two to be differentiated.
*
*HTML has & and &
*URIs have & and %26
*CSV has " and ""
*Most programming languages have " and \"
Your string doesn't have any rules to determine if an & is a delimiter or an ampersand, so you can't write code that can tell the difference.
A: True, rules to differentiate are recommended, and true, a RegExp pattern may fail if a key contains the ampersand -or the equal!- symbol, but it can be done with plain JavaScript. You just have to think in terms of key-value pairs, and live with the fact that there might not be a RegExp pattern to solve the problem: you will have to split the string into an array, loop through the elements and merge them if necessary:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<style id="styleTag" type="text/css">
</style>
<script type="text/javascript">
window.onload = function()
{
// test data
var s = "myTestKey=this is my test data & such&myOtherKey=this is the other value&aThirdKey=Hello=Hi&How are you&FourthKey=that's it!";
// the split is on the ampersand symbol!
var a = s.split(/&/);
// loop through &-separated values; we skip the 1st element
// because we may need to address the previous (i-1) element
// in our loop (you are REALLY out of luck if a[0] is not a
// key=value pair!)
for (var i = 1; i < a.length; i++)
{
// the abscence of the equal symbol indicates that this element is
// part of the value of the previous key=value pair, so merge them
if (a[i].search(/=/) == -1)
a.splice(i - 1, 2, a[i - 1] + '&' + a[i]);
}
Data.innerHTML = s;
Result.innerHTML = a.join('<br/>');
}
</script>
</head>
<body>
<h1>Hello, world.</h1>
<p>Test string:</p>
<p id=Data></p>
<p>Split/Splice Result:</p>
<p id=Result></p>
</body>
</html>
The output:
Hello, world.
Test string:
myTestKey=this is my test data & such&myOtherKey=this is the other value&aThirdKey=Hello=Hi&How are you&FourthKey=that's it!
Split/Splice Result:
myTestKey=this is my test data & such
myOtherKey=this is the other value
aThirdKey=Hello=Hi&How are you
FourthKey=that's it!
A: "myTestKey=this is my test data & such&myOtherKey=this is the other value".split(/&?([a-z]+)=/gi)
This returns:
["", "myTestKey", "this is my test data & such", "myOtherKey", "this is the other value"]
But if this is my test data & such would also contain an = sign, like this is my test data &such= something else, you're out of luck.
A: I suggest you to use
.split(/(?:=|&(?=[^&]*=))/);
Check this demo.
| |
doc_23538599
|
I don't want to waste my time following up each host to diagnose their ip addresses to get them fixed, so I thought about a way to sum it all up in a double click, but google doesn't seem to be helping me this time.
The steps are the following (from the cmd / batch):
1-enable administrative privileges
2-ipconfid /release
3-ipconfig /renew
4-convert the .txt into .bat
I am not sure that there is a step between 1 and 2, if it is mandatory to state the echo on/off.
But what I want to be sure of is, when I open the cmd, then I want to enable the administrative rights to open the local area connection status, and then do the rest.
As I could see that the code to open a file through admin rights is
runas /profile /user:administrator “HERE THE NAME OF THE FILE TO OPEN”
But there is no need to open a specific file to edit them, so if you could help me find the way just to run as admin through the cmd and the rest is easy.
A: You can invoke Powershell from batch file to invoke another batch file to run under elevated privilege.
Launcher.bat
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& { Start-Process "C:\Users\..\AdminProc.bat" -Verb Runas}"
AdminProc.bat
# Run any task that requires elevated privilege.
Net Stop "Sql Server (SQLEXPRESS)"
In second batch file you can run the ipconfig /release and ipconfig /renew with anyother command.
A: Create a .bat or .cmd file past the below save and run as Admin
ipconfig /release
ipconfig /renew
arp -d *
nbtstat -R
nbtstat -RR
ipconfig /flushdns
ipconfig /registerdns
exit
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.