id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_1500
|
package.json:
{
"name": "container",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"export": "next export",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"next": "12.3.0",
"react": "18.2.0",
"react-dom": "18.2.0"
},
"devDependencies": {
"@types/node": "18.7.17",
"@types/react": "18.0.19",
"@types/react-dom": "18.0.6",
"eslint": "8.23.1",
"eslint-config-next": "12.3.0",
"typescript": "4.8.3"
}
}
next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
webpack: (config, options) => {
const { dev } = options;
if (!dev) {
config.output = {
...config.output,
publicPath: '/container/latest/',
};
}
return config;
},
};
module.exports = nextConfig;
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charSet="utf-8"/>
<meta name="viewport" content="width=device-width"/>
<title>container</title>
<meta name="next-head-count" content="3"/>
<link rel="preload" href="/_next/static/css/ab44ce7add5c3d11.css" as="style"/>
<link rel="stylesheet" href="/_next/static/css/ab44ce7add5c3d11.css" data-n-g=""/>
<link rel="preload" href="/_next/static/css/ae0e3e027412e072.css" as="style"/>
<link rel="stylesheet" href="/_next/static/css/ae0e3e027412e072.css" data-n-p=""/>
<noscript data-n-css=""></noscript>
<script defer="" nomodule="" src="/_next/static/chunks/polyfills-c67a75d1b6f99dc8.js"></script>
<script src="/_next/static/chunks/webpack-b0082d3321e5f282.js" defer=""></script>
<script src="/_next/static/chunks/framework-09a2284fdc01dc36.js" defer=""></script>
<script src="/_next/static/chunks/main-017a64f48d901a37.js" defer=""></script>
<script src="/_next/static/chunks/pages/_app-fcb935ebbac35914.js" defer=""></script>
<script src="/_next/static/chunks/pages/index-a059660f80beee89.js" defer=""></script>
<script src="/_next/static/tE04v1pZdHo3sCwUsPHpc/_buildManifest.js" defer=""></script>
<script src="/_next/static/tE04v1pZdHo3sCwUsPHpc/_ssgManifest.js" defer=""></script>
</head>
<body>
<div id="__next"><div class="Home_container__bCOhY"><main class="Home_main__nLjiQ"><p>Hello Next</p></main></div></div><script id="__NEXT_DATA__" type="application/json">{"props":{"pageProps":{}},"page":"/","query":{},"buildId":"tE04v1pZdHo3sCwUsPHpc","nextExport":true,"autoExport":true,"isFallback":false,"scriptLoader":[]}</script>
</body>
</html>
The script tags start with "/_next" but I expect then to start with "/container/latest/_next". Am I misunderstanding how this property works?
Everything works fine in development (obviously) but it breaks in production (because I am deploying to aws s3 and cloudfront and I create a 'folder' structure matching the publicPath above of '/container/latest/' to place the files from the 'out' directory created by running next export.)
A: I think this was my mistake. I should have used assetPrefix instead of trying to change webpack's publicPath property.
next.config.js:
/** @type {import('next').NextConfig} */
const isProd = process.env.NODE_ENV === 'production';
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
assetPrefix: isProd ? '/container/latest/' : undefined,
webpack: (config, options) => {
// config webpack as required...
return config;
},
};
module.exports = nextConfig;
| |
doc_1501
|
A: As of yesterday (NDK r9d), gnustl was still more comprehensive, e.g. support for <thread>, <future>, and some other C++11 features. Even these depend on the toolchain: you could not use the default ARM gcc 4.6 to have them enabled.
OTOH, stlport license is no-nonsense free, like the rest of AOSP, while the linking exception to GPL v3 for gnustl is not easy to understand. See https://groups.google.com/d/topic/android-ndk/OWl_orR0DRQ for some older discussion.
If you look at the NDK release notes, you will find that in terms of fixed bugs these two STL implementations were more or less on par.
I would be glad to see performance benchmarks, but personally I have never encountered a situation where STL implementation variation resolved a real bottleneck.
A: GNU STL is distributed under GPLv3 license which is not acceptable for some people. NDK also provides STLport and it is possible to use it instead, but it is a bit more complicated as standalone tool-chain does not include it.
By default NDK tool-chain will link your C++ shared lib's against a static version of GNU STL lib. However if you are using several shared lib's it is not acceptable to link against the static version of STL as each of your shared lib will have its own copy of STL. This will result in several copies of global vars defined in STL and may lead to memory leak or corruption
IMPORTANT : Using the NDK toolchain directly has a serious limitation:
You won't be able to use any C++ STL (either STLport or
the GNU libstdc++) with it. Also no exceptions and no RTTI.
| |
doc_1502
|
counts =
{(0, 0): {'00': 0, '01': 4908, '10': 0, '11': 5092},
(0, 1): {'00': 0, '01': 5023, '10': 0, '11': 4977},
(1, 0): {'00': 0, '01': 5058, '10': 0, '11': 4942},
(1, 1): {'00': 0, '01': 4965, '10': 0, '11': 5035}}
and I want to sum counts[0,0] and counts [0, 1]to get
idealcounts = {'00': 0, '01': 9931, '10': 0, '11': 10069}
How do I extract the counts[0,r] values and then sum them all up?
Thank you for your help.
A: You can just use collections.Counter and update it with the sub-dictionaries you want:
from collections import Counter
data = {
(0, 0): {'00': 0, '01': 4908, '10': 0, '11': 5092},
(0, 1): {'00': 0, '01': 5023, '10': 0, '11': 4977},
(1, 0): {'00': 0, '01': 5058, '10': 0, '11': 4942},
(1, 1): {'00': 0, '01': 4965, '10': 0, '11': 5035}
}
counts = Counter()
for k in ((0, 0), (0, 1)):
counts.update(Counter(data[k]))
print(counts)
# Counter({'00': 0, '01': 9931, '10': 0, '11': 10069})
| |
doc_1503
|
$('.tooltip-basic').hover(function () {
var title = $(this).attr('title');
$(this).data('title', title).removeAttr('title');
$('<p class="tooltip-basic-message"></p>').text(title).appendTo(this).fadeIn('slow');
}, function () {
$(this).attr('title', $(this).data('title'));
$('.tooltip-basic-message').remove();
});
However, I am struggling to position the arrow under the tooltip, and position the tooltip above its div no matter what height it has.
Here is a Fiddle: http://jsfiddle.net/xA8LS/3/
A: First off, the abbr element should be a block level element.
.tooltip-basic {
position: relative;
display:block;
}
Second, the :before pseudo element should be absolutely positioned - not relatively.
.tooltip-basic-message:before {
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-top: 5px solid #285A98;
content:"";
display:block;
width: 0;
height: 0;
position: absolute;
bottom:-6px;
left: 5px;
z-index: 1;
}
Aside from that, some of the positioning needed to be changed.
Updated Example
Additionally, if you want the arrow centered:
Alternative Example
.tooltip-basic-message:before {
left: 50%;
margin-left: -2.5px;
}
A: in my experience
in some cases tooltip will not display properly because of responsiveness, so if it's an in table item you should use
$('[data-toggle="tooltip"]').tooltip({
container: 'table',
});
| |
doc_1504
|
void fun(void(*problematicFunPointer)(void*) problemFun){
...
}
Then, when I want to use this function like this:
void actualProblematicFun1(struct s_something * smt){
...
}
void actualProblematicFun2(struct s_something_else * smthels){
...
}
int main(){
fun(&actualProblematicFun1);
fun(&actualProblematicFun2);
}
When using -Werror, this throws compile error -Werror=incompatible-pointer-types. Is there a way to suppress warning for this particular case?
A:
Is there a way to suppress warning for this particular case?
Write the actual functions with proper argument type that matches the declaration.
void actualProblematicFun1(struct s_something * smt){
...
}
void actualProblematicFun2(struct s_something_else * smthels){
...
}
void actualProblematicFun1Trampoline(void *smt) {
actualProblematicFun1(smt);
}
void actualProblematicFun2Trampoline(void *smthels) {
actualProblematicFun2(smthels);
}
int main(){
fun(&actualProblematicFun1Trampoline);
fun(&actualProblematicFun2Trampoline);
}
| |
doc_1505
|
!(function () {
let iterator = 0;
let cbs = [];
class Room {
get side() {
const self = this;
return new Proxy([], {
get(t, p) {
return self.sides[p].description;
}
})
}
constructor(sides) {
this.sides = sides;
}
}
class Character {}
function start(roomMap) {
function showRoom(room) {
let finalArray = [
['in this room, there are four doors', '[ ok ]']
];
for (let i in room.sides) {
finalArray.push(['#' + (parseInt(i) + 1) + ': ' + room.side[i], '[ next ]']);
}
follow(...finalArray);
}
showRoom(roomMap);
}
function write(text, subtext = "") {
document.querySelector("#title").innerText = text;
document.querySelector("#subtitle").innerText = subtext;
}
function step(callback) {
cbs.push(callback);
}
function follow(...steps) {
function call(i) {
return function() {
const toCall = call(i + 1);
const st = steps[i];
let shouldContinue = true;
function callIt() {
step(toCall);
}
if (typeof st !== "undefined") {
if (typeof st === "object") {
write(...st);
} else if (typeof st === "function") {
const called = st();
if (called instanceof Promise) {
shouldContinue = false;
write(null, '[ loading... ]');
called.then(callIt);
} else if (typeof called === "object") {
write(...called);
}
}
if (shouldContinue) {
callIt();
}
} else {
write('the end', '[ ok ]');
}
}
}
call(0)();
}
window.onload = function () {
function next() {
const callback = cbs[iterator];
if (typeof callback === "function") {
callback();
iterator++;
}
}
document.querySelector("#subtitle").onclick = next;
document.onkeypress = function(e) {
if (e.key.trim().length === 0 || e.key === 'Enter' || e.key === 'Return') {
next();
}
}
};
follow(
["a game by ezra", "[ ok ]"],
["follow on-screen instructions", "[ ok ]"],
[null, "[ start ]"],
function() {
start(new Room([
{
description: 'creepy description'
},
{
description: 'another creepy description'
},
{
description: 'less creepy description'
},
{
description: 'boring description'
}
]));
}
);
})();
body {
background-color: #000000;
display: flex;
align-items: center;
justify-content: center;
font-family: monospace;
color: #ffffff;
height: 100vh;
flex-direction: column;
user-select: none;
}
#title {
font-size: 25px;
font-weight: 700;
}
#subtitle {
font-size: 18px;
}
#title:not(:empty) + #subtitle:not(:empty) {
margin-top: 10px;
}
#subtitle:hover {
cursor: pointer;
}
<div id="title"></div>
<div id="subtitle"></div>
However, as you can see, it gets stuck after the first press and thinks the game is over. I tried debugging and logging the iterator variable, but it was following the correct order,
meaning there were no hiccups with iterating over the array of callbacks.
So I'm just wondering what I'm doing wrong during the follow function that is referencing an undefined index on the cbs (callbacks) array.
Any help would be appreciated.
| |
doc_1506
|
item 1 ------------------ (54 items)
item 2 ---------------------------------(74 items)
item 2 -------(10 items)
Ideally, I would like the dashes to be replaced by a simple coloured bar.
I've searched Google, but maybe using the wrong search terms. I'd prefer a C# solution but would be happy to use JQuery if required.
A: I'd need a little more information to solve this specifically, but here goes some ideas:
I assume you are rendering a collection of some kind, say in a Repeater or Gridview?
I would recommend a Repeater if you're not using it, as it can do pretty specific things in this situation, here is an example:
<asp:Repeater id=Repeater1 runat="server">
<HeaderTemplate>
<table>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<%# DataBinder.Eval(Container.DataItem, "Name") %>
<span class='backgroundBar' style='width:<%# DataBinder.Eval(Container.DataItem, "Count") %>px;'> </span>
(<%# DataBinder.Eval(Container.DataItem, "Count") %> items)
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
Then
Object[] values = new Object[];
Repeater1.DataSource = values;
Repeater1.DataBind();
And you can replace the dashed line with some kind of div with a background image, or anything styled the way you'd like.
** Make sure you use single quotes in your style property as double quotes will throw an error with the inline code **
| |
doc_1507
|
I read that std::array is stored on the stack even though the count and size of the elements of the size is unknown.
the same way you can't read input of unknown length to the stack from the user.
what am I missing here?
A: To create an std::array you have to specify in its template (or let the compiler deduce) both the count and the type of the elements stored. That makes the size known at compile time, hence it can be instantiated on the stack.
std::array is nothing but a thin wrapper around C-style arrays. The size is fixed, it cannot grow nor shrink.
| |
doc_1508
|
Model
function listProductPerCategory($id, $limit, $start){
$this->db->select('
category.id, category.category, product.id, product.id_category,
product.name, product.picture, product.description, product.permalink, product.part_no
');
$this->db->join('category', 'product.id_category = category.id');
$this->db->where('product.id_category', $id);
$this->db->order_by('product.part_no');
$this->db->limit($limit, $start);
$query = $this->db->get($this->tableProduct);
return $query->result();
}
Controller
function listcategory($page = NULL) {
$id = $this->input->get('list');
$data['categoryHead'] = $this->M_home->listCategory();
$this->load->view('frontend/template/header', $data);
$data['productsLast'] = $this->M_home->listProductLast();
$data['productsLast2'] = $this->M_home->listProductLast2();
$data['category'] = $this->M_home->listCategory();
//paging
$config['base_url'] = base_url('categoryproduct'.'?'.http_build_query($_GET));
$config['total_rows'] = $this->M_home->listProductPerCategory_num_rows($id);
$config['per_page'] = $per_page = 12;
$config['uri_segment'] = 2;
$config['first_link'] = 'First';
$config['last_link'] = 'Last';
$config['next_link'] = 'Next';
$config['prev_link'] = 'Prev';
$config['page_query_string'] = TRUE;
//end paging
$this->pagination->initialize($config);
$data['paging'] = $this->pagination->create_links();
$page = ($this->uri->segment(2)) ? $this->uri->segment(2) : 0;
$data['listCategory'] = $this->M_home->listProductPerCategory($id, $per_page, $page);
$this->load->view('frontend/category', $data);
$this->load->view('frontend/template/footer');
}
A: You have understand that
In SQL LIMIT, start is starting number of record not PAGE.
But from what you passing to listProductPerCategory is page number
So from page 1 to page 2 it is only one record move on next page not 12 records.
So you need to fix in function listProductPerCategory (dont forget to change variable name which may you confuse yourself , change $start -> $page)
So you should get this as below
function listProductPerCategory($id, $limit, $page){
if($page < 1){
$page = 1;
}
if($page > 1){
$start = $limit * $page;
}else{
$start = 0;
}
$this->db->select('
category.id, category.category, product.id, product.id_category,
product.name, product.picture, product.description, product.permalink, product.part_no
');
$this->db->join('category', 'product.id_category = category.id');
$this->db->where('product.id_category', $id);
$this->db->order_by('product.part_no');
$this->db->limit($limit, $start);
$query = $this->db->get($this->tableProduct);
return $query->result();
}
A: Controller -
Try this -
function listcategory($page = 0){
$id = $this->input->get('list');
$data['categoryHead'] = $this->M_home->listCategory();
$this->load->view('frontend/template/header', $data);
$data['productsLast'] = $this->M_home->listProductLast();
$data['productsLast2'] = $this->M_home->listProductLast2();
$data['category'] = $this->M_home->listCategory();
//paging
$config['base_url'] = base_url('categoryproduct'.'?'.http_build_query($_GET));
$config['total_rows'] = $this->M_home->listProductPerCategory_num_rows($id);
$config['per_page'] = $per_page = 12;
$config['num_links'] = 2;
$config['uri_segment'] = 3;
$config['first_link'] = 'First';
$config['last_link'] = 'Last';
$config['next_link'] = 'Next';
$config['prev_link'] = 'Prev';
$config['page_query_string'] = TRUE;
//end paging
$this->pagination->initialize($config);
$data['paging'] = $this->pagination->create_links();
$data['page'] = $page;
// $page = ($this->uri->segment(2)) ? $this->uri->segment(2) : 0;
$data['listCategory'] = $this->M_home->listProductPerCategory($id, $per_page, $page);
$this->load->view('frontend/category', $data);
$this->load->view('frontend/template/footer');
Order by condition is wrong in your model.
Try this -
$this->order_by('title','ASC or DESC or RANDOM');
| |
doc_1509
|
fs.writeFile(bat_filePath, str_to_write, 'utf8', function (err) {
if (err) {
console.log(err);
callback({ success: 1, message: "File writing error" })
} else {
var ls = process.spawn(bat_filePath);
ls.stdout.on('data', function (data) {
});
ls.stderr.on('data', function (data) {
});
ls.on('close', function (code) {
if (code == 0) {
//success code
} else
console.log('Start');
// callback(code)
});
ls.on('exit', function() {
console.log("child process exit")
})
}
});
I am facing error:
The code is executing for first time, but when write another file it cause the below error.
internal/child_process.js:405
throw errnoException(err, 'spawn');
^
Error: spawn EBUSY
at ChildProcess.spawn (internal/child_process.js:405:11)
at spawn (child_process.js:677:9)
at Object.spawnWithSignal [as spawn] (child_process.js:911:17)
at E:\git_clone\imagej\controller\imagej.js:342:30
at FSReqCallback.oncomplete (fs.js:179:23) {
errno: -4082,
code: 'EBUSY',
syscall: 'spawn'
}
| |
doc_1510
|
Here is my coding that I did so far.
For i = 0 To 9
Title = myList(0, i, 0) 'Path of image title inside my array
Img = myList(0, i, 2) 'Path of image url inside my array
If Title <> "" Then
ImageList1.Images.Add("imgKey", New Icon(Img))
ListView1.Items.Add(Title, "imgKey")
End If
Next
Image title is looping normally but the image doesn't loop so if like I got 3 types of images inside my XML file, when display into ListView, all images are shown with the same image (only the first image - refer to my XML file).
Why is it like that? I'm looking forward your help. Thank you.
A: Thank you so much to @Steven Doggart for the solution.
Here is my coding that working all fine now.
For i = 0 To 9
Title = myList(0, i, 0) 'Path of image title inside my array
Img = myList(0, i, 2) 'Path of image url inside my array
If Title <> "" Then
ImageList1.Images.Add("imgKey" & i, New Icon(Img))
ListView1.Items.Add(Title, "imgKey" & i)
End If
Next
| |
doc_1511
|
plugin.xml
<extension
point="org.eclipse.help.toc">
<toc
file="HelpToc.xml"
primary="true">
</toc>
</extension>
HelpToc.xml
<?xml version="1.0" encoding="UTF-8"?>
<?NLS TYPE="org.eclipse.help.toc"?>
<toc label="Enide Maven README" topic=".README.md.html">
</toc>
Then help .html is created with GFMV plugin in .md file:
Is there way to redefine help .html file file location programmatically?
The goal is to enable taking Help content from generated at runtime docs (e.g. JavaDocs .htmls)
A: I haven't dug into it much, but have you checked out the tocProvider attribute of the org.eclipse.help.toc extension point?
A: An alternative is to have a help plugin that only defines anchors, then you can generate separate plugins with the help content you want and just hook into the anchors. That way you will also achieve separation between the actual table of contents and the help contents.
| |
doc_1512
|
A: If you want to login in website in a browser, using Facebook account from Facebook app - it is impossible, without intermediary application, or service. And even with it, I don't think, that you can get user login data.
Other approach - is try to launch Facebook app from your site, and show site from it, but again, you can't login to it, using app.
Why? Because the app, holds only token data, and nothing more. You can't get other information, like password, or email. Also, the work of browser, that save cookies and the app, that save token is different. You can't connect them together.
A: Clearly speaking it is not possible using website in browser.
Even it is also not possible if you develop any android app, the reason is that the facebook app will not share any data to any other app (even if it is running on the same device).
I also don't think that launching the facebook app from browser will be feasible for you, as you just want to use the facebook login system and then want the users back on your website (and again facebokk will not send any data to your web or app even if it is launched from your web or app).
A: I think it's not possible, because we wont link browser and an app.
I developed one android app with facebook login integration.If facebook native app already logged in, now i click my app facebook login button it directly redirect my app to my home page without asking fb username and password.
For me i used localStorage in javascript
localStorage.setItem("userName", userName);
localStorage.setItem("password", password);
var uname=localStorage.getItem('userName');
var pass=localStorage.getItem('password');
| |
doc_1513
|
SELECT FireEvent.ExerciseID,
FireEvent.FireEventID,
tempHitEvent.HitEventID,
FireEvent.AssociatedPlayerID,
tempHitEvent.AssociatedPlayerID,
FireEvent.EventTime,
tempHitEvent.EventTime,
FireEvent.Longitude,
FireEvent.Latitude,
tempHitEvent.Longitude,
tempHitEvent.Latitude,
tempHitEvent.HitResult,
FireEvent.AmmunitionCode,
FireEvent.AmmunitionSource,
FireEvent.FireEventID,
0 AS 'IsArtillery'
FROM FireEvent
LEFT JOIN (SELECT HitEvent.*,
FireEvent.FireEventID,
Rank()
OVER (
ORDER BY HitEvent.EventTime) AS RankValue
FROM HitEvent
WHERE FireEvent.EventTime BETWEEN
Dateadd(millisecond, -5000,
HitEvent.EventTime) AND
Dateadd(millisecond,
5000, HitEvent.EventTime) AND HitEvent.FiringPlayerID = FireEvent.PlayerID
AND HitEvent.AmmunitionCode =
FireEvent.AmmunitionCode
AND HitEvent.ExerciseID =
'D289D508-1479-4C17-988C-5F6A847AE51E'
AND FireEvent.ExerciseID =
'D289D508-1479-4C17-988C-5F6A847AE51E'
AND HitEvent.HitResult NOT IN ( 0, 1 ) ) AS
tempHitEvent
ON (
RankValue = 1
AND tempHitEvent.FireEventID =
FireEvent.FireEventID
)
WHERE FireEvent.ExerciseID = 'D289D508-1479-4C17-988C-5F6A847AE51E'
ORDER BY HitEventID
A: Use OUTER APPLY instead of LEFT JOIN. I have had to move some of your clauses around, but the below should produce the desired result
SELECT FireEvent.ExerciseID,
FireEvent.FireEventID,
tempHitEvent.HitEventID,
FireEvent.AssociatedPlayerID,
tempHitEvent.AssociatedPlayerID,
FireEvent.EventTime,
tempHitEvent.EventTime,
FireEvent.Longitude,
FireEvent.Latitude,
tempHitEvent.Longitude,
tempHitEvent.Latitude,
tempHitEvent.HitResult,
FireEvent.AmmunitionCode,
FireEvent.AmmunitionSource,
FireEvent.FireEventID,
0 AS 'IsArtillery'
FROM FireEvent
OUTER APPLY
( SELECT HitEvent.*, RANK() OVER (ORDER BY HitEvent.EventTime) AS RankValue
FROM HitEvent
WHERE HitEvent.FireEventID = FireEvent.FireEventID
AND FireEvent.EventTime BETWEEN DATEADD(MILLISECOND, -5000, HitEvent.EventTime) AND DATEADD(MILLISECOND, 5000, HitEvent.EventTime)
AND HitEvent.FiringPlayerID = FireEvent.PlayerID
AND HitEvent.AmmunitionCode = FireEvent.AmmunitionCode
AND HitEvent.ExerciseID = FireEvent.ExerciseID
AND HitEvent.HitResult NOT IN ( 0, 1 )
) AS tempHitEvent
WHERE COALESCE(RankValue, 1) = 1
AND FireEvent.ExerciseID = 'D289D508-1479-4C17-988C-5F6A847AE51E'
ORDER BY FireEvent.HitEventID
If you only want to return results where there is a matching HitEvent use CROSS APPLY. CROSS APPLY is to OUTER APPLY what INNER JOIN is to LEFT JOIN.
ADDENDUM
This can all be achieved using joins with no need for OUTER APPLY, by moving not using a subquery to join HitEvent, then performing the RANK function on all data, not just the HitEvent table. This all needs to be moved to a subquery so the result of the RANK function can be inlcuded in a WHERE clause.
SELECT *
FROM ( SELECT FireEvent.ExerciseID,
FireEvent.FireEventID,
HitEvent.HitEventID,
FireEvent.AssociatedPlayerID,
--HitEvent.AssociatedPlayerID,
FireEvent.EventTime,
HitEvent.EventTime [HitEventTime],
FireEvent.Longitude [FireEventLongitute],
FireEvent.Latitude [FireEventLatitute],
HitEvent.Longitude [HitEventLongitute],
HitEvent.Latitude [HitEventLatitute],
HitEvent.HitResult ,
FireEvent.AmmunitionCode,
FireEvent.AmmunitionSource,
0 [IsArtillery],
RANK() OVER(PARTITION BY HitEvent.FireEventID, HitEvent.FiringPlayerID, HitEvent.AmmunitionCode,HitEvent.ExerciseID ORDER BY HitEvent.EventTime) [RankValue]
FROM FireEvent
LEFT JOIN HitEvent
ON HitEvent.FireEventID = FireEvent.FireEventID
AND FireEvent.EventTime BETWEEN DATEADD(MILLISECOND, -5000, HitEvent.EventTime) AND DATEADD(MILLISECOND, 5000, HitEvent.EventTime)
AND HitEvent.FiringPlayerID = FireEvent.PlayerID
AND HitEvent.AmmunitionCode = FireEvent.AmmunitionCode
AND HitEvent.ExerciseID = FireEvent.ExerciseID
AND HitEvent.HitResult NOT IN ( 0, 1 )
) data
WHERE RanKValue = 1
This may offer slightly improved performance compared to using OUTER APPLY, it may not. It depends on your schema and the amount of data you are processing. There is no substitute for testing:
A: Cross Apply works in this scenario...
SELECT FireEvent.ExerciseID,
FireEvent.FireEventID,
tempHitEvent.HitEventID,
FireEvent.AssociatedPlayerID,
tempHitEvent.AssociatedPlayerID,
FireEvent.EventTime,
tempHitEvent.EventTime,
FireEvent.Longitude,
FireEvent.Latitude,
tempHitEvent.Longitude,
tempHitEvent.Latitude,
tempHitEvent.HitResult,
FireEvent.AmmunitionCode,
FireEvent.AmmunitionSource,
FireEvent.FireEventID,
0 AS 'IsArtillery'
,RankValue
FROM FireEvent
CROSS APPLY (SELECT HitEvent.*,
FireEvent.FireEventID,
Rank()
OVER (
ORDER BY HitEvent.EventTime) AS RankValue
FROM HitEvent
WHERE FireEvent.EventTime BETWEEN
Dateadd(millisecond, -5000,
HitEvent.EventTime) AND
Dateadd(millisecond,
5000, HitEvent.EventTime) AND HitEvent.FiringPlayerID = FireEvent.PlayerID
AND HitEvent.AmmunitionCode =
FireEvent.AmmunitionCode
AND HitEvent.ExerciseID =
'D289D508-1479-4C17-988C-5F6A847AE51E'
AND FireEvent.ExerciseID =
'D289D508-1479-4C17-988C-5F6A847AE51E'
AND HitEvent.HitResult NOT IN ( 0, 1 ) )
tempHitEvent
WHERE
RankValue = 1
AND tempHitEvent.FireEventID =
FireEvent.FireEventID
AND FireEvent.ExerciseID = 'D289D508-1479-4C17-988C-5F6A847AE51E'
ORDER BY HitEventID
A: You don't need the correlated subquery. You seem to have a relatively simple join, albeit on several fields at the same time.
The following FROM clause extracts the conditions from inside the subquery that refer to both tables and move them outside into the JOIN clause. This comes close to what you want, depending on whether the partition in the rank is doing what you expect:
FROM FireEvent fe left outer join
(SELECT HitEvent.*,
Rank() OVER (partition by FiringPlayerID, ExerciseID, FireEventID, FireEventID
ORDER BY HitEvent.EventTime) AS RankValue
FROM HitEvent
WHERE HitEvent.ExerciseID = 'D289D508-1479-4C17-988C-5F6A847AE51E' AND
HitEvent.HitResult NOT IN ( 0, 1 )
) he
ON he.FiringPlayerID = fe.PlayerId and
he.AmmunitionCode = fe.AmmunitionCode and
fe.EventTime BETWEEN Dateadd(millisecond, -5000, he.EventTime) AND
Dateadd(millisecond, 5000, he.EventTime) AND
fe.ExerciseID = 'D289D508-1479-4C17-988C-5F6A847AE51E' AND
RankValue = 1 , d
he.FireEventID = fe.FireEventID
| |
doc_1514
|
Drawable playArrowOverlay = ContextCompat.getDrawable(
getContext(),
R.drawable.ic_play_arrow_accent_dark);
playArrowOverlay.setAlpha(25);
GenericDraweeHierarchy hierarchyWithOverlay = sdvAttemptImage.getHierarchy();
hierarchyWithOverlay.setOverlayImage(playArrowOverlay);
sdvAttemptImage.setHierarchy(hierarchyWithOverlay);
A: Thanks for reporting this issue, this is indeed a bug of Fresco.
I've opened an issue on GitHub here: https://github.com/facebook/fresco/issues/1905
In the meantime, you can create a delegating Drawable that ignores setAlpha calls. This way, Fresco will not be able to change the alpha value of the underlying Drawable.
| |
doc_1515
|
but if url like this https://mywebsite.com/whatever/ then that's only time to execute the rewrite rule app/
I want to execute only the rewrite app/ if the url has parameter or whatever has sub name.
here my sample htaccess:
<IfModule mod_rewrite.c>
Header set Referrer-Policy "origin"
RewriteEngine On
RewriteRule ^(.*)$ app/$1 [L]
</IfModule>
A: Try with below currently you are testing with (.*) zero and unlimited times which is taking / in group as well.
<IfModule mod_rewrite.c>
Header set Referrer-Policy "origin"
RewriteEngine On
RewriteRule !^$ app%{REQUEST_URI} [L]
</IfModule>
| |
doc_1516
|
Scenario 1
pow_one <- function(x, print_info = TRUE) {
y <- x ^ 2
if (print_info) {
print(paste(x, "to the power two equals", y))
}
return(y)
}
Scenario 2
pow_two <- function(x, print_info = TRUE) {
if (print_info) {
y <- x ^ 2
print(paste(x, "to the power two equals", y))
return(y)
}
}
A: You think both the functions are same but they actually are not the same. They behave the same only when print_info is TRUE.
Consider this scenario
pow_one(3, FALSE)
#[1] 9
pow_two(3, FALSE)
pow_one returns 9 whereas pow_two returns nothing because your return is inside the if block for pow_two which I think is not your intended behaviour.
Being "best" is subjective but IMO pow_one is better than pow_two because you need to return y irrespective if it is printed or not which is controlled by print_info. Moreover, it is better to have a consistent behaviour for the function. It should always return a value or never return a value.
| |
doc_1517
|
public static class Utils
{
public static DataTable ImportExceltoDatatable(string filepath)
{
string connectionString = "Driver ={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)}; DBQ = " + filepath;
string query = "Select * From [SheetName$]";
using (var connection = new OdbcConnection(connectionString))
using (var adapter = new OdbcDataAdapter(query, connection))
{
DataSet dataset = new DataSet();
adapter.Fill(dataset); // <---------------- exception thrown here
DataTable datatable = dataset.Tables[0];
return datatable;
};
}
}
adapter.Fill(datasaet) throws the following exception
System.Data.Odbc.OdbcException: 'ERROR [IM002] [Microsoft][ODBC Driver
Manager] Data source name not found and no default driver specified'
In computer ODBC settings, Excel driver seems to be installed
what is the correct way of how to use this driver, do I have a mistake in the connection string?
Unfortunately, I found no other way than to use ODBC.
*
*NPOI, EPPLUS does not read XLSB.
*LinqToExcel needs Microsoft.ACE.OLEDB.12.0 registered on the machine.
*Microsoft.Office.Interop.Excel needs excel to be installed on the machine.
A: Had the same problem just now. In your pic you can see the "Platform" column says the driver is 64-bit. Switching the project to x64 (instead of Any CPU) fixes the problem.
| |
doc_1518
|
div
{
border: 4px solid;
color: red;
height: 100px;
width: 100px;
}
<div></div>
JSBIN
gives me a div with a red border. Usually not specifying a color will default to black. What is this odd inheritance?
A: Based on section 4.1 of the relevant Backgrounds and Borders Module spec, the initial border-color value is currentColor:
CSS Color Module - 4.4. currentColor color keyword
CSS1 and CSS2 defined the initial value of the border-color property to be the value of the color property but did not define a corresponding keyword. This omission was recognized by SVG, and thus SVG 1.0 introduced the currentColor value for the fill, stroke, stop-color, flood-color, and lighting-color properties.
CSS3 extends the color value to include the currentColor keyword to allow its use with all properties that accept a <color> value. This simplifies the definition of those properties in CSS3.
In other words, the value is treated as the following in your case:
border: 4px solid currentColor;
Therefore you could also use the currentColor value for something such as the background-color property. For instance:
div {
color: red;
width: 100px;
height: 100px;
border: 4px solid;
background-color: currentColor;
}
<div></div>
Small fun fact, if you change the font color (e.g. :hover), the bordercolor changes with it! It also works well with transitions!
A: In CSS, an element can have one of two "primary" colors: a foreground color, specified by the color property, and a background color, specified by the background-color property. Lots of other properties accept a color, but having black as the initial color value would be very arbitrary, so instead properties that accept a color value take on the computed foreground color by default.
Of course, this can result in a black border if the foreground color is black, but only then. And the text color is only black to start with because the default UA stylesheets make it so; CSS does not state anywhere that the initial value should be black, but that it is UA-dependent (CSS1, CSS2.1, CSS Color 3). For example, a UA in high-contrast mode or inverted-colors mode could specify the default color scheme to be white on black, or a different color combination entirely:
This behavior has been around since CSS1. The currentColor value, introduced in CSS Color 3 based on the equivalent SVG keyword, is now listed as the initial value of the respective properties in the respective CSS3 modules:
*
*border-color
*outline-color1
*box-shadow
Using attr() with a color value also falls back to currentColor when a value cannot be found. See CSS Values 3.
Prior to CSS3 there was no way to restore the color of a border or outline to the computed foreground color once overridden; see my answer to this related question. While this question uses the word "inherit", it should be noted that specifying border-color: inherit does not inherit from the color property — like all other CSS properties, it inherits from the border-color of the parent element.
1 The default is actually to invert the colors of the pixels underneath the outline, but supporting invert is not mandatory and if a browser chooses not to, the foreground color must be used instead.
| |
doc_1519
|
1. A typical admin user which is identified by email and authenticated with password
2. A remote application which connects to django and authenticates with pre-shared key and tokens. The email is not required for such type of user
Every type of user has different associated attributes. I know that I can extend User model in Django.
I already created email authentication backend. But this works for all the accounts, including the remote applications ones.
Is there any effective way to create a auth backend for a type of user?
A: You can create a custom authentication backend for the remote application and show it in your settings like this:
AUTHENTICATION_BACKENDS = (
'path.to.email.authentication',
'path.to.remote.app.authentication',
)
This way, Django will try to use the email authentication first and if that fails will try the remote app authentication.
You can read about custom authentication backends here
Hope it helps!
A: If you want to disable for some of you users password authentication you can use set_unusable_password. From the docs:
Marks the user as having no password set. This isn’t the same as having a blank string for a password. check_password() for this user will never return True. Doesn’t save the User object.
You may need this if authentication for your application takes place against an existing external source such as an LDAP directory.
| |
doc_1520
|
"modelCheck("var1_d.bug")"
"modelCheck("var2_d.bug")"
...
"modelCheck("var10_d.bug")"
I would usually use a for loop and paste (if I did not have to worry about the double quotation marks) as such:
for(i in 1:10){
str<-paste("modelCheck(var",i,"_d.bug)",sep="")
print(str)
}
However, I need to include the double quotation marks within the character string, hence the appeal for help?
A: Simply escape the quotation marks with backslashes:
paste("modelCheck(var\"",i,"_d.bug\")",sep="")
An alternative is to use single quotes to enclose the string:
paste('modelCheck(var"',i,'_d.bug")',sep="")
| |
doc_1521
|
i want to create a login page so that all four application have only one login page and
after the login from newly created page it skip login page of 4 application and next page after login must be displayed.
A: You should be looking at Single Sign On technologies.
SAML (security assertion markup language) is one ingredient technology that could solve such requirements. You would have a portal acting as a SAML Identity Provider, and your applications become SAML Service Providers. Many open source and commercial products are available that implement SAML that can help you integrate it.
A: Set a cookie from one of your application and check from the other applications whether the cookie is set for the correct domain. You can set the cookies value as the the currently logged in username.
So other applications can "trust" that and bypass login.
This is how we achieved single signon between our app and IBM Cognos.
Checkout this discussion for more details. - SSO between Java EE and Cognos application
| |
doc_1522
|
What's going on here? And what's the solution?
A: Pylons uses a multi-threaded application server and variables are not cleared from request to request. This is a performance issue, as re-instantiating entire class trees would be expensive. Instead of storing the data returned by the user in a class, use a sessions system (Pylons comes with one or use something like Beaker) or back-end database like SQLAlchemy, SQLObject, or PyMongo.
Additionally, due to the multi-threaded nature of the framework, you should avoid shared objects (like globals) like the plague unless you are very careful to ensure you are using them in a thread-safe way (e.g. read-only). Certain Pylons-supplied objects (request/response) have been written to be thread-local, so don't worry about those.
A: A common programmer oversight is that defining a list [] as a default argument or class initialiser is evaluated only once. If you have class variables such as lists, I recommend you initialise them in init. I'll give you an example.
>>> class Example(object):
... a = []
... def __init__(self):
... self.b = []
...
>>> foo = Example()
>>> bar = Example()
>>> foo.a
[]
>>> bar.a
[]
>>> foo.b
[]
>>> bar.b
[]
>>> foo.a.append(1)
>>> foo.b.append(2)
>>> foo.a
[1]
>>> foo.b
[2]
>>> bar.a
[1]
>>> bar.b
[]
| |
doc_1523
|
Type modelType = GetMyType();
So - modelType could be List<ClassA> or List<ClassB>, etc. depending on the situation.
How do I create this type, and then populate it?
I know I can do this:
var myList = Activator.CreateInstance(modelType);
But then how do I add items to it, which I would normally do with myList.Add(new ClassA()) or myList.Add(new ClassB()) knowing that I don't really know the ClassA or ClassB type - I just know that modelType is List<ClassA> - Is there some other way I should be instantiating it so that I can add items to it?
A: Have a look at this example, it uses the Type.GetGenericArguments Method to retrieve the lists inner type. Then proceed with reflection as usual.
static void Main(string[] args)
{
Type modelType = GetMyType();
var myList = Activator.CreateInstance(modelType);
var listInnerType = modelType.GetGenericArguments()[0];
var listInnerTypeObject = Activator.CreateInstance(listInnerType);
var addMethod = modelType.GetMethod("Add");
addMethod.Invoke(myList, new[] { listInnerTypeObject });
}
static Type GetMyType()
{
return typeof(List<>).MakeGenericType((new Random().Next(2) == 0) ? typeof(A) : typeof(B));
}
class A { }
class B { }
| |
doc_1524
|
Let's say I have a test plan with one thread which does successively 3 identical HTTP requests to one server. The thing is that for the first request, Connect time is (obviously) not equal to 0, but it is for second and third request.
However, from my understanding, Latency includes Connect time, hence for my first request, the Latency is always (much) larger than for the second and third request, and it does not reflect the time spent waiting (server processing time) for this first request.
Can I assume that, if I substract the Connect time from the Latency (Latency - Connect time), it gives me a meaningfull value of the server processing time (+ download content time maybe?)
A: See w3c time-taken HTTP request log field. Just turn this on and post process the HTTP request logs at the end of your test. You will have the complete processing time for each individual request.
| |
doc_1525
|
List<single_request> list_Srequests = new List<single_request>();
And I have added some classes into it. And I need count the number of classes, which equals to int totalNum_SingleReg;.
totalNum_SingleReg = list_Srequests.Count; // this call return true number,
// that equal to 8
However this one eventually num is equal to 68:
foreach (single_request sRequest in list_Srequests)
{
totalNum_SingleReg++;
}
I can't understand what wrong with last one. Any ideas?
A: you may have some other code between your item counts, If you need check the list count and foreach count, try below code
var count1 = list_Srequests.Count;
var count2 = 0;
foreach (var sRequest in list_Srequests)
{
count2 ++;
}
if(count1 == count2 )
Console.WriteLine("COUNT1 EQUAL TO COUNT2");
| |
doc_1526
|
This is my XML file
<root>
<value>3</value>
<value>1</value>
<value>7</value>
</root>
and this is my transformation:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:template match="root">
<output>
<xsl:variable name="availableValues" select="distinct-values(value)"/>
<!-- now the availableValues contains the sequence (3,1,7) -->
<!-- My goal is to get this into a sorted sequence (1,3,7) -->
<!-- This is just for testing the $availableValues -->
<xsl:attribute name="count" select="count($availableValues)"/>
<xsl:for-each select="$availableValues">
<val>
<xsl:value-of select="."/>
</val>
</xsl:for-each>
</output>
</xsl:template>
</xsl:stylesheet>
I have tried to use
<xsl:variable name="availableValues">
<xsl:for-each select="distinct-values(value)">
<xsl:sort/>
<xsl:value-of select="."/>
</xsl:for-each>
</xsl:variable>
but this (of course) doesn't give me a sequence, just the concatenation of the values (although sorted).
EDIT:
This is what I came up so far, and it looks like a proper solution. Is there a better solution?
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
>
<xsl:output indent="yes"/>
<xsl:template match="root">
<output>
<xsl:variable name="availableValues" as="xs:integer *">
<xsl:for-each select="distinct-values(value)">
<xsl:sort/>
<xsl:sequence select="."/>
</xsl:for-each>
</xsl:variable>
<!-- This is just for testing the $availableValues -->
<xsl:attribute name="count" select="count($availableValues)"/>
<xsl:for-each select="$availableValues">
<val>
<xsl:value-of select="."/>
</val>
</xsl:for-each>
</output>
</xsl:template>
</xsl:stylesheet>
A: Use xsl:perform-sort.
Here is an example from the link:
<xsl:perform-sort select="//BOOK">
<xsl:sort select="author/last-name"/>
<xsl:sort select="author/first-name"/>
</xsl:perform-sort>
| |
doc_1527
|
I have filled user name and email fields, but once I try to enter text in password fields, It's showing Strong password with yellow colour, And I am not able to enter any text.
I have tried almost all solutions, but nothing helped me. I don't want this autofill feature.
If I change device settings, autofill disable, then able to enter text, but end user with real device will effect due this issue.
So, How to fix this?
Any solutions?
Here is my code:
override func viewDidAppear(_ animated: Bool) {
self.createPasswordTextfield.isSecureTextEntry = true
self.confirmPasswordTextfield.isSecureTextEntry = true
if #available(iOS 10.0, *) {
createPasswordTextfield.textContentType = UITextContentType.streetAddressLine2
confirmPasswordTextfield.textContentType = UITextContentType.streetAddressLine2
}
if #available(iOS 12.0, *) {
createPasswordTextfield.textContentType = UITextContentType.oneTimeCode
confirmPasswordTextfield.textContentType = UITextContentType.oneTimeCode
}
}
A: I get some solution temporarily.
Way Around to bypass Auto-fill Strong Password Suggestion.
set isSecureTextEntry property to false.
self.createPasswordTextfield.secureTextEntry = false
self.confirmPasswordTextField.secureTextEntry = false
Add a UITextField Delegate Method and enable the isSecureTextEntry property.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == createPasswordTextfield {
createPasswordTextfield.isSecureTextEntry = true
}
return true
} else if textField == confirmPasswordTextfield {
confirmPasswordTextfield.isSecureTextEntry = true
}
return true
}
}
I found in this thread.
https://developer.apple.com/forums/thread/120703
| |
doc_1528
|
For whatever reason C# abstract classes (unlike Java abstract classes) can't 'ignore' inherited interface members. But why can't they just declare one of them abstract and then have concrete derived types deal with the implementation of both members?
If that's too ugly or impossible due to some language constraint, then just like concrete classes that inherit interface members with the same signature must explictly implement at least one of them, why can't abstract classes explicitly declare one of the inherited interface members abstract? Is it for the same reason?
A: This works just fine:
interface IFoo
{
void Foo();
}
abstract class FooBase : IFoo
{
public abstract void Foo();
}
After re-reading the question, I realize we're talking about inheriting multiple interfaces. I'm not sure about that scenario, but seriously, why in the world are you using two interfaces with identically named members. Yuck.
A: If a class inherits two interfaces with identically-named members but cannot use the same implementation for both, it should typically implement the members explicitly with methods that do nothing but chain to protected methods which may be virtual or abstract. It is generally a Bad Thing for a derived class to implement an interface which is also implemented by the base. It is generally better for inheritable classes should generally implement interface using virtual or abstract functions, so derived classes can override those without having to touch the interface.
| |
doc_1529
|
Preparing C compilation using already configured msc C compiler...
ERROR: Cannot start "nmake".ERROR: Cannot start "nmake".
Documentation suggested that espawn utility may show available toolchains, however it seems to crash:
PS C:\Program Files\Eiffel Software\EiffelStudio 18.07 GPL\tools\spec\win64\bin> & "C:\Program Files\Eiffel Software\EiffelStudio 18.07 GPL\tools\spec\win64\bin\espawn.exe" -l
Eiffel Environment Command Spawn Utility - Version: 18.07
Copyright Eiffel Software 1985-2018. All Rights Reserved.
Available C/C++ compilers:
espawn: system execution failed.
Following is the set of recorded exceptions:
******************************** Thread exception *****************************
In thread Root thread 0x0 (thread id)
*******************************************************************************
-------------------------------------------------------------------------------
Class / Object Routine Nature of exception Effect
-------------------------------------------------------------------------------
APPLICATION root's creation Segmentation violation:
<000000000363C588> Operating system signal. Exit
-------------------------------------------------------------------------------
APPLICATION root's creation
<000000000363C588> Routine failure. Exit
-------------------------------------------------------------------------------
Unfortunately I couldn't find any toolchain related stuff except for that espawn util so I've tried to launch Eiffel Studio from VS development command prompt hoping that it may implicitly rely on some environment variables. This indeed helped, however compilation still fails with linker error:
Preparing C compilation using already configured msc C compiler...
big_file_C28_c.c
eoption.c
big_file_E2_c.c
big_file_C26_c.c
big_file_C27_c.c
big_file_C30_c.c
big_file_C29_c.c
big_file_C31_c.c
eref.c
epoly.c
esize.c
big_file_C25_c.c
big_file_C24_c.c
big_file_C23_c.c
big_file_C22_c.c
big_file_C21_c.c
big_file_C20_c.c
big_file_C19_c.c
eplug.c
eskelet.c
enames.c
evisib.c
big_file_C18_c.c
big_file_C17_c.c
big_file_C16_c.c
big_file_C15_c.c
big_file_C13_c.c
big_file_C14_c.c
ececil.c
big_file_C12_c.c
einit.c
eparents.c
big_file_C11_c.c
big_file_C10_c.c
big_file_C9_c.c
big_file_C8_c.c
big_file_C7_c.c
big_file_C6_c.c
big_file_C5_c.c
big_file_C4_c.c
big_file_C3_c.c
big_file_C2_c.c
big_file_C1_c.c
Скопировано файлов: 1.
emain.c
Microsoft (R) Windows (R) Resource Compiler Version 10.0.10011.16384
Copyright (C) Microsoft Corporation. All rights reserved.
Microsoft (R) Incremental Linker Version 14.16.27024.1
Copyright (C) Microsoft Corporation. All rights reserved.
-STACK:5000000 -NODEFAULTLIB:libc -STACK:5000000 -NODEFAULTLIB:libc -SUBSYSTEM:WINDOWS -OUT:my_wel_application_1.exe
e1\emain.obj
"C:\Program Files\Eiffel Software\EiffelStudio 18.07 GPL\studio\spec\win64\lib\msc\finalized.lib" "C:\Program Files\Eiffel Software\EiffelStudio 18.07 GPL\library\wel\spec\msc\win64\lib\wel.lib"
USER32.lib WS2_32.lib ADVAPI32.lib GDI32.lib SHELL32.lib MSIMG32.lib COMDLG32.lib UUID.lib OLE32.lib OLEAUT32.lib COMCTL32.lib MPR.LIB SHLWAPI.LIB WINSPOOL.LIB
my_wel_application_1.res
E2\Eobj2.lib E1\eparents.obj E1\einit.obj E1\ececil.obj E1\evisib.obj
E1\enames.obj E1\eskelet.obj E1\eplug.obj E1\esize.obj E1\epoly.obj
E1\eref.obj E1\eoption.obj C31\Cobj31.lib C30\Cobj30.lib C29\Cobj29.lib
C28\Cobj28.lib C27\Cobj27.lib C26\Cobj26.lib C25\Cobj25.lib C24\Cobj24.lib
C23\Cobj23.lib C22\Cobj22.lib C21\Cobj21.lib C20\Cobj20.lib C19\Cobj19.lib
C18\Cobj18.lib C17\Cobj17.lib C16\Cobj16.lib C15\Cobj15.lib C14\Cobj14.lib
C13\Cobj13.lib C12\Cobj12.lib C11\Cobj11.lib C10\Cobj10.lib C9\Cobj9.lib
C8\Cobj8.lib C7\Cobj7.lib C6\Cobj6.lib C5\Cobj5.lib C4\Cobj4.lib
C3\Cobj3.lib C2\Cobj2.lib C1\Cobj1.lib
finalized.lib(econsole.obj) : error LNK2001: unresolved external symbol __iob_func
finalized.lib(console.obj) : error LNK2001: unresolved external symbol __iob_func
finalized.lib(file.obj) : error LNK2001: unresolved external symbol __iob_func
finalized.lib(main.obj) : error LNK2001: unresolved external symbol __iob_func
finalized.lib(except.obj) : error LNK2001: unresolved external symbol __iob_func
finalized.lib(sig.obj) : error LNK2001: unresolved external symbol __iob_func
finalized.lib(option.obj) : error LNK2001: unresolved external symbol __iob_func
finalized.lib(main.obj) : error LNK2019: unresolved external symbol _set_output_format referenced in function eif_rtinit
finalized.lib(run_idr.obj) : error LNK2001: unresolved external symbol sprintf
finalized.lib(except.obj) : error LNK2001: unresolved external symbol sprintf
finalized.lib(out.obj) : error LNK2001: unresolved external symbol sprintf
finalized.lib(file.obj) : error LNK2001: unresolved external symbol sprintf
finalized.lib(store.obj) : error LNK2001: unresolved external symbol sprintf
finalized.lib(econsole.obj) : error LNK2019: unresolved external symbol vfprintf referenced in function print_err_msg
finalized.lib(file.obj) : error LNK2019: unresolved external symbol fscanf referenced in function rt_swallow_nl
finalized.lib(retrieve.obj) : error LNK2019: unresolved external symbol sscanf referenced in function iread_header_new
finalized.lib(run_idr.obj) : error LNK2001: unresolved external symbol sscanf
my_wel_application_1.exe : fatal error LNK1120: 6 unresolved externals
NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\bin\HostX64\x64\link.EXE"' : return code '0x460'
Stop.
A: The compilation error when running from VS development command prompt is related to the mismatch between C compiler version and used Eiffel run-time library. Setting the corresponding environment variable before launching the compilation should fix the issue:
set ISE_C_COMPILER=msc_vc140
As to the original error, for some reason, C compilation fails on some machines, because EiffelStudio cannot find VS. The issue has even become a FAQ.
| |
doc_1530
|
private static void SendBackSpace(ushort charUnicode)
{
SEND_INPUT_FOR_32_BIT[] arrInput = new SEND_INPUT_FOR_32_BIT[1];
KEYBOARD_INPUT_FOR_32_BIT ki = new KEYBOARD_INPUT_FOR_32_BIT();
ki.VirtualKeyCode = charUnicode; // 0x08 for backspace
ki.ScanCode = 0;
ki.Time = 0;
ki.ExtraInfo =0;
SEND_INPUT_FOR_32_BIT input = new SEND_INPUT_FOR_32_BIT();
input.InputType = INPUTTYPE.KEYBOARD;
input.KeyboardInputStruct = ki;
arrInput[0] = input;
SendInput(1, arrInput, Marshal.SizeOf(typeof(SEND_INPUT_FOR_32_BIT)));
}
When I try to send a single backspace at a time, it works fine. But when I try to send two backspace (calling this method twice), it only sends one backspace instead of two. As a result only one existing character is deleted, where as it should delete two when I call it twice.
I am capturing the Keypress events on The RichTextBox. Surprisingly the same event and same code works perfectly fine when I am using it in normal TextBox. Any help is appreciated.
FIXED:
Looks like RichTextBox in C# handles Keypress events bit differently than regular TextBox. I modified the above code with this and it works fine now. Now I can send multiple backspaces in a Loop using the following code. Hopefully this would help someone.
private static void SendBackSpace(ushort charUnicode)
{
SEND_INPUT_FOR_32_BIT[] arrInput = new SEND_INPUT_FOR_32_BIT[2];
KEYBOARD_INPUT_FOR_32_BIT ki = new KEYBOARD_INPUT_FOR_32_BIT();
ki.VirtualKeyCode = charUnicode;
ki.ScanCode = 0;
ki.Time = 0;
ki.ExtraInfo = 0;
SEND_INPUT_FOR_32_BIT input = new SEND_INPUT_FOR_32_BIT();
input.InputType = INPUTTYPE.KEYBOARD;
input.KeyboardInputStruct = ki;
arrInput[0] = input;
ki.VirtualKeyCode = charUnicode;
ki.ScanCode = 0;
ki.Time = 0;
ki.ExtraInfo = 0;
ki.Flags = KEYEVENTF.KEYUP;
input.KeyboardInputStruct = ki;
arrInput[1] = input;
SendInput(2, arrInput, Marshal.SizeOf(typeof(SEND_INPUT_FOR_32_BIT)));
}
| |
doc_1531
|
class Square:
def __init__(mine = False, empty = 0):
self.mina = mine
....
def createPlan(size, sign):
spelplan = []
for i in range(size):
gameplan.append([sign]*size)
return gameplan
def square_attribut(gameplan):
gomdplan = spelplan
(help)
def showPlan(gameplan):
i = 0
bracket = list(range(0,len(gameplan)))
rownr = [" "] + bracket
for row in [bracket]+gameplan:
print(rownr[i],end = " ")
i += 1
for square in row:
print(square,end = " ")
print()
| |
doc_1532
|
I am forced to convert to UTF-8 in init
feature('DefaultCharacterSet','UTF-8');
...
I would like to convert my string to Windows-1252 Character to display it:
disp('âêéôïèç');
I'm getting this result
�������
How can I do to get the correct following result?
'âêéôïèç'
Thanks!
Regards,
A: Just to answer the original question, the following should work:
s = char([226 234 233 244 239 232 231]);
disp(s)
| |
doc_1533
|
Question:Q1: How do brokerages combine the IV readings of all the individual options in a chain for an expiration cycle, weigh them properly, account for things like Volatility skew, and come up with an overall implied volatility for the expiration that represents the Implied volatility of the entire chain?
Q2: Are there any common methodologies?
A: If by "chain" you mean all the actively traded options of the same type across all strikes / maturities, then what you are asking is how banks / brokers fit an entire volatility surface to all the observed prices. Which accounts for both the vol smile and vol skew.
Generally you need to extend the black scholes model with additional degrees of freedom to produce the smile and / or skew behaviour commonly observed. One common model is the SABR model which has a nice closed form relationship to the black scholes IV and reproduces vol skew not vol smile (term structure), the extension called dynamic SABR model also produces vol smiles, there is also the Heston model which exhibits both vol skew and smile.
| |
doc_1534
|
$myarr = array('name'=>'Adam', 'age'=>22, 'sex'=>'male');
foreach ($myarr as $k=>$v)
$$k = $v;
is there a way to pass a callback functionX and arrayX to another functionY, dynamically create variables from arrayX in functionY, and be able to reference those variables within functionX callback?
for example, I would like to:
function eachRecord($arr, $callback){
foreach ($arr as $k=>$v) $$k = $v;
$callback();
}
$myarr = array('name'=>'Adam', 'age'=>22, 'sex'=>'male');
eachRecord($myarr, function(){
echo "{$name} is a {$sex} of age {$age}.";
});
i don't want to have to pass variables back into the callback function, since i may not know the length or keys within the array, and i don't want to pollute the global scope with unknown variable names because they are created dynamically.
is there any way to do this? closures?
thanks
A: No, it's not possible. It's not hard to work around like this though:
function callback($values) {
extract($values);
echo "{$name} is a {$sex} of age {$age}.";
}
callback($myArr);
You're essentially only reinventing http://php.net/extract anyway.
| |
doc_1535
|
Integrity error: null value in column "email" violates not-null constraint
I think there is something wrong with my database. But I couldn't figure it why..
I'm using Django 1.5.1 and PSQL 9.1.9
THANK YOU VERY MUCH!!
models.py:
from django.db import models
class User(models.Model):
name = models.CharField(max_length=30)
email = models.EmailField(verbose_name='e-mail')
password = models.CharField(max_length=16)
views.py:
from portfolioSite.forms import register_form
from django.shortcuts import render
from django.http import HttpResponseRedirect
from portfolioSite.models import User
def register(request):
if request.method == 'POST':
registerForm = register_form(request.POST)
if registerForm.is_valid():
User.objects.create(name = registerForm.cleaned_data['name'],
email = registerForm.cleaned_data['email'],
password = registerForm.cleaned_data['password2'])
return HttpResponseRedirect('/success/')
else:
registerForm = register_form()
return render(request, 'register_form.html', {'form':registerForm})
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/home/guangyi/Django/projects/mysite/portfolioSite/views.py" in register
13. password = registerForm.cleaned_data['password2']
File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py" in create
149. return self.get_query_set().create(**kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in create
402. obj.save(force_insert=True, using=self.db)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in save
546. force_update=force_update, update_fields=update_fields)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in save_base
650. result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py" in _insert
215. return insert_query(self.model, objs, fields, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in insert_query
1661. return query.get_compiler(using=using).execute_sql(return_id)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py" in execute_sql
937. cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/util.py" in execute
41. return self.cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/postgresql_psycopg2/base.py" in execute
56. six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/postgresql_psycopg2/base.py" in execute
54. return self.cursor.execute(query, args)
Exception Type: IntegrityError at /register/
Exception Value: null value in column "email" violates not-null constraint
I check my db, I saw there is a table called porfolioSite_user, but when I drop it, psql told me the table does not exit...so confused....
A: Check your template to make sure the email field in your form is submitting the 'email' input correctly. If it's submitting nothing under 'email' when you hit submit, that's the likely cause of your problem.
There are a number of registration apps that you can install that will get rid of the trouble you're having with this. I recommend django-registration-1.5 since youre using a version the version of django with customizable user models. It would be the simplest way to go, but in case you're doing this for self-enrichment, Theres a number of other things you can try if the form appears ok. You can check your south migrations to make sure that they're all up to date, or if you're in testing phases and your database doesn't matter, you can flush the database to see if it gets rid of the error.
model fields have two similar options, but do different things. They are the 'null=True' value and the 'blank=True' one. You only have 'blank=True', which is the validator for the python side of creating the object. However, when you try to save it to the database, you'll get an error, and thats what's most likely happening here. Since your 'email' model is missing the the 'null=True' option on it, you get an error because you're submitting a 'null' value to a not-null constraint. However, adding 'null=True' to your model is not the right thing to do in this situation.
if you want to save yourself a headache, I suggest plugging django-registration-1.5 into your project and letting that app do the registration for you.
A: By default all fields in a django model are required and do not accept null values. In order for a field to accept nulls, you need to add null=True to the model field definition.
The problem in your case is that the form does not validate that an email is required; so it is accepting blanks in the email field.
Another issue is that you are using a model called User when django already comes with a complete authentication system with users, permissions and - yes - even the registration and forgot password forms (see more on this in the documentation). This application provides a User model as well.
Finally, django will never make any destructive changes to your database. This means if you delete a model, or delete add a column to a model the syncdb command will not make these changes. You will have to drop the database and then run syncdb again. Later on you can learn about applications like South that help keep track of these changes and do the database modifications for you.
A: Try to check the email field before you send a POST request, make sure the email field is not NULL before you send the request.
| |
doc_1536
|
I have an application that allows users to lay out a floor in 3D space. I want the size of the floor to automatically stretch after a 3D rotation so that it always covers a certain area.
Anyone know a formula for working this out?
EDIT: I guess what I am really trying to do is convert degrees to pixels.
On a 2D plane say 100 x 100 pixels, a -10 degree change on rotationX means that the plane has a gap at the top where it is no longer visible. I want to know how many pixels this gap will be so that I can stretch the plane.
In Flex, the value for the display objects height property remains the same both before and after applying the rotation, which may in fact be a bug.
EDIT 2: There must be a general math formula to work this out rather than something Flash/Flex specific. When viewing an object in 3D space, if the object rotates backwards (top of object somersaults away from the viewer), what would the new visible height be based on degrees of rotation? This could be in pixels, metres, cubits or whatever.
A: Have you tried using the object's bounding rectangle and testing that?
var dO:DisplayObject = new DisplayObject();
dO.rotation = 10;
var rect:Rectangle = dO.getRect();
// rect.topLeft.y is now the new top point.
// rect.width is the new width.
// rect.height is the new height.
As to the floor, I would need more information, but have you tried setting floor.percentWidth = 100? That might work.
A: Have you checked DisplayObject.transform.pixelBounds? I haven't tried it, but it might be more likely to take the rotation into account.
A: Rotation actually changes DisplayObject's axis's (i.e. x and y axes are rotated). That is why you are not seeing the difference in height. So for getting the visual height and y you might try this.var dO:DisplayObject = new DisplayObject();
addChild();
var rect1:Rectangle = dO.getRect(dO.parent);
dO.rotation = 10;
var rect2:Rectangle = dO.getRect(dO.parent);
rect1 and rect2 should be different in this case. If you want to check the visual coordinates of the dO then just change dO.parent with root.
A: I don't have a test case, but off the top of my head I'd guess something like:
var d:DisplayObject;
var rotationRadians:Number = d.rotationX * Math.PI / 180;
var visibleHeight:Number = d.height * Math.cos(rotationRadians);
This doesn't take any other transformations into account, though.
| |
doc_1537
|
protected void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
setContentView(R.layout.activity_clientlogin);
getActionBar().show();
getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FF4444")));
....
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_clientlogin, menu);
return super.onCreateOptionsMenu(menu);
}
menu_clientlogin:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/action_offline_mode"
android:name="@string/offline_mode"
android:showAsAction="always"/>
</menu>
Everything worked perfectly until I added a Navigation Drawer, I used the code from the example project. The ActionBar color is still red but all the items are invisible (There is not text shown). If I click at the right corner of the ActionBar I see that I select an item and onOptionsItemSelected is triggered correctly.
I have the same problem in all other activities of my project. Another example (The ActionBar color is changed programmaticly, the drawericon is also shown):
My application uses this theme:
<resources>
<!--
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
-->
<style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">
<!--
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
-->
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>
</resources>
| |
doc_1538
|
When I run /usr/lib/kscreenlocker_greet --testing, I get an output of:
KCrash: Application 'kscreenlocker_greet' crashing...
Floating point exception (core dumped)
I'm trying to run it with gdb to try and pin the exact location of the bug, but I'm not sure where to set the breakpoints in order to isolate the bug. Should I be looking for calls to KCrash? Or perhaps a raise() call? Can I get gdb to print off the relevant line of code that causes SIGFPE?
Thanks for any advice you can offer.
A:
but I'm not sure where to set the breakpoints in order to isolate the bug
You shouldn't need to set any breakpoints at all: when a process running under GDB encounters a fatal signal (such as SIGFPE), the OS notices that the process is being traced by the debugger, and notifies the debugger (instead of terminating the process). That in turn causes GDB to stop, and prompt you for additional commands. It is at that time that you can look around and understand what caused the crash.
Example:
cat -n t.c
1 #include <fenv.h>
2
3 int foo(double d) {
4 return 1/d;
5 }
6
7 int main()
8 {
9 feenableexcept(FE_DIVBYZERO);
10 return foo(0);
11 }
gcc -g t.c -lm
./a.out
Floating point exception
gdb -q ./a.out
(gdb) run
Starting program: /tmp/a.out
Program received signal SIGFPE, Arithmetic exception.
0x000000000040060e in foo (d=0) at t.c:4
4 return 1/d;
(gdb) bt
#0 0x000000000040060e in foo (d=0) at t.c:4
#1 0x0000000000400635 in main () at t.c:10
(gdb) q
Here, as you can see, GDB stops when SIGFPE is delivered, and allows you to look around and understand the crash.
In your case, you would want to first install debuginfo symbols for KDE, and then run
gdb --args /usr/lib/kscreenlocker_greet --testing
(gdb) run
| |
doc_1539
|
it save to table wp_postmeta . my problem is save cusotm table .
add_action('woocommerce_product_options_general_product_data', 'woocommerce_product_custom_fields');
// Save Fields
add_action('woocommerce_process_product_meta', 'woocommerce_product_custom_fields_save');
function woocommerce_product_custom_fields()
{
global $woocommerce, $post;
//Custom Product Number Field
woocommerce_wp_text_input(
array(
'id' => '_custom_product_number_field',
'placeholder' => 'Custom Product Number Field',
'label' => __('Custom Product Number Field', 'woocommerce'),
'type' => 'number',
'custom_attributes' => array(
'step' => 'any',
'min' => '0'
)
)
);
}```
above code create field and save value .
i want to save custom table
what should i do ;
| |
doc_1540
|
eg . Main instance is on us-east-1 and it has DB read replica in eu-central-1 it just showing loader screen on clicking create blue/green deployment
When clicking on create Blue/Green deployment it should show screen with related settings for deployment but it just showing loader
A: Blue-Green deployments currently don't support cross-region deployments. If you take a look at the limitations in the documentation below, you can see where they state Cross Region Read Replicas are not supported.
https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/blue-green-deployments-overview.html#blue-green-deployments-limitations
| |
doc_1541
|
=query('Form Responses 1'!A2:AC,"Select A,B,D,L,M,N,O,P Where L is not null")
This selects the columns A,B,D,L,M,N,O,P Where L is not null but if L is null, I want to select the columns A,B,D,Y,Z,AA,AB,AC instead.
So far, I've tried both of the following:
=query('Form Responses 1'!A2:AC,"Select A,B,D,L,M,N,O,P Where L is not null" AND "Select A,B,D,Y,Z,AA,AB,AC Where Y is not null")
=query('Form Responses 1'!A2:AC,"Select A,B,D,L,M,N,O,P Where L is not null" OR "Select A,B,D,Y,Z,AA,AB,AC Where Y is not null")
A: Answer
The following formula should produce the result you desire:
=ARRAYFORMULA(IF(ISBLANK(L2:L),{A2:A,B2:B,D2:D,Y2:Y,Z2:Z,AA2:AA,AB2:AB,AC2:AC},{A2:A,B2:B,D2:D,L2:L,M2:M,N2:N,O2:O,P2:P}))
Explanation
First, the =ISBLANK function is used to check whether the value of column L is empty or not. This creates an array of boolean values which are fed into the =IF function. Depending on the result of =ISBLANK one of two possible sets of columns are selected.
Everything is contained within =ARRAYFORMULA so that it functions properly across many rows.
Functions used:
*
*=ISBLANK
*=IF
*=ARRAYFORMULA
| |
doc_1542
|
I'm using pandas library to read the CSV data, but also using encode('utf-8').
At first it worked, but I had to make some changes to the original file and after saving it and making:
python manage.py collectstatic
I'm getting error when running the command:
python manage.py ubigeo_peru
I've solved this by importing the file as an Excel file, but still
wondering what is wrong with the CSV.
tmp_data=pd.ExcelFile("static/data/ubigeo-peru.xlsx")
tmp_data=tmp_data.parse("ubigeo-peru")
I also see that the encoding error only appear on github when viewing RAW Data:
https://raw.githubusercontent.com/OmarGonD/stickers_gallito/master/static/data/ubigeo-peru.csv
ubigeo_peru.py
import pandas as pd
import csv
from shop.models import Peru
from django.core.management.base import BaseCommand
tmp_data=pd.read_csv('static/data/ubigeo-peru.csv',sep=',', encoding="utf-8")
# tmp_data=pd.read_csv('static/data/ubigeo-peru.csv',sep=',')
class Command(BaseCommand):
def handle(self, **options):
products = [
Peru(
departamento=row['departamento'],
provincia=row['provincia'],
distrito=row['distrito'],
costo_despacho_con_recojo=row['costo_despacho_con_recojo'],
costo_despacho_sin_recojo=row['costo_despacho_sin_recojo'],
dias_despacho = row['dias_despacho']
)
for idx, row in tmp_data.iterrows()
]
Peru.objects.bulk_create(products)
The data looks good on github and when is opened on excel.
https://github.com/OmarGonD/stickers_gallito/blob/master/static/data/ubigeo-peru.csv
Error when running the command locally or remotly:
$ python manage.py ubigeo_peru
D:\virtual_envs\stickers-gallito-app\lib\site-packages\requests\__init__.py:91: RequestsDependencyWarning: urllib3 (1.25.3) or chardet (3.0.4) doesn't match a supported version!
RequestsDependencyWarning)
Traceback (most recent call last):
File "pandas\_libs\parsers.pyx", line 1134, in pandas._libs.parsers.TextReader._convert_tokens
File "pandas\_libs\parsers.pyx", line 1240, in pandas._libs.parsers.TextReader._convert_with_dtype
File "pandas\_libs\parsers.pyx", line 1256, in pandas._libs.parsers.TextReader._string_convert
File "pandas\_libs\parsers.pyx", line 1494, in pandas._libs.parsers._string_box_utf8
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc1 in position 0: invalid start byte
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "manage.py", line 19, in <module>
execute_from_command_line(sys.argv)
File "D:\virtual_envs\stickers-gallito-app\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "D:\virtual_envs\stickers-gallito-app\lib\site-packages\django\core\management\__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "D:\virtual_envs\stickers-gallito-app\lib\site-packages\django\core\management\__init__.py", line 224, in fetch_command
klass = load_command_class(app_name, subcommand)
File "D:\virtual_envs\stickers-gallito-app\lib\site-packages\django\core\management\__init__.py", line 36, in load_command_class
module = import_module('%s.management.commands.%s' % (app_name, name))
File "C:\Users\OGONZALES\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "D:\web_proyects\stickers-gallito-app\shop\management\commands\ubigeo_peru.py", line 8, in <module>
tmp_data=pd.read_csv('static/data/ubigeo-peru.csv',sep=',', encoding="utf-8")
File "D:\virtual_envs\stickers-gallito-app\lib\site-packages\pandas\io\parsers.py", line 678, in parser_f
return _read(filepath_or_buffer, kwds)
File "D:\virtual_envs\stickers-gallito-app\lib\site-packages\pandas\io\parsers.py", line 446, in _read
data = parser.read(nrows)
File "D:\virtual_envs\stickers-gallito-app\lib\site-packages\pandas\io\parsers.py", line 1036, in read
ret = self._engine.read(nrows)
File "D:\virtual_envs\stickers-gallito-app\lib\site-packages\pandas\io\parsers.py", line 1848, in read
data = self._reader.read(nrows)
File "pandas\_libs\parsers.pyx", line 876, in pandas._libs.parsers.TextReader.read
File "pandas\_libs\parsers.pyx", line 891, in pandas._libs.parsers.TextReader._read_low_memory
File "pandas\_libs\parsers.pyx", line 968, in pandas._libs.parsers.TextReader._read_rows
File "pandas\_libs\parsers.pyx", line 1094, in pandas._libs.parsers.TextReader._convert_column_data
File "pandas\_libs\parsers.pyx", line 1141, in pandas._libs.parsers.TextReader._convert_tokens
File "pandas\_libs\parsers.pyx", line 1240, in pandas._libs.parsers.TextReader._convert_with_dtype
File "pandas\_libs\parsers.pyx", line 1256, in pandas._libs.parsers.TextReader._string_convert
File "pandas\_libs\parsers.pyx", line 1494, in pandas._libs.parsers._string_box_utf8
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc1 in position 0: invalid start byte
(stickers-gallito-app)
A: According to your commit comment, your latest edit was to "correct the encoding" of that file. However, what you did was to change the coding to a single-byte encoding, perhaps Windows CP 1252 (or ISO 8859-1/15, all of which are pretty similar). The file is not UTF-8, so you are lying to Pandas when you tell it that it is:
tmp_data=pd.read_csv('static/data/ubigeo-peru.csv',sep=',', encoding="utf-8")
Excel will cheerfully handle Windows CP 1252, and apparently whatever Github uses to render CSV files will do that as well. But Pandas goes by the encoding you tell it to use. In short, the fact that a file renders correctly in a browser or application does not mean that the original file was in the encoding you think it is in.
The particular error is generated when Pandas' CSV reader hits the first line for Áncash, because the Á character is 0xC1 in Western European single-byte encodings, and as the error message says 0xC1 is one of the handful of values which cannot appear in a UTF-8 file. The fact that it chokes at that point means that it didn't notice the incorrect encoding of, for example, ó in Asunción, which probably means that it has inserted an replacement character or possibly misinterpreted the input.
In any event, you should either restore the file to the UTF-8 version, or give Pandas the correct encoding when you read it.
| |
doc_1543
|
Here are devices and platforms I tested and the result of loading the image:
*
*All major desktop browsers (i.e. Win/IE, Mac/Win Safari, Mac/Win Chrome, Win/Opera, Mac/Win FireFox). PASSED
*iPhone 3G, running iOS 4.2.1, Mobile Safari. FAILED
*Opera Mini, on said iPhone 3G device. PASSED
*A colleague's iPhone 4S, running Mobile Safari. PASSED
*iOS Simulator, with Hardware->Version 5.0, Mobile Safari. PASSED
*iOS Simulator, with Hardware->Version 4.3.2, Mobile Safari. FAILED
*Android device, Version 2.3.3. PASSED
*Android SDK Emulator, Versions 1.5, 2.2, 2.3.3. PASSED
I decided to focus my attention on the iOS Simulator, Ver 4.3.2, since the image didn't even load up on a powerful desktop computer.
I thought it may be a memory issue with iOS 4.3.2 and Mobile Safari, perhaps related to the resource limits for images (iOS Development Guidelines). I understand there is a workaround for image limits (i.e. 6.5MB) but that didn't work for me, either (documented later).
The next thing I looked at was the size and dimension of the image. I downloaded a few free images (saved as GIFs) from the Internet and stored them locally on the server, all but one similar or larger in size and dimension than the image in question and they all loaded successfully in iOS Simulator, Ver 4.3.2.
FYI, the image sizes and dimensions were:
*
*238KB, 2428x1531
*414KB, 2993x2050
*238KB, 2000x1490
*196KB, 2192x2541
*196KB, 850x638
Going back to the image workaround, if I understand it right, the main idea is wrap the img in a canvas tag (I correctly called the drawImage function in JavaScript), which I did. Unfortunately, the GIF still did not load. I tried loading the image as a background-image in a div tag, as well, and, again, this did not work.
I can't think of anything else to try. Is it possible the GIF is corrupt? I honestly have no idea what else can I do.
Let me add in all the above methods I tried that failed, the other images I had downloaded all worked correctly (again, within the context of iOS Simulator, Version 4.3.2). And I even looked at the simple mistakes like spelling errors and the source and filename of the GIF in question is spelled correctly. I even tried changing the image extension from GIF to JPG and then PNG and the image still did not load.
I would appreciate any help. Thank you.
Update
I tried checking the validity of the image using the link here, How do I programmatically check whether an image (PNG, JPEG, or GIF) is corrupted?, and the image was not corrupt. If I find a solution, I'll be sure to document it.
Thank you.
Update2
I got a copy of iranView and saved the GIF as a JPG (not just renamed it, which is what I did last time) and the image loaded in iOS Simulator, version 4.3.2, Mobile Safari. Using this same method, I tried saving the GIF as a PNG, because JPG is too large, but it did not load. Then, I tried saving the GIF as a JPG, and I saved the JPG as a GIF, but it did not load, either. Only JPG worked.
Update3
It turns out that those images I tested are really JPEGs; so, I had to retest. I downloaded the images from Google images, ensuring they are GIFs and larger than 2 MP. Here is what I found:
Re-reading the Known iOS Resource Limits section from the Apple Developer site, it says:
The maximum size for decoded GIF, PNG, and TIFF images is 3 megapixels
for devices with less than 256 MB RAM and 5 megapixels for devices
with greater or equal than 256 MB RAM. That is, ensure that width *
height ≤ 3 * 1024 * 1024 for devices with less than 256 MB RAM. Note
that the decoded size is far larger than the encoded size of an image.
The maximum decoded image size for JPEG is 32 megapixels using
subsampling. JPEG images can be up to 32 megapixels due to
subsampling, which allows JPEG images to decode to a size that has one
sixteenth the number of pixels. JPEG images larger than 2 megapixels
are subsampled—that is, decoded to a reduced size. JPEG subsampling
allows the user to view images from the latest digital cameras.
The maximum size for a canvas element is 3 megapixels for devices with
less than 256 MB RAM and 5 megapixels for devices with greater or
equal than 256 MB RAM. The height and width of a canvas object is 150
x 300 pixels if not specified.
If all the above is ironclad, then why does images "earth_lights.gif" and "logoJDC_orange_GIF.gif" display on the iPhone 3G (4.2.1), yet does not display on iOS Simulator (4.3.2)? I tested all images with IrfanView to ensure their formats are correct - GIFs are truly GIFs and JPGs are truly JPGs. Based on all this testing, I'm leaning towards deducing Mobile Safari's decoding of GIFs, at least on dated iOS firmware, is inconsistent, as opposed to concluding the GIF image I was originally trying to display is corrupt.
| |
doc_1544
|
My problem is the core logic can block for several seconds if the requested number of output elements is large. Since I've been playing with ES6 for this project, my first thought was to factor out the element creation into a generator[2]. However, the only way I can find to get all the results from this generator is Array.from, which doesn't help with the blocking.
I've played around with .map, .all, .coroutine, and a couple of other things, in an attempt to asynchronously collect the results from the generator, but I haven't had any luck. Is there any nice way to do this with Bluebird? (Or perhaps a better way of doing it altogether?)
Native ES6 Promise.all can take an iterator and give back an array of values, but V8 doesn't support this yet. Also, in my experimentation with polyfills/Firefox, it seems to be synchronous.
This is not-too-common operation, so I don't care much about absolute performance. I just want to avoid blocking the event queue, and I would prefer a nice, easy to read and maintain solution.
[1]:
let Bluebird = require('bluebird');
let templates = ...; // logic to load data templates
function createRandomElementFromRandomTemplate(templates) {
let el;
// synchronous work that can take a couple of milliseconds...
return el;
};
api.createRandomElements = function(req, res) {
let numEls = req.params.numEls;
Bluebird.resolve(templates)
.then(templates => {
let elements = [];
// numEls could potentially be several thousand
for(let i = 0; i < numEls; ++i) {
elements.push(createRandomElementFromRandomTemplate(templates));
}
return elements;
})
.then(elements => {
res.json(elements);
})
.error(err => {
res.status(500).json(err);
});
}
[2]:
function* generateRandomElementsFromRandomTemplate(templates, numEls) {
for(let i = 0; i < numEls; ++i) {
let el;
// synchronous work that can take a couple of milliseconds...
yield el;
}
}
api.createRandomElements = function(req, res) {
let numEls = req.params.numEls;
Bluebird.resolve(templates)
.then(templates => {
// this still blocks
return Array.from(generateRandomElementsFromRandomTemplate(templates, numEls));
})
.then(elements => {
res.json(elements);
})
.error(err => {
res.status(500).json(err);
});
}
A: Here's a halfway-decent solution I found after looking more closely at Bluebird's .map() as Benjamin suggested. I still have the feeling I'm missing something, though.
The main reason I started with Bluebird was because of Mongoose, so I left a bit of that in for a more realistic sample.
let Bluebird = require('bluebird');
let mongoose = require('mongoose');
Bluebird.promisifyAll(mongoose);
const Template = mongoose.models.Template,
UserPref = mongoose.models.UserPref;
// just a normal function that generates one element with a random choice of template
function createRandomElementFromRandomTemplate(templates, userPrefs) {
let el;
// synchronous work that can take a couple of milliseconds...
return el;
}
api.generate = function(req, res) {
let userId = req.params.userId;
let numRecord = req.params.numRecords
let data;
Bluebird.props({
userprefs: UserPref.findOneAsync({userId: userId}),
templates: Template.findAsync({})
})
.then(_data => {
data = _data;
// use a sparse array to convince .map() to loop the desired number of times
return Array(numRecords);
})
.map(() => {
// ignore the parameter map passes in - we're using the exact same data in each iteration
// generate one item each time and let Bluebird collect them into an array
// I think this could work just as easily with a coroutine
return Bluebird.delay(createRandomElementFromRandomTemplate(data.templates, data.userprefs), 0);
}, {concurrency: 5})
.then(generated => {
return Generated.createAsync(generated);
})
.then(results => {
res.json(results);
})
.catch(err => {
console.log(err);
res.status(500);
});
};
| |
doc_1545
|
Fatal error: Uncaught Doctrine\ORM\Mapping\MappingException: The
target-entity Shop cannot be found in 'User#shops'. in
I just have a User class.
/**
* @Entity
**/
class User
{
/** @Id
* @Column(type="integer")
* @GeneratedValue
**/
protected $id;
/**
* @OneToMany(targetEntity="Shop", mappedBy="user")
*/
protected $shops;
public function __construct()
{
$this->shops = new \Doctrine\Common\Collections\ArrayCollection();
}
}
Who has multiple Shops.
/**
* @Entity
*/
class Shop
{
/** @Id
* @Column(type="integer")
* @GeneratedValue
**/
protected $id;
/**
* @ManyToOne(targetEntity="User", inversedBy="shops")
*/
protected $user;
}
They are in the same directory, so it is not a namespace issue isn't it ?
Getters & Setters has been generated has well, but still does not change a thing.
TIPS : If a put all my classes in the same php file, it works !
A: Provided these are the full files, you are not writing any namespace declarations on the classes. Therefore the Entity classes are put in the \ root namespace.
So to resolve this you will either need to use the FQN (Full Qualified Name) or import the classes.
Using FQN (my recommendation)
/**
* @OneToMany(targetEntity="\Shop", mappedBy="user")
*/
(add the same in the other class as well)
Using import
Add this on the top of the User class
use \Shop;
(the inverse in the other class of course)
Note: The PHP Interpreter doesn't check for usages in Annotations, so if you don't use the class elsewhere in the file, PHP might show a warning about an unused import if that is enabled.
| |
doc_1546
|
My project structure looks like this:
root/
int-test/
build.gradle
web/
build.gradle
build.gradle
settings.gradle
File content
root/settings.gradle:
include ':web'
include ':int-test'
root/build.gradle:
apply plugin: 'java'
root/web/build.gradle:
apply plugin: 'war'
apply from: 'https://raw.github.com/akhikhl/gretty/master/pluginScripts/gretty.plugin'
gretty {
contextPath = '/'
integrationTestTask = 'intTests'
}
task intTests << {
println 'This task will run in just the right time'
}
root/int-test/build.gradle:
apply plugin: 'java'
task intTests << {
println 'All integration testing is done in here'
}
When I run "./gradlew -q intTests", this is the output:
All integration testing is done in here
2014-12-11 15:37:02.046 INFO - Logging initialized @1157ms
2014-12-11 15:37:02.554 INFO - jetty-9.2.3.v20140905
2014-12-11 15:37:02.682 WARN - ServletContainerInitializers: detected. Class hierarchy: empty
2014-12-11 15:37:03.114 INFO - Started o.a.g.JettyWebAppContext@7da22e4a{/,file:/Users/fredrik/callista/dev/grettyfitnesse/web/build/inplaceWebapp/,AVAILABLE}
2014-12-11 15:37:03.130 INFO - Started ServerConnector@2590ae17{HTTP/1.1}{0.0.0.0:8080}
2014-12-11 15:37:03.130 INFO - Started @2245ms
2014-12-11 15:37:03.137 WARN - Jetty 9.2.3.v20140905 started and listening on port 8080
2014-12-11 15:37:03.158 WARN - runs at:
2014-12-11 15:37:03.159 WARN - http://localhost:8080/
This task will run in just the right time
2014-12-11 15:37:03.221 INFO - Stopped ServerConnector@2590ae17{HTTP/1.1}{0.0.0.0:8080}
2014-12-11 15:37:03.229 INFO - Stopped o.a.g.JettyWebAppContext@7da22e4a{/,file:/Users/fredrik/callista/dev/grettyfitnesse/web/build/inplaceWebapp/,UNAVAILABLE}
2014-12-11 15:37:03.232 WARN - Jetty 9.2.3.v20140905 stopped.
Server stopped.
So, the intTests task in the web project will run in the right moment but the intTests task in the int-test project will run way to early (before the web server has been started). How do I set this up so that the gretty plugin "connects" to the intTests task defined in my int-test project?
Things I have tried:
* Setting "integrationTestTask = ':int-test:intTests'" hoping that it would be enough to specify in which subproject gretty should be looking for the correct task. Result - jetty is not even started.
* Creating the intTests task in the root build.gradle trying to extend that task in int-test. Result - no difference.
* Added a dependsOn(":int-test:intTests") to the intTests task in web project. Result - no difference
A: First, check if gretty.integrationTestTask = ":int-test:intTests" works. If not, add the following to int-tests/build.gradle:
intTests {
dependsOn(":web:taskThatStartsTheWebServer")
finalizedBy(":web:taskThatStopsTheWebServer")
}
(You can find the task names in the Gretty docs or the output of gradle tasks.)
Note that it's task foo { dependsOn "bar" }, not task foo << { dependsOn "bar" }. Recent Gradle versions will detect this mistake and fail the build.
| |
doc_1547
|
public class MainActivity extends Activity implements NumberPicker.OnValueChangeListener, View.OnClickLis``tener {
String[] searches = {"Height", "Weight", "Hair Colour"};
List<String> childList;
List<String> groupList;
Map<String, List<String>> advSearchOption;
ExpandableListView expListView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createGroupList();
createCollection();
expListView = (ExpandableListView) findViewById(R.id.search_list);
final ExpandableListAdapter expListAdapter = new ExpandableListAdapter(
this, groupList, advSearchOption);
expListView.setAdapter(expListAdapter);
expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
Intent k;
@Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
switch (childPosition){
case 0:
k = new Intent(getApplicationContext(), ChildActivity.class);
break;
case 1:
k = new Intent(getApplicationContext(), ChildActivity.class);
break;
}
startActivity(k);
return true;
}
});
private void createGroupList() {
groupList = new ArrayList<String>();
groupList.add("Advanced Search");
}
private void createCollection() {
// preparing laptops collection(child)
String[] searches = {"Height", "Weight", "Hair Colour"};
advSearchOption = new LinkedHashMap<String, List<String>>();
for (String advSearch : groupList) {
if (advSearch.equals("Advanced Search")) {
loadChild(searches);
}
advSearchOption.put(advSearch, childList);
}
}
private void loadChild(String[] searchOptions) {
childList = new ArrayList<String>();
for (String model : searchOptions)
childList.add(model);
}
private void setGroupIndicatorToRight() {
/* Get the screen width */
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
package com.mycompany.testing;
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Activity context;
private Map<String, List<String>> advSearchOptions;
private List<String> options;
public ExpandableListAdapter(Activity context, List<String> options,
Map<String, List<String>> advSearchOptions) {
this.context = context;
this.advSearchOptions = advSearchOptions;
this.options = options;
}
public Object getChild(int groupPosition, int childPosition) {
return advSearchOptions.get(options.get(groupPosition)).get(childPosition);
}
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
public View getChildView(final int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final String laptop = (String) getChild(groupPosition, childPosition);
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.child_item, null);
}
TextView item = (TextView) convertView.findViewById(R.id.advSearch);
item.setText(laptop);
return convertView;
}
public int getChildrenCount(int groupPosition) {
return advSearchOptions.get(options.get(groupPosition)).size();
}
public Object getGroup(int groupPosition) {
return options.get(groupPosition);
}
public int getGroupCount() {
return options.size();
}
public long getGroupId(int groupPosition) {
return groupPosition;
}
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String laptopName = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.group_item,
null);
}
TextView item = (TextView) convertView.findViewById(R.id.advSearch);
item.setTypeface(null, Typeface.BOLD);
item.setText(laptopName);
return convertView;
}
public boolean hasStableIds() {
return true;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
| |
doc_1548
|
Is there any way to disable this effect entirely? I have seen ways here to display an image upon background activation that pushes on top of the view and is displayed first in place of the snapshot when the user returns to the app, but I would like this feature to go away entirely and not have to save any snapshots or any other screen capture when the user goes into the app again. Can anyone suggest a way to do this?
Note that I am not talking about taking a screenshot with home button + sleep button press.
A: In the applicationWillResignActive: method of your app delegate, you can make a UIImageView of something inconspicuous pop-up. For example, let's say your application holds a user's passwords. Someone is walking behind the user and the user presses the home button. This calls the applicationWillResignActive: method, which puts up perhaps a map view, so when the walker is gone and the user reopens the application, it opens directly to a map view instead of to a brief snapshot of the users passwords. This is how you might implement it:
//AppDelegate.m
- (void)applicationWillResignActive:(UIApplication *)application {
UIImageView *image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"picOfMap.png"]];
image.frame = self.view.frame;
image.contentMode = UIViewContentModeCenter;
[self.window.rootViewController.view addSubview: image];
}
And here's a description of when applicationWillResignActive: is called:
This method is called to let your application know that it is about to move from the active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. An application in the inactive state continues to run but does not dispatch incoming events to responders. (UIApplicationDelegate Reference)
There may be some bugs in the code because I'm not familiar with working in the App Delegate, but that's the gist of what you should do.
A: Here is a Technical Q&A by Apple on this topic: https://developer.apple.com/library/archive/qa/qa1838/_index.html
In short, code snippets in Swift are following:
func applicationDidEnterBackground(_ application: UIApplication) {
let someVCToShowInAppSwitcher = ...
window?.rootViewController?.present(someVCToShowInAppSwitcher, animated: false)
}
and
func applicationWillEnterForeground(_ application: UIApplication) {
// Make sure that we'll dismiss an expected VC, e.g.:
if window?.rootViewController?.presentedViewController?.view.accessibilityIdentifier == "someVCToShowInAppSwitcher" {
window?.rootViewController?.dismiss(sender: self)
}
}
| |
doc_1549
|
I have set it to be callable from right click, Command Palette, Activity Bar, Keyboard Shortcuts or clicking on the WebView button.
Now, I've been asked to identify the call source.
I'd prefer to not create myExtension.doSomething.rightClick, myExtension.doSomething.webview, etc.
I've checked and this does not come in the default args when the command handler is called.
| |
doc_1550
|
*
*My date column is currently in UTC;
*I need to convert it to EST.
A: It can be achieved using the new Date and Time functions (introduced in the 17 Sep 2020 Update).
0) Upgrade the Date Field
Ensure that the Date field has been upgraded to to the newer Date field type.
Added a GIF to elaborate:
1) EST
The Calculated Field below looks at the DATETIME_DIFF between CURRENT_DATETIME("UTC") and CURRENT_DATETIME("EST") and then subtracts the difference with the DateTime field (titled Field in this report):
PARSE_DATETIME(
"%s",
CAST(CAST(FORMAT_DATETIME("%s", Field)AS NUMBER) - DATETIME_DIFF(CURRENT_DATETIME("UTC"), CURRENT_DATETIME("EST"), SECOND)AS TEXT ))
Google Data Studio Report and a GIF to elaborate:
A: to_char(timezone('America/Toronto', timezone('UTC', table.created_at)), 'YYYYMMDDHH') AS created_at_datehour
| |
doc_1551
|
This is my trigger:
ALTER TRIGGER [dbo].[DUPLICATES]
ON [dbo].[AMGR_User_Fields_Tbl]
FOR INSERT, UPDATE
AS
DECLARE @Alphanumericcol VARCHAR (750)
-- This trigger has been created to check that duplicate rows are not inserted into table.
-- Check if row exists
SELECT @Alphanumericcol
FROM Inserted i, AMGR_User_Fields_Tbl t
WHERE t.AlphaNumericCol = i.AlphaNumericCol
AND t.Client_Id = i.Client_Id
-- (@Alphanumericcol = 1)
-- Display Error and then Rollback transaction
BEGIN
RAISERROR ('This row already exists in the table', 16, 1)
ROLLBACK TRANSACTION
END
The result I get is, if I input a duplicate number it fills in a null in the column so my question is how do I get it to tell me its duplicate and let me insert a new one
| |
doc_1552
|
http://developers.facebook.com/docs/opengraph
if your open graph page has coordinates in the meta data like this:
<html xmlns:og="http://ogp.me/ns#">
<head>
...
[REQUIRED TAGS]
<meta property="og:latitude" content="37.416343"/>
<meta property="og:longitude" content="-122.153013"/>
<meta property="og:street-address" content="1601 S California Ave"/>
<meta property="og:locality" content="Palo Alto"/>
<meta property="og:region" content="CA"/>
<meta property="og:postal-code" content="94304"/>
<meta property="og:country-name" content="USA"/>
...
</head>
would it work? An open graph page would have an ID and could this ID work for the checkin app?
Is it possible for me to create an open graph page and use it with the checkin app or does this only work for established businesses with established physical locations?
A: I have been wondering the same thing. I think this might help.
| |
doc_1553
|
public interface IDatabase
{
void Save();
}
public class SqlDatabase : IDatabase
{
public void Save()
{
Console.WriteLine("Saving data to Database");
}
}
// Simple calling class...works fine!
IDatabase database = new SqlDatabase();
How do I do that in MOQ?
Mock<IDatabase> mockDatabase = new Mock<SqlDatabase>(); does NOT work!!!
Error CS0029 Cannot implicitly convert type SqlDatabase to IDatabase
/////// UNIT TEST
[Fact]
public void SaveToDatabase()
{
string comment = "Team, I know that times are tough! Product sales have been disappointing for the past three quarters. We have a competitive product, but we need to do a better job of selling it!";
Mock<IDatabase> mockDatabase = new Mock<IDatabase>();
// Not Required!
// Mock<AnalyzerModel> mockAnalyzerModel = new Mock<AnalyzerModel>();
// mockDatabase.Setup(x => x.Save(mockAnalyzerModel.Object));
var sut = new ToneAnalyzerEngine(mockDatabase.Object);
var v = sut.Analyze(comment, MockToneAnalyzerResultSadness());
mockDatabase.Verify(x => x.Save(It.IsAny<AnalyzerModel>()), Times.Once);
mockDatabase.VerifyNoOtherCalls();
}
/////// Code Called
internal bool Analyze(string comment, ToneAnalyzerResult toneAnalyzerResult)
{
bool isPositive = IsPositive(toneAnalyzerResult);
AnalyzerModel analyzerModel = CreateAnalyzerModel(Guid.NewGuid().ToString(), isPositive, comment);
_database.Save(analyzerModel);
return isPositive;
}
| |
doc_1554
|
out of them. Have tried to play with gl_PointCoord and gl_FragCoord without any results. Maybe, someone here could help me?
I need effect similar to this animated gif:
uniform float time;
uniform vec2 mouse;
uniform vec2 resolution;
#define M_PI 3.1415926535897932384626433832795
float rand(vec2 co)
{
return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);
}
void main( ) {
float size = 30.0;
float prob = 0.95;
vec2 pos = floor(1.0 / size * gl_FragCoord.xy);
float color = 0.0;
float starValue = rand(pos);
if (starValue > prob)
{
vec2 center = size * pos + vec2(size, size) * 0.5;
float t = 0.9 + sin(time + (starValue - prob) / (1.0 - prob) * 45.0);
color = 1.0 - distance(gl_FragCoord.xy, center) / (0.5 * size);
color = color * t / (abs(gl_FragCoord.y - center.y)) * t / (abs(gl_FragCoord.x - center.x));
}
else if (rand(gl_FragCoord.xy / resolution.xy) > 0.996)
{
float r = rand(gl_FragCoord.xy);
color = r * ( 0.25 * sin(time * (r * 5.0) + 720.0 * r) + 0.75);
}
gl_FragColor = vec4(vec3(color), 1.0);
}
As I understand have to play with vec2 pos, setting it to a vertex position.
A: You don't need to play with pos. As Vertex Shader is only run by each vertex, there is no way to process its pixel values there using Pos. However, you can do processing pixel using gl_PointCoord.
I can think of two ways only for changing the scale of a texture
*
*gl_PointSize in Vertex Shader in opengl es
*In Fragment Shader, you can change the texture UV value, for example,
vec4 color = texture(texture0, ((gl_PointCoord-0.5) * factor) + vec2(0.5));
If you don't want to use any texture but only pixel processing in FS,
you can set UV like ((gl_PointCoord-0.5) * factor) + vec2(0.5)
instead of uv which is normally set as fragCoord.xy / iResolution.xy in Shadertoy
| |
doc_1555
|
class Vertex
{
public:
std::vector<float> coords;
//other functionality here - largely irrelevant
};
And lets say we create a Vertex object as below:
Vertex v0(1.f, 5.f, 7.f);
I am wondering if there is anyway to assign a name to each element of a vector?
Let's say that each std::vector will only ever have a size of 3. I know I can access an element or index of the vector in a way such as v0.coords[0] through to v0.coords[2];
However, I am wondering if there is a way in which I could assign a name to each element of the vector, ie:
v0.coords.x == v0.coords[0];
v0.coords.y == v0.coords[1];
v0.coords.z == v0.coords[2];
So that if I was to access the vector, I could access via a name rather than an index.
Is such a thing possible? If so, how do I go about creating such aliasing?
A:
I am wondering if there is anyway to assign a name to each element of a vector?
No, there is not. At least, not the way you want.
I suppose you could use macros, eg:
#define coords_x coords[0]
#define coords_y coords[1]
#define coords_x coords[2]
Now you can use v0.coords_x, v0.coords_y, and v0.coords_z as needed.
Or, you can use getter methods, eg:
class Vertex
{
public:
vector<float> coords;
//other functionality here - largely irrelevant
float& x(){ return coords[0]; }
float& y(){ return coords[1]; }
float& z(){ return coords[2]; }
};
Now you can use v0.x(), v0.y(), and v0.z() as needed.
But really, in this situation, there is just good no reason to use a vector at all. It is simply the wrong tool for the job. Use a struct instead, eg:
struct Coords
{
float x;
float y;
float z;
};
class Vertex
{
public:
Coords coords;
//other functionality here - largely irrelevant
};
Alternatively:
class Vertex
{
public:
struct
{
float x;
float y;
float z;
} coords;
//other functionality here - largely irrelevant
};
Now you can use v0.coords.x, v0.coords.y, and v0.coords.z as needed.
| |
doc_1556
|
i have attached hover and mouseout event to id='nf1' using this code
$("#nf"+n).hover(function(){
$("#nf"+$(this).attr("post_id")+"post_delete").show();
});
$("#nf"+n).mouseout(function(){
$("#nf"+$(this).attr("post_id")+"post_delete").hide();
});
Here n is post_id and i am looping all post_id got from response.This attach events but not giving expected behaviour Like when mouse over to id='nf1post_delete' it is hide
Please ask if any doubts
A: The way you're describing this, you will actually want to pass two functions to .hover(), one for the action on mouseenter and one for the action on mouseleave. You can pass only one function to .hover(), but it will run that function when you roll over and when you roll out.
http://api.jquery.com/hover/
So, try this instead:
$("#nf"+n).hover(function(){
$("#nf"+$(this).attr("post_id")+"post_delete").show();
},function(){
$("#nf"+$(this).attr("post_id")+"post_delete").hide();
});
The .mouseout() function isn't needed at all.
A: At first, .hover() includes mouseenter and mouseleave. Do you put both function in there and don't use an additional event. Also don't use mouseout(). Use instead mouseleave().
So you either use hover(function(){},function(){}); alone, or you use mouseenter() and mouseleave().
A: Since you're manipulating the DOM, I'm going to recommend using jQuery .on() instead of .hover():
$(document).on({
mouseover: function(){
$("#nf"+$(this).attr("post_id")+"post_delete").show();
},
mouseout: function(){
$("#nf"+$(this).attr("post_id")+"post_delete").hide();
}
}, "#nf"+n);
If you're creating something in the DOM after the page has loaded, .on() helps to attach event listeners to it.
jQuery API for .on()
| |
doc_1557
|
import sys
from os import replace
from random import *
from time import sleep
# The horses
a = 'jack'
b = 'slow'
c = 'thunder'
# array for the horses racing
Horses = [a, b, c]
Position = []
# Race start point
countA = 0
# message afer race is done
msg = '\nRace Finished\nGetting results.'
# Length of the race
distance = 15
# starting amount
money = int( input( "Insert Money: " ) )
print( )
# The starting position of each horse
jack = 0
slow = 0
thunder = 0
# compare countA to distance:
def raceAlgorithm(countA, msg, distance,jack,slow,thunder):
while countA != distance:
dice = randint( 1, 6 )
sleep( 1 )
countA += 1
if dice <= 2:
jack += 1
# print('\n'+str(countB))
# print(a)
elif dice <= 4:
slow += 1
# print('\n'+str(countC))
# print(b)
else:
thunder += 1
# print('\n'+str(countD))
# print(c)
if jack + slow + thunder == distance:
print( msg )
Position.append( jack )
Position.append( slow )
Position.append( thunder )
Position.sort( reverse=True )
# Horse selection
def horse_selection():
while True:
print( '\n.....Select Horse....' )
print( Horses )
horse = input('\nSelect Horse:')
if horse in Horses:
print( '\n...........You have Chosen......' )
print( '\n<<....>> ' + horse + ' <<....>>' )
return horse
break
# print your starting wallet
while True:
if 0 < money < 51:
print( 'You have €' + str( money ) + ' euros in your wallet.' )
print( )
break
else:
print( "This amount is not allowed\nThe limit is 50. Try Again!!" )
print( )
money = int( input( "Insert Money: " ) )
sleep( 1 )
print( )
def bet_amt(money):
amt = int( input( '\nEnter the amount you want to bet: ' ) )
if amt > money:
print( 'Insufficient Funds' )
sleep( 1 )
bet_amt( money )
elif amt < 0:
print( 'This amount is not allowed' )
sleep( 1 )
bet_amt( money )
else:
money -= amt
print( 'You have €' + str( money ) + " euros left." )
# If they want to pay
def myBet():
# if choice is one of this
Continue = ['Y', 'y']
Cancel = ['N', 'n']
while True:
Bet = input( '\nDo you want to place a bet:\n Enter Y/n: ' )
if Bet in Continue:
bet_amt( money )
break
elif Bet in Cancel:
print( '\nCome back again next time\nPlease take your voucher.' )
exit( )
else:
print( '\nInvalid Choice. Try Again!!!!' )
sleep( 1 )
def race_results():
if jack in Position[0]:
print(a)
elif slow in Position[0]:
print(b)
else:
print(c)
while money > 0:
bet_amt( money )
else:
exit( )
# myBet function
myBet( )
# picking your horse
horse_selection( )
print( )
# race countdown
for i in range( 10, 0, -1 ):
print( i )
sleep( 1 )
# Start of race
print( '\n..The race Has begun..' )
# race algorithm
raceAlgorithm( countA, msg, distance, jack, slow, thunder)
print( )
print( *Position, sep='\n' )
race_results( )
I am trying to print the name of the horse that's in first position rather than just the int. I get a cannot reiterate int error when i try to print the first position of the list.
A: You can assign the function to a variable and display the name of Horse wherever required.
# picking your horse
hs = horse_selection( )
print(hs)
A: In [11]: type(jack)
Out[11]: int
In [12]: type (Position[0])
Out[12]: int
Your code is using is in for comparison which, I don't believe, is valid for comparing ints. You should use ==
def race_results():
if jack == Position[0]:
print(a)
elif slow == Position[0]:
print(b)
else:
print(c)
while money > 0:
bet_amt( money )
else:
exit( )
My results:
..The race Has begun..
Race Finished
Getting results.
7
5
3
thunder
| |
doc_1558
|
A: You can use a NativeImageLoader for the conversion.
import org.datavec.image.loader.NativeImageLoader;
(...)
Mat cvImage();
// Fill in your Mat with something
NativeImageLoader nil = new NativeImageLoader();
INDArray image = nil.asMatrix(cvImage).div;
Make sure you have the dependency for datavec in your pom.xml. What error do you get?
| |
doc_1559
|
I'm using the .NET SDK and the API I am using is this one.
https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.cognitiveservices.vision.computervision.computervisionclientextensions.readasync?view=azure-dotnet
I have also confirmed that the actual REST API the SDK calls is the following POST /vision/v3.2/read/analyze
https://centraluseuap.dev.cognitive.microsoft.com/docs/services/computer-vision-v3-2/operations/5d986960601faab4bf452005
According to documentation, that should be the OCR Read API, am I correct?
https://learn.microsoft.com/en-us/azure/cognitive-services/computer-vision/vision-api-how-to-topics/call-read-api
I am puzzled as to why my calls are getting charged as S3 instead of S2. This is important for me because S3 is 50% more expensive than S2. Using the Pricing Calculator, 1000 S2 transactions is $1, whereas 1000 S3 transactions is $1.5.
https://azure.microsoft.com/en-us/pricing/calculator/?service=cognitive-services
What's the difference between OCR and "Describe and Recognize Text" anyways? OCR (Optical Character Recognition) by definition must recognize text. I am calling the Read API without any of the optional parameters so I did not ask for "Describe" hence the call should be S2 feature rather than S3 feature I think.
I already posted this question at Microsoft Q&A but I thought SO might get more traffic hence help me get an answer faster.
https://learn.microsoft.com/en-us/answers/questions/689767/computer-vision-api-charged-as-s3-transaction-inst.html
A: To help you understand, you need a bit of history of those services. Computer Vision API (and all "calling" SDKs, whether C#/.Net, Java, Python etc using these APIs) have moved frequently and it is sometimes hard to understand which SDK calls which version of the APIs.
API operations history
Regarding optical character reading operations, there have been several operations:
Computer Vision 1.0
See definition here was containing:
*
*OCR operation, a synchronous operation to recognize printed text
*Recognize Handwritten Text operation, an asynchronous operation for handwritten text (with "Get Handwritten Text Operation Result" operation to collect the result once completed)
Computer Vision 2.0
See definition here. OCR was still there, but "Recognize Handwritten Text" was changed. So there were:
*
*OCR operation, a synchronous operation to recognize printed text
*Recognize Text operation, asynchronous (+ Get Recognize Text Operation Result to collect the result), accepting both printed or handwritten text (see mode input parameter)
*Batch Read File operation, asynchronous (+ "Get Read Operation Result" to collect the result), which was also processing PDF files whereas the other one were only accepting images. It was intended "for text-heavy documents"
Computer Vision 2.1 was similar in terms of operations.
Computer Vision 3.0
See definition here.
Main changes: Recognize Text and Batch Read File were "unified" into a Read operation, with models improvements. No more need to specify handwritten / printed for example (see link).
The Read API is optimized for text-heavy images and multi-page, mixed language, and mixed type (print – seven languages and handwritten – English only) documents
So there were:
*
*OCR operation, a synchronous operation to recognize printed text
*Read operation, asynchronous (+ Get Read Result to collect the result), accepting both printed or handwritten text, images and PDF inputs.
Same for Computer Vision v3.1-preview.1, v3.1-preview.2, v3.1, v3.2-preview.1, v3.2-preview.2, v3.2-preview.3
SDKs
All recent versions of the SDKs implementing a Read method are calling this 3.x. operation. See the changelog for example for .Net SDK here:
v7.0.x of the SDK "supports v3.2 Cognitive Services Computer Vision API endpoints."
Conclusion
It is normal that you are billed S3 for Read. But the calculator is misleading as the "Recognize Text" term should be changed for "Read".
If you really want to use OCR operation, use RecognizePrintedTextAsync method of the SDK which is the one using it.
OCR is an old model, used only for printed text. Read operation is the latest model.
I can also confirm (based on a few tests that I made) that the performance is lower than Read operation. If you want to quickly test, you can use your key on this website: it is an open-source portal created by another Microsoft MVP, where I also contributed. You will be able to see both results of OCR and Read operations. It is currently using 6.0.0 SDK version of Computer Vision (see source).
Sample:
OCR result:
Read result:
| |
doc_1560
|
java.lang.ClassNotFoundException: com.datastax.spark.connector.rdd.CassandraRDD". But I included spark-cassandra-connector_2.10 in my pom.xml which has com.datastax.spark.connector.rdd.CassandraRDD class.Am i missing any other settings or environment variables.
A: You need to make sure that the connector is on the class-path for the executor using the -cp option or that it is a bundled jar in the spark context (using the SparkConf.addJars() ).
Edit for Modern Spark
In Spark > 1.X it's usually recommend that you use the spark-submit command to place your dependencies on the executor classpath. See
http://spark.apache.org/docs/latest/submitting-applications.html
| |
doc_1561
|
Is there any other way to persist the culture in the Url on navigation other than this ?
app.UseRequestLocalization(new RequestLocalizationOptions
{
ApplyCurrentCultureToResponseHeaders = true
});
A: Which RequestCultureProvider are you using?
You can use RouteDataRequestCultureProvider and a route with a pattern containing culture such as {culture}/{controller}/{action}/{id?}
The ApplyCurrentCultureToResponseHeaders attribute will be in 5.0 and is not in 3.1. See Add Content-Language header in localization middlewware
Hope that helps.
| |
doc_1562
|
I know that ThreadStatic won't work because a SignalR thread can be shared between multiple requests.
For reference I am hosting it within IIS and using the latest version of SignalR (2.2.0)
A: This is certainly very late for answering this question and maybe you have already figured out something for this. This is just an attempt to share my thought on this problem.
So to start with, you can enable authentication for SignalR, and then you can use Context.User.xxx in your hub methods.
For enabling authentication for all hubs you can do something like this:
public partial class Startup {
public void Configuration(IAppBuilder app) {
app.MapSignalR();
GlobalHost.HubPipeline.RequireAuthentication();
}
}
Once you do that you can still use your usual authentication pipeline to authenticate your requests, and those information will be supplied to Hub methods via Context.User property. Below is one example from here.
public async Task JoinRoom(string roomName)
{
await Groups.Add(Context.ConnectionId, roomName);
Clients.Group(roomName).addChatMessage(Context.User.Identity.Name + " joined.");
}
Along with this you can maintain per-user data in an out-of-memory storage (so that it can scale out), such as Redis cache or something similar.
Or as an alternative approach, you can also extend HubPipelineModule, and create a custom one to have more granular control on events.
public class LoggingPipelineModule : HubPipelineModule
{
protected override bool OnBeforeIncoming(IHubIncomingInvokerContext context)
{
return base.OnBeforeIncoming(context);
}
protected override bool OnBeforeOutgoing(IHubOutgoingInvokerContext context)
{
return base.OnBeforeOutgoing(context);
}
}
public void Configuration(IAppBuilder app)
{
GlobalHost.HubPipeline.AddModule(new LoggingPipelineModule());
app.MapSignalR();
}
Hope this helps. Also it would be interesting to know how you have dealt with the problem.
| |
doc_1563
|
I get my user id through api call in java and in PHP api function, used the following code:
$user_id = $this->session->userdata('user_id');
Normally this returns my user id when i call this funcion through api.
But in java when it calls the api, than it returns null.
user id =
But if i hardcode the user id in PHP like this:
$user_id = "3";
Then java can get the user id through api call. But do not want to use any hard code value in PHP. Any suggestions please.
| |
doc_1564
|
You can see it for yourself with this snippet:
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 10.0, 10.0)];
for (NSUInteger i = 0; i < 100; i++) {
view.transform = CGAffineTransformRotate(view.transform, ((90.0) / 180.0 * M_PI));
NSLog(@"%@", NSStringFromCGRect(view.frame));
}
Any help is greatly appreciated!
A: If the floating point inaccuracies are causing problems, one possible workaround for exactly 90 degrees is to specify the matrix by hand:
// rotate by 90˚
view.transform = CGTransformConcat(view.transform,
CGAffineTransformMake(0, 1, -1, 0, 0, 0));
These magic numbers come from the equation of a rotation matrix:
⎛ cos α sin α 0 ⎞
⎜-sin α cos α 0 ⎟
⎝ 0 0 1 ⎠
And then the left 6 parameters become the parameters to CGAffineTransformMake
when α = 90˚, we get (0, 1, -1, 0, 0, 0)
A: If you're looking to normalize these values, you can use CGRectIntegral. From the docs (this may change the rectangle)
A rectangle with the smallest integer values for its origin and size
that contains the source rectangle. That is, given a rectangle with
fractional origin or size values, CGRectIntegral rounds the
rectangle’s origin downward and its size upward to the nearest whole
integers, such that the result contains the original rectangle.
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 10.0, 10.0)];
for (NSUInteger i = 0; i < 100; i++) {
view.transform = CGAffineTransformRotate(view.transform, M_PI_2);
NSLog(@"%@", NSStringFromCGRect(CGRectIntegral(view.frame)));
}
| |
doc_1565
|
library(tidyverse)
data <- data_frame(programme = rep(rep(c('A', 'B', 'C'), each = 10),10), value = rnorm(300),
phase = rep(c("incoming", "torque"),150))
splitted_data <- data %>%
split(., .$phase)
all_lms <- splitted_data %>%
map(~lm(value~programme, .))
So here I am comparing the three programs separately for the two phases (I have much more models than this).
This is fast, however, looking at the call stored in the lm objects, one can see that the data field is equal to .
all_lms$incoming$call$data
If I want to use this list further down the line with other functions that need to know where the data used to fit the model are stored, I would need to change this field to the actual name of the object where the data are stored, so for example for all_lms$incoming$call$data I would like to have splitted_data$incoming.
If I try to assign another value to the data field as a string, as in
all_lms$incoming$call$data <- "splitted_data$incoming", it doesn't work, as it is, well a string, and not the object. At the same time, if I try to assign it as an object, as in all_lms$incoming$call$data <- splitted_data$incoming, it is all the actual object that is assigned, i.e. the data frame, and not a link to the object.
Is there a way to do what I want or should I just perform the pipeline model by model several times ?
A: I think your method already does assign just a reference to the object (or a "link" to the object as you put it), rather than copying it. For his book Advanced R Hadley Wickham created the tool lobstr to help track references
> library(lobstr)
> library(tidyverse)
> data <- data_frame(programme = rep(rep(c('A', 'B', 'C'), each = 10),10), value = rnorm(300),
phase = rep(c("incoming", "torque"),150))
> splitted_data <- data %>%
split(., .$phase)
> all_lms <- splitted_data %>%
map(~lm(value~programme, .))
> all_lms$incoming$call$data <- splitted_data$incoming
> lobstr::obj_addr(all_lms$incoming$call$data)
[1] "0x158be36a8"
> lobstr::obj_addr(splitted_data$incoming)
[1] "0x158be36a8"
They both point to the same object. all_lms$incoming$call$data doesn't get copied to it's own object unless it's modified
> all_lms$incoming$call$data[1, "value"] <- 2
> lobstr::obj_addr(all_lms$incoming$call$data)
[1] "0x1594845c8"
Read all about this copy-on-modify at https://adv-r.hadley.nz/names-values.html#copy-on-modify
| |
doc_1566
|
I run into problems when using MTLTexture with depth32Float pixel format. MPSImageGaussianBlur or any other performance shader isn't accepting it as source texture.
I tried to convert it using: depthBufferTexture.makeTextureView(pixelFormat: .bgra8Unorm) but got error saying:
validateArgumentsForTextureViewOnDevice:1406: failed assertion source texture pixelFormat (MTLPixelFormatDepth32Float) not castable.
Is there any way how to convert depth32Float to bgra8UNorm or any other pixel format?
A: Converting from depth32Float to bgra8UNorm, in my opinion, does not make much sense, they have different dimensions and number of channels. In your case, the best solution would be using MTLPixelFormatR32Float.
To convert from depth32Float to MTLPixelFormatR32Float use MTLComputeCommandEncoder.
| |
doc_1567
|
I have a dataset that looks like this:
case Regions forecastTime WindSpeed_low
1 1 EAST COAST-CAPE ST FRANCIS AND SOUTH 2010-01-01 09:00:00 35
2 1 EAST COAST-CAPE ST FRANCIS AND SOUTH 2010-01-01 12:00:00 25
3 1 EAST COAST-CAPE ST FRANCIS AND SOUTH 2010-01-03 03:00:00 25
4 27 EAST COAST-CAPE ST FRANCIS AND SOUTH 2010-01-05 09:00:00 15
5 27 EAST COAST-CAPE ST FRANCIS AND SOUTH 2010-01-05 16:00:00 00
WindSpeed_high poly_id
1 45 fea1-289
2 NA fea1-289
3 NA fea1-289
4 20 fea1-289
5 NA fea1-289
Each issued forecast has a case number, an associated region and forecast time.
My goal is to expand the forecast times for each case to include all hours between the times the forecast changed:
case Regions forecastTime WindSpeed_low
1 1 EAST COAST-CAPE ST FRANCIS AND SOUTH 2010-01-01 09:00:00 35
2 1 EAST COAST-CAPE ST FRANCIS AND SOUTH 2010-01-01 10:00:00 35
3 1 EAST COAST-CAPE ST FRANCIS AND SOUTH 2010-01-01 11:00:00 35
4 1 EAST COAST-CAPE ST FRANCIS AND SOUTH 2010-01-01 12:00:00 25
5 1 EAST COAST-CAPE ST FRANCIS AND SOUTH 2010-01-01 13:00:00 25
WindSpeed_high poly_id
1 45 fea1-289
2 45 fea1-289
3 45 fea1-289
4 NA fea1-289
5 NA fea1-289
Here the forecast is the same between 2010-01-01 09:00:00 and 2010-01-01 11:59:59, fd$WindSpeed_low == 35 and fd$WindSpeed_high == 45, however at 2010-01-01 12:00:00 the forecast changes to fd$WindSpeed_low == 25 and fd$WindSpeed_high == NA. I was thinking I could group each forecast by case, but I am stuck on how I should go about this expansion correctly. I am relatively new to R.
A: You may use complete and fill from tidyr -
library(dplyr)
library(tidyr)
df %>%
group_by(case, Regions) %>%
complete(forecastTime = seq(min(forecastTime),max(forecastTime),by='hour')) %>%
fill(WindSpeed_low, poly_id) %>%
ungroup
| |
doc_1568
|
$(".date").focus(function() {
this.setSelectionRange(0, 2);
});
The problem is this only works if I focus on input field with a mouse click. But if moving between input fields with TABULAR key on keyboard then the entire text in input field is selected. Can this be controlled via JavaScript as well?
Here is also JSFiddle which demonstrates above.
A: It sounds like the default handler is being run after yours.
Prevent this by stopping the browser's default handler by running:
$(".date").focus(function(e) {
e.preventDefault();
this.setSelectionRange(0, 2);
});
A: i posted here an answer, which is related to what you want , check it out: how-to-select-particular-text-in-textbox
| |
doc_1569
|
// cant use this method see comment tagged ERROR further down
def webRollbackFactory(parentTask) {
tasks.create(name: "webRollback.${parentTask.name}", type: Copy, dependsOn: [webBackup]) {
onlyIf { patentTask.state.failure != null }
from(zipTree("${webPublishPath}/../${getWebBackupName()}")) { include '*' }
into webPublishPath
doLast {
println "\nwebRollback.${parentTask.name}.doLast"
}
}
}
// this task which do the same works with out problems
task webRollback_webPublish(type: Copy) {
onlyIf { webPublish.state.failure != null }
from(zipTree("${webPublishPath}/../${getWebBackupName()}")) { include '*' }
into webPublishPath
doLast {
println "\nwebRollback.webPublish.doLast"
}
}
task webPublish(type: com.ullink.Msbuild) {
dependsOn msbuild, webBackup
projectFile = "${webPublishProjectDir}/${webPublishProjectFileName}"
targets = ['Publish']
parameters = [PublishProfile: webPublishProfile]
configuration = BUILD_TYPE
parameters.maxcpucount
doLast {
println '\nwebPublish.doLast'
}
// ERROR: fails with: Could not find method webRollbackFactoy() for arguments [task ':webAccessTest'] on task ':webAccessTest' of type org.gradle.api.tasks.Exec.
//finalizedBy webRollbackFactory(webPublish)
// the version that works
finalizedBy webRollback_webPublish
}
I am on Gradle 4.8
A: The reason you get that error is because the closure being evaluated does not find the function declared in the main file.
Try changing your function to a closure as a variabe reference and then it should work.
webRollbackFactory = { parentTask ->
tasks.create(name: "webRollback.${parentTask.name}", type: Copy, dependsOn: [webBackup]) {
onlyIf { patentTask.state.failure != null }
from(zipTree("${webPublishPath}/../${getWebBackupName()}")) { include '*' }
into webPublishPath
doLast {
println "\nwebRollback.${parentTask.name}.doLast"
}
}
}
| |
doc_1570
|
Which method gives better performance?
A: If you already know the qualifier, then you must use scan.addColumn(). If you are not sure about the qualifier and you want to compare the qualifier with a particular value (using operators like greater, less, equal etc), then you must use QualifierFilter. It is mentioned in the HBase documentation of QualifierFilter-
If an already known column qualifier is looked for, use Get.addColumn(byte[], byte[]) directly rather than a filter.
| |
doc_1571
|
Here it is:
using UnityEngine;
using System.Collections;
public class FollowCamera : MonoBehaviour {
public float interpVelocity;
public float minDistance;
public float followDistance;
public GameObject target;
public Vector3 offset;
Vector3 targetPos;
void Start () {
targetPos = transform.position;
}
void FixedUpdate () {
if (target)
{
Vector3 posNoZ = transform.position;
posNoZ.z = target.transform.position.z;
Vector3 targetDirection = (target.transform.position - posNoZ);
interpVelocity = targetDirection.magnitude * 5f;
targetPos = transform.position + (targetDirection.normalized * interpVelocity * Time.deltaTime);
transform.position = Vector3.Lerp( transform.position, targetPos + offset, 0.25f);
}
}
}
The script makes the camera follow a rotating target.
A: You are updatng camera position on FixedUpdate. Change it to LateUpdate. FixedUpdate is designed for other purposes and is called less often usually then every frame. LateUpdate is called every frame and after Update so if your target is updated on Update camera will update its position later, what is desired.
| |
doc_1572
|
I'm using twitter bootstrap on my site and when I collapse the window partially, this happens!
If I collapse the window further, then the desired button appears and the links disappear.
Q) Why is this happening? I want the nav links to collapse at this window width, leaving the button. Nav code below:
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/" style="font-size: 24px;">My brand name</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav">
<li class="<%= GetCssClassNavItemHome() %>"><a href="/">Home</a></li>
<li class="<%= GetCssClassNavItem("/about") %>"><a href="/about">About</a></li>
<li class="<%= GetCssClassNavItem("/services") %>"><a href="/services">Services</a></li>
<li class="<%= GetCssClassNavItem("/project") %>"><a href="/projects">Projects</a></li>
<li class="<%= GetCssClassNavItem("/prices") %>"><a href="/prices">Prices</a></li>
<li class="<%= GetCssClassNavItem("/blog") %>"><a href="/blog">Blog</a></li>
<li class="<%= GetCssClassNavItem("/contact") %>"><a href="/contact">Contact</a></li>
</ul>
<ul class="nav navbar-nav navbar-right nav-pills">
<li>
<a target="_blank" href="http://www.linkedin.com/">
<i class="fa fa-linkedin fa-2x"></i>
</a>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container -->
A: The problem is the padding applied in the class .container - 15px both left and right. If you reduce the padding, the problem goes away.
If you add another class to the div.container - in this example, say lesspadding:
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container lesspadding">
etc.
and then apply different padding to the new class, like so:
.lesspadding {
padding-left: 10px;
padding-right: 2px;
}
Bootply here
| |
doc_1573
|
typedef map<string, map<string,map<string,vector<double>>> > mapofmaps;
Need to add rows with key1+key2+key3 being unique.
A: mapofmaps m;
m["key1"]["key2"]["key3"] = { 1.0, 2.0, 3.0 };
| |
doc_1574
|
adders = []
for n in range(1, 4):
adders.append(lambda x: x + n)
I am getting below output for adders[0](10)
13
My understanding is that x + n will be evaluated at the compile time.
So, the output for adders[0](10) should be :
11
My understanding is that python should be adding lambda x: x + 1, lambda x: x + 2 and lambda x: x + 3 to adders. Please help me understand why python is not doing that?
Please let me know if I am misunderstanding something.
| |
doc_1575
|
Sub Process()
Validate()
'SomeMorecode...
End Sub
Sub Validate()
'...
'...
End Sub
A: First, you need to understand that Subs don't return values. They are like void functions in C.
Second, use Exit Sub whenever you want to exit from a certain Sub.
Alternatively, if you would like to exit from a function, use Exit Function
Or, If you want to exit from a Do Loop, Exit Do Exit While, etc.
Bare in mind, that if you do Exit Function before actually returning anything, then a default value will automatically be set. In the case of Booleans, the value will be False.
You get the idea
Sub MyFirstSub()
If Validate() Then
'Do more work here
Else
Exit Sub ' Early Exit
End If
'Other things to do after validation is TRUE
'...
'...
End Sub
Function Validate() As Boolean
' Do validation here and either return TRUE or FALSE
If Rnd(1) > 0.5 Then
Validate = True
Else
Validate = False
End If
End Function
| |
doc_1576
|
How would I design my MySQL database if I have these fields:
ID,
lat,
long,
date - multiple dates,
time - multiple times
I know I should put it into two tables, right? And how would those two tables look?
Thanks!
A: Your first table might be called "location" and it would have an "id" column as its primary key, along with two columns called "latitude" and "longditude" (which could be varchar or a numeric type, depending what your application requires). Your second table might be called "location_event" and it could have an "id" column as its primary key, along with a foreign key column called "location_id" that is a reference to the primary key of the "location" table. This "location_event" table would also have a "date" column and a "time" column (of types date and time respectively).
A: It's hard to tell what you're trying to do from the terse description but third normal form dictates that any column should be dependent on:
*
*the key.
*the whole key.
*nothing but the key.
To that end, I'd say my initial analysis would generate:
Location
LocId primary key
Lat
Long
Events
LocId foreign key Location(LocId)
Date
Time
This is based on my (possibly flawed) analysis that you want to store a location at which zero or more events can happen.
It's good practice to put the events in a separate table since the alternative is to have arrays of columns which is never a good idea.
A: As far as I can guess the date en time are couple always appearing together. In that case I would suggest two tables, location and time.
CREATE TABLE location (
id INT NOT NULL,
lat FLOAT NOT NULL,
long FLOAT NOT NULL,
PRIMARY KEY (id)
)
CREATE TABLE time (
id INT NOT NULL,
locationid INT NOT NULL,
date DATE NOT NULL,
time DATE NOT NULL
)
Optionally you can add a foreign key constraint
ALTER TABLE time ADD CONSTRAINT location_fk_constraint FOREIGN KEY location_fk_constraint (locationid)
REFERENCES location (id)
ON DELETE CASCADE
ON UPDATE CASCADE;
A: OK, let's say, for the sake of argument, that you are talking about longitude and latitude. That these are entries in some kind of list (perhaps a sea log? Arrgh, me maties!) of longitude and latitude. And that each of these long/lat pairs may appear more than once in the list.
Perhaps you want to build a database that figures out how many appearances each long/lat pair has, and when each appearance happened?
So how's this: First we have a table of the long/lat pairs, and we'll give each of those an ID.
ID long lat
-- ----- -----
1 11111 22222
2 33333 44444
3 55555 66666
Next, we'll have another table, which will assign each appearance of the long/lat pairs a date/time:
ID date time
-- ---- -----
1 1/1/1900 12:30
1 2/2/1900 12:31
1 3/2/1900 12:30
2 1/1/1930 08:21
Let's say you'll call the first table "longlat" and the second one "appearances".
You could find all the appearances of a single long/lat pair by doing something like:
SELECT date,time FROM appearances
LEFT JOIN longlat ON appearances.ID=longlat.ID
WHERE longlat.long = 11111 AND longlat.lat = 22222
You could count how many times something happened at a longitude of 11111, by doing:
SELECT count(ID) FROM appearances
LEFT JOIN longlat ON appearances.ID=longlat.ID
WHERE longlat.long = 11111
Hope that helps! I gotta admit, it's really quite annoying to try and guess what people mean... Try making yourself more clear in the future, and you'll see that the help you'll get will be that much more useful, concise and targeted at what you need.
Good luck!
| |
doc_1577
|
How to display a time and date like below image. I have a code for capturing image. But how can i display time and date in capturing image. Here is the code for launching camera application
My Code:
public class MyCameraActivity extends Activity {
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
photoButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
}
A: check these links link1 and link2
Here the image you are having is taken onto a canvas. Now the canvas is used to modify the image by writing something on it using something like
Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setStyle(Style.FILL);
canvas.drawPaint(paint);
paint.setColor(Color.BLACK);
paint.setTextSize(20);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String currentDateandTime = sdf.format(new Date());
canvas.drawText(currentDateandTime , 10, 25, paint);
This may help you to draw the text onto the image.
Give it a try.
A: imagename = String.valueOf(System.currentTimeMillis());
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
String path = Environment.getExternalStorageDirectory() + "/Pictures/" + "pic_" + imagename + ".jpg";
File file = new File(path);
imageUri = Uri.fromFile(file);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageUri);
//on activity Result
Canvas canvas = new Canvas(drawableBitmap);
canvas.drawBitmap(drawableBitmap, 0, 0, null);
Paint paint = new Paint();
paint.setColor(getResources().getColor(R.color.Orange));
paint.setTextSize(22);
DateFormat dateFormatter1 = new SimpleDateFormat("dd-MM-yyyy");
DateFormat dateFormatter2 = new SimpleDateFormat("hh:mm:ss");
dateFormatter1.setLenient(false);
dateFormatter2.setLenient(false);
java.util.Date today = new java.util.Date();
// java.util.Timer;
String d = dateFormatter1.format(today);
String t = dateFormatter2.format(today);
canvas.drawText("" + d + ", " + t, 20f , loadedBitmap.getHeight() - 24, paint);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
drawableBitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
String path = Environment.getExternalStorageDirectory()+ "/Pictures/" + "pic_" + imagename + ".jpg";
File file = new File(path);
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
fo.write(bytes.toByteArray());
fo.close();
| |
doc_1578
|
EDIT:
FooModule::User would definitely give me the correct one.
What I had meant to ask was:
If ApplicationController includes FooModule, would User or ::User still give me app/models/user?
A: Refer to them using their full names, FooModule::User and ::User
Generally if you just use User, it should assume you mean ::User, unless you are within FooModule. Either way, use FooModule::User or ::User to be sure.
| |
doc_1579
|
https://www.kaggle.com/neuromusic/avocado-prices
I am trying to plot the price volatility (standard deviation) of avocados, by year, month and avocado type, like the picture below
I tried to code it like this but I keep getting the error 'value' must be an instance of str or bytes, not a float:
month_dict = {1 : 'Jan',
2: 'Feb',
3: 'Mar',
4: 'Apr',
5: 'May',
6: 'Jun',
7: 'Jul',
8: 'Aug',
9: 'Sep',
10: 'Oct',
11: 'Nov',
12: 'Dec'}
cal_years =[2015, 2016, 2017]
types = ['conventional','organic']
df['Month'] = pd.to_datetime(df.index).month
fig, ax = plt.subplots(2,3, figsize=(15,10), sharey=True)
for type in types:
for axy in range(2):
for axx in range(3):
df_plot = df[(df['type'] == types[axy]) & (df['year'] == cal_years[axx])]
df_plot = df_plot.groupby('Month', as_index=False)['AveragePrice'].std()
df_plot['Month'] = df_plot['Month'].map(month_dict)
ax[axy, axx].plot('Month','AveragePrice',data=df_plot, color='blue',marker='o')
ax[axy, axx].set_title(str(cal_years[axx]) + ' ' + types[axy])
ax[axy, axx].tick_params(axis='x', rotation=45)
fig.suptitle('Season price fluctuation', size=16)
Would appreciate if anyone can point out why the code is not working as I expected. Many thanks
| |
doc_1580
|
SQL ConnectionException:Cannot create Poolable Connectionfactory
(IO error:Network Adapter could not establish the connection).
Installed Oracle11g in virtual machine.
Please give me solution.
Thanks in Advance.
A: *
*Make sure you have Oracle JDBC driver somewhere in JMeter Classpath
*Make sure you have configured network adapter in the virtual machine in Bridge mode (not "host-only", not "NAT") so the virtual machine would have its own IP address.
*Make sure port 1521 (or whatever is used by Oracle) is not blocked by OS firewall. Check if you are able to connect to the port using i.e. telnet client
*Add JDBC Connection Configuration test element and provide JDBC url of your Oracle instance along with credentials there.
See The Real Secret to Building a Database Test Plan With JMeter guide to learn more about setting up JMeter for databases load testing
| |
doc_1581
|
<?php
//some code here
?>
<form>
<input />
</form>
And according to this example, I want to get the input's content to use further in PHP and/or insert in the desired input some variables from my PHP code, how can I perform this?
A: You can post the data to php from a HTML form
<?php
// data is available in php POST array
var_dump($_POST);
// create a var to hold the post data
$sNameOfPostVar = "";
// if posted, set the var to the value of the posted content
if(isset($_POST['NameOfPostVar'])){
$sNameOfPostVar = $_POST['NameOfPostVar'];
}
?>
<!-- current action is blank to send to same page as php script -->
<form method='post' action=''>
<input name='NameOfPostVar' value='<?php echo $sNameOfPostVar;?>' />
</form>
| |
doc_1582
|
Is there any "trick" or something that I can do to make this work?
Heres's an example of how I'm using it (this is a function I've created in my controller):
formatIconStatus: function(status){
var view = this.getView();
if (status != null){
if (status == "YES"){
status = "sap-icon://accept";
}else{
status = "sap-icon://error";
}
return status;
}
},
Thanks in advance!
A: Yes, there is. If you are using a JSView this in formatter functions and event listeners points to the Control it belongs to. For formatter functions you can change this by assigning the function like in this example:
new sap.m.Button({
text : {
path : "/buttonText",
formatter : $.proxy(oController.myTextFormatter, oController);
}
});
With the help of jQuery.proxy you can set this within myTextFormatter to oController. This allows you to call this.getView() within your formatter since this will now point to the controller.
In order to set the scope for event listeners you can either assign the function the same way as shown above or you can use a different approach offered by the framework like in the following example:
new sap.m.Button({
press : [oController.myPressHandler, oController]
});
Using this notation, the framework will call the event listener (myPressHandler) with the second entry of the array as scope.
This pattern is valid for most event listeners across the UI5 framework. Basically, you have three options when assigning event listeners:
*
*fnListenerFunction
*[fnListenerFunction, oListenerScope]
*[oData, fnListenerFunction, oListenerScope]
Using XMLViews you don´t have to set the scope manually as it´s set to the associated controller by default.
| |
doc_1583
|
*
*I can't create a new png for it
*I can't change the implementation (so I can't use other icons like FontAwesome etc)
*I must use the same <img> element so I cannot make use of <canvas>. So somehow I want the new, transformed image to have the exact structure as the replaced image.
So far I have tried Filtrr and Caman but they use <canvas> elements. fabric.js does the same.
Do you know any other method to achieve this? It must work in Firefox/Chrome/Safari so no IE. CSS is also accepted instead of JavaScript, but as I know and tested, using filter: invert in CSS does not work in Firefox.
Thanks!
Example: I don't know how useful an example can be in my situation, but here it is:
I have this:
<div class="icon">
<img src="myicon.png" data-activepath="activemyicon.png">
</div>
myicon.png is a white icon and I want to make it black in the browser. How can I achieve this (using CSS or JS) and keep the same HTML structure and elements?
FIX:
Please note that there are 2 answers that fixed this problem. Unfortunately I can only accept one answer. So here they are:
*
*the CSS version
*the JS version
A: Since you don't need to support IE you can use this CSS filter:
.icon img{
filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'invert\'><feColorMatrix type=\'matrix\' values=\'-1 0 0 0 1 0 -1 0 0 1 0 0 -1 0 1 0 0 0 1 0\'/></filter></svg>#invert");
-webkit-filter:invert(100%);
filter: invert(100%);
}
that will work with the current version of firefox too.
A: I don't really understand why you can't use canvas while you can change js.
So, if you can save your icon on the server, could you try this code :
function changeImgColor(img) {
var can = document.createElement('canvas');
can.width = img.width;
can.height = img.height;
var ctx = can.getContext('2d');
ctx.drawImage(img, 0, 0);
var imageData = ctx.getImageData(0, 0, img.width, img.height);
var data = imageData.data;
var c = 255;
for (var i = 0; i < data.length; i += 4) {
if (data[i] == c && data[i + 1] == c && data[i + 2] == c) {
data[i] = 0;
data[i + 1] = 0;
data[i + 2] = 0;
}
// overwrite original image
ctx.putImageData(imageData, 0, 0);
}
var newdata = can.toDataURL("image/png");
img.src = newdata;
}
changeImgColor(document.getElementsByTagName('img')[0]);
check fiddle
Ps : you may have to hit "run" in order to load icons in results
A: this may be a bit of a change to your original idea, but have you considered using Font Awesome instead? It will be way quicker to change font color than to redraw images.
A: It will work only chrome.
img {
-webkit-filter: grayscale(100%);
-moz-filter: grayscale(100%);
filter: grayscale(100%);
}
| |
doc_1584
|
This code :
%reset -f
import torch.nn as nn
import numpy as np
import torch
my_softmax = nn.Softmax(dim=-1)
mu, sigma = 0, 0.1 # mean and standard deviation
train_dataset = []
image = []
image_x = np.random.normal(mu, sigma, 24).reshape((3 , 4, 2))
train_dataset.append(image_x)
x = torch.tensor(train_dataset).float()
print(x)
print(my_softmax(x))
my_softmax = nn.Softmax(dim=1)
print(my_softmax(x))
prints following :
tensor([[[[-0.1500, 0.0243],
[ 0.0226, 0.0772],
[-0.0180, -0.0278],
[ 0.0782, -0.0853]],
[[-0.0134, -0.1139],
[ 0.0385, -0.1367],
[-0.0447, 0.1493],
[-0.0633, -0.2964]],
[[ 0.0123, 0.0061],
[ 0.1086, -0.0049],
[-0.0918, -0.1308],
[-0.0100, 0.1730]]]])
tensor([[[[ 0.4565, 0.5435],
[ 0.4864, 0.5136],
[ 0.5025, 0.4975],
[ 0.5408, 0.4592]],
[[ 0.5251, 0.4749],
[ 0.5437, 0.4563],
[ 0.4517, 0.5483],
[ 0.5580, 0.4420]],
[[ 0.5016, 0.4984],
[ 0.5284, 0.4716],
[ 0.5098, 0.4902],
[ 0.4544, 0.5456]]]])
tensor([[[[ 0.3010, 0.3505],
[ 0.3220, 0.3665],
[ 0.3445, 0.3230],
[ 0.3592, 0.3221]],
[[ 0.3450, 0.3053],
[ 0.3271, 0.2959],
[ 0.3355, 0.3856],
[ 0.3118, 0.2608]],
[[ 0.3540, 0.3442],
[ 0.3509, 0.3376],
[ 0.3200, 0.2914],
[ 0.3289, 0.4171]]]])
So first tensor is prior to softmax being applied, second tensor is result of softmax applied to tensor with dim=-1 and third tensor is result of softmax applied to tensor with dim=1 .
For result of first softmax can see corresponding elements sum to 1, for example [ 0.4565, 0.5435] -> 0.4565 + 0.5435 == 1.
What is summing to 1 as result of of second softmax ?
Which dim value should I choose ?
Update : The dimension (3 , 4, 2) corresponds to image dimension where 3 is the RGB value , 4 is the number of horizontal pixels (width) , 2 is the number of vertical pixels (height). This is an image classification problem. I'm using cross entropy loss function. Also, I'm using softmax in final layer in order to back-propagate probabilities.
A: You have a 1x3x4x2 tensor train_dataset. Your softmax function's dim parameter determines across which dimension to perform Softmax operation. First dimension is your batch dimension, second is depth, third is rows and last one is columns. Please look at picture below (sorry for horrible drawing) to understand how softmax is performed when you specify dim as 1.
In short, sum of each corresponding entry of your 4x2 matrices are equal to 1.
Update: The question which dimension the softmax should be applied depends on what data your tensor store, and what is your goal.
Update: For image classification task, please see the tutorial on official pytorch website. It covers basics of image classification with pytorch on a real dataset and its a very short tutorial. Although that tutorial does not perform Softmax operation, what you need to do is just use torch.nn.functional.log_softmax on output of last fully connected layer. See MNIST classifier with pytorch for a complete example. It does not matter whether your image is RGB or grayscale after flattening it for fully connected layers (also keep in mind that same code for MNIST example might not work for you, depends on which pytorch version you use).
A: For most of Deep Learning Problems,we will definitely come up with batches. So dim will always be 1. Don't get confused with it.Through that we just say the function to do operation along the contents of each batch(Here it is a vector i.e if you have 8 classes, 8 elements will be there in each row). You can also mention dim=-1 too.
| |
doc_1585
|
public class RedisSettings
{
public RedisSettings(ConfigurationOptions configuration, int db = 0, IRedisValueConverter converter = null, Func<ICommandTracer> tracerFactory = null, TextWriter connectionMultiplexerLog = null);
}
I want to set value for IRedisValueConverter converter from code instead of config.
How should I set it?
public static readonly RedisSettings Default = new RedisSettings("localhost");
A: Use:
public RedisSettings(ConfigurationOptions configuration, converter: YourConvertobject);
Converter is an optional argument and by default it is null. By providing a value you can set it from code. For more information read Named & Optional parameters
| |
doc_1586
|
Here's my code: (also available on CodePen)
const alphabet = ["a", "b", "c", "d", "e"];
function alphaPosition(seq) {
//'temp' gets 'seq' to avoid making changes directly on the provided argument.
let temp = seq;
//adds indexes to each element in the 'temp' array:
for (let i = 1; i <= temp.length; i++) {
temp[i - 1] = temp[i - 1] + i;
}
return temp;
}
console.log(
"Step 1. 'alphabet' array before running the 'alphaPosition' function:"
);
console.log(alphabet);
console.log(
"Step 2. This is the final value of 'temp' in 'alphaPosition' after running the function. An index has been added to every element in the array, as expected:"
);
console.log(alphaPosition(alphabet));
console.log(
"Step 3. Here's the 'alphabet' array after running 'alphaPosition'. Indexes have also been added to every element, despite not modifying the function argument directly:"
);
console.log(alphabet);
Output:
/*
-> Step 1. 'alphabet' array before running the 'alphaPosition' function:
-> ["a", "b", "c", "d", "e"]
-> Step 2. This is the final value of 'temp' in 'alphaPosition' after running the function. An index has been added to every element in the array, as expected:
-> ["a1", "b2", "c3", "d4", "e5"]
-> Step 3. Here's the 'alphabet' array after running 'alphaPosition'. Indexes have also been added to every element, despite not modifying the function argument directly:
-> ["a1", "b2", "c3", "d4", "e5"]
*/
Why do changes to 'temp' spread to 'alphabet'? I would expect that, since I defined 'alphabet' as a constant, it shouldn't even be possible to modify it. Also, I never make changes to it in my function. I only use it to define 'temp'. Is there any way to prevent these spreads from happening?
I experimented doing something similar with a numeric const instead of an array, and everything worked as intended:
const number = 10;
function numChange(n) {
//'virtualN' gets 'n' to avoid making changes directly on the provided argument.
let virtualN = n;
//modify 'virtualN' multiple times to emulate what was done to the 'temp' array in the alphaPosition function.
for (let i = 1; i <= 5; i++) {
virtualN = "iteration" + i;
}
return virtualN;
}
console.log(
"Step 1. See the value of 'number' before running the numChange function:"
);
console.log(number);
console.log(
"Step 2. This is the final value of 'virtualN' in 'numChange(number)' after running the function. As expected, it's been modified from its initual value by the 'for' loop:"
);
console.log(numChange(number));
console.log(
"Step 3. Finally, we can see the value of 'number' is still the same as before running the numChange function. As expected, only the value of virtualN changed while the argument 'n' suffered no modifications:"
);
console.log(number);
Output:
/*
-> Step 1. See the value of 'number' before running the numChange function:
-> 10
-> Step 2. This is the final value of 'virtualN' in 'numChange(number)' after running the function. As expected, it's been modified from its initual value by the 'for' loop:
-> iteration5
-> Step 3. Finally, we can see the value of 'number' is still the same as before running the numChange function. As expected, only the value of virtualN changed while the argument 'n' suffered no modifications:
-> 10
*/
Why does using an intermediary variable to avoid making changes to the original work for numbers and not for arrays?
I'd be extremely grateful for any help or clarification on this. I've added my code to this CodePen in case you'd like to tweak it or experiment more with it.
Thank you in advance for any help.
A: This is about how assignment works in javascript. Given the following code:
const a = { foo: "bar" };
const b = a;
Variables a and b both point to the same object. This means there is only one object in memory and mutating the object a points to will be reflected when you try to access the object using b and vice versa. For example:
const a = { foo: "bar" };
const b = a;
a.foo = "baz";
console.log(a);
console.log(b);
So now, how do we make this not happen? We can do this by assigning a shallow copy of a to b. This can be done a few different ways, the following uses the spread operator (...):
const a = { foo: "bar" };
const b = { ...a };
a.foo = "baz";
console.log(a);
console.log(b);
So now, there are two different objects in memory. You'll notice I called this a shallow copy, which is important: if you have deep objects you'll need to copy deeply to accomplish the same kind of decoupling.
How to fix this in your specific case:
The TLDR for your specific case is that your temp variable should be a shallow copy of the array, not a reference to the existing array:
let temp = [...seq];
A: This seems to be a duplicate of this.
and the underlying answer is here.
I explain why below:
It would seem that for Strings and numbers, javascript is pass by value, and objects such as arrays is pass by reference.
What this means is that in your first example; the function is taking a reference to the original array, and when you do let temp = seq, temp is actually just a pointer to the original object passed in. In this case that is alphabet so when you modify temp; it is actually modifying alphabet.
Pass by value just sends to the function the value, so the original variable stays the same as in your number example.
In order to get your intended outcome you would want to make a Deep Copy of your array like let temp = deepCopy(seq).
Use of const I think may just be syntax for the user to know not to modify it and some editors will not let you remodify const in the code, but in this case its happening in a roundabout way.
| |
doc_1587
|
George wanted to bake cookies. He asked Mom to help him.
George decided he would bake chocolate-chip cookies. First, Mom had to buy the ingredients. She bought flour, sugar, and chocolate chips. Next, George and Mom mixed together all the ingredients. Finally, they put the cookies in the oven for ten minutes. Last, they let the cookies cool down, and ate them.
"These are delicious!" said George.
I want to convert this to an array with lines of up to 50 characters each.
I have currently:
var lines = text.split(/\r|\n/g);
lines.forEach(function (item, index) {
words = item.match(/.{1,50}\b/g);
});
This almost works, but it ignores periods and things like that, so I'm left with
George wanted to bake cookies. He asked Mom to
help him
George decided he would bake chocolate-chip
cookies. First, Mom had to buy the ingredients.
She bought flour, sugar, and chocolate chips. Next
, George and Mom mixed together all the
ingredients. Finally, they put the cookies in the
oven for ten minutes. Last, they let the cookies
cool down, and ate them
"These are delicious!" said George.
What am I doing wrong?
A: You can use spaces instead of word boundaries (that matches between a letter and a dot):
For example with this pattern:
/\S(?:.{0,48}\S)?(?!\S)/g
details:
\S # all that is not a white-space
(?:.{0,48}\S)? # between 0 and 48 characters followed by a non white character
(?!\S) # not followed by a non-white character (in other words, followed
# by a white space or the end of the string)
The other advantage is that the pattern avoids leading and trailing spaces.
A: You are using g the global modifier. Which returns all the matches, not just the first one. You seem to need the first 50 characters only. The anchor b will keep the the last word not broken and hence actual string might be less than 50 characters. This should give you the proper result:
var lines = text.split(/\r|\n/g);
lines.forEach(function (item, index) {
words = item.match(/.{1,50}\b/);
alert(words);
});
You'll have to modify further considering if you want to keep spaces and punctuations out of count.
| |
doc_1588
|
"ps -ef | grep amqzlaar0 | awk '{print $(NF-1)}' "
system() function is failing with exit code -1 when i use pipe symbol "|". But, if I issue just system("ps -ef"),it works.
Please help me on how to execute a pipe seperated command using system.
Your help is much appreciated.
Regards,
Sriram
A: I believe you should not run a command to check that amqzlaar0 is running, but query the proc(5) filesystem (on Linux).
Notice that /proc/ is not portable (e.g. not standardized in Posix). Some Unixes don't have it, and Solaris and Linux have very different /proc/ file systems.
If really want to run a command, use e.g. snprintf(3) to build the command (or std::string or std::ostringstream) then use popen(3) (and pclose) to run the command
Read Advanced Linux Programming to get a better view of Linux Programming. See also syscalls(2)
BTW, some people might have aliased e.g. grep (perhaps in their .bashrc), so you probably should put full paths in your command (so /bin/grep not grep etc...).
A: Just run ps -Ef. You're a C++ programmer. The equivalent of grep and awk is not hard in C++, and it's faster in C++ (doesn't require two additional processes)
| |
doc_1589
|
But it looks like possible, for example:
-(int)AddMethod:(int)X :(int)Y
{
return X + Y;
}
-(int)AddMethod:(int)X
{
return X;
}
to call 1st one write [self AddMethod :3];
to call last one write [self AddMethod: 3 :4];
A: No, it is not, mostly because Objective-C doesn't use functions, it uses methods.
Method overloading, on the other hand, is possible. Sort of.
Consider, if you will, a class with a method take an argument on the form of either an NSString * or a const char *:
@interface SomeClass : NSObject {
}
- (void)doThingWithString:(NSString *)string;
- (void)doThingWithBytes:(const char *)bytes;
@end
While the method itself won't go around choosing the proper method with a given input; one could still say that doThing: was overloaded, at least in the sense that the two methods taking a different parameter to achieve the same functionality.
A: Method overloading is not possible in Objective-C. However, your example actually will work because you have created two different methods with different selectors: -AddMethod:: and AddMethod:. There is a colon for each interleaved parameter. It's normal to put some text in also e.g. -addMethodX:Y: but you don't have to.
A: Technically, method overloading is not possible in Objective-C. In practice you can usually achieve the same results, also in cases where you couldn't in C++. In Objective-C, method names include a colon in front of each argument, and the colons are PART OF THE METHOD NAME, which means your example uses different method names. In practice this becomes a sort of pseudo-named-parameters functionality, and you can get a pseudo method overloading by argument FUNCTION rather than argument TYPE. In most cases this will actually be more useful, but it is not method overloading in the strict sense, because the method names are different.
Example:
-(void)makeSquareWithX1:(float)x1 Y1:(float)y1 X2:(float)x2 Y2:(float)y2;
-(void)makeSquareWithX1:(float)x1 Y1:(float)y1 width:(float)width height:(float)height;
This would work in Objective-C, but you couldn't get similar functionality in C++, because the argument number and types are the same, only argument functions are different. In some few cases the C++ model can achieve more useful functionality. This is demonstrated by the NSKeyedArchiver class:
-(void)encodeFloat:(float)realv forKey:(NSString *)key
-(void)encodeInt32:(int32_t)intv forKey:(NSString *)key
Here they had to make argument types part of the moethod name, which is ugly. If I could choose between C++ overloading and Objective-C "overloading", I would still choose the latter.
A: You could start with a generic method which routes based on the type of the object you pass in.
- (void)doSomething:(id)obj;
Then you can check the type to see if it's NSData or UIImage and route it internally to the appropriate methods.
- (void)doSomethingWithData:(NSData *)data;
- (void)doSomethingWithImage:(UIImage *)image;
You can also choose to only support expected types and gracefully decline to process unsupported types or fail explicitly.
Look up NSAssert1, NSAssert2, etc for another approach.
A: Note that if you need / want to overload functions when combining Objective-C with C++ it is possible. I only mention this because in XCode you need to change your .m file to a .mm file for it to treat it this way, which tripped me up for a few minutes.
Example header:
void addMethod(NSInteger a);
void addMethod(NSInteger a, NSInteger b);
If you are including this in a .m file you'll get a warning:
Conflicting types for 'addMethod'
Changing your .m file into a .mm clears the issue.
A: You can overload C functions with newer compilers - Syntax is a little clunky though (nothing a quick #define can't fix), but it works well.
function overloading in C
A: Categories provide another way to emulate c-style method overloading in Objective C. As an example, consider the following interface declarations:
@interface MyClass
{
}
@end
@interface MyClass ( MethodVersion1 )
- (void) doSomething : (int) val;
@end
@interface MyClass ( MethodVersion2 )
- (void) doSomething : (double) val;
@end
The different parameter types are resolved by the Categories.
| |
doc_1590
|
{
name: "Subject",
index: "Subject",
width: 120,
formatter:'select',
editable: true,
edittype:'select',
editoptions: {
value: '1:sport;2:science',
multiple: true,
size: 2
},
editrules: { required: false}
},
But this JSON is hard coded with the multiselect options. I'm trying to find a way where I can return the data that is now hardcoded as:
'1:sport;2:science'
to come from a controller action in my MVC code. Is this possible?
A: You could use have your controller action return a JsonResult:
public ActionResult Foo()
{
var data = "1:sport;2:science";
var model = new
{
name = "Subject",
index = "Subject",
width = 120,
formatter = "Select",
editable = true,
edittype = "select",
editoptions = new
{
value = data,
multiple = true,
size = 2
},
editrules = new
{
required = false
}
};
return Json(model, JsonRequestBehavior.AllowGet);
}
In this example I have used an anonymous type but you could define a view model that matches this structure and then return an instance of this view model.
A: Like this:
var ms = "";
$.get('pathtomvc', function(txt) {
ms = txt;
});
// your code goes here
{
name: "Subject",
index: "Subject",
width: 120,
formatter:'select',
editable: true,
edittype:'select',
editoptions: {
value: ms,
multiple: true,
size: 2
},
editrules: { required: false}
},
| |
doc_1591
|
your routing table ActionPath = C:\Users####\AppData\Roaming\Microsoft\Network\Connections\Cm\DDBD2EC9-C6B1-4735-922F-BEB3FE5A94CB\CMROUTE.DLL
ReturnValue = 0x0 [cmdial32] 18:19:09 13 Disconnect Event
CallingProcess = C:\WINDOWS\system32\CMMON32.EXE [CMMON32] 18:19:09
26 External Disconnect due to Lost Connection
The azure VPN gateway does not report any issues.
Regards,
Joe
| |
doc_1592
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections.Generic;
[System.Serializable]
public class Person
{
public string name;
public Sprite icon;
}
public class CreateScrollList : MonoBehaviour
{
public GameObject namePrefab;
public List<Person> personList;
public Transform contentPanel;
// Use this for initialization
void Start()
{
PopulateList();
}
void PopulateList()
{
foreach (var person in personList)
{
GameObject newPerson = Instantiate(namePrefab) as GameObject;
NamePrefab generatedName = newPerson.GetComponent<NamePrefab>();
generatedName.nameLabel.text = person.name;
generatedName.icon = person.icon;
newPerson.transform.SetParent(contentPanel);
}
}
}
{
"array": [
"https://cdn1.iconfinder.com/data/icons/hawcons/32/699297-icon-68-document-file-app-512.png",
"https://d1gzq6u422bfcj.cloudfront.net/workflow_icons/99b9a7050c2f46b4b0b657e4ab0bedf4.png",
"https://cfcdnpull-creativefreedoml.netdna-ssl.com/wp-content/uploads/2016/06/New-instagram-icon.jpg"
]
}
| |
doc_1593
|
I am looking for way to increment and update in python, I am not abe to even update it with a predefined value in python. the doc doesn't specify any python samples.
I am using firebase_admin sdk like this,
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
for more check docs https://firebase.google.com/docs/firestore/solutions/counters
A: Unfortunately (to me it just doesn't feel right), adding support for transforms in your codebase means you have to use google-cloud-firestore next to firebase_admin.
You can then use Transforms such as Increment, ArrayRemove, etc.
Sample code:
from google.cloud.firestore_v1 import Increment
# assuming shard_ref is a firestore document reference
shard_ref.update({'count': Increment(1)})
A: another option is use Firebase Realtime Database URL as a REST endpoint. ( All we need to do is append .json to the end of the URL and send a request from our favorite HTTPS client)
for your case, use conditional request. explanation and example described at https://firebase.google.com/docs/database/rest/save-data#section-conditional-requests
| |
doc_1594
|
Whenever a user interacts with Bot over SFB and asks to fetch some details, I want the Bot to get these details from my companies internal system using the user's authentication token which should have generated when user login to SFB.
So, is there any way to get user's token from SFB which the Bot can use to get the required information on user's behalf? I can't use the Bot credential to get the information requested by the user on his/her behalf. My companies internal system, SFB uses the same Azure AD for user authentication.
I refer the questions Authenticate user across channels in Microsoft bot Framework, Skype for Business channel doesn't pass authentication credentials correctly but that doesn't help me to answer my question.
I referred Authenticate user in Microsoft bot framework link and If I ask the user to authenticate by using something https://blogs.msdn.microsoft.com/tsmatsuz/2016/09/06/microsoft-bot-framework-bot-with-authentication-and-signin-login/ then every time user ask some question, I need to ask the user to authenticate and that won't be a good for user experience as the user has already been authenticated over SFB.
Can someone please help me with some documentation that I can refer to resolve this issue?
A: I don't know about getting the token via the Skype channel directly, but I believe you could write UCMA code that would capture communication with a Skype user configured to be your bot, then transmit the conversation to the bot using Directline, with full knowledge of the user transmitted to the bot. You would then capture the result and reply to the user using the UCMA code.
| |
doc_1595
|
#!/bin/bash
APP_ROOT="/home/user/public_html/app"
export RAILS_ENV=production
export JRUBY_OPTS="--1.9"
export PATH=/home/user/.rbenv/shims:/home/user/.rbenv/bin:$PATH
case $1 in
start)
echo $$ > $APP_ROOT/puma.pid;
cd $APP_ROOT;
exec 2>&1 puma -b tcp://127.0.0.1:5000 1>/tmp/puma.out
;;
stop)
kill `cat $APP_ROOT/puma.pid` ;;
*)
echo "usage: puma {start|stop}" ;;
esac
exit 0
This works from the command line and it works even if I execute it after running the below to simulate the monit shell:
env -i PATH=/bin:/usr/bin:/sbin:/usr/sbin /bin/sh
The relevant monitrc lines are below:
check process puma with pidfile /home/user/public_html/app/puma.pid
start program = "/usr/bin/env PATH=/home/user/.rbenv/shims:/home/user/.rbenv/bin:$PATH /home/user/puma.sh start"
stop program = "/usr/bin/env PATH=/home/user/.rbenv/shims:/home/user/.rbenv/bin:$PATH /home/user/puma.sh stop"
The monit log shows it constantly try to start puma, and it even gets so far as regenerating a new PID, but is never able to actually start puma. Every time I try to run this script from every other context I can think of it works - except from monit.
A: I managed to get this to work after reading this post: running delayed_job under monit with ubuntu
For some reason, changing my monitrc to use the following syntax made this work. I have no idea why:
start program = "/bin/su - user -c '/usr/bin/env PATH=/home/user/.rbenv/shims:/home/user/.rbenv/bin:$PATH /home/user/puma.sh start'"
stop program = "/bin/su - user -c '/usr/bin/env PATH=/home/user/.rbenv/shims:/home/user/.rbenv/bin:$PATH /home/user/puma.sh stop'"
| |
doc_1596
|
I have coded the button as follows,
<button class="btn pull-right{{setButtonStyle(S.Id)}}"
ng-class="{true:'btn-primary', false:'btn-secondary'}[!S.isFollow]"
ng-click="toggleFollow(S.Id)"> {{!S.isFollow && 'Follow' || 'Unfollow'}}
</button>
The ng-click function handles the DB tables and also toggles the button UI. It is as follows,
$scope.toggleFollow = function (userId) {
var element = $scope.followIds.indexOf(userId);
if (element == -1) {
// Follow user
$scope.Searched[Sindex].isFollow = !$scope.Searched[Sindex].isFollow; // Toggles the button
console.log("Follow called");
})
} else if (element > -1) {
// Unfollow user
$scope.Searched[Sindex].isFollow = !$scope.Searched[Sindex].isFollow; // Toggles the button
console.log("Unfollow called");
})
}
}
The issue is that the button does not toggle at random. I suspect that the AngularJS digest loop doesn't fire every time the button is clicked.
I know for sure that the Angular function gets called every time when the button is clicked. So only the toggle doesn't fire as expected. So how do I force toggle the button every time it is clicked?
A: In your case ,its best to use angular's $apply()
$apply- is used to execute some code at first and then call the $digest() method internally , so that all watches are checked and the corresponding watch listener functions are called.
You make this happen in 2 ways.
First approach- use $apply(), without arguments at the end of your button's implementation code, like below example
$scope.toggleFollow = function (userId) {
if (element == -1) {
//...your button's implementation code
}
else if (element >= -1) {
//....your button's implementation code
}
//Call $apply()
$scope.$apply();
}
Second Approach (recomended)- write the button's implementation code inside the function (ie.the function that is passed as a parameter to $apply), so that, the function executes first, and ones function exits, AngularJS will call the $digest() ,so that all watches are checked for the changes in the watched values..
$scope.toggleFollow = function (userId) {
//Call $apply() ,passing the function as parameter
$scope.$apply(function(){
if (element == -1) {
//...your button's implementation code
}
else if (element >= -1) {
//....your button's implementation code
}
});
}
For more information on $apply, refer this document. It would give you a better understanding and working of it.
Hope this helps out.
Cheers
| |
doc_1597
|
function initMap(lat, lng){
if (lat & lng) {
lat = parseFloat(lat)
lng = parseFloat(lng)
} else {
lat = -72.43234
lng = 1.23423
}
}
if user getLocation() then it will fetch current location, but it will never retrieve other location in map.
function initMap(lat, lng){
if (lat & lng) {
lat = parseFloat(lat)
lng = parseFloat(lng)
} else {
getLocation()
}
}
getLocation() {
// code for current location html5
}
| |
doc_1598
|
For above graph.
for every vertex:
remove back edge from children to it.
It think this will always result in a DAG but i'm not able to prove it.
is there any proof for it or can someone provide a counter argument?
A: Let S be the set of processed nodes.
Hypothesis
*
*S has no cycle.
*Any node of S has no backedge from children.
Initialization:
Add 1 to S.
*
*1 has no backedge according to your alg
*it is not a cycle (does not loop to itself since no backedge)
Recurrence:
*
*No cycle:
Let t be the next node to add.
S is acyclic by hypothesis
To get a cycle in S U {t}, we need t to be in a cycle.
But t can't have an edge to any node n of S. Because if so, there exists a link from n to t (graph is originally undirected), which means t is a child of n. By your algorithm, when n was added to S, backedge from t has been removed.
Since there is is no edge from t to any node in S, there is no cycle involving t in S U {t}.
So S U { t } is still acyclic.
*
*No backedge:
All nodes in S are ok by hypothesis.
When adding t, the children of t have their backedge edge (to t) removed.
So S U {t} is still ok
| |
doc_1599
|
example in "header.h"
typedef HANDLE R_HANDLE;
the HANDLE data type is not accessible in the header , and there are some functions that use this data type as a parameter or as a return value
How do I export this data type "HANDLE" to be used from Python functions ?
Is there a method of dealing directly with "R_HANDLE" ?
rem : for classic structs and c data types , I'am using the approach of Python CookBook, using ctypes
Thanks
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.