qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
list
response
stringlengths
0
115k
71,270,008
Im trying to make a get route that will only return the names of recipes but im getting all the info in the array instead. Is there some thing im missing? ``` const express = require('express'); const { recipes } = require('./data/data.json'); const app = express(); function filterByQuery(query, recipesArray) { let filterResults = recipesArray; if (query.name) { filterResults = filterResults.filter(recipes => recipes.name === query.name); } return filterResults; }; app.get('/recipes', (req, res) => { let results = recipes; if (req.query) { results = filterByQuery(req.query, results); } res.json(results); }); app.listen(3000, () => { console.log(`Server is running on port 3000!`); }); ```
2022/02/25
[ "https://Stackoverflow.com/questions/71270008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16968160/" ]
Try like this ```js function fileType() { return new Promise((resolve, reject) => { fs.readdir( path.resolve(__dirname, "access"), (err, files) => { if (err) { reject(err); } else { resolve(files.map((file) => { // resolve here return file.split(".").slice(0, -1).join("."); })) } } ); // if you resolve you promise here, you resolve it before the readdir has been resolved itself. }); } ```
3,089,897
all the while, I am using `setw` for my ANSI text file alignment. Recently, I want to support UTF-8 in my text file. I found out that `setw` no longer work. ``` #include <windows.h> #include <iostream> // For StringCchLengthW. #include <Strsafe.h> #include <fstream> #include <iomanip> #include <string> #include <cassert> std::string wstring2string(const std::wstring& utf16_unicode) { // // Special case of NULL or empty input string // if ( (utf16_unicode.c_str() == NULL) || (*(utf16_unicode.c_str()) == L'\0') ) { // Return empty string return ""; } // // Consider WCHAR's count corresponding to total input string length, // including end-of-string (L'\0') character. // const size_t cchUTF16Max = INT_MAX - 1; size_t cchUTF16; HRESULT hr = ::StringCchLengthW( utf16_unicode.c_str(), cchUTF16Max, &cchUTF16 ); if ( FAILED( hr ) ) { throw std::exception("Error during wstring2string"); } // Consider also terminating \0 ++cchUTF16; // // WC_ERR_INVALID_CHARS flag is set to fail if invalid input character // is encountered. // This flag is supported on Windows Vista and later. // Don't use it on Windows XP and previous. // // CHEOK : Under Windows XP VC 2008, WINVER is 0x0600. // If I use dwConversionFlags = WC_ERR_INVALID_CHARS, runtime error will // occur with last error code (1004, Invalid flags.) //#if (WINVER >= 0x0600) // DWORD dwConversionFlags = WC_ERR_INVALID_CHARS; //#else DWORD dwConversionFlags = 0; //#endif // // Get size of destination UTF-8 buffer, in CHAR's (= bytes) // int cbUTF8 = ::WideCharToMultiByte( CP_UTF8, // convert to UTF-8 dwConversionFlags, // specify conversion behavior utf16_unicode.c_str(), // source UTF-16 string static_cast<int>( cchUTF16 ), // total source string length, in WCHAR's, // including end-of-string \0 NULL, // unused - no conversion required in this step 0, // request buffer size NULL, NULL // unused ); assert( cbUTF8 != 0 ); if ( cbUTF8 == 0 ) { throw std::exception("Error during wstring2string"); } // // Allocate destination buffer for UTF-8 string // int cchUTF8 = cbUTF8; // sizeof(CHAR) = 1 byte CHAR * pszUTF8 = new CHAR[cchUTF8]; // // Do the conversion from UTF-16 to UTF-8 // int result = ::WideCharToMultiByte( CP_UTF8, // convert to UTF-8 dwConversionFlags, // specify conversion behavior utf16_unicode.c_str(), // source UTF-16 string static_cast<int>( cchUTF16 ), // total source string length, in WCHAR's, // including end-of-string \0 pszUTF8, // destination buffer cbUTF8, // destination buffer size, in bytes NULL, NULL // unused ); assert( result != 0 ); if ( result == 0 ) { throw std::exception("Error during wstring2string"); } std::string strUTF8(pszUTF8); delete[] pszUTF8; // Return resulting UTF-8 string return strUTF8; } int main() { // Write the file content in UTF-8 { std::ofstream file; file.open("c:\\A-UTF8.txt"); file << std::setw(12) << std::left << wstring2string(L"我爱你") << "????" << std::endl; file << std::setw(12) << std::left << "ILU" << "????"; } { std::ofstream file; file.open("c:\\A-ANSI.txt"); file << std::setw(12) << std::left << "WTF" << "????" << std::endl; file << std::setw(12) << std::left << "ILU" << "????"; } return 0; } ``` My output for **A-ANSI.txt** is ``` WTF ???? ILU ???? ``` My out put for **A-UTF8.txt** is ``` 我爱你 ???? ILU ???? ``` How can I make A-UTF8.txt's text aligned properly?
2010/06/22
[ "https://Stackoverflow.com/questions/3089897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/72437/" ]
Even in a "monospaced" font, [some East Asian characters are wider than others](http://unicode.org/reports/tr11/). You also have to consider combining characters, which have no width of their own. There's a [`wcswidth`](http://www.cl.cam.ac.uk/~mgk25/ucs/wcswidth.html) function that may do what you want.
26,789,804
So before the update there was a simple way to log into google drive and manipulate your google docs - with ruby. Before you were able to log into your google drive with this. ``` require 'google_drive' $session = GoogleDrive.login("[email protected]", "password") ``` But now you get the warning message: ``` WARNING: GoogleDrive.login is deprecated and will be removed in the next version. Use GoogleDrive.login_with_oauth instead. ``` So I went to the git [hub page](https://github.com/gimite/google-drive-ruby) to see how google wants us to use their services with high level languages, and found out they want us to use oAuth2. Like so. ``` require 'google/api_client' require 'google_drive' client = Google::APIClient.new( :application_name => 'Example Ruby application', :application_version => '1.0.0' ) auth = client.authorization auth.client_id = "YOUR CLIENT ID" auth.client_secret = "YOUR CLIENT SECRET" auth.scope = "https://www.googleapis.com/auth/drive " + "https://spreadsheets.google.com/feeds/" auth.redirect_uri = "urn:ietf:wg:oauth:2.0:oob" print("1. Open this page:\n%s\n\n" % auth.authorization_uri) print("2. Enter the authorization code shown in the page: ") auth.code = $stdin.gets.chomp auth.fetch_access_token! access_token = auth.access_token $session = GoogleDrive.login_with_oauth(access_token) ``` This is fine and all but I can't save the auth variable. I would like to hard code this in the script so I don't have to keep going to google to get a new access\_token. So I've tried to get the access\_token and adding it to the script like so. ``` require 'google/api_client' require 'google_drive' client = Google::APIClient.new access_token = "TokenFromGoogleHardCoded" $session = GoogleDrive.login_with_oauth(access_token) # $session doesn't connect ``` I'm not sure I'm attacking this problem in the correct manor. I would like to save the complete auth variable and hard code it in my scripts.
2014/11/06
[ "https://Stackoverflow.com/questions/26789804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2097165/" ]
I figured out this mess. ``` auth.scope = "https://www.googleapis.com/auth/drive " + "https://spreadsheets.google.com/feeds/" ``` The auth.scope is missing a url. [REFERENCE](https://github.com/gimite/google-drive-ruby/issues/59) from github ``` auth.scope = "https://docs.google.com/feeds/" + "https://www.googleapis.com/auth/drive " + "https://spreadsheets.google.com/feeds/" ``` You can reuse your access\_token, but first you need to get it. WARNING: The auth.access\_token is only good for an hour. If you need another one you need to call auth.refresh! This will issue you another access\_token. ``` require 'google/api_client' require 'google_drive' client = Google::APIClient.new( :application_name => 'Example Ruby application', :application_version => '1.0.0' ) auth = client.authorization auth.client_id = "YOUR CLIENT ID" auth.client_secret = "YOUR CLIENT SECRET" auth.scope = "https://www.googleapis.com/auth/drive " + "https://spreadsheets.google.com/feeds/" auth.redirect_uri = "urn:ietf:wg:oauth:2.0:oob" print("1. Open this page:\n%s\n\n" % auth.authorization_uri) print("2. Enter the authorization code shown in the page: ") auth.code = $stdin.gets.chomp auth.fetch_access_token! access_token = auth.access_token system'clear' print "Save your access token\n\n" print access_token print "\nSave your refresh token\n\n" print auth.refresh_token ``` This chunk of code should print out your access\_token/refresh\_token in your console. Now you can hard code your application. ``` require "google/api_client" require "google_driver" client = Google::APIClient.new( :application_name => 'Example Ruby application', :application_version => '1.0.0' ) auth = client.authorization auth.client_id = "Your Client ID" auth.client_secret = "Your client secret" access_token = "token you saved from the terminal" session = GoogleDrive.login_with_oauth(access_token) for file in session.files p file.title end ``` And eventually your "access\_token" will expire. At this point you need to "refresh" it. You can call to see if your access\_token is expired by calling ``` auth.expires_at ``` You can get a new access token with this example. ``` require 'google/api_client' require 'google_drive' $client_id = "YOUR CLIENT ID" $client_secret = "YOUR CLIENT SECRET" $refresh_token = "SAVED REFRESH TOKEN" client = Google::APIClient.new(:application_name => 'Example Ruby application', :application_version => '1.0.0') auth = client.authorization auth.client_id = $client_id auth.client_secret = $client_secret auth.scope = "https://docs.google.com/feeds/" + "https://www.googleapis.com/auth/drive " + "https://spreadsheets.google.com/feeds/" auth.redirect_uri = "urn:ietf:wg:oauth:2.0:oob" auth.refresh_token = $refresh_token #here's the magic sauce auth.refresh! #as you can see above auth.access_token wasn't passed a value # but if you call it now you'll see you have a new access_token auth.access_token => new token from server ```
78,880
Is it possible exploit stack buffer overflows on an Arduino board?
2013/08/14
[ "https://electronics.stackexchange.com/questions/78880", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/18249/" ]
Your question can be read two ways, DarkCoffee: If a particular Arduino based device can be induced to overflow its stack, can it be exploited? =============================================================================================== Yes, it is possible to exploit a stack overflow on an Arduino. One possible attack is the [return oriented programming](https://en.wikipedia.org/wiki/Return-oriented_programming) method, which requires sufficiently complex firmware. So, one defense here is to keep your firmware as simple as possible. It is highly unlikely that the [Arduino "hello world" sketch](http://arduino.cc/en/Tutorial/Blink?from=Tutorial.BlinkingLED) is vulnerable. That shouldn't be much comfort to you, though, because an LED blinker isn't terribly *useful*. Useful firmware will have more functions, and therefore more function tails to harvest for use in an abstract machine. The Arduino also has a boot loader, which inherently has the power to overwrite firmware. It may be possible to exploit it to overwrite existing benign but vulnerable firmware with malign firmware. My reading of the first page of [the INRIA attack paper](http://arxiv.org/abs/0901.3482) leads me to believe it combines both approaches: return oriented programming to execute enough code to activate the self-flashing ability of the microcontroller so that arbitrary code can be permanently loaded. Are there stack overflow attacks on Arduinos in general? ======================================================== I'm not aware of any attack that works on all Arduino based devices. Again, the "hello world" LED blinker sketch is probably invulnerable, simply because it is too trivial to be vulnerable. The more code you write, the more likely it is that you will create a vulnerability. Note that writing 5,000 lines of code then replacing 2 [kLOC](https://en.wikipedia.org/wiki/Source_lines_of_code) with 1,000 new lines isn't a net savings of 1 kLOC from a security standpoint. If those 5 kLOC were secure and you messed up while writing some of the new 1 kLOC, it's still a vulnerability. The moral of the story is that the most secure code tends to be that which is stared at the longest, and that means keeping it unchanged as long as possible. Obviously, every vulnerability should be patched ASAP. This is no argument for keeping old vulnerabilities around. It's an argument against adding features thoughtlessly to code you believe secure though inspection, audit, and analysis.
10,377,685
beginner PHP programmer here trying to use the mailchimp API... I keep getting this PHP error with regard to my first line of code here.... I am posting a value from a form, as you can see, but I am not sure what is going on. The error: Warning: Variable passed to each() is not an array or object in xxxxxxx on line 24 (which is the first line) ``` while (list($key, $val) = each($_POST['MCgroup'])) { $interest .= ($count>0 ? ", " : ""); $interest .= $val; $count++; } echo $interest; //echos NOTHINGblank $mergeVars = array( 'INTERESTS'=>$interest ); echo $mergeVars; //echos the word ARRAY ``` From what I have researched, OBVIOUSLY I am not passing an actual ARRAY... but also from what I have found, my syntax all seems correct. (But I could be overlooking something). Here is the part of the form code that is passing the values ``` <input type="hidden" name="MCgroup" id="MCgroup" value="My Interest One" /> <input type="hidden" name="MCgroup" id="MCgroup" value="My Interest Two" /> ``` or I COULD change it to ``` <input type="hidden" name="MCgroup" id="MCgroup" value="My Interest One, My Interest Two" /> ``` I just am not sure how to make THAT into an array. Help please! Thanks!
2012/04/30
[ "https://Stackoverflow.com/questions/10377685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/576562/" ]
Try using a `\` at the end of the line to continue the string to the next line.
13,987,673
Kind of asking for your opinion more than asking a question with a definite right/wrong answer. I'm fairly new to OOPHP I have done some OO programming in the past. What I am having trouble getting my head round is the best way to share objects (or more their state) between pages. I'm trying to avoid cramming lots of data into the $\_SESSION and i don't like the idea of posting all the data in a form each page change either. Any insights would be appreciated. Thanks TT
2012/12/21
[ "https://Stackoverflow.com/questions/13987673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1913265/" ]
There is nothing at all wrong with saving "lots of data" in the `$_SESSION`. By doing this you are not at all increasing transfer size or anything so you're not affecting the client as `$_SESSION` is purely server-side. > > I'm trying to avoid cramming lots of data into the $\_SESSION and i don't like the idea of posting all the data in a form each page change either. > > > As above, this is a non-issue, you're not "posting all the data in a form each page change", it's stored server-side in a flat file that is simply deserialized automatically when you reopen the session, and put into `$_SESSION`. Provided that `$_SESSION`'s lifetime is enough for you, you should use it. If you need something more persistent than a `$_SESSION`, for example you need to store an object against a user for the whole time that they're logged in, you can consider either serializing objects in a database and pulling them out on pageload, or simply recreating an object from values you store against the user.
74,464,255
SO I'm trying to install Moodle using Ubuntu and I followed the instructions from <https://www.linode.com/docs/guides/how-to-install-moodle-on-ubuntu-server-2004/> , but when I type localhost/moodle on my browser, it just displays the PHP code which I'll add. I should be displayed with the Moodle installation steps right? I can't imagine it would be a problem with Moodle itself but rather a PHP issue. Any help would be greatly appreciated! ``` <?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Moodle frontpage. * * @package core * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com) * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ if (!file_exists('./config.php')) { header('Location: install.php'); die; } require_once('config.php'); require_once($CFG->dirroot .'/course/lib.php'); require_once($CFG->libdir .'/filelib.php'); redirect_if_major_upgrade_required(); $urlparams = array(); if (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_MY) && optional_param('redirect', 1, PARAM_BOOL) === 0) { $urlparams['redirect'] = 0; } $PAGE->set_url('/', $urlparams); $PAGE->set_pagelayout('frontpage'); $PAGE->set_other_editing_capability('moodle/course:update'); $PAGE->set_other_editing_capability('moodle/course:manageactivities'); $PAGE->set_other_editing_capability('moodle/course:activityvisibility'); // Prevent caching of this page to stop confusion when changing page after making AJAX changes. $PAGE->set_cacheable(false); require_course_login($SITE); $hasmaintenanceaccess = has_capability('moodle/site:maintenanceaccess', context_system::instance()); // If the site is currently under maintenance, then print a message. if (!empty($CFG->maintenance_enabled) and !$hasmaintenanceaccess) { print_maintenance_message(); } $hassiteconfig = has_capability('moodle/site:config', context_system::instance()); if ($hassiteconfig && moodle_needs_upgrading()) { redirect($CFG->wwwroot .'/'. $CFG->admin .'/index.php'); } // If site registration needs updating, redirect. \core\hub\registration::registration_reminder('/index.php'); if (get_home_page() != HOMEPAGE_SITE) { // Redirect logged-in users to My Moodle overview if required. $redirect = optional_param('redirect', 1, PARAM_BOOL); if (optional_param('setdefaulthome', false, PARAM_BOOL)) { set_user_preference('user_home_page_preference', HOMEPAGE_SITE); } else if (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_MY) && $redirect === 1) { redirect($CFG->wwwroot .'/my/'); } else if (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_USER)) { $frontpagenode = $PAGE->settingsnav->find('frontpage', null); if ($frontpagenode) { $frontpagenode->add( get_string('makethismyhome'), new moodle_url('/', array('setdefaulthome' => true)), navigation_node::TYPE_SETTING); } else { $frontpagenode = $PAGE->settingsnav->add(get_string('frontpagesettings'), null, navigation_node::TYPE_SETTING, null); $frontpagenode->force_open(); $frontpagenode->add(get_string('makethismyhome'), new moodle_url('/', array('setdefaulthome' => true)), navigation_node::TYPE_SETTING); } } } // Trigger event. course_view(context_course::instance(SITEID)); $PAGE->set_pagetype('site-index'); $PAGE->set_docs_path(''); $editing = $PAGE->user_is_editing(); $PAGE->set_title($SITE->fullname); $PAGE->set_heading($SITE->fullname); $courserenderer = $PAGE->get_renderer('core', 'course'); echo $OUTPUT->header(); $siteformatoptions = course_get_format($SITE)->get_format_options(); $modinfo = get_fast_modinfo($SITE); $modnamesused = $modinfo->get_used_module_names(); // Print Section or custom info. if (!empty($CFG->customfrontpageinclude)) { // Pre-fill some variables that custom front page might use. $modnames = get_module_types_names(); $modnamesplural = get_module_types_names(true); $mods = $modinfo->get_cms(); include($CFG->customfrontpageinclude); } else if ($siteformatoptions['numsections'] > 0) { echo $courserenderer->frontpage_section1(); } // Include course AJAX. include_course_ajax($SITE, $modnamesused); echo $courserenderer->frontpage(); if ($editing && has_capability('moodle/course:create', context_system::instance())) { echo $courserenderer->add_new_course_button(); } echo $OUTPUT->footer(); ``` I looked at the modules in my httpd.conf file, but when adding "LoadModule php\_module modules/libphp.so" apache throws an error when attempting to restart.
2022/11/16
[ "https://Stackoverflow.com/questions/74464255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
To remove columns based on array of column numbers ``` let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content], MyList={1,2}, x = Table.RemoveColumns(Source,List.Transform(MyList, each Table.ColumnNames(Source){_})) in x ``` To remove columns where contents of rows in that column are identical ``` let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content], #"Unpivoted Columns" = Table.UnpivotOtherColumns(Source, {}, "Attribute", "Value"), #"Grouped Rows" = Table.Group(#"Unpivoted Columns", {"Attribute"}, {{"Test", each if List.Count(List.Distinct([Value]))=1 then true else false}}), x = Table.RemoveColumns(Source,Table.SelectRows(#"Grouped Rows", each ([Test] = true))[Attribute]) in x ```
13,869,966
I have data similar to that seen in this [gist](https://gist.github.com/4280658) and I am trying to extract the data with numpy. I am rather new to python so I tried to do so with the following code ``` import numpy as np from datetime import datetime convertfunc = lambda x: datetime.strptime(x, '%H:%M:%S:.%f') col_headers = ["Mass", "Thermocouple", "T O2 Sensor",\ "Igniter", "Lamps", "O2", "Time"] data = np.genfromtxt(files[1], skip_header=22,\ names=col_headers,\ converters={"Time": convertfunc}) ``` Where as can be seen in the gist there are 22 rows of header material. In Ipython, when I "run" the following code I receive an error that ends with the following: ``` TypeError: float() argument must be a string or a number ``` The full ipython error trace can be seen [here](https://gist.github.com/4280768). I am able to extract the six columns of numeric data just fine using an argument to genfromtxt like usecols=range(0,6), but when I try to use a converter to try and tackle the last column I'm stumped. Any and all comments would be appreciated!
2012/12/13
[ "https://Stackoverflow.com/questions/13869966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1902480/" ]
This is happening because `np.genfromtxt` is trying to create a float array, which fails because `convertfunc` returns a datetime object, which cannot be cast as float. The easiest solution would be to just pass the argument `dtype='object'` to `np.genfromtxt`, ensuring the creation of an object array and preventing a conversion to float. However, this would mean that the other columns would be saved as strings. To get them properly saved as floats you need to specify the `dtype` of each to get a [structured array](http://docs.scipy.org/doc/numpy/user/basics.rec.html). Here I'm setting them all to double except the last column, which will be an object dtype: ``` dd = [(a, 'd') for a in col_headers[:-1]] + [(col_headers[-1], 'object')] data = np.genfromtxt(files[1], skip_header=22, dtype=dd, names=col_headers, converters={'Time': convertfunc}) ``` This will give you a structured array which you can access with the names you gave: ``` In [74]: data['Mass'] Out[74]: array([ 0.262 , 0.2618, 0.2616, 0.2614]) In [75]: data['Time'] Out[75]: array([1900-01-01 15:49:24.546000, 1900-01-01 15:49:25.171000, 1900-01-01 15:49:25.405000, 1900-01-01 15:49:25.624000], dtype=object) ```
52,988,583
I want to attach more than one file to the mail sent. Mail facade: ``` public function build() { return $this->from('[email protected]') ->to('[email protected]') ->view('mails.demo') ->text('mails.demo_plain') ->with( [ 'testVarOne' => '1', 'testVarTwo' => '2', ]) ->attach(public_path('/img').'/NHLS.jpg', [ 'as' => 'NHLS.jpg', 'mime' => 'image/jpeg', ]); } ``` }
2018/10/25
[ "https://Stackoverflow.com/questions/52988583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5384905/" ]
You can store all of your attachment in array and then loop through it to attach all the attachments ``` $attachments = [ // first attachment '/path/to/file1', // second attachment '/path/to/file2', ... ]; public function build() { $email = $this->view('mails.demo')->subject('Test subject') ->from('[email protected]') ->to('[email protected]') ->text('mails.demo_plain'); // $attachments is an array with file paths of attachments foreach($attachments as $filePath){ $email->attach($filePath); } return $email; } ```
163,629
I wrote a function in C++ which uses binary multiplication (a form of binary exponentation): ``` public: Point mul(Point p, unsigned int n) { // actually these Points shouldn't have negative coordinates, I use Point(-1, -1) as neutral element on addition (like 0) Point r = Point(-1, -1); n = mod(n, m); // the %-operator doesn't return a non-negative integer in every case so I wrote a function unsigned int mask = 1 << (sizeof (n) - 1); // more flexible and platform independent than 1 << 31 for (; mask; mask >>= 1) { r = add(r, r); if (mask & n) r = add(r, p); } return r; } ``` **Notes:** * The function calculates points on elliptic curves over a finite field GF(`m`) * `Point` is a class I wrote for this. It doesn't do much beside holding two coordinates `x` and `y` * I just wondered if there is an easier / cleaner solution for binary multiplcation in C++ than I implemented * The algorithm is like 'double and add' instead of 'square and multiply' **EDITS:** This is my `Point` class: ``` class Point { public: long long int x, y; public: Point(long long int _x, long long int _y) { x = _x; y = _y; } public: void print() { cout << "("; cout << x; cout << ", "; cout << y; cout ")"; } }; ``` The `mul` function is part of the class `EllipticCurve`: ``` class EllipticCurve { public: int a; int b; unsigned int m; public: EllipticCurve(int _a, int_b, unsigned int modul) { a = _a; b = _b; m = modul; } public: Point generate(unsigned long long int x) { // looks for Points on the curve with the given x coordinate // returns the first matching point } public: Point add(Point p, Point q) { // complex addition function with if-else trees // the function code is not needed for this question } public: Point mul(Point p, unsigned int n) { // see above } }; ``` Please remember that this question is about the `mul` function, not the rest of the code. I inserted it only for a better understanding.
2017/05/18
[ "https://codereview.stackexchange.com/questions/163629", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/118039/" ]
> > > ``` > n = mod(n, m); // the %-operator doesn't return a non-negative integer in every case so I wrote a function > > ``` > > I would find a comment explaining `m` more useful than a comment explaining why you made a `mod` function, because everyone ends up writing a `mod` function which behaves sensibly. I don't know much about elliptic curves, but I have worked with finite fields. Are you *sure* it makes sense to take `n mod m` as though they were integers? The only makes sense to me if `m` is also the characteristic (i.e. if it's a field of prime order). --- > > > ``` > unsigned int mask = 1 << (sizeof (n) - 1); // more flexible and platform independent than 1 << 31 > for (; mask; mask >>= 1) > > ``` > > Why loop down? If you loop up then you get the platform-independence for free, and also you loop fewer times when `n` is small. Obviously the loop invariant would change, but it would be closer to school long multiplication and so might also be more maintainable. ``` for (; n; n >>= 1) { if (n & 1) r = add(r, p); p = add(p, p); } ```
3,767,047
I am developing a Java command line application and I need to display an asterisk (\*), or any similar sign, when the user inputs the password. I have tried using the replace() method but it accepts only one character. Is there a way to pass all the letters and numbers as an argument for this replace method. Or else what is the method of masking the suer input. I cannot use the console.readPassword technique here, because I need the password (tpyed by the user) in the String data type.
2010/09/22
[ "https://Stackoverflow.com/questions/3767047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/319271/" ]
Actually, you cannot use the replace method. By using it, the user input is still visible, and you're only changing the value you stored into memory. If you need the password as a String (that's not recommended for security reasons, but anyway...): ``` char[] pwd = console.readPassword(); String str = new String(pwd); ```
60,370,681
I have attached the [link](https://easyupload.io/fybjz2) to the site files(zip), I just want to attach the css to the html so that I will not have a call for a file that wastes my time and slows the site down. Thanks in advance!
2020/02/24
[ "https://Stackoverflow.com/questions/60370681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6544218/" ]
If you are trying to use Decodable, which is the defacto standard for parsing json in Swift. Then you should create structs for each item that you have. ``` struct Complaint: Decodable { let createdAt: String let updatedAt: String let userId: Int let type: String let subject: String let description: String let status: String let date: String? let adminId: Int let id: Int } struct ComplaintComments: Decodable { let id: Int let resolutionStatus: String? // this is optional because you have shown that some of the values could be null. let resolutionDate: String? let comments: String let complaintId: Int let updatedByUserId: Int } struct OrderComplaint: Decodable { var complaintComments: [ComplaintComments] var complaint: Complaint } ``` Then you can use it in the following way: ``` let decoder = JSONDecoder() let result = try! decoder.decode([OrderComplaint].self, from: data) ``` NB: You may not wish to force unwrap here as that will cause your app to crash, you should use a do/catch. If an item in your struct could be null, then you need to make sure that item is an optional otherwise it will not parse correctly. This [article](https://www.avanderlee.com/swift/json-parsing-decoding/) by SwiftLee gives a good overview on how to use Decodable.
15,882,395
I try to generate a movie using the matplotlib movie writer. If I do that, I always get a white margin around the video. Has anyone an idea how to remove that margin? Adjusted example from <http://matplotlib.org/examples/animation/moviewriter.html> ``` # This example uses a MovieWriter directly to grab individual frames and # write them to a file. This avoids any event loop integration, but has # the advantage of working with even the Agg backend. This is not recommended # for use in an interactive setting. # -*- noplot -*- import numpy as np import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import matplotlib.animation as manimation FFMpegWriter = manimation.writers['ffmpeg'] metadata = dict(title='Movie Test', artist='Matplotlib', comment='Movie support!') writer = FFMpegWriter(fps=15, metadata=metadata, extra_args=['-vcodec', 'libx264']) fig = plt.figure() ax = plt.subplot(111) plt.axis('off') fig.subplots_adjust(left=None, bottom=None, right=None, wspace=None, hspace=None) ax.set_frame_on(False) ax.set_xticks([]) ax.set_yticks([]) plt.axis('off') with writer.saving(fig, "writer_test.mp4", 100): for i in range(100): mat = np.random.random((100,100)) ax.imshow(mat,interpolation='nearest') writer.grab_frame() ```
2013/04/08
[ "https://Stackoverflow.com/questions/15882395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2156909/" ]
Passing `None` as an arguement to `subplots_adjust` does not do what you think it does [(doc)](http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure.subplots_adjust). It means 'use the deault value'. To do what you want use the following instead: ``` fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None) ``` You can also make your code much more efficent if you re-use your `ImageAxes` object ``` mat = np.random.random((100,100)) im = ax.imshow(mat,interpolation='nearest') with writer.saving(fig, "writer_test.mp4", 100): for i in range(100): mat = np.random.random((100,100)) im.set_data(mat) writer.grab_frame() ``` By default `imshow` fixes the aspect ratio to be equal, that is so your pixels are square. You either need to re-size your figure to be the same aspect ratio as your images: ``` fig.set_size_inches(w, h, forward=True) ``` or tell `imshow` to use an arbitrary aspect ratio ``` im = ax.imshow(..., aspect='auto') ```
28,654,076
When I start a docker container it fails because an existing pid file: ``` [root@newhope sergio]# docker logs sharp_shockley httpd (pid 1) already running httpd (pid 1) already running httpd (pid 1) already running httpd (pid 1) already running ``` How can I remove such a file, because I don't find it. ``` [root@newhope sergio]# docker version Client version: 1.4.1 Client API version: 1.16 Go version (client): go1.3.3 Git commit (client): 5bc2ff8/1.4.1 OS/Arch (client): linux/amd64 Server version: 1.4.1 Server API version: 1.16 Go version (server): go1.3.3 Git commit (server): 5bc2ff8/1.4.1 [root@newhope sergio]# find / -name "httpd.pid" find: ‘/run/user/1000/gvfs’: Permiso denegado ```
2015/02/22
[ "https://Stackoverflow.com/questions/28654076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/481895/" ]
Try: ``` docker-compose down ``` To destroy any environments that are already running.
6,259,003
i'm facing a problem right now, i need to count the number of time a certain MxM matrix appears inside a NxN one (this one should be larger than the first one). Any hints on how to do this? I'm going to implement it in C and there is no option to change it. **Revision 1** Hi everyone, i would really like to say thank to all the answers and opinions on the matter. I should tell you that after many hours of hard work we have come to a solutions that is not strictly like the Boyer-Moore approach, but rather an algorithm on my own. I'm planning on publishing it once is tested and finished. The solutions is now being adapted to be paralelized for speed optimization using the university cluster with the C Library MPI.
2011/06/06
[ "https://Stackoverflow.com/questions/6259003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/545622/" ]
Hm, sounds like a 2-dimensional version of string matching. I wonder if there's a 2D version of Boyer-Moore? [A Boyer-Moore Approach for Two-Dimensional Matching](http://techreports.lib.berkeley.edu/accessPages/CSD-93-784.html) Ah, apparently there is. :-)
47,386,191
can someone fix my code, I want to make variable for disable my textbox ``` foreach (var item in Model.rol_tb_approve1) { if (Model.rol_tb_form1.id == item.id_form) { if (item.status == 1) { <text> @{ var new = "disabled"; } </text> } } } <div> <h3>I. Permasalahan<h3> @Html.TextAreaFor(x => x.rol_tb_form1.permasalahan, new { @style = "width:98%", @rows = "3", @new }) </div> ``` I want if item.status is 1, I can edit it, but if item.status is 2, textarea will disabled
2017/11/20
[ "https://Stackoverflow.com/questions/47386191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8817043/" ]
Check `status` and add disable property to the textarea. ``` foreach (var item in Model.rol_tb_approve1) { if (Model.rol_tb_form1.id == item.id_form) { <div> <h3>I. Permasalahan<h3> if (item.status == 1) { @Html.TextAreaFor(x => x.rol_tb_form1.permasalahan, new { @style = "width:98%", @rows = "3"}) } else { @Html.TextAreaFor(x => x.rol_tb_form1.permasalahan, new { @style = "width:98%", @rows = "3", @readonly = "readonly" }) } </div> } } ``` If you have more texarea, then you could do something like: ``` foreach (var item in Model.rol_tb_approve1) { if (Model.rol_tb_form1.id == item.id_form) { <div> <h3>I. Permasalahan<h3> if (item.status == 1) { @Html.TextAreaFor(x => x.rol_tb_form1.permasalahan, new { @style = "width:98%", @rows = "3",id="firsttextarea"}) @Html.TextAreaFor(x => x.rol_tb_form1.permasalahan, new { @style = "width:98%", @rows = "3",id="secondtextarea"}) @Html.TextAreaFor(x => x.rol_tb_form1.permasalahan, new { @style = "width:98%", @rows = "3",id="thirdtextarea"}) } else { @Html.TextAreaFor(x => x.rol_tb_form1.permasalahan, new { @style = "width:98%", @rows = "3", @readonly = "readonly",id="firsttextarea" }) @Html.TextAreaFor(x => x.rol_tb_form1.permasalahan, new { @style = "width:98%", @rows = "3", @readonly = "readonly",id="secondtextarea" }) @Html.TextAreaFor(x => x.rol_tb_form1.permasalahan, new { @style = "width:98%", @rows = "3", @readonly = "readonly",id="thirdtextarea" }) } </div> } } ``` You can use ternary operator ``` foreach (var item in Model.rol_tb_approve1) { if (Model.rol_tb_form1.id == item.id_form) { <div> <h3>I. Permasalahan<h3> @Html.TextAreaFor(x => x.rol_tb_form1.permasalahan,(item.status == 1)? new { @style = "width:98%", @rows = "3" }: {@style = "width:98%", @rows = "3", @readonly = "readonly"}) </div> } } ```
22,227
At the very commencement of my writing "career" (I have virtually zero experience), I have an idea I would like to flesh out and turn into a full story. Being extremely proud of the concepts I have developed, I don't want to ruin the story by attempting to pursue publication it while I am still unexperienced, but I don't want to have to wait too long to actually start writing it. In general, is it better to start developing/writing ideas (with the goal of publication) as soon as they are had, or to reserve them until one has more experience in order to get the most out of it? What ideas are fine to develop at the start of one's career? Should ideas with large potential be reserved or acted on immediately (considering skill level)? (PS: This is also my first Writers.SE question so feel free to be as critical as you like!)
2016/06/03
[ "https://writers.stackexchange.com/questions/22227", "https://writers.stackexchange.com", "https://writers.stackexchange.com/users/19213/" ]
Use your best ideas. Write them as well as you can. Yes, your writing will improve with experience. And your ideas will also improve with experience. If you reserve your "best ideas" until you're a better writer, then your early stories will exhibit neither your best ideas nor your best writing. Why hamper yourself like that? Sometimes people love great stories even if the writing is somewhat clumsy. Use your best ideas. Give people a chance to love your story even as you gain writing experience. Writing your best ideas will keep you motivated, and that will make your writing better. Maybe not as good as it will be, but as good as it can be for now. Don't worry about wasting a great idea. You will have more great ideas. Plenty of them. There is no need to hold back. Use your best ideas. Write them as well as you can.
8,976,414
How do I get structure of temp table then delete temp table. Is there a sp\_helptext for temp tables? Finally is it possible to then delete temp table in same session or query window? Example: ``` select * into #myTempTable -- creates a new temp table from tMyTable -- some table in your database tempdb..sp_help #myTempTable ``` [Reference](http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=72960).
2012/01/23
[ "https://Stackoverflow.com/questions/8976414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/487328/" ]
You need to use quotes around the temp table name and you can delete the temp table directly after using `drop table ...`. ``` select * into #myTempTable -- creates a new temp table from tMyTable -- some table in your database exec tempdb..sp_help '#myTempTable' drop table #myTempTable ```
3,449,294
Given the following formula: ``` Precision = TP / (TP + FP) Recall = TPR (True Positive Rate) F1 = 2((PRE * REC)/(PRE + REC)) ``` What is the correct interpretation for f1-score when precision is `Nan` and recall isn't?
2019/11/24
[ "https://math.stackexchange.com/questions/3449294", "https://math.stackexchange.com", "https://math.stackexchange.com/users/393216/" ]
The determinant would be equal to either the product of the secondary diagonal or negative the product of the secondary diagonal, depending on the dimension of the matrix: $$ \lvert A \rvert = \pm a\_{n1} a\_{(n-1)2} a\_{(n-2)3} \cdots a\_{1n}. $$ One way to show this is to reverse the order of the rows of your matrix, which is a permutation of rows (hence preserving the absolute value of the determinant) that converts your matrix into an upper triangular matrix. The main diagonal of this upper triangular matrix is composed of the elements on the secondary diagonal of your original matrix, and its product is the determinant of the upper triangular matrix. --- The $\pm$ sign depends on the sign of the permutation of the rows, which you can determine by the minimum number of swaps required to move all rows to their final positions: the sign is positive if the number of swaps is even, negative if the number of swaps is odd. For a $2\times 2$ matrix, you swap rows $1$ and $2$; one swap, so $\lvert A\rvert = -a\_{21}a\_{12}.$ For a $3\times 3$ matrix, you swap rows $1$ and $3$; one swap, so $\lvert A\rvert = -a\_{31}a\_{22}a\_{13}.$ For a $4\times 4$ matrix, you swap rows $1$ and $4$ and swap rows $2$ and $3$; two swaps, so $\lvert A\rvert = a\_{41}a\_{32}a\_{23}a\_{14}.$ For a $5\times 5$ matrix, you swap rows $1$ and $5$ and swap rows $2$ and $4$; two swaps, so $\lvert A\rvert = a\_{51}a\_{42}a\_{33}a\_{24}a\_{15}.$ Every time you increase the number of rows by $4$ you incur two more swaps, so the sign for an $(n+4)\times(n+4)$ matrix is the same as for an $n\times n$ matrix, and so the pattern repeats: $-,-,+,+,-,-,+,+,\ldots.$
29,778,363
I'm trying to set proxy for weka 3.7 package manager like this tutorial: <https://weka.wikispaces.com/How+do+I+use+the+package+manager%3F#GUI> package manager-Using a HTTP proxy ``` java -Dhttp.proxyHost=some.proxy.somewhere.net -Dhttp.proxyPort=port weka.gui.GUIChooser ``` but it gives me this error: ``` Error: Could not find or load main class weka.gui.GUIChooser ``` I have already check the path and classpath and weka runs with runweka.bat without any problem.
2015/04/21
[ "https://Stackoverflow.com/questions/29778363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3247018/" ]
I found the solution after playing with the paths; knb answer is correct but you need to include weka.jar in the command. ``` java -cp weka.jar -Dhttp.proxyHost=some.proxy.somewhere.net -Dhttp.proxyPort=port weka.gui.GUIChooser ```
55,253,260
I am trying retrieve weather forecasting from DarkSky using their API with the code below. I am interested only in the part of hourly forecasting data: ``` url="https://api.darksky.net/forecast/api_key/33.972386,-84.231986" response = requests.get(url) data = response.json() data ``` Here is the part of JSON data I get from data pull: ``` {'latitude': 33.972386, 'longitude': -84.231986, 'timezone': 'America/New_York', 'currently': {'time': 1553052005, 'summary': 'Clear', 'icon': 'clear-night', 'nearestStormDistance': 23, 'nearestStormBearing': 169, 'precipIntensity': 0, 'precipProbability': 0, 'temperature': 43.69, 'apparentTemperature': 43.69, 'dewPoint': 25.61, 'humidity': 0.49, 'pressure': 1026.37, 'windSpeed': 1.42, 'windGust': 4.94, 'windBearing': 79, 'cloudCover': 0, 'uvIndex': 0, 'visibility': 3.86, 'ozone': 309.99}, 'minutely': {'summary': 'Clear for the hour.', 'icon': 'clear-night', 'data': [{'time': 1553052000, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553052060, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553052120, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553052180, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553052240, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553052300, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553052360, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553052420, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553052480, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553052540, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553052600, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553052660, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553052720, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553052780, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553052840, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553052900, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553052960, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553053020, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553053080, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553053140, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553053200, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553053260, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553053320, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553053380, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553053440, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553053500, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553053560, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553053620, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553053680, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553053740, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553053800, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553053860, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553053920, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553053980, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553054040, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553054100, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553054160, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553054220, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553054280, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553054340, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553054400, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553054460, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553054520, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553054580, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553054640, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553054700, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553054760, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553054820, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553054880, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553054940, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553055000, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553055060, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553055120, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553055180, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553055240, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553055300, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553055360, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553055420, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553055480, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553055540, 'precipIntensity': 0, 'precipProbability': 0}, {'time': 1553055600, 'precipIntensity': 0, 'precipProbability': 0}]}, 'hourly': {'summary': 'Clear throughout the day.', 'icon': 'clear-day', 'data': [{'time': 1553050800, 'summary': 'Clear', 'icon': 'clear-night', 'precipIntensity': 0, 'precipProbability': 0, 'temperature': 44.13, 'apparentTemperature': 44.13, 'dewPoint': 25.62, 'humidity': 0.48, 'pressure': 1026.33, 'windSpeed': 1.24, 'windGust': 4.78, 'windBearing': 93, 'cloudCover': 0, 'uvIndex': 0, 'visibility': 3.49, 'ozone': 310.66}, {'time': 1553054400, 'summary': 'Clear', 'icon': 'clear-night', 'precipIntensity': 0, 'precipProbability': 0, 'temperature': 42.82, 'apparentTemperature': 42.82, 'dewPoint': 25.57, 'humidity': 0.5, 'pressure': 1026.44, 'windSpeed': 1.95, 'windGust': 5.25, 'windBearing': 60, 'cloudCover': 0, 'uvIndex': 0, 'visibility': 4.6, 'ozone': 308.68}, {'time': 1553058000, 'summary': 'Clear', 'icon': 'clear-night', 'precipIntensity': 0, 'precipProbability': 0, 'temperature': 42.45, 'apparentTemperature': 40.02, 'dewPoint': 25.52, 'humidity': 0.51, 'pressure': 1026.39, 'windSpeed': 4.15, 'windGust': 8.98, 'windBearing': 61, 'cloudCover': 0, 'uvIndex': 0, 'visibility': 10, 'ozone': 307.84}, {'time': 1553061600, 'summary': 'Clear', 'icon': 'clear-night', 'precipIntensity': 0, 'precipProbability': 0, 'temperature': 41.97, 'apparentTemperature': 38.42, 'dewPoint': 25.8, 'humidity': 0.52, 'pressure': 1025.98, 'windSpeed': 5.52, 'windGust': 11.44, 'windBearing': 63, 'cloudCover': 0, 'uvIndex': 0, 'visibility': 10, 'ozone': 307.21}, {'time': 1553065200, 'summary': 'Clear', 'icon': 'clear-night', 'precipIntensity': 0, 'precipProbability': 0, 'temperature': 40.7, 'apparentTemperature': 36.97, 'dewPoint': 25.86, 'humidity': 0.55, 'pressure': 1025.88, 'windSpeed': 5.44, 'windGust': 10.93, 'windBearing': 61, 'cloudCover': 0, 'uvIndex': 0, 'visibility': 10, 'ozone': 306.76}, ``` Now this is bit complex json file and I have tried using json\_normalize on hourly part of json file: ``` json_normalize(data['hourly']) ``` but im getting the the response like this: ``` data icon summary 0 [{'time': 1553050800, 'summary': 'Clear', 'ico... clear-day Clear throughout the day. ``` Any idea how do I access the temperature and pressure on hourly data part? So i need to get time, temperature, pressure and humidity for every hour available. Thank you
2019/03/20
[ "https://Stackoverflow.com/questions/55253260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11229812/" ]
You should be able to access the first element in the hourly data by ``` data['hourly']['data'][0]['humidity'] ``` So if you iterate over data['hourly']['data'] you should be able to get the data you want. E.g. ``` for data_point in data['hourly']['data']: print data_point['humidity'] ```
112,382
I have the following problem: *Place the first 11 natural numbers in the circles so that the sum of the four numbers at the tops of each of the five sectors-beams of the star equals 25*. [![enter image description here](https://i.stack.imgur.com/Qx90p.png)](https://i.stack.imgur.com/Qx90p.png) I came up with the fact that $6$ should be central number as the sum of numbers from 1 to 11 is 66. But how should I distribute all threes of sum=19 - i don't know. Would appreciate **any** help. Source of the contest [link](http://mmmf.msu.ru/archive/20122013/z5/z5300313.html)
2021/10/30
[ "https://puzzling.stackexchange.com/questions/112382", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/77350/" ]
Assuming "sector beams" are the five kite-shaped things joined in the centre one solution would be > > > ``` > > 7 > > > 8 2 5 6 > > 11 > 4 3 > 1 > > 9 10 > > ``` > > > >
68,595,207
I am not being able to wrap my head around this issue in a generic way with Typescript, I would appreciate any help! * A Factory should deploy a Contract * A CustomFactory is a Factory and should deploy a CustomContract (that is a Contract) * A MockFactory should be a wrapper of all this logic Something like this would be the goal (semi pseudocode) ``` interface MockFactory<F extends Factory> extends F { deploy: (...args: Parameters<F.prototype.deploy>) => MockContract<F.prototype.deploy.returnValue> } ``` In order to illustrate the issue even better I created a [Playground](https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgMIHtxUWZBvAXwFgAoU0SWRFAMR3SgE99Tk3kATCABwBt1GALmQAKAHQS4UAOYBnYXBCMA2gF0AlMgC8APjSYw2BGADcpYmRIJecWbLQBXWWHQBbDFhzJgrvhFcQ4PYehl6EpKTWtsFOLq50xgzMPn4BQcgJLkwsJOycPPyMIgAewiAOrgBG0AA0yELI5VXQ6sKosW4hRrh4rHnsUBBgDlAg%20ARmuewWFqRgjNwoALLoCADWXTgAPKjIEMWQIBzBBt16WvqexsgAZGi3OXmuq2sAClDoi1DzZRXVUJNZiQKNB4EhkCt1pkklsaHsDoFjhl6Ew9PtDki4b0pmwAPS4-J8ATIWQAC3QDl4HGQpLgADcUGBSShuFI4AFKPZ0DBkEyUDAHCBjMBMITCt4QLJgFwMqJQLzScB7AhbCh2s43NCmOo%20niCVwicwyRSqchBsNRsg4BCXptrtyFShzSMxvNFsgHXzkAKhWARWMDeLQFKZXCRJCNqdtuq4nawHp5dbpIFoMAEMgAO5wRg6nFigTCcSSGTyZCvNkc6CyWFibgfFxuiBiQMCHSaXQ29Zxmt19ANhZNluMMTO0YANTgvAcEB05iAA) where you can see the errors
2021/07/30
[ "https://Stackoverflow.com/questions/68595207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16563093/" ]
Just solved by using ReturnType and Parameters, as well needed to transform the interface into a type: ```js interface Contract {} interface Factory { deploy: (...args: any[]) => Contract; } class CustomContract implements Contract {} class CustomFactory implements Factory { deploy(x: number, y: number): CustomContract { return {}; } } type MockContract<C extends Contract> = Contract & C & { mockProperty: number; } type MockFactory<F extends Factory> = F & { // deploy should have the parameters of the function deploy inside F (in this case CustomFactory) // deploy should return a MockContract of the return type of the function deploy inside F (MockContract<CustomContract> in a generic way) deploy: (...args: Parameters<F['deploy']>) => MockContract<ReturnType<F['deploy']>> } const example: MockFactory<CustomFactory> = {} as any; example.deploy(1, 2); ``` [Updated Playground](https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgMIHtxUWZBvAXwFgAoU0SWRFAMR3SgE99Tk3kATCABwBt1GALmQAKAHQS4UAOYBnYXBCMA2gF0AlMgC8APjSYw2BGADcpYmRIJecWbLQBXWWHQBbDFhzJgrvhFcQ4PYehl6EpKTWtsFOLq50xgzMPn4BQcgJLkwsJOycPPyMIgAewiAOrgBG0AA0yELI5VXQ6sKosW4hRrh4rHnsUBBgDlAg%20ARmuewWFqRgjNwoALLoCADWXTgAPKjIEMWQIBzBBt16WvqexsgAZGi3OXmuq2sAClDoi1DzZRXVUJNZiR5otkCt1pkklsaHsDoFjhl6ExzhkHr0pmwAPSY-J8ATIWQAC3QDl4HGQhLgADcUGBCShuFI4AFKPZ0DBkHSUDAHCBjMBMLjCt4QLJgFxUSJQJzCcB7AhbCh2s43JCmOo%20licVw8cwiSSychBsNRsg4GCXptruyZShjSMxiCUDaucgeXywAKxjrhaAxRKYSJwRtTttlXErWA9NLzdJAtBgAhkAB3OCMDUYoUCYTiSQyeTIV5MlnQWTQ5QAch9Agrqh0ml0FvWka2ACUhg6ACoLCDlqsFGt1nTmCJWTDOWHMvzCYNqxg7DrxJGMFGEM32RSMSb7Ke8CBiatFACMdQATOpJkA)
16,131,853
how to display an activity when leaving an activity, the execution in the method "OnDestroy" ``` protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); Bundle savedInstanceState = null; this.onCreate(savedInstanceState); //launch a code to display a activity } ```
2013/04/21
[ "https://Stackoverflow.com/questions/16131853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2282259/" ]
`onCreate(savedInstanceState)` is a `super` call in the `onCreate()` method of your `Activity`. Do it like you would start any `Activity` ``` protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); Intent intent = new Intent(CurrentActivity.this, NextActivity.class); startActivity(intent); } ``` where `CurrentAcivity` is the `Actviity` you are currently in and `NextActivity` is the `Actviity` you want to start. [Intent](http://developer.android.com/reference/android/content/Intent.html) [Activity](http://developer.android.com/reference/android/app/Activity.html) Read through the documentation above and pay particular attention to the Activity Lifecycle. You don't have to do this in `onDestroy()` and if this is all you are doing there then you don't need to override `onDestroy()` at all. You can put this anywhere in your code and call `finish()` and `onDestroy()` will be called for you automatically
63,096,136
So I am trying to implement the search feature, as you can see I am using a `FutureBuilder` to do it. When the API called it returns the result as expected but when I try using it inside the Future builder it the data is always null: ``` @override Widget buildResults(BuildContext context) { return FutureBuilder<List<SearchModel>>( future: getResults(), builder: ( BuildContext context, AsyncSnapshot<List<SearchModel>> snapshot) { if (snapshot.connectionState == ConnectionState.done) { logger.d(snapshot.hasData); return ListView.builder( itemBuilder: (context, index) { return ListTile( title: Text(snapshot.data[index].title), onTap: () { close(context, snapshot.data[index]); }, ); }, itemCount: snapshot.data.length, ); } else { return Center( child: CircularProgressIndicator(), ); } }, ); } Future<List<SearchModel>> getResults() async { SharedPreferences prefs = await SharedPreferences.getInstance(); String language = prefs.getString('language'); var data; List<SearchModel> results = []; data = await http.get(Constants.BASE_URL + "/search/" + language + "/" + query,); results = (data.map((model) => SearchModel.fromJson(model)).toList()); return results; } ```
2020/07/26
[ "https://Stackoverflow.com/questions/63096136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3775862/" ]
I don't know your API and it's JSON response, so this this is a best guess what your code *should* look like: ``` Future<List<SearchModel>> getResults() async { final prefs = await SharedPreferences.getInstance(); final language = prefs.getString('language'); final response = await http.get(Constants.BASE_URL + "/search/" + language + "/" + query); final results = ((response.body as List).map((model) => SearchModel.fromJson(model)).toList()); return results; } ``` That said, you need to check the `FutureBuilder` for `snapshot.hasError` and you need to check your response for `response.statusCode == 200` (or whatever is appropriate for that call) because there is a lot that can go wrong on an external call and you need your app to not crash under those circumstances.
398,066
I am the web administrator for a small company. We host our website on our own server. The site runs on PHP and MySQL. I access the server via SSH. I am not very familiar with UNIX/LINUX commands, but I was given instructions by the previous web administrator on how to back up the website. Basically, I need to export a mysqldump operation to a .sql file on the server, then move it to a local, secure location. I back up the website via the zip operation and download that via FTP. I do not have access to the Apache server configuration so I cannot enable shell commands in PHP. However, I would like to write some kind of simple batch-style program that can access the shell, log in, and run a series of commands automatically. Then the administrator can simply download those files off (or, better yet, the downloading process could be automated as well). Is this even possible? If so, could you direct me to where to start to learn about something like this? I don't even know what to search for. Thanks so much.
2012/06/12
[ "https://serverfault.com/questions/398066", "https://serverfault.com", "https://serverfault.com/users/124702/" ]
IMO, the easiest solution would be to set up a `cron` job on server side, that dumps SQL database(-s), copies relevant files, packs that all into archive and moves to FTP folder. After this is done, the file can be either downloaded manually, or, for example, synchronized to remote machine using `rsync`. Some relevant links: * [cron tutorial](http://clickmojo.com/code/cron-tutorial.html) * [rsync tutorial](http://www.fredshack.com/docs/rsync.html) * [Ready solution, that covers SQL backup via cron, and sending the archive via mail](http://paulbradley.tv/38/)
1,290,975
I am new to using prepared statements in mysql with php. I need some help creating a prepared statement to retrieve columns. I need to get information from different columns. Currently for a test file, I use the **completely unsecure** SQL statement: ``` $qry = "SELECT * FROM mytable where userid='{$_GET['userid']}' AND category='{$_GET['category']}'ORDER BY id DESC" $result = mysql_query($qry) or die(mysql_error()); ``` Can someone help me create a **secure** mysql statement using input from url parameters (as above) that is prepared? BONUS: Prepared statements are suppose to increase speed as well. Will it increase overall speed if I only use a prepared statement three or four times on a page?
2009/08/17
[ "https://Stackoverflow.com/questions/1290975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/111691/" ]
Here's an example using mysqli (object-syntax - fairly easy to translate to function syntax if you desire): ``` $db = new mysqli("host","user","pw","database"); $stmt = $db->prepare("SELECT * FROM mytable where userid=? AND category=? ORDER BY id DESC"); $stmt->bind_param('ii', intval($_GET['userid']), intval($_GET['category'])); $stmt->execute(); $stmt->store_result(); $stmt->bind_result($column1, $column2, $column3); while($stmt->fetch()) { echo "col1=$column1, col2=$column2, col3=$column3 \n"; } $stmt->close(); ``` Also, if you want an easy way to grab associative arrays (for use with SELECT \*) instead of having to specify exactly what variables to bind to, here's a handy function: ``` function stmt_bind_assoc (&$stmt, &$out) { $data = mysqli_stmt_result_metadata($stmt); $fields = array(); $out = array(); $fields[0] = $stmt; $count = 1; while($field = mysqli_fetch_field($data)) { $fields[$count] = &$out[$field->name]; $count++; } call_user_func_array(mysqli_stmt_bind_result, $fields); } ``` To use it, just invoke it instead of calling bind\_result: ``` $stmt->store_result(); $resultrow = array(); stmt_bind_assoc($stmt, $resultrow); while($stmt->fetch()) { print_r($resultrow); } ```
16,967,689
I understand that CSS fetch images relative to it's own location but how do I do this the same way for within Wordpress theme? Scenario: I have a search box right of my header. The search box came with the Twentyeleven Wordpress theme and has the following css: ``` background: url(images/Search-Button.jpg) no-repeat; ``` It renders out the background image located in the images folder inside the themes folder. it found the image here: ``` C:\wamp\www\wordpress\wp-content\themes\twentyeleven\images\Search-Button.jpg ``` Now, I wanted to add a logo somewhere beside it so I added this to the theme's header.php: ``` <div id="Title_logo"> <img src="images/Logo.png" /> </div> ``` but it doesn't render the image successfully because it is not looking for the image at `"...\wp-content\themes\twentyeleven\images\Logo.png"` (same directory as Search-Button.jpg). instead the result image ***src*** was: *C:\wamp\www\images\Logo.png* and reported that the image was not found. How did the background image work? or can somebody at least show me the proper way, and explain why this is not working? I'd like it to work even when I rename the theme folder.
2013/06/06
[ "https://Stackoverflow.com/questions/16967689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2128576/" ]
You do have to do it like this; ``` <div id="Title_logo"> <img src="<?php echo get_template_directory_uri(); ?>/images/Logo.png" /> </div> ``` Then it will also work if you install your theme on another server. See: <http://codex.wordpress.org/Function_Reference/get_template_directory_uri#bodyContent> The way you did it in you example (src="images/Logo.png") points the browser to your root folder, because the whole Wordpress cms is build from the **index.php** in your root folder. So you have to tell your browser (via php) that the image is in the images directory in the theme-directory. The css file is also loaded that way, but calls his referrals to related files **from the place where it exists**. (the theme-directory). So in css you can refer to your files like you normally should, but from the theme-docs (php) you have to use the special Wordpress functions in your paths, hence the function: `get_template_directory_uri();` [get\_template\_directory\_uri documentation](https://codex.wordpress.org/Function_Reference/get_template_directory_uri)
81,156
What reasoning is used by mainstream kosher certification agencies to certify food items containing only kosher ingredients but packaged and/or designed to look and/or taste non-kosher. For example, imitation crab (dyed and shaped to look like crab meat and used in sushi) or artificially flavored snacks illustrated with pictures of meat and dairy, such as [this](http://herrs.com/Products/CheeseCurls/BuffaloBlueCheeseCurls.html). (I'm waiting to hear back from the O-U.) Since first posting this, I came across Halachipedia's post on this topic: > > There is no maris ayin issue involved in eating surimi since people know that surimi shrimp etc exists, we do not have to worry that one will think he is eating a non-kosher product. > > > They cite as a source for this argument [Halachically Speaking (vol. 5, Issue 12, p. 3)](http://www.shemayisrael.com/parsha/halacha/volume_5_issue_12.pdf) which actually does not appear to present any reasoning at all(?), (though there may be more information in the Journal of Halacha and Contemporary Society 50 p.107, cited in footnote 10) which I have yet to obtain. As a counterpoint to this argument, the New York Times [recently](https://www.nytimes.com/2016/06/19/nyregion/kosher-sushi-in-brooklyn.html) seemd to feel the need to clarify the artificial source of the crab in kosher-certified California rolls: > > Orthodox Jews are eating dragon rolls, rainbow rolls, tsunami rolls and California rolls (using imitation crab)... > > > [![Buffalo Blue Cheese Curls](https://i.stack.imgur.com/xDryL.jpg)](https://i.stack.imgur.com/xDryL.jpg)
2017/03/22
[ "https://judaism.stackexchange.com/questions/81156", "https://judaism.stackexchange.com", "https://judaism.stackexchange.com/users/2840/" ]
As [Rabbi Yehuda Spitz explains](//ohr.edu/this_week/insights_into_halacha/5080), for many dairy-look pareve products there is an understanding among the general population that, even though it looks like it's dairy, it's not, and, because of that understanding, there's no need to specially indicate to people that the product is pareve. Even for those who wish to be more stringent, he explains, and even for products without such an understanding, it's sufficient to have a product label indicating the pareve status. He's referring to meat and milk issues, i.e. whether a dairy-look pareve food can be served with meat. Likely, then, the same would apply to the question of whether a meat-and-milk-look product can be served at all, and perhaps also to the question of whether a non-kosher-species-look product can be served at all. Then a label indicating the kosher status would suffice — and these products have that.
33,301,709
I am new in sharetribe, and I integrated sharetribe in my application, now I want to integrate payment option in my ruby application. I search about that but in my admin side there is no option for payment. How to enable payment option in sharetribe?
2015/10/23
[ "https://Stackoverflow.com/questions/33301709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4627335/" ]
Instead of `while`, use `do`...`while`. That way, the loop will always run at least once. ``` num_of_triangles = 0; do { printf("Number of triangles (must be greater than 2) = "); scanf("%d", &num_of_triangles); while (getchar() != '\n'); // this flushes the input buffer } while (num_of_triangles < 3); ``` Also, don't `fflush(stdin)`, as that's undefined behavior. EDIT: It seems that Visual Studio allows `fflush(stdin)`. From [MSDN](https://msdn.microsoft.com/en-us/library/9yky46tz.aspx): > > The fflush function flushes a stream. If the file associated with > stream is open for output, fflush writes to that file the contents of > the buffer associated with the stream. **If the stream is open for > input, fflush clears the contents of the buffer.** fflush negates the > effect of any prior call to ungetc against stream. Also, fflush(NULL) > flushes all streams opened for output. The stream remains open after > the call. fflush has no effect on an unbuffered stream. > > > In general however, this behavior shouldn't be depended on. Doing something more portable like the above code is preferable.
70,211,933
Having a tibble and a simple scatterplot: ``` p <- tibble( x = rnorm(50, 1), y = rnorm(50, 10) ) ggplot(p, aes(x, y)) + geom_point() ``` I get something like this: [![enter image description here](https://i.stack.imgur.com/YgDHH.png)](https://i.stack.imgur.com/YgDHH.png) I would like to align (center, left, right, as the case may be) the title of the x-axis - here rather blandly *x* - with a specific value on the axis, say the off-center *0* in this case. Is there a way to do that declaratively, without having to resort to the dumb (as in "free of context") trial-and-error `element_text(hjust=??)`. The `??` are rather appropriate here because every value is a result of experimentation (my screen and PDF export in RStudio **never** agree on quite some plot elements). Any change in the data or the dimensions of the rendering may (or may not) invalidate the `hjust` value and I am looking for a solution that graciously repositions itself, much like the axes do. --- Following the suggestions in the comments by @tjebo I dug a little deeper into the coordinate spaces. `hjust = 0.0` and `hjust = 1.0` clearly align the label with the Cartesian coordinate system extent (but magically left-aligned and right-aligned, respectively) so when I set specific limits, calculation of the exact value of `hjust` is straightforward (aiming for *0* and `hjust = (0 - -1.5) / (3.5 - -1.5) = 0.3`): ``` ggplot(p, aes(x, y)) + geom_point() + coord_cartesian(ylim = c(8, 12.5), xlim = c(-1.5, 3.5), expand=FALSE) + theme(axis.title.x = element_text(hjust = 0.3)) ``` This gives an acceptable result for a label like *x*, but for longer labels the alignment is off again: ``` ggplot(p %>% mutate(`Longer X label` = x), aes(x = `Longer X label`, y = y)) + geom_point() + coord_cartesian(ylim = c(8, 12.5), xlim = c(-1.5, 3.5), expand=FALSE) + theme(axis.title.x = element_text(hjust = 0.3)) ``` Any further suggestions much appreciated.
2021/12/03
[ "https://Stackoverflow.com/questions/70211933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3304426/" ]
Use [`Series.str.replace`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.replace.html) with [`Series.str.upper`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.upper.html) and then mapping by `Series` from `codes` by [`Series.map`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html): ``` df['id_plain'] = df['id'].str.replace('[\W_]+', '', regex=True).str.upper() df['code'] = df['id_plain'].map(codes.set_index('id_plain')['code']) print (df) id id_plain code 0 ab-c ABC 1 1 ab-c ABC 1 2 d_ef DEF 2 3 gh.i GHI 3 4 ab-c ABC 1 5 ab-c ABC 1 6 d_ef DEF 2 7 gh.i GHI 3 ```
51,856,963
I look for a comfortable way of converting a custom type variable to char[] (string) for the purpose of immediate fprinting. Here is what I intend to do, yet still flawed. ``` #include <stdio.h> #include <string.h> char * toStr (int); void main (void) { printf("%s , %s , %s \n", toStr(1), toStr(2), toStr(3)); } char * toStr (int z) { static char oS[100]; sprintf(oS, "%d", z); printf("Will return: %s\n", oS); return oS; } ``` This will display ``` Will return: 3 Will return: 2 Will return: 1 1 , 1 , 1 ``` I see what the problem is here, printf seems to print the content of static char oS once for all three calls in its parameterlist. It does not evaluate each call exactely when it is needed in the format string. But i need the static (as one possible way) to make the content of oS available outside of toStr. I feel like I am almost there, of corse I want the output ``` 1 , 2 , 3 ``` on screen. Is there a possiblility to get what I want, without having to mallocate and free every part or storing each return of toStr in a sepearate variable just to fprint them aftwerwards? Isn't it possible to fprint the return values of the same function multiple times in one call?
2018/08/15
[ "https://Stackoverflow.com/questions/51856963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10228659/" ]
Local `static` variables are *shared* between all invocations of the function. That means all calls will use the same buffer and return the same pointer to the same string. And since the evaluation order of arguments is not specified (I don't remember if it's implementation defined, undefined, or just simply not specified), then you don't know which will be the last call (which will be the call the decides which the contents of the array will have). The only thing you *do* know is that *all* arguments must be evaluated *before* the actual call to the function is made. Arguments and expressions are not evaluated lazily.
47,271,882
How do I get the count of each values within the group using pandas ? In the below table, I have Group and the Value column, and I want to generate a new column called count, which should contain the total nunmber of occurance of that value within the group. my **df** dataframe is as follows **(without the count column)**: ``` ------------------------- | Group| Value | Count? | ------------------------- | A | 10 | 3 | | A | 20 | 2 | | A | 10 | 3 | | A | 10 | 3 | | A | 20 | 2 | | A | 30 | 1 | ------------------------- | B | 20 | 3 | | B | 20 | 3 | | B | 20 | 3 | | B | 10 | 1 | ------------------------- | C | 20 | 2 | | C | 20 | 2 | | C | 10 | 2 | | C | 10 | 2 | ------------------------- ``` I can get the counts using this: ``` df.groupby(['group','value']).value.count() ``` but this is just to view, I am having difficuly putting the results back to the dataframe as new columns.
2017/11/13
[ "https://Stackoverflow.com/questions/47271882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2305273/" ]
Using `transform` ``` df['count?']=df.groupby(['group','value']).value.transform('count').values ```
37,725,796
The following code should handle http request by produce a request message to some remote server (kafka broker) and wait for consuming a response for it. when a respond message arrive - it should be returned as an http respond (json or something). ``` router.get('/status', function(req, res, next) { // init the producer ... // 1st async function producer.on('ready', function () { // some code for generating payloads (data for a message) ... // 2nd async function producer.send(payloads, function (err, data) { // some log of success sending message ... // 3rd async function consumer.on('message', function (message) { // got some response message res.send("message: " + message); }); }); }); }); ``` Can I make these sync together even tow it's not mine? **EDIT:** I'll try to be more clear. Consider the following code: ``` function boo() { // part 1 - init some consumer console.log("1. finish init"); // part 2 - This is async function. whenever messages will arrive - this function will be fetched. consumer.on('message', function (message) { console.log("2. message arrive!"); return message; } // part 3 console.log("3. end function"); return null; } ``` Assume that part 2 happen after 1 second. The output will be: ``` 1. finish init 3. end function 2. message arrive! ``` while my goal is to wait for the async message (part 2) and return it's value. How can I achieve that?
2016/06/09
[ "https://Stackoverflow.com/questions/37725796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1011253/" ]
I don't see any reference to the JavaScript code in your HTML file. Include a link to it under all the other JS files and it should work.
74,087,478
I am having some trouble with `ScrollView`, I have the following code: ``` struct ContentView: View { private enum Constants { static let cellSize = CGSize(width: 100.0, height: 100.0) static let rowSpacing: CGFloat = 8.0 } @State private var rowCount = 1 @State private var contentOffset = CGPoint.zero private var scrollViewHeight: CGFloat { CGFloat(rowCount) * Constants.cellSize.height + (CGFloat(rowCount) - 1.0) * Constants.rowSpacing } var body: some View { NavigationView { ScrollView(.horizontal) { ScrollView { LazyVStack(spacing: Constants.rowSpacing) { ForEach((0..<rowCount), id: \.self) { _ in LazyHStack { ForEach((1...20), id: \.self) { Text("Cell \($0)") .frame( width: Constants.cellSize.width, height: Constants.cellSize.height ) .background(.red) } } } } } .scrollIndicators(.hidden) } .ignoresSafeArea(edges: .bottom) .frame(maxHeight: scrollViewHeight) .scrollIndicators(.hidden) .toolbar { Button("Add Row") { rowCount += 1 } Button("Remove Row") { rowCount -= 1 } } .navigationTitle("Test") } } } ``` For some reason the `ScrollView` content is centered vertically: [![enter image description here](https://i.stack.imgur.com/6Yyxs.png)](https://i.stack.imgur.com/6Yyxs.png) I need the content to align to the top. Any idea on how to fix this?
2022/10/16
[ "https://Stackoverflow.com/questions/74087478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4083744/" ]
[![enter image description here](https://i.stack.imgur.com/JHydd.png)](https://i.stack.imgur.com/JHydd.png) You used `Vstack` and `Spacer` to align the area of the horizontal scroll view to the top. Please check if the implementation you want is correct. ``` import SwiftUI struct ContentView: View { private enum Constants { static let cellSize = CGSize(width: 100.0, height: 100.0) static let rowSpacing: CGFloat = 8.0 } @State private var rowCount = 1 @State private var contentOffset = CGPoint.zero private var scrollViewHeight: CGFloat { CGFloat(rowCount) * Constants.cellSize.height + (CGFloat(rowCount) - 1.0) * Constants.rowSpacing } var body: some View { NavigationView { VStack { ScrollView(.horizontal) { ScrollView { LazyVStack(spacing: Constants.rowSpacing) { ForEach((0..<rowCount), id: \.self) { _ in LazyHStack { ForEach((1...20), id: \.self) { Text("Cell \($0)") .frame( width: Constants.cellSize.width, height: Constants.cellSize.height ) .background(.red) } } } } } .scrollIndicators(.hidden) } .background(.cyan) .ignoresSafeArea(edges: .bottom) .frame(maxHeight: scrollViewHeight) .scrollIndicators(.hidden) .toolbar { Button("Add Row") { rowCount += 1 } Button("Remove Row") { rowCount -= 1 } } .navigationTitle("Test") Spacer() } } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } ```
360,117
I have a file containing the following informations: ``` gene 3025..3855 /gene="Sp34_10000100" /ID="Sp34_10000100" CDS join(3025..3106,3722..3855) /gene="Sp34_10000100" /codon_start=1 /ID="Sp34_10000100.t1.cds1,Sp34_10000100.t1.cds2" mRNA 3025..3855 /ID="Sp34_10000100.t1" /gene="Sp34_10000100" gene 12640..13470 /gene="Sp34_10000200" /ID="Sp34_10000200" CDS join(12640..12721,13337..13470) /gene="Sp34_10000200" /codon_start=1 /ID="Sp34_10000200.t1.cds1,Sp34_10000200.t1.cds2" mRNA 12640..13470 /ID="Sp34_10000200.t1" /gene="Sp34_10000200" gene 15959..20678 /gene="Sp34_10000300" /ID="Sp34_10000300" CDS join(15959..16080,16268..16367,18913..19116,20469..20524,20582..20678) /gene="Sp34_10000300" /codon_start=1 /ID="Sp34_10000300.t1.cds1,Sp34_10000300.t1.cds2,Sp34_10000300.t1.cds3,Sp34_10000300.t1.cds4,Sp34_10000300.t1.cds5" mRNA 15959..20678 /ID="Sp34_10000300.t1" /gene="Sp34_10000300" gene 22255..23085 /gene="Sp34_10000400" /ID="Sp34_10000400" ``` I want to delete all the **gene** sections but **CDS** and **mRNA** information should be there. The output should be like this: ``` CDS join(3025..3106,3722..3855) /gene="Sp34_10000100" /codon_start=1 /ID="Sp34_10000100.t1.cds1,Sp34_10000100.t1.cds2" mRNA 3025..3855 /ID="Sp34_10000100.t1" /gene="Sp34_10000100" CDS join(12640..12721,13337..13470) /gene="Sp34_10000200" /codon_start=1 /ID="Sp34_10000200.t1.cds1,Sp34_10000200.t1.cds2" mRNA 12640..13470 /ID="Sp34_10000200.t1" /gene="Sp34_10000200" CDS join(15959..16080,16268..16367,18913..19116,20469..20524,20582..20678) /gene="Sp34_10000300" /codon_start=1 /ID="Sp34_10000300.t1.cds1,Sp34_10000300.t1.cds2,Sp34_10000300.t1.cds3,Sp34_10000300.t1.cds4,Sp34_10000300.t1.cds5" mRNA 15959..20678 /ID="Sp34_10000300.t1" /gene="Sp34_10000300" ``` Please give me any suggestion how to do this.
2017/04/20
[ "https://unix.stackexchange.com/questions/360117", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/199195/" ]
awk is usually easier to read and understand: Here is a simple program that writes by default, and toggle a "wewrite" to "0" (= off, we will not write) when it sees a line where the first word is "gene", and put it back on when he sees a line where the first word is "CDS" or "mRNA" : ``` awk ' BEGIN { weprint=1 } ( $1 == "gene" ) { weprint=0 } ( $1 == "CDS" ) || ( $1 == "mRNA" ) { weprint=1 } ( weprint == 1) { print $0 ;} ' file_to_read ``` BEGIN is done before any lines are read. The other `( test ) { action if test successful }` are parsed for each line of input (... unless an action contains `next`, which then would ignore the rest of those and instead would go fetch the next line of input) This will only print sections "CDS" and "mRNA" and not "gene" This could be "golfed" (for example, the default action for a successfull 'test' is to print $0, so you could have just `( weprint == 1)` as the last line, but it would be less clear to grasp, imo...)
8,348,013
I have a stored procedure that is doing a two-step query. The first step is to gather a list of VARCHAR2 type characters from a table and collect them into a table variable, defined like this: ``` TYPE t_cids IS TABLE OF VARCHAR2(50) INDEX BY PLS_INTEGER; v_cids t_cids; ``` So basically I have: ``` SELECT item BULK COLLECT INTO v_cids FROM table_one; ``` This works fine up until the next bit. Now I want to use that collection in the where clause of another query within the same procedure, like so: ``` SELECT * FROM table_two WHERE cid IN v_cids; ``` Is there a way to do this? I am able to select an individual element, but I would like to use the table variable like a would use a regular table. I've tried variations using nested selects, but that doesn't seem to work either. Thanks a lot, Zach
2011/12/01
[ "https://Stackoverflow.com/questions/8348013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/728278/" ]
You have several choices as to how you achieve this. If you want to use a collection, then you can use the TABLE function to select from it but the type of collection you use becomes important. for a brief example, this creates a database type that is a table of numbers: ``` CREATE TYPE number_tab AS TABLE OF NUMBER / ``` > > Type created. > > > The next block then populates the collection and performs a rudimentary select from it using it as a table and joining it to the `EMP` table (with some output so you can see what's happening): ``` DECLARE -- Create a variable and initialise it v_num_tab number_tab := number_tab(); -- -- This is a collection for showing the output TYPE v_emp_tabtype IS TABLE OF emp%ROWTYPE INDEX BY PLS_INTEGER; v_emp_tab v_emp_tabtype; BEGIN -- Populate the number_tab collection v_num_tab.extend(2); v_num_tab(1) := 7788; v_num_tab(2) := 7902; -- -- Show output to prove it is populated FOR i IN 1 .. v_num_tab.COUNT LOOP dbms_output.put_line(v_num_tab(i)); END LOOP; -- -- Perform a select using the collection as a table SELECT e.* BULK COLLECT INTO v_emp_tab FROM emp e INNER JOIN TABLE(v_num_tab) nt ON (e.empno = nt.column_value); -- -- Display the select output FOR i IN 1 .. v_emp_tab.COUNT LOOP dbms_output.put_line(v_emp_tab(i).empno||' is a '||v_emp_tab(i).job); END LOOP; END; ``` You can see from this that the database TYPE collection (number\_tab) was treated as a table and could be used as such. Another option would be to simply join your two tables you are selecting from in your example: ``` SELECT tt.* FROM table_two tt INNER JOIN table_one to ON (to.item = tt.cid); ``` There are other ways of doing this but the first might suit your needs best. Hope this helps.
1,687,224
Determine if it is a group or not for each operation defined on a set. 1. Define $\ast$ on $\Bbb Z$ by $a\ast b = |ab|$. 2. Define $\ast$ on $\Bbb Z$ by $a\ast b = \max \{a,b\}$. 3. Define $\ast$ on $\Bbb Z$ by $a\ast b = a + b +1$. 4. Define $\ast$ on $\Bbb Z$ by $a\ast b = ab +b$. 5. Define $\ast$ on $\Bbb Z$ by $a\ast b = a + ab +b$. For 1, $a\ast b = |ab|$. Identity: $a\*e = |a \cdot e| = a $ There is no such e. Thus, it is not a group. For 2, $a\ast b = \max \{a,b\}$. There is no identity element such that $a \ast e = \max \{a, e\} = a$ Thus, it is not a group. For 3, $a\ast b = a + b +1$. Identity: $a\ast e = a + e + 1$, with $e = -1$, $a \*e = a - 1 +1 = a$ Inverse: There is no $x \in \Bbb Z$ such that $a \* x = a +x+1 = e = -1$. For 4, $a\ast b = ab +b$ $(a \*b)\*c = (ab + b) \* c = (ab + b)c +c = abc +bc +c$ $a\*(b\*c) = a \*(bc +c) = a(bc +c) + bc + c = abc + ac +bc+c$ Thus, $(a \*b)\*c \neq a\*(b\*c)$ Therefore, it is not a group. For 5, $a\ast b = a + ab +b$ Identity: $a\*e = a + ae + e = a$ with $e =0$, $a\*e=a + 0 + 0 = a$ Inverse: There is no $x \in \Bbb Z$ such that $a\*x = a +ax + x = e$ Thus, it is not a group. Those are my solutions. I am not quite sure if I got it though.
2016/03/07
[ "https://math.stackexchange.com/questions/1687224", "https://math.stackexchange.com", "https://math.stackexchange.com/users/270833/" ]
You need to be a little more rigorous with your proofs. For $1$, you can say, let $a=-1$. Then for all $b \in \mathbb{Z}$, $|ab|$ is nonnegative, so $a\*b=|ab|\neq a$, so there is no identity. For $2$, assume there is an identity $e$. Then $e\*(e-1)=\max\{e,e-1\}=e\neq e-1$. (We know that the difference between integers is an integer, so $e-1 \in \mathbb{Z}$). This contradicts $e$ being the identity, so it is not a group. Try going through these again and go through what the statement says- if you go through it directly, it should be easy to give a rigorous proof.
39,250,189
I am trying to automate testing for a site that uses an iFrame(?) sort of punch-out which links to another website's catalogue to make purchases. The process is the user will login and be able to select a set of catalogues to connect to. Upon clicking a catalogue set they will be prompted w/ this security dialog: [![IE Security Dialog](https://i.stack.imgur.com/U5Ad9.png)](https://i.stack.imgur.com/U5Ad9.png) and once they click 'Show all content' they are prompted w/ this: [![IE Prompt 02](https://i.stack.imgur.com/Theuc.png)](https://i.stack.imgur.com/Theuc.png) This will take them to the actual catalogue site where they can place orders. Is there any way to interact w/ these prompts?
2016/08/31
[ "https://Stackoverflow.com/questions/39250189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3780040/" ]
Responding to your latest update, I have a `Sub` that creates a series each time it's called from ***MultiSheetPlot*** Sub. You can actually add more parameters to this Sub (as long as you remeber to pass them in the Calling). ``` Option Explicit Dim cht As Chart Sub MultiSheetPlot() Set cht = Charts.Add cht.ChartType = xlLine ' call the series creation chart function (each time for each series you want to add to the existing chart Call Create_SeriesChart("Sheet1", Sheets("Sheet1").Range("E12:E6232"), 1, True, msoThemeColorText1) Call Create_SeriesChart("Sheet1", Sheets("Sheet1").Range("Y12:Y6232"), 1, True, msoThemeColorText1) End Sub ' ------ this Sub creates a series to the chart, it receives the following parameters: ------ ' 1. seriesName - String ' 2. serValues - Range ' 3. lineWeight - Double (the weight of the line) ' 4. lineVis - Boolean (if you want to hide a certail series) ' 5. lineColor - MsoColorType (using the current's PC Theme colors Sub Create_SeriesChart(seriesName As String, serValues As Range, lineWeight As Double, lineVis As Boolean, lineColor As MsoColorType) Dim Ser As Series Set Ser = cht.SeriesCollection.NewSeries With Ser .Name = seriesName .Values = serValues .Format.Line.Weight = lineWeight If lineVis = True Then .Format.Line.Visible = msoTrue Else .Format.Line.Visible = msoFalse End If .Format.Line.ForeColor.ObjectThemeColor = lineColor ' Line color Black End With End Sub ```
35,235,442
Using the Advanced Drive Service in my google AppScript app: <https://developers.google.com/apps-script/advanced/drive> I have a custom property PUBLIC called 'listingid' and am trying to get its value. Unfortunately ``` Drive.Properties.get(fileId, 'listingid'); ``` defaults to trying to get a PRIVATE property of that name, which is returning an error: `Property not found: key = listingid and visibility = PRIVATE` I can't find any documentation for the method, and ``` Drive.Properties.get(fileId, 'listingid', 'PUBLIC'); ``` doesn't work. Can someone please help? Thank you!
2016/02/05
[ "https://Stackoverflow.com/questions/35235442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/686348/" ]
Figured this out finally. Try echoing `Yii::$app->defaultRoute` somewhere in your view file or controller action. ``` echo Yii::$app->defaultRoute; ``` According to [official documentation on Yii2 Controller](https://github.com/yiisoft/yii2/blob/master/docs/guide/structure-controllers.md) on Default Controller: Each application has a default controller specified via the yii\base\Application::defaultRoute property. When a request does not specify a route, the route specified by this property will be used. For [yii\web\Application|Web applications](https://github.com/yiisoft/yii2/blob/master/framework/web/Application.php), its value is `'site'`, while for [yii\console\Application|console](https://github.com/yiisoft/yii2/blob/master/framework/console/Application.php) applications, it is `'help'`. Therefore, if a URL is <http://hostname/index.php>, then the '`site`' controller will handle the request. Also, You may change the default controller with the following application configuration: ``` [ 'defaultRoute' => 'main', ] ```
7,640
The problem I would like to solve is as follow: 1. go to a website which is protected by client certificate authentication using browser 2. once the security challenge dialog box is shown, select on the dialog 3. look through the list of certificates I have in my keystore 4. select the desired certificate and click 'ok' Is this possible with Selenium/Webdriver? ![enter image description here](https://i.stack.imgur.com/43D7t.jpg)
2014/01/28
[ "https://sqa.stackexchange.com/questions/7640", "https://sqa.stackexchange.com", "https://sqa.stackexchange.com/users/6845/" ]
Two parts to this answer: First, to answer the question, there are many test runners. Some of them by default will run in a particular order, it may be the order they appear in code, or alphabetically, or some other order. There is often a way to tell the test runner to execute them in a particular order by providing some additional command line parameters, or altering the config. From your screenshot you're using junit, junit actually does not have a way to force the order of execution, see this for details: <https://stackoverflow.com/questions/3693626/how-to-run-test-methods-in-specific-order-in-junit4> The second part is not directly answering the question, but is important and is also discussed in the linked answer from stackoverflow. You should avoid having tests that need to be run in a specific order. What if you want to execute only the last test, or debug the last test? Do you have to wait for all of the other tests to execute? What if one of the tests early in the chain fails, likely all of the rest of the tests will fail as well. What happens when you get a large suite of tests and you want to execute them in parallel? It is typically a best practice to have individual tests self contained and not relying on other other tests for the reasons outlined above.
70,937,591
I am installing the scikit-survival package in Python. When I run ``` pip install scikit-survival ``` I get an error on msbuild, I attach the elements of interest below: ``` PS C:\WINDOWS\system32> pip install scikit-survival .. Building wheels for collected packages: qdldl Building wheel for qdldl (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [24 lines of output] running bdist_wheel running build running build_ext -- Selecting Windows SDK version to target Windows 10.0.22000. CMake Error at CMakeLists.txt:4 (project): Failed to run MSBuild command: MSBuild.exe to get the value of VCTargetsPath: Impossibile trovare il file specification -- Configuring incomplete, errors occurred! See also "C:/Users/xyz/AppData/Local/Temp/pip-install- uyja9anj/qdldl_c05b02902dbe43b69e2860ddcf14a11a/c/build/CMakeFiles/CMak eOutput.log". Impossibile trovare il file specification CMake Error: Generator: execution of make failed. Make command was: MSBuild.exe qdldlamd.vcxproj /p:Configuration=Release /p:Platform=x64 /p:VisualStudioVersion=14.0 /v:m && building 'qdldl' extension cl : warning della riga di comando D9002 : l'opzione sconosciuta '- std=c++11' verr… ignorata qdldl.cpp c\qdldl/include/qdldl.h(5): fatal error C1083: Non Š possibile aprire il file inclusione: 'qdldl_types.h': No such file or directory error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\BuildTools\\VC\\Tools\\MSVC\\14.30.30705\\bin\\HostX86\\x 64\\cl.exe' failed with exit code 2 [end of output] ... ``` The issue is with MSbuild.exe. Do you know how it can be solved? I have installed both Visual Studio Community with Python extensions and Visual Studio Build Tools.
2022/02/01
[ "https://Stackoverflow.com/questions/70937591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2896633/" ]
try: ``` pip install pipwin pipwin install <package> ```
1,852,061
I have a form which posts using ajax and reloads the div underneath. I need the textbox to clear when the submit button is pressed. ``` <form name=goform action="" method=post> <textarea name=comment></textarea> <input type=submit value=submit> </form> ```
2009/12/05
[ "https://Stackoverflow.com/questions/1852061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115949/" ]
Add an `id` for the `textarea`. ``` <textarea name='comment' id='comment'></textarea> ``` Hook into the submit process and add: ``` $('#comment').val(''); ```
175,957
on yosemite i now get chrome error when clicking link from skype or using alfred to open customized urls. the links and custom urls fail to open and instead I am presented with a dialog that says 'The application google chrome is not open anymore', even though the application is open. ![x](https://i.imgur.com/dgIt389.png) any ideas what may be causing this issue?
2015/03/09
[ "https://apple.stackexchange.com/questions/175957", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/83871/" ]
After restarting I can no longer reproduce the issue and chrome operates as normal.
47,076,555
Can someone explain how to validate an email adress in Django? So for Example i want to check if an email is a valid college email adress with the ending .edu . How can i do that? ``` from django import forms from .models import SignUp class SignUpForm(forms.ModelForm): class Meta: model = SignUp fields = ['full_name','email'] def clean_email(self): email = self.cleaned_data.get('email') return email ```
2017/11/02
[ "https://Stackoverflow.com/questions/47076555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8185346/" ]
Assuming that your `SignUp.email` field is an `EmailField`, Django will take care of validating that it's a valid email address. All you need to do is check that it ends in `.edu`, and raise a `ValidationError` if it doesn't. ``` class SignUpForm(forms.ModelForm): class Meta: model = SignUp fields = ['full_name','email'] def clean_email(self): email = self.cleaned_data.get('email') if not email.endswith('.edu'): raise forms.ValidationError("Only .edu email addresses allowed") return email ``` If might be better to create a validator and add it to your model field. This way, Django will run your validator when you use your `SignUpForm` and when it does model validation in other places like the Django admin. ``` from django.core.exceptions import ValidationError def validate_edu_email_address(value): if email.endswith('.edu'): raise forms.ValidationError("Only .edu email addresses allowed") class SignUp(models.Model): email = models.EmailField(validators=[validate_edu_email_address]) ... ```
45,216,144
So I have the following situation: I committed some work locally, without pushing to the remote repository. I want to move this local code to another branch, because if I pull, there will be modifications that will ruin all the work I put locally. This is the output of `git status` on the old branch: ``` On branch <branch_name> Your branch is ahead of 'origin/<branch_name>' by 1 commit. (use "git push" to publish your local commits) nothing to commit, working directory clean ``` And this is the output of `git status` on the newly created branch: ``` On branch <branch_name> nothing to commit, working directory clean ```
2017/07/20
[ "https://Stackoverflow.com/questions/45216144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7200751/" ]
If you made the branch after you committed it should contain the commit that you are wanting to move. You can verify this with `git log`, you should see your commit as the first on in the log. On the branch that you no longer want the commit to be do `git reset --hard HEAD~`. This removes the commit from the branch and reset the branch so that you can now pull without any issue. (Be sure that your commit is on the other branch as after doing this your commit will be gone). If the commit is not on your other branch, you can either delete the branch and create it again from the original branch with `git checkout -b <branch name>` or you can cherry-pick it into your branch with `git cherry-pick <SHA of your commit>` which will make a copy of the commit on your branch. Then you can reset the original branch with the steps above.
9,496
Marking exams can be long, boring, and un-engaging. It is important one remain focused though to ensure that the evaluation is fair to each student. What are some methods one can employ to maintain focus and not zone-out while reading answers?
2013/04/19
[ "https://academia.stackexchange.com/questions/9496", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/-1/" ]
There is two issues in your question. 1. How to be fair to each student when it comes to this boring task of evaluating them My own policy is the "mark-one-question-and-shuffle" : I correct the first question/problem for all the students, then I shuffle the whole stack and go for another question that I also pick at random. This way if I am tired or in a bad mood, it will impact everybody, so it will be fair. 1. How to stay focus for a long marking session I cannot answer to that and I guess it depends of many personal factors. Personally, I find marking tasks boring but easy to do and easy to focus on. It's like driving, some people can drive for hours, others can't. To tell the truth, marking is somehow relaxing for me.
50,194,925
I want to append multiple files named lab\_X.txt to one single output file final.txt. Knowing that all the files in one folder are the ones that I need I moved them into the current directory and used `cat *.txt > final.txt`, knowing that `>` overwrites the file. I want to insert a simple message between the files similar to `=============`, is that possible?
2018/05/05
[ "https://Stackoverflow.com/questions/50194925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7971087/" ]
Even though you're going to the ngrok url, the host header in the request is still set as the name of your site. Laravel uses the host header to build the absolute url for links, assets, etc. ngrok includes the ngrok url in the `X-Original-Host` header, but Laravel doesn't know anything about that. There are two basic solutions to the issue: 1. update the request with the proper server and header values, or 2. use the `forceRootUrl()` method to ignore the server and header values. --- **TrustedProxies and Forwarded Host** If you're using TrustedProxies (default in Laravel >= 5.5), and you have it configured to trust all proxies (`protected $proxies = '*';`), you can set the `X-Forwarded-Host` header to the `X-Original-Host` header. Laravel will then use the value in the `X-Forwarded-Host` header to build all absolute urls. You can do this at the web server level. For example, if you're using apache, you can add this to your `public/.htaccess` file: ``` # Handle ngrok X-Original-Host Header RewriteCond %{HTTP:X-Original-Host} \.ngrok\.io$ [NC] RewriteRule .* - [E=HTTP_X_FORWARDED_HOST:%{HTTP:X-Original-Host}] ``` If you prefer to handle this in your application instead of the web server, you will need to update the Laravel request. There are plenty of places you could choose to do this, but one example would be in your `AppServiceProvider::boot()` method: ``` public function boot(\Illuminate\Http\Request $request) { if ($request->server->has('HTTP_X_ORIGINAL_HOST')) { $request->server->set('HTTP_X_FORWARDED_HOST', $request->server->get('HTTP_X_ORIGINAL_HOST')); $request->headers->set('X_FORWARDED_HOST', $request->server->get('HTTP_X_ORIGINAL_HOST')); } } ``` --- **Not Using TrustedProxies** If you're not using TrustedProxies, you can't use the `.htaccess` method. However, you can still update the server and headers values in your application. In this case, you'd need to overwrite the Host header: ``` public function boot(\Illuminate\Http\Request $request) { if ($request->server->has('HTTP_X_ORIGINAL_HOST')) { $request->server->set('HTTP_HOST', $request->server->get('HTTP_X_ORIGINAL_HOST')); $request->headers->set('HOST', $request->server->get('HTTP_X_ORIGINAL_HOST')); } } ``` --- **Using `forceRootUrl()`** If you don't want to modify any headers or the Laravel request, you can simply tell the URL generator what root url to use. The URL generator has a `forceRootUrl()` method that you can use to tell it to use a specific value instead of looking at the request. Again, in your `AppServiceProvider::boot()` method: ``` public function boot(\Illuminate\Http\Request $request) { if ($request->server->has('HTTP_X_ORIGINAL_HOST')) { $this->app['url']->forceRootUrl($request->server->get('HTTP_X_FORWARDED_PROTO').'://'.$request->server->get('HTTP_X_ORIGINAL_HOST')); } } ```
63,211,572
Consider the following two pieces of code. Both return data to a Web API Get call. Both return a list of items. Both work. The first one was taken from Visual Studio starter Blazor Wasm App. The second one was taken from an online tutorial. tblTitles is a table in a remote database, accessed through \_dataContext. Which of these should be used and why? Or perhaps one suits better for a specific situation? ``` [HttpGet] //First method: public IEnumerable<TitlesTable> Get() { var titles = _dataContext.tblTitles.ToList(); return titles; } //Second method: public async Task<IActionResult> Get() { var titles = await _dataContext.tblTitles.ToListAsync(); return Ok(titles); } ```
2020/08/02
[ "https://Stackoverflow.com/questions/63211572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3656651/" ]
I believe you're noticing the different [available controller return types](https://learn.microsoft.com/en-us/aspnet/core/web-api/action-return-types?view=aspnetcore-3.1). From that docs page: > > ASP.NET Core offers the following options for web API controller > action return types: > > > * Specific type > * `IActionResult` > * `ActionResult<T>` > > > The page offers considerations of when to use each.
47,268,176
I am working on a project which requires me to get all the list of all information from a table --*Just like in a blog*, i used the `all()` method to do this but when i try to get the method i declared in my Model i get an error, saying > > the collection instance does not exists > > > But when i use The `Model::find($id)->relationship()->name;` it works fine. Is there any way to load all relationship with the `all()` function in laravel. Thanks for your help..
2017/11/13
[ "https://Stackoverflow.com/questions/47268176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7963133/" ]
When you perform `Model::find($id)->relationship();` you are actually accesing to the [Dynamic relationships Properties](https://laravel.com/docs/5.5/eloquent-relationships#relationship-methods-vs-dynamic-properties) You need to convert it into a collection using `Model::find($id)->relationship()->get();` Then you can perform any [collection method](https://laravel.com/docs/5.5/eloquent-collections#available-methods) to get the result you want. After doing this you can access to its attributes like this: ``` $model_varible = Model::find($id)->relationship()->get(); $model_variable = $model_variable->find($id)->name; ``` Let me know if this works for you.
32,889,677
I am trying to create an array of hash in python but it is not working ``` data = ["long","short","fanouts"] app = [] for da in data: app.append(app[name] = da) ``` output ``` File "test.py", line 5 app.append(app[name] = da) SyntaxError: keyword can't be an expression ``` Please could anyone help me with correct code i am new to python
2015/10/01
[ "https://Stackoverflow.com/questions/32889677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2745724/" ]
When you write ``` abc(x=y) ``` the interpreter reads that as trying to call a function with a keyword argument. So reading your line ``` app.append(app[name] = da) ``` it thinks you have a keyword argument `app[name]`, which does not make sense as a keyword argument. If you want to append a dict to your list, you could do it like this: ``` app.append({name:da}) ``` as long as `name` and `da` are existing variables.
208,184
I'm writing an app in C# (.net 3.5) and I have a question about class design: I'd like to create a class which accesses a file (read, write) and provides its content to the users (instanciators) of the class. The most common operation on an instance will be to retrieve a certain value from the file. The actual read and write (io) operations are faily expensive so I'd like to keep the file data in memory and let all instances access this data. The class is located in an assembly that is used from various applications simultaniously, so I guess I should be worrying about thread safety. How do I design this with respect to thread-safety and unit-testability (for unit-tests, different inputfiles must be used than in operational code)? Any help is greatly appreciated.
2008/10/16
[ "https://Stackoverflow.com/questions/208184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16440/" ]
Firstly, make your class implement an appropriate interface. That way, clients can test their behaviour without needing real files at all. Testing the thread safety is hard - I've never seen anything which is really useful on that front, though that's not to say the tools aren't out there. For unit testing your class, I'd suggest that if possible it should work with a general stream rather than just a file. Then you can embed different test files in your test assembly, and refer to them with [GetManifestResourceStream](http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getmanifestresourcestream.aspx). I've done this several times in the past, with great success.
16,342,655
``` function authonticate() { $.ajax({ type: "POST", url: "http://lp18mobile.azurewebsites.net/LP18WS.asmx/AuthonticateUser", contentType: "application/jsonp; charset=utf-8", data: { "some data" }, dataType: "json", success: function (msg) { //success } }, error: function (msg) { //error }, }); } ``` i have used Jquery,json,html5,webservice to develop the application. When I run the app it will throw ``` undefined error at "XMLHttpRequest cannot load http://lp18mobile.azurewebsites.net/LP18WS.asmx/AuthonticateUser. Origin http://'localhost:5733/..' is not allowed by Access-Control-Allow-Origin." ``` why?
2013/05/02
[ "https://Stackoverflow.com/questions/16342655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2343766/" ]
**Your code is actually attempting to make a CORS request, not an ordinary POST.** Modern browsers will only allow Ajax calls to pages in the **same domain** as the source HTML page. In other words, whenever the HTML page that tries to make an Ajax request is not on the same domain as the target URL (in your case, `lp18mobile.azurewebsites.net:80`), the browser won't make the call (as you'd expect). Instead, it will try to make a CORS request. Bear in mind that, for the browser, `localhost:80` and `localhost:5733` (same host, but different ports) **are different domains**. CORS request? What is that? --------------------------- [Wikipedia says](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing): **Cross-origin resource sharing (CORS)** is a mechanism that allows a web page to make `XMLHttpRequests` to another domain. Such "cross-domain" requests would otherwise be forbidden by web browsers, due to the **[same origin security policy](http://en.wikipedia.org/wiki/Same_origin_policy)**. To put it shortly, to perform a CORS request, your browser: * Will first send an `OPTION` request to the target URL + That's how it found out that `Origin ... is not allowed by Access-Control-Allow-Origin.` * And then **only if** the server response to that `OPTION` contains the [adequate headers (`Access-Control-Allow-Origin` is one of them)](http://enable-cors.org/server.html) to allow the CORS request, the browser will perform the call (almost exactly the way it would if the HTML page were at the same domain). + If the expected headers don't come, the browser simply gives up (like it did to you). How to make it work? -------------------- **If you can't change the web service or the HTTP server where it is hosted**: There is nothing you can do about it other than deploying that HTML file in a server located at the same domain of the service (in your scenario, `lp18mobile.azurewebsites.net:80`). **If you do can change the web service:** To enable CORS in ASP.NET web services, you can just add the headers by adding the following line **to your source pages**: ``` Response.AppendHeader("Access-Control-Allow-Origin", "*"); ``` But this is just a workaround to get you started. You really should get to know more about the CORS headers. More details in: [Using CORS to access ASP.NET services across domains](http://enable-cors.org/server.html) **If you do can change the HTTP server of the web service:** Check [this link](http://enable-cors.org/server_apache.html) to see how you can do it on Apache. [Click here](http://enable-cors.org/server_iis7.html) to learn how to enable it in IIS7 or [here](http://enable-cors.org/server_iis6.html) to make it in IIS6. How about JSONP? ---------------- To use JSONP in this scenario, you'd have to change the service to return information via GET, as you can't POST using JSONP. ([This answer](https://stackoverflow.com/questions/2699277/post-data-to-jsonp) points to some hacks, but that's going too far, I think.) I don't have access to the HTTP server or the web service. No workarounds at all, then? --------------------------------------------------------------------------------------- There are some options, but none of them is a clean workaround, really. You could set up an application (at the same domain/port of your HTML file) that forwards every TCP/IP request to `lp18mobile.azurewebsites.net:80`, and then fool your browser. Or you could set up a mirror of that web service in you domain/port. You see, it all becomes too dirty from this point on.
8,182,563
I have a custom asp.net control which contains some checkBoxes. I know how to get the checkBox, that was clicked ``` $('#customer-category-control input:checkbox').click(function(event) { var el = $(this).attr('name'); }; ``` Suggest me, please, how to get only all checked checkBoxes by click and make a JSON object from their names.
2011/11/18
[ "https://Stackoverflow.com/questions/8182563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/468345/" ]
``` var names=[]; $('#customer-category-control input[type="checkbox"]:checked').each(function (i, el){ names.push(el.name); }); console.log(names); // => ['foo','bar'...] ```
59,362,064
I have created a list of items that are scrollable. The list has a title section at the top and uses a box-shadow that overlays on top of the list. When I add a highlight hover effect to the list items, the list item highlight goes in-front of the box-shadow. Is there a way to have the box-shadow always show in-front? Example provided: <https://codepen.io/jwaugh3/pen/WNbopGX> ``` ``` <div class="gameList"> <div class="gameListTitle"> <h1>Title Block</h1> <h2>Box-Shadow Below</h2> </div> <div class="scroller"> <div class="force-overflow"> <div class="gameTile"> <h class="gameTileText gameTimeGrid">*GameTime*</h> <h class="gameTileText tournamentNameGrid">*TournamentName, Year*</h> <h class="gameTileText teamOneGrid"><img src="../resources/Griffinlogo_square.png" class="teamIcon">*TeamName*</h> <h class="gameTileText teamOneScoreGrid">*SeriesScore*</h> <h class="gameTileText teamTwoGrid"><img src="../resources/IG.jpg" class="teamIcon">*TeamName*</h> <h class="gameTileText teamTwoScoreGrid">*SeriesScore*</h> </div> <div class="gameTileSpacer"></div> </div> </div> ``` .gameList { grid-column-start: 1; grid-column-end: 2; grid-row-start: 2; grid-row-end: 4; background-color: #6B6B6B; border-radius: 10px; } .gameListTitle { z-index: 1; border-radius: 10px 10px 0px 0px; background-color: #6B6B6B; color: white; padding: 10px; box-shadow: 0px 10px 6px -1px rgba(0,0,0,0.58); } .scroller { overflow-y: scroll; height: 85%; margin-right: 2px; width: 100%; } ::-webkit-scrollbar { margin-top: 10px; width: 12px; background-color: rgb(0,0,0,0); } ::-webkit-scrollbar-track { margin-top: 10px; margin-bottom: 10px; background-color: rgb(0,0,0,0); box-shadow: inset 0 0 6px rgba(0,0,0,0.3); border-radius: 10px; } ::-webkit-scrollbar-thumb { margin-top: 10px; margin-bottom: 10px; background: white; box-shadow: inset 0 0 6px rgba(0,0,0,.3); border-radius: 10px; } .force-overflow { margin-right: 3px; /*margin added to right of list for scrollbar overlap*/ } .gameTile { padding: 10px; display: grid; grid-template-rows: 1fr 1fr 1fr; grid-template-columns: 1fr 1fr; } .gameTile:hover { background-color: #A0A0A0; z-index: 1; } .gameTileText { font-size: 1rem; font-weight: bold; color: white; padding: 3px; vertical-align: middle; } .teamIcon { max-width: 25px; } .gameTimeGrid { grid-row-start: 1; grid-row-end: 2; grid-column-start: 1; grid-column-end: 2; } .tournamentNameGrid { grid-row-start: 1; grid-row-end: 2; grid-column-start: 2; grid-column-end: 3; } .teamOneGrid { grid-row-start: 2; grid-row-end: 3; grid-column-start: 1; grid-column-end: 2; } .teamOneScoreGrid { grid-row-start: 2; grid-row-end: 3; grid-column-start: 2; grid-column-end: 3; text-align: center; } .teamTwoGrid { grid-row-start: 3; grid-row-end: 4; grid-column-start: 1; grid-column-end: 2; } .teamTwoScoreGrid { grid-row-start: 3; grid-row-end: 4; grid-column-start: 2; grid-column-end: 3; text-align: center; } .gameTileSpacer { width: 100%; height: 3px; background-color: #2D2D2D; } ``` ```
2019/12/16
[ "https://Stackoverflow.com/questions/59362064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12547131/" ]
You're using CSS Grid all you need to do is add `display:grid` to `.gameList` which seems to be missing ? ```css .gameList { grid-column-start: 1; grid-column-end: 2; grid-row-start: 2; grid-row-end: 4; background-color: #6B6B6B; border-radius: 10px; display: grid /* Added */ } /* z-index :1 */ .gameListTitle { z-index: 1; border-radius: 10px 10px 0px 0px; background-color: #6B6B6B; color: white; padding: 10px; box-shadow: 0px 10px 6px -1px rgba(0, 0, 0, 0.58); } /* no z-index or lower than .gameListTitle z-index*/ .scroller { overflow-y: scroll; height: 85%; margin-right: 2px; width: 100%; } ::-webkit-scrollbar { margin-top: 10px; width: 12px; background-color: rgb(0, 0, 0, 0); } ::-webkit-scrollbar-track { margin-top: 10px; margin-bottom: 10px; background-color: rgb(0, 0, 0, 0); box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3); border-radius: 10px; } ::-webkit-scrollbar-thumb { margin-top: 10px; margin-bottom: 10px; background: white; box-shadow: inset 0 0 6px rgba(0, 0, 0, .3); border-radius: 10px; } .force-overflow { margin-right: 3px; /*margin added to right of list for scrollbar overlap*/ } .gameTile { padding: 10px; display: grid; grid-template-rows: 1fr 1fr 1fr; grid-template-columns: 1fr 1fr; } .gameTile:hover { background-color: #A0A0A0; z-index: 1; } .gameTileText { font-size: 1rem; font-weight: bold; color: white; padding: 3px; vertical-align: middle; } .teamIcon { max-width: 25px; } .gameTimeGrid { grid-row-start: 1; grid-row-end: 2; grid-column-start: 1; grid-column-end: 2; } .tournamentNameGrid { grid-row-start: 1; grid-row-end: 2; grid-column-start: 2; grid-column-end: 3; } .teamOneGrid { grid-row-start: 2; grid-row-end: 3; grid-column-start: 1; grid-column-end: 2; } .teamOneScoreGrid { grid-row-start: 2; grid-row-end: 3; grid-column-start: 2; grid-column-end: 3; text-align: center; } .teamTwoGrid { grid-row-start: 3; grid-row-end: 4; grid-column-start: 1; grid-column-end: 2; } .teamTwoScoreGrid { grid-row-start: 3; grid-row-end: 4; grid-column-start: 2; grid-column-end: 3; text-align: center; } .gameTileSpacer { width: 100%; height: 3px; background-color: #2D2D2D; } ``` ```html <div class="gameList"> <div class="gameListTitle"> <h1>Title Block</h1> <h2>Box-Shadow Below</h2> </div> <div class="scroller"> <div class="force-overflow"> <div class="gameTile"> <h class="gameTileText gameTimeGrid">*GameTime*</h> <h class="gameTileText tournamentNameGrid">*TournamentName, Year*</h> <h class="gameTileText teamOneGrid"><img src="../resources/Griffinlogo_square.png" class="teamIcon">*TeamName*</h> <h class="gameTileText teamOneScoreGrid">*SeriesScore*</h> <h class="gameTileText teamTwoGrid"><img src="../resources/IG.jpg" class="teamIcon">*TeamName*</h> <h class="gameTileText teamTwoScoreGrid">*SeriesScore*</h> </div> <div class="gameTileSpacer"></div> <div class="gameTile"> <h class="gameTileText gameTimeGrid">*GameTime*</h> <h class="gameTileText tournamentNameGrid">*TournamentName, Year*</h> <h class="gameTileText teamOneGrid"><img src="../resources/Griffinlogo_square.png" class="teamIcon">*TeamName*</h> <h class="gameTileText teamOneScoreGrid">*SeriesScore*</h> <h class="gameTileText teamTwoGrid"><img src="../resources/IG.jpg" class="teamIcon">*TeamName*</h> <h class="gameTileText teamTwoScoreGrid">*SeriesScore*</h> </div> <div class="gameTileSpacer"></div> <div class="gameTile"> <h class="gameTileText gameTimeGrid">*GameTime*</h> <h class="gameTileText tournamentNameGrid">*TournamentName, Year*</h> <h class="gameTileText teamOneGrid"><img src="../resources/Griffinlogo_square.png" class="teamIcon">*TeamName*</h> <h class="gameTileText teamOneScoreGrid">*SeriesScore*</h> <h class="gameTileText teamTwoGrid"><img src="../resources/IG.jpg" class="teamIcon">*TeamName*</h> <h class="gameTileText teamTwoScoreGrid">*SeriesScore*</h> </div> <div class="gameTileSpacer"></div> <div class="gameTile"> <h class="gameTileText gameTimeGrid">*GameTime*</h> <h class="gameTileText tournamentNameGrid">*TournamentName, Year*</h> <h class="gameTileText teamOneGrid"><img src="../resources/Griffinlogo_square.png" class="teamIcon">*TeamName*</h> <h class="gameTileText teamOneScoreGrid">*SeriesScore*</h> <h class="gameTileText teamTwoGrid"><img src="../resources/IG.jpg" class="teamIcon">*TeamName*</h> <h class="gameTileText teamTwoScoreGrid">*SeriesScore*</h> </div> <div class="gameTileSpacer"></div> <div class="gameTile"> <h class="gameTileText gameTimeGrid">*GameTime*</h> <h class="gameTileText tournamentNameGrid">*TournamentName, Year*</h> <h class="gameTileText teamOneGrid"><img src="../resources/Griffinlogo_square.png" class="teamIcon">*TeamName*</h> <h class="gameTileText teamOneScoreGrid">*SeriesScore*</h> <h class="gameTileText teamTwoGrid"><img src="../resources/IG.jpg" class="teamIcon">*TeamName*</h> <h class="gameTileText teamTwoScoreGrid">*SeriesScore*</h> </div> <div class="gameTileSpacer"></div> <div class="gameTile"> <h class="gameTileText gameTimeGrid">*GameTime*</h> <h class="gameTileText tournamentNameGrid">*TournamentName, Year*</h> <h class="gameTileText teamOneGrid"><img src="../resources/Griffinlogo_square.png" class="teamIcon">*TeamName*</h> <h class="gameTileText teamOneScoreGrid">*SeriesScore*</h> <h class="gameTileText teamTwoGrid"><img src="../resources/IG.jpg" class="teamIcon">*TeamName*</h> <h class="gameTileText teamTwoScoreGrid">*SeriesScore*</h> </div> <div class="gameTileSpacer"></div> <div class="gameTile"> <h class="gameTileText gameTimeGrid">*GameTime*</h> <h class="gameTileText tournamentNameGrid">*TournamentName, Year*</h> <h class="gameTileText teamOneGrid"><img src="../resources/Griffinlogo_square.png" class="teamIcon">*TeamName*</h> <h class="gameTileText teamOneScoreGrid">*SeriesScore*</h> <h class="gameTileText teamTwoGrid"><img src="../resources/IG.jpg" class="teamIcon">*TeamName*</h> <h class="gameTileText teamTwoScoreGrid">*SeriesScore*</h> </div> <div class="gameTileSpacer"></div> <div class="gameTile"> <h class="gameTileText gameTimeGrid">*GameTime*</h> <h class="gameTileText tournamentNameGrid">*TournamentName, Year*</h> <h class="gameTileText teamOneGrid"><img src="../resources/Griffinlogo_square.png" class="teamIcon">*TeamName*</h> <h class="gameTileText teamOneScoreGrid">*SeriesScore*</h> <h class="gameTileText teamTwoGrid"><img src="../resources/IG.jpg" class="teamIcon">*TeamName*</h> <h class="gameTileText teamTwoScoreGrid">*SeriesScore*</h> </div> <div class="gameTileSpacer"></div> <div class="gameTile"> <h class="gameTileText gameTimeGrid">*GameTime*</h> <h class="gameTileText tournamentNameGrid">*TournamentName, Year*</h> <h class="gameTileText teamOneGrid"><img src="../resources/Griffinlogo_square.png" class="teamIcon">*TeamName*</h> <h class="gameTileText teamOneScoreGrid">*SeriesScore*</h> <h class="gameTileText teamTwoGrid"><img src="../resources/IG.jpg" class="teamIcon">*TeamName*</h> <h class="gameTileText teamTwoScoreGrid">*SeriesScore*</h> </div> <div class="gameTileSpacer"></div> <div class="gameTile"> <h class="gameTileText gameTimeGrid">*GameTime*</h> <h class="gameTileText tournamentNameGrid">*TournamentName, Year*</h> <h class="gameTileText teamOneGrid"><img src="../resources/Griffinlogo_square.png" class="teamIcon">*TeamName*</h> <h class="gameTileText teamOneScoreGrid">*SeriesScore*</h> <h class="gameTileText teamTwoGrid"><img src="../resources/IG.jpg" class="teamIcon">*TeamName*</h> <h class="gameTileText teamTwoScoreGrid">*SeriesScore*</h> </div> <div class="gameTileSpacer"></div> <div class="gameTile"> <h class="gameTileText gameTimeGrid">*GameTime*</h> <h class="gameTileText tournamentNameGrid">*TournamentName, Year*</h> <h class="gameTileText teamOneGrid"><img src="../resources/Griffinlogo_square.png" class="teamIcon">*TeamName*</h> <h class="gameTileText teamOneScoreGrid">*SeriesScore*</h> <h class="gameTileText teamTwoGrid"><img src="../resources/IG.jpg" class="teamIcon">*TeamName*</h> <h class="gameTileText teamTwoScoreGrid">*SeriesScore*</h> </div> <div class="gameTileSpacer"></div> <div class="gameTile"> <h class="gameTileText gameTimeGrid">*GameTime*</h> <h class="gameTileText tournamentNameGrid">*TournamentName, Year*</h> <h class="gameTileText teamOneGrid"><img src="../resources/Griffinlogo_square.png" class="teamIcon">*TeamName*</h> <h class="gameTileText teamOneScoreGrid">*SeriesScore*</h> <h class="gameTileText teamTwoGrid"><img src="../resources/IG.jpg" class="teamIcon">*TeamName*</h> <h class="gameTileText teamTwoScoreGrid">*SeriesScore*</h> </div> <div class="gameTileSpacer"></div> <div class="gameTile"> <h class="gameTileText gameTimeGrid">*GameTime*</h> <h class="gameTileText tournamentNameGrid">*TournamentName, Year*</h> <h class="gameTileText teamOneGrid"><img src="../resources/Griffinlogo_square.png" class="teamIcon">*TeamName*</h> <h class="gameTileText teamOneScoreGrid">*SeriesScore*</h> <h class="gameTileText teamTwoGrid"><img src="../resources/IG.jpg" class="teamIcon">*TeamName*</h> <h class="gameTileText teamTwoScoreGrid">*SeriesScore*</h> </div> <div class="gameTileSpacer"></div> </div> </div> </div> ``` Why does it work ? > > **The [z-index](https://developer.mozilla.org/en-US/docs/Web/CSS/z-index) property sets the z-order of a positioned element and its descendants or flex items.** > > > **Positioned element:** is an element who's position property is set to a value other than static **Flex item:** is an child element of a flex container `display:flex;` or a grid container `display:grid;` Now your `z-index:1` on `.gameListTitle` will be effective.
133,723
I've been asked to implement some external commands to be called by our email server in order to perform some basic check over outgoing messages. I'm doing a research to understand what kind of checks I can implement. Some notes: * keyword DLP rules are under scrutiny * there's no confidential classification scheme in the company. We're gonna do it in the near future. Therefore, there's still no way to identify a document based on classification keyword * there's no budget to implement a dedicated DLP solution Here are some checks I thought to implement: * count the number of messages sent by a user per day. If the number of messages of the current day is higher of a defined threshold (in percentage, say 100%) compared to the average number of messages sent in the last N days, raise an alert. I should also consider a minimum number of messages, below which this check has no sens * analyze the size or the number of attachments sent by a user per day. Same check over a threshold as described in the previous rule Did any of you performed any kind of such an activity? Do you have any advise on other kind of rules or approach?
2016/08/12
[ "https://security.stackexchange.com/questions/133723", "https://security.stackexchange.com", "https://security.stackexchange.com/users/121264/" ]
I don't mean this to sound harsh, but this is part of my day job, and to be honest I don't think you have the experience or scope necessary to pull something like this off successfully by yourself while achieving any sort of meaningful result. DLP is a HUGE domain. You haven't even been given any clear direction in what it is you need to be catching which makes this all the more difficult. Stolen internal sales leads or books of business? PII? HIPAA? PCI? You might not pass an audit of the latter two rolling your own solution (talk to your auditor BEFORE you start development). And neither of your triggers will catch anything but a rogue spambot running on your network. In my experience people that exfiltrate data know they're doing something bad and take at least ONE step to cover it up. They're also not going to suddenly start sending 100x more emails than they usually do. At best using a regex for socials or A/R numbers might catch some accidental cases of Outlook autocompleting the wrong address and the sender sending it without looking. * How are you going to distinguish 16-digit card numbers from any other 16-digit sequence? * You could catch them all, but who is reviewing these false positives? Is anybody? If you don't have the budget for a commercial solution, do you even have analysts that are going to review anything you find? * Word documents. Are you capturing and/or reading through those? * Text files or docs renamed as something else? * Images. Are you performing OCR on all outbound images? * Alternate data streams/stego? * If I export cardholder information to a PDF and stick it in an encrypted zip file, would you catch that? What if I stuck that encrypted zip inside another encrypted rar? You'd have to decrypt at least one layer of zip/rar file and parse a PDF to catch it. You could block all binary attachments, but when they turn to an alternate channel to send it out another way, will you catch that? * You want to catch social security numbers? How are you going to distinguish those from mistyped phone numbers? Is 273-555-1010 a phone number or a social? How about 123769931? The same regexes will catch either. Keep in mind none of these cases involve a change in velocity or attachments, as you're proposing you'd look for. It's just one malicious email among many benign ones I'll send that day. Maybe yours is different but in my experience most people aren't dumb enough to just dump PII into the body of an email and send it; 90% of the time it's encapsulated in at least one other format (pdf, txt, doc, doc inside zip, zip inside rar, etc). Your question specifically pertained to email, but you also need to consider people using Facebook messaging, Dropbox, USB sticks, etc. to exfiltrate data...otherwise you might as well not bother. Email is just one tiny vector. Don't mean to dump on you, just pointing out some of my own experiences with this field in the hopes it spares you some headache. You have no idea what you're getting into if you have no budget for tooling. DLP is one of the few areas I truly believe commercial solutions can do far better than rolling your own.
11,976,234
I am trying to get the raw XML response from a web service, instead of the usual set of POJOs. I am using a webservice client that I generated (so I have access to the client's code) from a WSDL and some schemas. The client is generated in RAD 7.5, I think using JAX-WS. I've been looking at the client code itself, but I'm not even sure if the client code ever handles raw XML or if it passes it off to other libraries.
2012/08/15
[ "https://Stackoverflow.com/questions/11976234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/192801/" ]
You can do it using ``` javax.xml.ws.handler.soap.SOAPHandler<javax.xml.ws.handler.soap.SOAPMessageContext> ``` you can simply get message using `SOAPMessageContext#getMessage()` and convert message to String using method ``` public static String getXmlMessage(SOAPMessage message) throws Exception { ByteArrayOutputStream os = new ByteArrayOutputStream(); message.writeTo(os); final String encoding = (String) message.getProperty(SOAPMessage.CHARACTER_SET_ENCODING); if (encoding == null) { return new String(os.toByteArray()); } else { return new String(os.toByteArray(), encoding); } } ``` Also you can read here about SOAP handler on client side [Article](http://www.mkyong.com/webservices/jax-ws/jax-ws-soap-handler-in-client-side/)
3,995,253
I have a simple question. Is it possible to somehow get a log of what is taking so much time to load when starting VS2010? On a default install, starting the IDE is very quick (~1-2 s), but with a batch of extensions installed, the time taken for the IDE to launch is prohibitive of using it to "just have a peek at a file". I know I can "enable and disable extensions one by one", but I'm looking for a better way that gives me numbers, not 'feelings'. Hope someone out there knows a good way to do this. Edit: Follow-up question: [Can I selectively disable packages from loading into VS2010?](https://stackoverflow.com/questions/3996242/can-i-selectively-disable-packages-from-loading-into-vs2010)
2010/10/22
[ "https://Stackoverflow.com/questions/3995253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/63621/" ]
You can use `devenv /log` as detailed here: [MSDN Blogs: Troubleshooting Extensions with the Activity Log](https://web.archive.org/web/20160116023730/http://blogs.msdn.com:80/b/visualstudio/archive/2010/02/24/troubleshooting-with-the-activity-log.aspx). 1. Run `devenv /log` 2. Close the IDE again to close the log `Win`+`R`, 3. Run `%APPDATA%\Microsoft\VisualStudio\10.0\ActivityLog.xsl` 4. Wait for it to load in Visual Studio 5. Open `%APPDATA%\Microsoft\VisualStudio\10.0\ActivityLog.xml` in a web browser and it will format itself nicely.
5,977,579
I need to have a string as a global variable. There is a possibility for multiple threads to set the global variable. Should I have to go for mutex for this? Or will OS handle such actions. Going for mutex affects the application performance. I am not concerned about the order of actions happening. I am afraid of the data corruption. Could somebody let me know about this.
2011/05/12
[ "https://Stackoverflow.com/questions/5977579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/399924/" ]
It sounds like you understand all of the concerns. If the global variable can be corrupt you definitely need to lock it in a mutex. This will affect performance, since this part is by definition now going to be synchronous. That being said, you will want to lock the smallest part of the code as necessary, to minimize the time that synchronous code is being called.
519,095
I have a ~2006 Macbook (1,1) that I am trying to resurrect as a Linux machine. I no longer want nor need OS X, so I want to install Arch as the only OS on this machine. I have tried several times to get Arch Linux installed, but I get hung up every time when it comes to installing the bootloader. I have even gotten Grub2 to install, but I can't get it to install and then boot. I've attempted following the [ArchLinux Macbook guide](https://wiki.archlinux.org/index.php/MacBook) for EFI, along with the [Beginner's Guide](https://wiki.archlinux.org/index.php/Beginners'_Guide). I've read quite a bit about [UEFI](https://wiki.archlinux.org/index.php/Unified_Extensible_Firmware_Interface), but I still can't seem to figure out where to put my bootloader. From the errors I get when I install, it would appear that the laptop is not booting in UEFI mode, so none of the UEFI bootloader directions work. I get hung up at the following command: ``` grub-install --target=i386-efi --efi-directory=/boot/efi --bootloader-id=arch_grub --recheck ``` It tells me to run `modprobe efivars` before chrooting, but I do that and nothing happens. My understanding is that my Macbook is EFI rather than BIOS, but without it booting into UEFI mode, I can't install a UEFI bootloader. What do I need to do to make the bootloader (1) install and (2) work. As mentioned above, I don't need OS X, and would like Arch to be the only OS on this computer.
2012/12/13
[ "https://superuser.com/questions/519095", "https://superuser.com", "https://superuser.com/users/154408/" ]
If you want to establish remote connection to the box using RDP , run ``` mstsc /v:<servername:port> ``` If you want to connect to network share on the remote computer, use this: ``` net use * \\servername\sharename ``` You might need to have permissions for the share 'sharename', unless it is shared as public.
41,789,179
i need to create empty spaces between xml tags.my input xml looks like below ``` <?xml version="1.0" encoding="UTF-8"?> <EPCISDocument schemaVersion="" creationDate=""> <EPCISHeader> <StandardBusinessDocumentHeader> <HeaderVersion/> <Sender> <Identifier Authority=""/> <ContactInformation> <Contact/> <EmailAddress/> <FaxNumber/> <TelephoneNumber/> <ContactTypeIdentifier/> </ContactInformation> </Sender> <Receiver> <Identifier Authority=""/> <ContactInformation> <Contact/> <EmailAddress/> <FaxNumber/> <TelephoneNumber/> <ContactTypeIdentifier/> </ContactInformation> </Receiver> <DocumentIdentification> <Standard/> <TypeVersion/> <InstanceIdentifier/> <Type/> <MultipleType/> <CreationDateAndTime/> </DocumentIdentification> <Manifest> <NumberOfItems/> <ManifestItem> <MimeTypeQualifierCode/> <UniformResourceIdentifier/> <Description/> <LanguageCode/> </ManifestItem> </Manifest> <BusinessScope> <Scope> <BusinessService> <BusinessServiceName/> <ServiceTransaction TypeOfServiceTransaction="" IsNonRepudiationRequired="" IsAuthenticationRequired="" IsNonRepudiationOfReceiptRequired="" IsIntegrityCheckRequired="" IsApplicationErrorResponseRequired="" TimeToAcknowledgeReceipt="" TimeToAcknowledgeAcceptance="" TimeToPerform="" Recurrence=""/> </BusinessService> <CorrelationInformation> <RequestingDocumentCreationDateTime/> <RequestingDocumentInstanceIdentifier/> <ExpectedResponseDateTime/> </CorrelationInformation> </Scope> </BusinessScope> </StandardBusinessDocumentHeader> </EPCISHeader> <EPCISBody> <EventList> <ObjectEvent> <eventTime/> <recordTime/> <eventTimeZoneOffset/> <epcList> <epc type=""/> </epcList> <action/> <bizStep/> <disposition/> <readPoint> <id/> </readPoint> <bizLocation> <id/> </bizLocation> <bizTransactionList> <bizTransaction type=""/> </bizTransactionList> <GskEpcExtension> <nhrn> </nhrn> </GskEpcExtension> </ObjectEvent> </EventList> ``` using xslt code i am adding the few prefixes and below is the xslt code ``` <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:epcis="http://apse.com" xmlns:sbdh="http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader" xmlns:gsk="http://epcis.gsk.com"> <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> <xsl:strip-space elements="*"/> <!-- identity transform --> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="EPCISDocument"> <epcis:EPCISDocument> <xsl:apply-templates select="node()|@*"/> </epcis:EPCISDocument> </xsl:template> <xsl:template match="GskEpcExtension|GskEpcExtension//*"> <xsl:element name="gsk:{name()}"> <xsl:apply-templates select="node()|@*"/> </xsl:element> </xsl:template> <xsl:template match="StandardBusinessDocumentHeader|StandardBusinessDocumentHeader//*"> <xsl:element name="sbdh:{name()}"> <xsl:apply-templates select="node()|@*"/> </xsl:element> </xsl:template> </xsl:stylesheet> ``` the output my code is coming as expected.but i got new requirement like in the input xml under gskepcextension node one of the field nhrn coming with sapces. but in the ouput xml it is ending like gsk:/nhrn. i need like gsk:nhrn gsk:/nhrn. if value coming in the input for that field it is populating as expected.but when it is coming with space it is not populating as expected.could anyone help on this. for example the output should be like below ``` <gsk:nhrn> </gsk:nhrn> ```
2017/01/22
[ "https://Stackoverflow.com/questions/41789179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7369491/" ]
I think this will solve your problem: ``` import zlib import zipfile import io def fetch(key_name, start, len, client_s3): """ range-fetches a S3 key """ end = start + len - 1 s3_object = client_s3.get_object(Bucket=bucket_name, Key=key_name, Range="bytes=%d-%d" % (start, end)) return s3_object['Body'].read() def parse_int(bytes): """ parses 2 or 4 little-endian bits into their corresponding integer value """ val = (bytes[0]) + ((bytes[1]) << 8) if len(bytes) > 3: val += ((bytes[2]) << 16) + ((bytes[3]) << 24) return val def list_files_in_s3_zipped_object(bucket_name, key_name, client_s3): """ List files in s3 zipped object, without downloading it. Returns the number of files inside the zip file. See : https://stackoverflow.com/questions/41789176/how-to-count-files-inside-zip-in-aws-s3-without-downloading-it Based on : https://stackoverflow.com/questions/51351000/read-zip-files-from-s3-without-downloading-the-entire-file bucket_name: name of the bucket key_name: path to zipfile inside bucket client_s3: an object created using boto3.client("s3") """ bucket = bucket_name key = key_name response = client_s3.head_object(Bucket=bucket_name, Key=key_name) size = response['ContentLength'] eocd = fetch(key_name, size - 22, 22, client_s3) # start offset and size of the central directory cd_start = parse_int(eocd[16:20]) cd_size = parse_int(eocd[12:16]) # fetch central directory, append EOCD, and open as zipfile! cd = fetch(key_name, cd_start, cd_size, client_s3) zip = zipfile.ZipFile(io.BytesIO(cd + eocd)) print("there are %s files in the zipfile" % len(zip.filelist)) for entry in zip.filelist: print("filename: %s (%s bytes uncompressed)" % (entry.filename, entry.file_size)) return len(zip.filelist) if __name__ == "__main__": import boto3 import sys client_s3 = boto3.client("s3") bucket_name = sys.argv[1] key_name = sys.argv[2] list_files_in_s3_zipped_object(bucket_name, key_name, client_s3) ```
33,180,948
When I am trying to export a column value '2015-05-04 23:39:22.003168' to Teradata Table using SQOOP Export. The Export was successful, but the data is loaded as '2015-05-04 23:39:22.000000' The milliseconds are converted to ZEROs The Data Type of the column in Teradata is Timestamp(6). The Teradata connector used is: teradata-connector-1.4.0.jar Here, how can I send milliseconds as it is to Teradata. Regards, D V N
2015/10/16
[ "https://Stackoverflow.com/questions/33180948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5455696/" ]
1: I looked at the reasonably large non-library clojure project i'm working on right now and ran this: ``` ls **/*.clj | xargs wc -l | awk '{print $1}' | head -n -1 > counts ``` and opend a repl and ran ``` user> (float (/ (reduce + counts) (count counts))) 208.76471 ``` I see that on a project with 17k LOC **our average clojure file has 200 lines** in it. I found one with 1k LOC. 2: Yes, I'll get started breaking that long one down as soon as I have free time. some very long ones such as clojure.core are very long becaues of clojure's one pass design and the need to self-bootstrap. they need to build the ability to have many namespaces for instance before they can do so. For other fancy libraries it may very well be that they had some other design reason for a large file though usually it's a case of "pull request welcome" in my expierence. 3: I do work in a large team with a few large files, we handle merge conflicts with git, though because changes tend to be within a function these come up, for me, much less often than in other languages. I find that it's simply not a problem.
37,873,050
I am new in Swift and iOS. Please send me the sample code for `POST` request with `JSON` data to external database for login app in iOS using Swift
2016/06/17
[ "https://Stackoverflow.com/questions/37873050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6374170/" ]
Try ``` string[] columnNames = dt.Columns.Cast<DataColumn>() .Select(x => x.ColumnName) .ToArray(); dataGridView1.DataSource = columnNames; ``` Or ``` dataGridView1.DataSource = dt.Columns.Cast<DataColumn>() .Select(x => x.ColumnName) .ToArray(); ```
70,290,041
I have a certain script (python), which needs to be automated that is relatively memory and CPU intensive. For a monthly process, it runs ~300 times, and each time it takes somewhere from 10-24 hours to complete, based on input. It takes certain (csv) file(s) as input and produces certain file(s) as output, after processing of course. And btw, each run is independent. We need to use configs and be able to pass command line arguments to the script. Certain imports, which are not default python packages, need to be installed as well (requirements.txt). Also, need to take care of logging pipeline (EFK) setup (as ES-K can be centralised, but where to keep log files and fluentd config?) Last bit is monitoring - will we be able to restart in case of unexpected closure? Best way to automate this, tools and technologies? My thoughts ----------- Create a docker image of the whole setup (python script, fluent-d config, python packages etc.). Now we somehow auto deploy this image (on a VM (or something else?)), execute the python process, save the output (files) to some central location (datalake, eg) and destroy the instance upon successful completion of process. So, is what I'm thinking possible in Azure? If it is, what are the cloud components I need to explore -- answer to my somehows and somethings? If not, what is probably the best solution for my use case? Any lead would be much appreciated. Thanks.
2021/12/09
[ "https://Stackoverflow.com/questions/70290041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2453089/" ]
Normally for short living jobs I'd say use an [Azure Function](https://learn.microsoft.com/en-us/azure/azure-functions). Thing is, they have a maximum runtime of 10 minutes unless you put them on an [App Service Plan](https://learn.microsoft.com/en-us/azure/app-service/overview-hosting-plans). But that will costs more unless you manually stop/start the app service plan. If you can containerize the whole thing I recommend using [Azure Container Instances](https://azure.microsoft.com/en-us/services/container-instances) because you then only pay for what you actual use. You can use an Azure Function to start the container, based on [an http request](https://learn.microsoft.com/en-us/azure/container-instances/container-instances-tutorial-azure-function-trigger), timer or something like that. You can set a restart policy to indicate what should happen in case of unexpected failures, see [the docs](https://learn.microsoft.com/bs-cyrl-ba/azure/container-instances/container-instances-restart-policy#container-restart-policy). Configuration can be passed from the Azure Function to the container instance or you could leverage the [Azure App Configuration](https://learn.microsoft.com/en-us/azure/azure-app-configuration/overview) service.
17,378,726
I've 2 tables Sales & Purchase, Sales table with fields SaleId, Rate, Quantity, Date, CompanyId, UserID. Purchase table with fields PurchaseId, Rate, Quantity, Date, CompanyId, UserID. I want to select a record from either table that have highest Rate\*Quantity. ``` SELECT SalesId Or PurchaseId FROM Sales,Purchase where Sales.UserId=Purchase.UserId and Sales.CompanyId=Purchase.CompanyId AND Sales.Date=Current date AND Purchase.Date=Current date AND Sales.UserId=1 AND Purchase.UserId=1 AND Sales.CompanyId=1 AND Purchase.ComoanyId=1 ```
2013/06/29
[ "https://Stackoverflow.com/questions/17378726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2516394/" ]
Try: ``` select top 1 * from (select SalesId ID, Rate, Quantity, 'Sales' TransactionType from sales union all select PurchaseId ID, Rate, Quantity, 'Purchase' TransactionType from purchase) order by Rate * Quantity desc ```
46,319,068
My string is : Hi my, name is abc I would like to output "Hi Name". [Basically first word of comma separated sentences]. However sometimes my sentence can also be Hi my, "name is, abc" [If the sentence itself has a comma then the sentence is enclosed with ""]. My output in this case should also be "Hi Name". So Far I've done this ``` $str = "hi my,name is abc"; $result = explode(',',$str); //parsing with , as delimiter foreach ($result as $results) { $x = explode(' ',$results); // parsing with " " as delimiter forach($x as $y){} } ```
2017/09/20
[ "https://Stackoverflow.com/questions/46319068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/828983/" ]
You can use `explode` to achieve YOUR RESULT and for IGINORE `'` OR `"` use trim ``` $str = 'hi my,"name is abc"'; $result = explode(',',$str); //parsing with , as delimiter $first = explode(' ',$result[0]); $first = $first[0]; $second = explode(' ',$result[1]); $second = trim($second[0],"'\""); $op = $first." ".$second; echo ucwords($op); ``` **EDIT** or if you want it for all , separated values use foreach ``` $str = 'hi my,"name is abc"'; $result = explode(',',$str); //parsing with , as delimiter $op = ""; foreach($result as $value) { $tmp = explode(' ',$value); $op .= trim($tmp[0],"'\"")." "; } $op = rtrim($op); echo ucwords($op); ```
51,925
We are currently evaluating different applications that interface with Visual Studio 2008 (C#) and Subversion to do automated builds of our core libraries. We are hoping to have nightly builds performed and either email the list of changes made to each developer or have the latest versions be pushed to each workstation. What has been your experience with these tools and what are some recommendations? --- **Suggested software** * [Cruise Control .NET](http://confluence.public.thoughtworks.org/display/CCNET/Welcome+to+CruiseControl.NET) * [Hudson](http://hudson-ci.org/) * [TeamCity](http://www.jetbrains.com/teamcity/) **Suggested articles** * [Continuous Integration: From Theory to Practice 2nd Edition (CC.net)](http://dotnet.org.za/cjlotz/archive/2008/01/15/continuous-integration-from-theory-to-practice-2nd-edition.aspx) * [Automating Your ASP.NET Build and Deploy Process with Hudson](http://blogs.freshlogicstudios.com/Posts/View.aspx?Id=87a1c0f7-a75e-4f1a-8d3a-6c52c6ad9f46)
2008/09/09
[ "https://Stackoverflow.com/questions/51925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3111/" ]
Cruise Control.net (ccnet) does everything you are looking for. Its pretty easy to use, just make sure if you are going to run it as a service, you give it an account and don't make it run as network service, that way you can give it rights on intranet boxes and have it do xcopy deploys. It has all kinds of email modes, on failure, on all, on fix after failure, and many many more.
20,185,143
How to get the Name value using Post method in php like this ``` <input type="text" name="<?php echo $result['name'];?>" id=""> ``` How to Post the Name value..? ``` <?php $name=$_POST[''] --? here how can i get the value using name. ``` Please help me.Thanks Is this Correct..? $name=$\_POST['$result['name']'];
2013/11/25
[ "https://Stackoverflow.com/questions/20185143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2637639/" ]
The current (3.4.1) S3Reader plugin is not compatible with the AWSSDK 2.\* version. Go to the Package Manager: 1) Uninstall S3Reader plugin Uninstall-Package ImageResizer.Plugins.S3Reader -ProjectName YourProjectName 2) Uninstall AWSSDK Uninstall-Package AWSSDK -ProjectName YourProjectName 3) Install AWSSDK 1.5.\* version (at the moment the latest is 1.5.39.0) Install-Package AWSSDK -ProjectName YourProjectName -Version 1.5.39.0 4) Install S3Reader plugin ignoring the dependencies Install-Package ImageResizer.Plugins.S3Reader -ProjectName YourProjectName-IgnoreDependencies That should fix your problem!! Cheers...
44,053,965
I have experience writing C# and Angular1 code, but Angular2+ and RxJs are new to me. I've just written an Angular4 login component and I feel like I've written a code smell by caching the result of the login method in the map function of the observable. I have an AuthenticationService which the LoginComponent calls login on: ``` login(username: string, password: string): Observable<User> { return this.http .post('/api/users/login', { username: username, password: password }) .map((response: Response) => { let loginResult = response.json(); this.user = loginResult.user as User localStorage.setItem(tokenStorageName, loginResult.token); return this.user; }) .catch(this.handleError); ``` } It feels strange to save state in the map function because as far as I'm aware that should just be a translation function. I want to cache the user and token which come back from the login result so that I don't have to make another service call if I want the users data. Here is the logic of the login component: ``` login() { this.isLoading = true; this.authenticationService.login(this.model.username, this.model.password) .subscribe( result => { let returnUrl = this.activatedRoute.snapshot.queryParams['returnUrl'] || '/' this.router.navigate([returnUrl]); }, error => { if (error != null && error.code == unauthorizedCode) { this.error = 'Username or password incorrect'; } else { this.error = 'Error logging in'; } this.isLoading = false; }); ``` It also doesn't feel right for the LoginComponent to call setUser on the AuthenticationService or a UserCache. Can someone give me some advice into best practices here please?
2017/05/18
[ "https://Stackoverflow.com/questions/44053965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/837883/" ]
There will be edge case but accomplishes your goal ```js $(function () { $(".main").each(function (index, element) { var $element = $(element); var wrapped = $element.text().replace(/(.+?)((\d{1,3},?)+)/g, '$1<span class="wrap">$2</span>'); $element.html(wrapped); }); }); ``` ```css .wrap { background-color: yellow; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="main">Item 7,000</div> <div class="main">Item 960</div> <div class="main">Item 7,000,000</div> ```
16,670,584
I've been experiencing an odd problem with IE10 when redirecting the page on an 'oninput' event (with no equivalent issue when using Chrome). I've produced the most pared-down version of the code that still exhibits the problem, as follows: ``` <html> <head> <script type="text/javascript"> function onChangeInputText() { window.location.href = "oninput_problem.html"; // Back to this page. } </script> </head> <body> <input type="text" oninput="onChangeInputText()" value="£" /> </body> </html> ``` On my Windows 7 PC using IE10, this code when browsed to (either by double clicking or via Apache) repeatedly redirects as if the act of initialising the value of the input text box itself is generating an immediate 'oninput' event. However, when I change the initial input text box value from the '£' symbol to a letter 'A', the repeated redirection doesn't occur. I first noticed this problem as part of a project I'm working on. In that case, the user's input should cause a delayed page refresh, which began repeatedly redirecting when I entered a '£' symbol. As I say, the above code is the most pared-down version I produced in trying to track what was causing the issue. Does anyone else experience this using IE10? If so, can anyone explain why IE10 is behaving this way?
2013/05/21
[ "https://Stackoverflow.com/questions/16670584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1773721/" ]
I've found the following that appears to indicate that this may be a bug in IE10: [social.msdn.microsoft.com: Event oninput triggered on page load](http://social.msdn.microsoft.com/Forums/en-US/iewebdevelopment/thread/95e6b9fa-786d-4b32-b457-c891f3744ed3) Also, there's a follow-up bug report (within the page linked to above): [connect.microsoft.com: onInput event fires on loading the page when input @value is non-ASCII](https://connect.microsoft.com/IE/feedback/details/776510/oninput-event-fires-on-loading-the-page-when-input-value-is-non-ascii#details%20,%20including%20a%20JSfiddle%20of%20the%20issue%3a%20http://jsfiddle.net/Y2tfp/) EDITED TO ADD: At the bottom of the page pointed to by the second link, there's what would seem to be an unhelpful reply from Microsoft stating that they are unable to reproduce the bug described, so it may be a while before the issue is fixed...
12,280,111
I am a jQuery newbie and was wondering whether it is possible to pass in a TextBox as an argument for a jQuery function. Something like this: ``` <input id="MyInput" value="" type="text" > //how/what to pass in this function to change the value of the input? function SetValueTextBox(? ?) { //change the value of the MyInput Textbox } ``` Ofcourse i have more than 1 TextBox where I would like to use this hence the question.
2012/09/05
[ "https://Stackoverflow.com/questions/12280111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1029283/" ]
You can do this (not 100% sure what you looking for): ``` function SetValueTextBox(textboxid, value) { //change the value of the MyInput Textbox $('#' + textboxid).val(value); } ```
59,794,999
``` ``` #include <iostream> #include <string> #include <sstream> #include <vector> #include <fstream> using namespace std; bool findCurrentNumber (int currentNumber, int foundNumber) { if (currentNumber == foundNumber) { return true; } return false; } int main() { ifstream inputFile; inputFile.open("C:\\Projects\\data.txt"); if (!inputFile) { cerr << "Error reading file "; } else { int searchCurrentNumber; cout << "Please type in the number you are looking for: "; cin >> searchCurrentNumber; bool foundRelevantSection = false; string delimiter = "energy"; size_t pos = 0; string token; string line; while (getline(inputFile, line)) { while ((pos = line.find(delimiter)) != string::npos) { token = line.substr(0, pos); //check the found token //cout << token << endl; line.erase(0, pos + delimiter.length()); stringstream ss; //store the whole string into stringstream ss << token; string temp; int found; while (!ss.eof()) { //extract the word by word from stream ss >> temp; //Check the given word is integer or not if (stringstream(temp) >> found) cout << "Number found: " << found << " " << endl;; //no space at the end of string temp = ""; } if (findCurrentNumber (searchCurrentNumber, found) == true) { while (getline (inputFile, line)) { if (foundRelevantSection) { //if no matches were found, the function returns "string::npos" if(line.find("total") != string::npos) { //relevant section ends now foundRelevantSection = false; } else { cout << line << endl; } } else { if (line.find("point") != string::npos ) { foundRelevantSection = true; } } } } else { cout << "The number is not equal on this line compared to what is typed in!" << endl; } } } //closes the while-loop } //closes the if/else-statement inputFile.close(); return 0; } ``` ``` Hi all, I would like to parse an input file having this format: > > > ``` > point 152 # energy # 0.5 > 152 152 152 152 152 152 > 152 152 152 152 152 152 > total 0.011 0.049 0.035 > > point 153 # energy # 1.5 > 153 153 153 153 153 153 > 153 153 153 153 153 153 > total 0.015 0.050 0.040 > > ``` > > The code accepts an user-supplied integer and compares it to the number extracted from e.g. the string "point 152 # energy". If the user enters the number "152", the code should give following numbers: > > > ``` > output: > 152 152 152 152 152 152 > 152 152 152 152 152 152 > > ``` > > Unfortunately, my code returns exactly the opposite if number 152 is entered or if number 153 is entered no values are returned. Could anyone help me and tell me what I am doing wrong? I am grateful for any hint! Thanks in advance! Best wishes, DaveS
2020/01/17
[ "https://Stackoverflow.com/questions/59794999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7095595/" ]
Db2 11.5 ModPack 1, ModPack 2 and ModPack 3 (i.e. Db2 11.5.1.0, Db2 11.5.2.0 and Db2 11.5.3.0 respectively ) are available as a container only release For example from <https://www.ibm.com/support/knowledgecenter/en/SSEPGG_11.5.0/com.ibm.db2.luw.wn.doc/doc/c_whats_new_v11-5-1.html> > > This mod pack release is currently available in the following Db2 products: > > > * The single container deployments of Db2 Warehouse and IBM Integrated Analytics System (IIAS) * The container micro-service deployment of Db2 on Red Hat OpenShift * The Db2 cartridge used by IBM Cloud Pak for Data Similar statements are on the what's new pages for 11.5.2 and 11.5.3 See the main What's new page for information on container-only Db2 Mod Pack releases <https://www.ibm.com/support/knowledgecenter/en/SSEPGG_11.5.0/com.ibm.db2.luw.wn.doc/doc/r_whats_new_home.html> > > IBM® offers a number of Db2-based solutions for small to enterprise > size container environments [e.g., Db2 Community Edition, Db2 > Warehouse, the IBM Integrated Analytics System (IIAS)]. > > > These > container-deployed products, and the Db2 engine that powers them, are > released at regular intervals between traditional Db2 on-prem > releases. The Db2 engine for these products is identified using the > Mod Pack numbering scheme currently used in the Db2 product signature. > > > New features that are available in these container-deployed Mod Pack > releases are rolled into a subsequent Db2 on-prem release. The on-prem > release also contains any new features that are available in the > container-deployed release that aligns with its release date. So, each > on-prem release of Db2 aligns with a similarly numbered > container-ready release. > > > Container releases are available from the IBM Cloud Container Registry. E.g. for Db2 Warehouse, see the instructions here <https://www.ibm.com/support/knowledgecenter/SSCJDQ/com.ibm.swg.im.dashdb.doc/admin/get_image.html> The fixlist for Db2 11.5.1.0 and later releases can be found here <https://www.ibm.com/support/pages/fix-list-db2-version-115-linux-unix-and-windows>
301
The arithmetic hierarchy defines the $\Pi\_1$ formulae of arithmetic to be formulae that are provably equivalent to a formula in [prenex normal form](http://en.wikipedia.org/wiki/Prenex_normal_form) that only has universal quantifiers, and $\Sigma\_1$ if it is provably equivalent to a prenex normal form with only existential quantifiers. A formula is $\Delta\_1$ if it is both $\Pi\_1$ and $\Sigma\_1.$ These formulae are often called recursive: why?
2010/07/21
[ "https://math.stackexchange.com/questions/301", "https://math.stackexchange.com", "https://math.stackexchange.com/users/100/" ]
If a formula $\phi(x\_1, ... x\_n)$ is in both $\Sigma\_1, \Pi\_1$, then one can define a Turing machine to determine whether it is true or false. Namely, in parallel, search for a collection of parameters that makes true the existential formula, and search for a collection of formulas that makes false the universal formula. If the first happens, return true; if the second happens, return false. One of these must exist, so the Turing machine always halts. (The set of $x\_1,...x\_n$ such that $\phi(x\_1, ... , x\_n)$ is valid if $\phi$ belongs to $\Sigma\_1$ is, by contrast, is only recursively enumerable.) By contrast, since the action of any Turing machine is simulable by existential formulas in first-order logic (i.e. there exists a number $k$ such that $M$ halts in $k$ steps), any language which is recursively enumerable can be expressed by existential formulas. Any language whose *complement* is recursively enumerable can similarly be expressed by universal formulas (by the analog of deMorgan's laws). So any recursive language (i.e., one which is both recursively enumerable and whose complement is r.e.), can be expressed in both ways.
24,401,957
One thing bothers me, I am developing iOS app. Firstly when hasPerformedFirstLaunch I load core data, it works good. But later, when I'll update my app. I would like to change core data. How can I do this or How you do this? It is an app where a lot of data that will accrue updates. My first launch ``` if (![[NSUserDefaults standardUserDefaults] boolForKey:@"hasPerformedFirstLaunch"]) { [self initialCoreData]; [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"hasPerformedFirstLaunch"]; [[NSUserDefaults standardUserDefaults] synchronize]; } ```
2014/06/25
[ "https://Stackoverflow.com/questions/24401957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3705920/" ]
You may find the [following answer](https://stackoverflow.com/a/16063711/1641941) helpful as it explains prototype, constructor function and the value of `this`. In this case I would not advice doing it like you do. You don't own String and modifying it breaks encapsulation. The only "valid" situation would be if you need to implement an existing method to support older browsers (like Object.create). More info on that [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain#Bad_practice.3A_Extension_of_native_prototypes). You could do what you're doing with: ``` encodeURIComponent( $("body").find("option:selected").first().text() ); ``` So other then liking the other syntax there really isn't any reason for it.
21,206,261
I want to pass value from second activity to first. The second activity starts after first activity. I used `onActivityResult` and simple `Intent`. The code calls first activity but the `toast` not works. SECOND ACTIVITY: ``` @Override public void onBackPressed(){ Intent i = new Intent(this,ae.class); setResult(RESULT_OK, i); i.putExtra("name","name"); startActivityForResult(i,0); } } ``` FIRST ACTIVITY: ``` @Override protected void onActivityResult(int requestCode ,int resultCode ,Intent data ) { super.onActivityResult(requestCode, resultCode, data); String name =getIntent().getExtras().getString("name"); if(resultCode == RESULT_OK){ switch(requestCode){ case 0: if(resultCode == RESULT_OK){ Toast.makeText(this, name, Toast.LENGTH_LONG).show(); } } } ```
2014/01/18
[ "https://Stackoverflow.com/questions/21206261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3182141/" ]
From FirstActivity, start nextActivity like this- ``` startActivityForResult(intent, code); ``` then in SecondActivity, setResult()- ``` Intent intent=new Intent(); intent.putExtra("MESSAGE",message); setResult(2,intent); finish(); ``` and then in FirstActivity, check code in onActivityResult(). You were not getting result because you are starting the second activity by startActivity() only. I hope this will help you surely.
69,811
I just installed drush in my ssh home directory. Is there a drush command for updating all sites inside home directory that have drupal 7? There is to mention that i have also non drupal sites and i would not like drush to mess with these. Thanks
2013/04/12
[ "https://drupal.stackexchange.com/questions/69811", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/14824/" ]
You can simply create a Bash script, and feed in all the folder names in the sites/dir into Drush. See [this script](http://thejaffes.org/2013-01-20/bash-script-updating-drupal-core) for updating a Drupal site; modify it according your needs- Remember that testing is a very important part of every site upgrade. You should include a manual testing phase after the pm-update, and then push each tested site back to the live site as they are found to be working.
69,571,562
According to this reorder rules [reorder Rules](https://i.stack.imgur.com/Pot7C.png) if I have code like this ``` volatile int a = 0; boolean b = false; foo1(){ a= 10; b = true;} foo2(){if(b) {assert a==10;}} ``` Make Thread A to run foo1 and Thread b to run foo2, since a= 10 is a volatile store and b = true is a normal store, then these two statements could possible be reordered, which means in Thread B may have b = true while a!=10? Is that correct? Added: Thanks for your answers! I am just starting to learn about java multi-threading and have been troubled with keyword volatile a lot. Many tutorial talk about the visibility of volatile field, just like "volatile field becomes visible to all readers (other threads in particular) after a write operation completes on it". I have doubt about how could a completed write on field being invisible to other Threads(or CPUS)? As my understanding, a completed write means you have successfully written the filed back to cache, and according to the MESI, all others thread should have an Invalid cache line if this filed have been cached by them. One exception ( Since I am not very familiar with the hardcore, this is just a conjecture )is that maybe the result will be written back to the register instead of cache and I do not know whether there is some protocol to keep consistency in this situation or the volatile make it not to write to register in java. In some situation that looks like "invisible" happens examples: ``` A=0,B=0; thread1{A=1; B=2;} thread2{if(B==2) {A may be 0 here}} ``` suppose the compiler did not reorder it, what makes we see in thread2 is due to the store buffer, and I do not think a write operation in store buffer means a completed write. Since the store buffer and invalidate queue strategy, which make the write on variable A looks like invisible but in fact the write operation has not finished while thread2 read A. Even we make field B volatile, while we set a write operation on field B to the store buffer with memory barriers, thread 2 can read the b value with 0 and finish. As for me, the volatile looks like is not about the visibility of the filed it declared, but more like an edge to make sure that all the writes happens before volatile field write in ThreadA is visible to all operations after volatile field read( volatile read happens after volatile field write in ThreadA has completed ) in another ThreadB. By the way, since I am not an native speakers, I have seen may tutorials with my mother language(also some English tutorials) say that volatile will instruct JVM threads to read the value of volatile variable from main memory and do not cache it locally, and I do not think that is true. Am I right? Anyway, Thanks for your answers, since not a native speakers, I hope I have made my expression clearly.
2021/10/14
[ "https://Stackoverflow.com/questions/69571562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7222983/" ]
I'm pretty sure the assert can fire. I think a volatile load is only an acquire operation (<https://preshing.com/20120913/acquire-and-release-semantics/>) wrt. non-volatile variables, so nothing is stopping load-load reordering. Two `volatile` operations couldn't reorder with each other, but reordering with non-atomic operations is possible in one direction, and you picked the direction without guarantees. (Caveat, I'm not a Java expert; it's possible but unlikely `volatile` has some semantics that require a more expensive implementation.) --- More concrete reasoning is that if the assert can fire when translated into asm for some specific architecture, it must be allowed to fire by the Java memory model. Java `volatile` is (AFAIK) equivalent to C++ `std::atomic` with the default `memory_order_seq_cst`. Thus `foo2` can JIT-compile for ARM64 with a plain load for `b` and an LDAR acquire load for `a`. `ldar` can't reorder with *later* loads/stores, but can with earlier. (Except for `stlr` release stores; ARM64 was specifically designed to make C++ `std::atomic<>` with `memory_order_seq_cst` / Java `volatile` efficient with `ldar` and `stlr`, not having to flush the store buffer immediately on seq\_cst stores, only on seeing an LDAR, so that design gives the minimal amount of ordering necessary to still recover sequential consistency as specified by C++ (and I assume Java).) On many other ISAs, sequential-consistency stores do need to wait for the store buffer to drain itself, so they are in practice ordered wrt. later non-atomic loads. And again on many ISAs, an acquire or SC load is done with a normal load preceded with a *barrier* which blocks loads from crossing it in either direction, [otherwise they wouldn't work](https://preshing.com/20131125/acquire-and-release-fences-dont-work-the-way-youd-expect/). That's why having the volatile load of `a` compile to an acquire-load instruction that just does an acquire *operation* is key to understanding how this can happen in practice. (In x86 asm, all loads are acquire loads and all stores are release stores. Not sequential-release, though; x86's memory model is program order + store buffer with store-forwarding, which allows StoreLoad reordering, so Java `volatile` stores need special asm. **So the assert *can't* fire on x86, except via [compile/JIT-time reordering of the assignments](https://stackoverflow.com/questions/69568946/java-instruction-reordering-and-cpu-memory-reordering).** This is a good example of one reason why testing lock-free code is hard: a failing test can prove there is a problem, but testing on some hardware/software combo can't prove correctness.)
245,657
`startScript.sh` is in `/root/script/startScript.sh` `script1.sh`is in `/root/script/test/script1.sh` `script2.sh` is in `/root/script/test/script2.sh` `startScript.sh` looks like below ``` #!/bin/bash #some code! sh `pwd`/test/script1.sh 2>&1 & sh `pwd`/test/script2.sh 2>&1 & #some code ``` `script2.sh` and `script1.sh` look like below ``` #!/bin/bash > `pwd`/process_ids.txt while true;do echo "The Process: `ps`" >> `pwd`/process_ids.txt #some code to parse the process, etc. and echo it done ``` Here is the thing is, the `process_ids.txt` file is creating in `/root/script`. But according to `scriptx.sh` the `pwd` is `/root/scripts/test/`. I displayed the `pwd` in `scriptx.sh`, it is showing `/root/script/`. How can I get the `pwd` of `scriptx.sh`?
2015/11/26
[ "https://unix.stackexchange.com/questions/245657", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/96601/" ]
Why don't you just add `test/` to the path of the file you're trying to create, i.e. ``` #!/bin/bash > `pwd`/test/process_ids.txt while true;do echo "The Process: `ps`" >> `pwd`/test/process_ids.txt #some code to parse the process, etc. and echo it done ```
30,554,370
I have a webpage which contains while loop, i have assign an id to each element inside the while loop, here is an example: < tagname id="show\_div\_1">< /tagname> The "show\_id\_" is static but "1" is dynamic which comes from loop and it will be increase to 2,3,4 ...etc. Anyone knows how to select such elements using javascript or jquery? Or is there any alternative way to do so?
2015/05/31
[ "https://Stackoverflow.com/questions/30554370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2900561/" ]
Try: ``` $('tagname[id^="show_div_"]'); ```
16,173,835
please somebody can help me to find out what is happened. I have my WCF service which worked fine, and now suddenly I have this error: > > **The server did not provide a meaningful reply; this might be caused by a contract mismatch, a premature session shutdown or an internal > server error** > > > I must tell that it still works when I select some thousands of records, but when the data is huge I receive this error, although before it worked fine! ``` private static string ConnString = "Server=127.0.0.1; Port=5432; Database=DBname; User Id=UName; Password=MyPassword;" DataTable myDT = new DataTable(); NpgsqlConnection myAccessConn = new NpgsqlConnection(ConnString); myAccessConn.Open(); string query = "SELECT * FROM Twitter"; NpgsqlDataAdapter myDataAdapter = new NpgsqlDataAdapter(query, myAccessConn); myDataAdapter.Fill(myDT); foreach (DataRow dr in myDT.Rows) { **WHEN I HAVE TOO MANY RECORDS IT STOPS HERE** ... ``` **web.config** ``` <configuration> <system.web> <compilation debug="false" targetFramework="4.0" /> <httpRuntime maxRequestLength="2147483647" executionTimeout="100000" /> </system.web> <system.diagnostics> <trace autoflush="true" /> <sources> <source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true"> <listeners> <add name="traceListener" type="System.Diagnostics.XmlWriterTraceListener" initializeData="Traces4.svclog"/> </listeners> </source> </sources> </system.diagnostics> <system.serviceModel> <bindings> <basicHttpBinding> <binding name="BasicHttpBinding_IDBService" closeTimeout="00:30:00" openTimeout="00:30:00" receiveTimeout="00:30:00" sendTimeout="00:30:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" messageEncoding="Text" textEncoding="utf-8" transferMode="Streamed" useDefaultWebProxy="true"> <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" /> <security mode="None"> <transport clientCredentialType="None" proxyCredentialType="None" realm="" /> <message clientCredentialType="UserName" algorithmSuite="Default" /> </security> </binding> </basicHttpBinding> </bindings> <client> <endpoint address="" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IDBService" contract="DBServiceReference.IDBService" name="BasicHttpBinding_IDBService" /> </client> <behaviors> <serviceBehaviors> <behavior name=""> <serviceMetadata httpGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="true" /> <dataContractSerializer maxItemsInObjectGraph="2147483646" /> </behavior> </serviceBehaviors> </behaviors> <serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="true" /> </system.serviceModel> </configuration> ``` **client config** (Edited) ``` <configuration> <system.serviceModel> <bindings> <basicHttpBinding> <binding name="BasicHttpBinding_IRouteService" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"> <security mode="None" /> </binding> <binding name="BasicHttpBinding_IDBService" closeTimeout="00:30:00" openTimeout="00:30:00" receiveTimeout="00:30:00" sendTimeout="00:30:00" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" transferMode="Buffered" > <security mode="None" /> </binding> </basicHttpBinding> <customBinding> <binding name="CustomBinding_IRouteService"> <binaryMessageEncoding /> <httpTransport maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" /> </binding> </customBinding> </bindings> <client> <endpoint address="http://dev.virtualearth.net/webservices/v1/routeservice/routeservice.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IRouteService" contract="BingRoutingService.IRouteService" name="BasicHttpBinding_IRouteService" /> <endpoint address="http://dev.virtualearth.net/webservices/v1/routeservice/routeservice.svc/binaryHttp" binding="customBinding" bindingConfiguration="CustomBinding_IRouteService" contract="BingRoutingService.IRouteService" name="CustomBinding_IRouteService" /> <endpoint address="" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IDBService" contract="DBServiceReference.IDBService" name="BasicHttpBinding_IDBService" /> </client> </system.serviceModel> </configuration> ``` In my file **scvlog** I don' t get any exception! I don't have any other idea what else I can do for understand where is the problem. **Please somebody help me!!!**
2013/04/23
[ "https://Stackoverflow.com/questions/16173835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2265919/" ]
A different answer, just in case anyone arrives here as I did looking for a general answer to the question. It seems that the DataContractSerializer that does the donkey-work is incredibly finicky, but doesn't always pass the real error to the client. The server process dies straight after the failure - hence no error can be found. In my case the problem was an enum that was used as flags, but not decorated with the [Flags] attribute (picky or what!). To solve it I created an instance of the serializer and inspected the error in the debugger; here's a code snippet since I have it to hand. **EDIT:** In response to request in comments ... Amended the code snippet to show the helper method I now use. Much the same as before, but in a handy generic wrapper. ``` public static T CheckCanSerialize<T>(this T returnValue) { var lDCS = new System.Runtime.Serialization.DataContractSerializer(typeof(T)); Byte[] lBytes; using (var lMem1 = new IO.MemoryStream()) { lDCS.WriteObject(lMem1, returnValue); lBytes = lMem1.ToArray(); } T lResult; using (var lMem2 = new IO.MemoryStream(lBytes)) { lResult = (T)lDCS.ReadObject(lMem2); } return lResult; } ``` And to use this, instead of returning an object, return the object after calling the helper method, so ``` public MyDodgyObject MyService() { ... do lots of work ... return myResult; } ``` becomes ``` public MyDodgyObject MyService() { ... do lots of work ... return CheckCanSerialize(myResult); } ``` Any errors in serialization are then thrown *before* the service stops paying attention, and so can be analysed in the debugger. Note; I wouldn't recommend leaving the call in production code, it has the overhead of serializing and deserializing the object, without any real benefit once the code is debugged. Hope this helps someone - I've wasted about 3 hours trying to track it down.
493,004
If I have a countable set of intervals $\{ A\_n \}^{\infty}\_{n=1}$ where $A\_n = (n, \infty)$, and take the intersection $ \cap\_{n=1}^{\infty} A\_n $ my assumption is that this set would be $\varnothing$, since $\lim\_{n \to \infty}A\_n$ would be $(\infty,\infty)$. Or in the case of the extended reals where $A\_n = [n, \infty]$, then the same limit would be $[\infty,\infty]$
2013/09/13
[ "https://math.stackexchange.com/questions/493004", "https://math.stackexchange.com", "https://math.stackexchange.com/users/59576/" ]
You can’t toss limits around quite that cavalierly: if you applied the same reasoning to sets $B\_n=\left(-\frac1n,\frac1n\right)$, you’d conclude that $\bigcap\_{n\in\Bbb Z^+}B\_n=(0,0)=\varnothing$, which is false: $\bigcap\_{n\in\Bbb Z^+}B\_n=\{0\}$. However, your conclusion is correct: $\bigcap\_{n\in\Bbb Z^+}A\_n=\varnothing$. The reason is that if $x$ is any real number, then by the Archimedean property there is an $n\_x\in\Bbb Z^+$ such that $n\_x\ge x$. Then $x\notin A\_{n\_x}$, and therefore $x\notin\bigcap\_{n\in\Bbb Z^+}A\_n$. Since this is true of every $x\in\Bbb R$, it must be that $\bigcap\_{n\in\Bbb Z^+}A\_n=\varnothing$.
5,433,393
I'm parsing a doc and I get the following error: ``` Exception in thread "main" java.lang.NumberFormatException: For input string: "null" at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1222) at java.lang.Float.valueOf(Float.java:388) at CentroidGenerator$Centroid.averageLat(CentroidGenerator.java:403) at CentroidGenerator.getCentroids(CentroidGenerator.java:30) at CentroidGenerator.main(CentroidGenerator.java:139) ``` This is the part of code throwing the exception: ``` if (latitude!=null) { //if (!latitude.equals("null")) { String[] latValues = latitude.split(" "); float sum = 0; for (int i = 0; i < latValues.length; i++) { sum = sum + Float.valueOf(latValues[i].trim()).floatValue(); } latitude = Float.toString(sum / (float) latValues.length); //} } ``` As you can see I've tried to check for "null" strings but even uncommenting the second if statement I get the same error. thanks
2011/03/25
[ "https://Stackoverflow.com/questions/5433393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/257022/" ]
Maybe one of the values is "null" (for example, the string : `"123.4 null 5 null"`) not the first one, so I think a proper solution will be: ``` String[] latValues = latitude.split(" "); float sum = 0; for (int i = 0; i < latValues.length; i++) { if (!latValues[i].equals("null")) sum = sum + Float.valueOf(latValues[i].trim()).floatValue(); } latitude = Float.toString(sum / (float) latValues.length); ``` or instead, add try-cath inside the for loop and ignore values that are not numbers. *EDIT* As pointed in comments (Sualeh), it is better to use try / catch because today it's "null" tomorrow it's something else (i.e. double spaces...). ``` try { sum = sum + Float.valueOf(latValues[i].trim()).floatValue(); } catch (NumberFormatException e) { // log e if you want... } ```
7,057,119
I want do hover in a div, append a new div in body part, some code here. but my problem is: now it is not append a new div but replace the first all html. Where is the problem? Thanks. <http://jsfiddle.net/U7QqB/3/> JS ``` jQuery(document).ready(function() { $('.click').hover(function(){ var html = $(this).find('.text').html(); $('body').append('<div id="object"/>').html(html).css({'top':'200px','left':'300px','z-index':'10'}); }); }); ``` css ``` .click{position:realavite;top:100px;left:300px;} .text{display:none;} .object{position:absolute;} ``` html ``` <body> <h1>A hover append div text</h1> <div class="click"> <img src="http://nt3.ggpht.com/news/tbn/U7Q-7enFr00rUM/1.jpg" /> <div class="text">text</div> </div> </body> ```
2011/08/14
[ "https://Stackoverflow.com/questions/7057119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/783396/" ]
That's because [append()](http://api.jquery.com/append/) returns the *original* jQuery object (the one containing the `<body>` element), not a new one containing the appended content. You can use [appendTo()](http://api.jquery.com/appendTo/) instead: ``` $('<div id="object">').appendTo('body').html(html).css({ 'top': '200px', 'left': '300px', 'z-index': '10' }); ```
67,066,812
I have a parent record I need to create, and then a series of child records to create (order not important). Then I need to do a follow-up logging action. I know how to create a chain of single actions on an observable by mapping them together, so, I could do: -- create one parent record, return its id: `createParentRecord(parentInfo: parentType): Observable<number>` -- create one child record, return its id `createChildRecord(childInfo: childType): Observable<number>` -- log the entry `logStuff(parentId: number, childId: number)` -- composite function does all the work, returning the parentId ``` doTheThing(): Observable<number> { /* ... */ let parentId: number; let childId: number; return createParent(parentInfo).pipe( tap(id => (parentId = id)), mergeMap(id => { childInfo.parentId = parentId; return createChildRecord(childInfo);} ), mergeMap(childId => { childInfo.childId = childId; return logStuff(parentId, childId); ), map( () => parentId) ); } ``` Question ======== This works great. BUT if I have childInfo[] rather than childInfo, how do I do this? how do I handle an array of childInfo[] to subscribe to and return inner observable results? I just want a number back of how many succeeded - or just whatever results come back from each observable? Do I use forkJoin()? I can't for the life of me figure this out. Help?
2021/04/12
[ "https://Stackoverflow.com/questions/67066812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3047037/" ]
If I understand right your question, I would proceed like this. Comments are inline ``` function doTheThing(): Observable<any> { /* ... */ let parentId: number; // somehow there is an array of children info to be saved const childInfos = new Array(3).fill({}) return createParent('Parent Info').pipe( tap(id => (parentId = id)), concatMap(id => { // each childInfo is filled with the result of the createParent operation childInfos.forEach(c => c.parentId = parentId); // an array of Observable is created - each one represents a createChildRecord operation const childInfosObs = childInfos.map(ci => createChildRecord(ci)) // all child record operations are executed in parallel via forkJoin return forkJoin(childInfosObs); }), concatMap(childIds => { // forkJoin returns an array of results with the same order as the array of Observables passed to forkJoin // therefore we can loop through the array and set each childInfo with its result childInfos.forEach((ci, i) => ci.childId = childIds[i]) // last thing we do is to log and then return the results of the forkJoin return logStuff(parentId, childIds).pipe( map(() => childIds) ); } ) ); } ``` Note that I use `concatMap` instead of `mergeMap`. Unless there is a specific reason, anytime I do DB or Rest operations I prefer `concatMap` just to keep the sequence of operations. You can also enrich every observable contained in `childInfosObs` with some error handling logic if required, considering that `forkJoin` would error if any of the Observables it tries to execute errors. [Here a stackblitz](https://stackblitz.com/edit/rxjs-ojkd5p?file=index.ts) with an example of the proposed solution.
59,792
I have made this sentence: > > To determine the ending point of this context, we can select the parent node if it encloses the results section, otherwise we should specify another anchor which identifies the ending point of the context or have a common ancestor with the first anchor which encloses the section. > > > I think it may be too long. How would you shorten such sentence?
2015/06/20
[ "https://ell.stackexchange.com/questions/59792", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/11569/" ]
> > To determine the ending point of this context, we can select the > parent node if it encloses the results section, otherwise we should > specify another anchor which identifies the ending point of the > context or have a common ancestor with the first anchor which encloses > the section. > > > **We must determine the ending point of the context. To do so, we can select the parent node if it encloses the results section; if it does not, we must specify another anchor which identifies the ending point of the context.** Your sentence goes off the track (or at least it gets unclear) with "or *have* a common ancestor...". "Have" might be in the wrong number. It might need to be "has". Is the subject "we" or is the subject "another anchor"? In light of your reply in the comments: **...specify another anchor. This anchor must identify the ending point of the context, or it must have a common ancestor with the first anchor that encloses the section.**
217,200
We see that the Elder Wand is able to perform magic that would not normally be possible with a regular wand. For example, in *Harry Potter and the Deathly Hallows*, Harry fixes his broken wand with it: (emphasis mine) > > He laid the broken wand upon the headmaster’s desk, touched it with the very tip of **the Elder Wand**, and said, “Reparo.” > > > As his wand resealed, red sparks flew out of its end. **Harry knew that he had succeeded**. He picked up the holly and phoenix wand and felt a sudden warmth in his fingers, as though wand and hand were rejoicing at their reunion. > > > Previously in this novel, the same spell using *Hermione's* wand (a lesser wand) failed. Knowing that the Elder Wand can perform magic that other wands cannot (from the above example), would the Elder Wand have been able to destroy the Horcruxes using a simple *Bombarda* or something like that? I'm not asking about Fiendfyre, because we know that can destroy Horcruxes, but it's also very dangerous and hard to control. We also can't assume that being able to destroy a Horcrux means that it has the ability to repair it once more. Note for Answerers: Acceptable answers include answers from canon, J.K. Rowling interviews, Pottermore, Wikia *with reliable sources* (so generally no Wikia), and any speculation based on the prior sources listed. Note for Closevoters/Downvoters: This is *not* primarily opinion-based! See the note I left for answerers; I am looking for *official* answers...
2019/08/08
[ "https://scifi.stackexchange.com/questions/217200", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/-1/" ]
Well, any wand can destroy a Horcrux. Fiendfyre is one of the few substances in the magical world which can destroy a Horcrux. > > ‘It must have been Fiendfyre!’ whimpered Hermione, her eyes on the broken pieces. > > > ‘Sorry?’ > > > ‘Fiendfyre – cursed fire – it’s one of the substances that destroy Horcruxes, but I would never, ever have dared use it, it’s so dangerous. How did Crabbe know how to –?’ > > > As for the Elder Wand, I think that basic destructive curses like *Reducto* or *Incendio* would still not be effective since Albus Dumbledore was in the possession of the Gaunt ring for a time and was unable to destroy it with his wand. Instead he used the sword. He was perhaps unwilling to cast such dark and terrible magic as a Fiendfyre. The same thing happened in the cave where the fake Horcrux was hidden. Dumbledore decided to take it with him instead of just destroying it once and for all right then and there. The Elder Wand, while capable of feats of magic beyond normal wands cannot destroy Horcruxes with simple spells.
1,746,248
> > > > > > Question: The number $2$ is a real root of $z^3=8$. Find the distance $|2-w|$ if $w$ is a complex root of $z^3=8$ leaving your answer in surd form. > > > > > > > > > --- What I have attempted: $$z^3=8$$ $$ \frac{z^3}{8} = 1$$ $$ \left(\frac{z}{2} \right)^3 = 1 $$ $$ \frac{z}{2} = \omega^2 , \omega , 1 $$ $$ z = -1±\sqrt{3}i , 2$$ Plotting this on geogebra: [![enter image description here](https://i.stack.imgur.com/MqLbe.png)](https://i.stack.imgur.com/MqLbe.png) I see that it forms an equilateral triangle , how can i find this distance between the 2 complex roots $ z = -1±\sqrt{3}i$ ? The answer is $2\sqrt{3}$ but I am not how this was reached with the distance formula?
2016/04/17
[ "https://math.stackexchange.com/questions/1746248", "https://math.stackexchange.com", "https://math.stackexchange.com/users/298824/" ]
The minimal polynomial of $w$ and $\bar w$ is $z^2+2z+4$. On the other hand, the square of this distance is, by Vieta's relations: $$(2-w)(2-\bar w)=4-2(w+\bar w)+w\bar w=4-2(-2)+4=12$$ whence $\;\lvert 2-w\rvert=2\sqrt 3$.
1,246,512
I'm trying to translate some Common Lisp code into Scheme code. The Common Lisp code has a `deftype`. Are `deftype`s in Scheme the same as `deftype`s in Common Lisp? How do you translate a `deftype` in Common Lisp into equivalent code in Scheme?
2009/08/07
[ "https://Stackoverflow.com/questions/1246512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7648/" ]
Common Lisp `deftype` doesn't have an exact Scheme equivalent. You will have to translate type definitions by hand, or write a `deftype` macro in terms of whatever Scheme record library is available in your system. Bare Scheme doesn't have user-defined types at all. In an R5RS system, you will have to look up the relevant SRFIs (e.g. [SRFI-9 (Record types)](http://srfi.schemers.org/srfi-9/), [SRFI-57 Records](http://srfi.schemers.org/srfi-57/), [SRFI-99 ERR5RS records](http://srfi.schemers.org/srfi-99/)) and also see what SRFIs and language extensions does your particular Scheme system implement; Scheme systems generally aren't very consistent in their implementations of anything beyond the minimal Scheme standard. R6RS Scheme has records [in its standard library](http://www.r6rs.org/final/html/r6rs-lib/r6rs-lib-Z-H-7.html#node_chap_6).
25,681,055
I m new in Anguar js . I have created a **controller** and **pass the data** but my **controller** not working can u please help me . **My code is this** **Angular code is** ``` var app = angular.module('myApp', []); app.controller('myController', function($scope) { $scope.person=[ {name:"Raj", gender:"M"}, {name: "raja", gender:"M"}, {name:"sevitra" gender:"F"} ] }); ``` **HTML Code is** ``` <body ng-app="myApp"> <div controller="myController"> <a href="javascript:void()"> <button>Add New Field</button> </a> <div class="advance-menu-wraper"> <ul> <li> {{"person[0].name"}} + {{"person[0].gender"}} <div class="head-text">Field 1:</div> <div class="description-text"> <a href="#">How many staff members are proficient in Oracla programing</a> </div> </li> <li> <div class="head-text">Field 2:</div> <div class="description-text"> <form name="addForm"> <textarea rows="2"></textarea> <div class="send-btn"> <button> <i class="fa fa-check">Submit</i> </button> </div> </form> </div> </li> </ul> </div> </div> </body> ``` **[Demo link](http://plnkr.co/edit/Ffq0lzR97eneIUXEnZyG?p=preview)**
2014/09/05
[ "https://Stackoverflow.com/questions/25681055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1365428/" ]
Your expression won't work: ``` {{"person[0].name"}} + {{"person[0].gender"}} ``` yields: "{{"person[0].name"}} + {{"person[0].gender"}}" in your html. The correct expression would be: ``` {{person[0].name + person[0].gender}} ``` Moreover you have an syntax error in your array. The last object misses a comma. This is a working plunkr: <http://plnkr.co/edit/R9ojp8TWd7AloRrlPlZh?p=preview>
36,940,291
I am creating an AWS Lambda function that is runned monthly. Each month process some data and write that back to S3 Bucket. Do you know how you can you write a file from AWS Lambda Java to a S3 bucket?
2016/04/29
[ "https://Stackoverflow.com/questions/36940291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4690135/" ]
The same way you can write a file to S3 from any Java application. Use the [AWS SDK for Java](https://aws.amazon.com/sdk-for-java/).
52,008,565
I am relatively new to wordpress plugin development and I have read through the wordpress codex but outside of best practices and simple example of the uninstall functionality I am not getting much in the way of what the plugin can do when the user actually uninstalls it. What I am looking to achieve is when an user uninstalls my plugin a popup appears asking them if they want to just remove the plugin files or the plugin files and all of the content the plugin has uploaded to their site. For a bit more context my plugin's primary function is to migrate data stored on a separate server into the user's instance of wordpress as posts and those posts are what I am looking to remove if the user selects that option. Below is my current setup for the uninstall and when I click uninstall in wordpress, wordpress does uninstall my plugin(removes the plugin folder and files from its directory) but the popup isn't displaying during this process. I originally thought it was a styling issue but the HTML in the popup file isn't being loaded. I have also checked the file path variable and it's the correct path. So I am not sure what is preventing the popup from being displayed and allowing the user to select whether or not the content should be deleted along with the plugin or not. Any help or insight in this matter would be greatly appreciated! uninstall.php ``` <?php //checks to make sure Wordpress is the one requesting the uninstall if (!defined('WP_UNINSTALL_PLUGIN')) { die; } $my_plugin_file_path = trailingslashit(plugin_dir_path(__FILE__)); include $my_plugin_file_path . 'templates/my-plugin-uninstall-popup.php'; ``` my-plugin-uninstall-popup.php ``` <!-- styling for popup --> <!-- end of styling for popup --> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h2 class="modal-title" id="myModalLabel">Uninstall popup</h2> </div> <div class="modal-body"> <form action="<?php echo esc_url( $my_plugin_file_path . 'my-plugin-uninstall-executor.php' ); ?>" method="post"> <label>Do you want to remove the content that this plugin has uploaded?</label> <input id="delete-content-yes" name="delete-content" value="YES" type="radio" />Yes <input id="delete-content-no" name="delete-content" value="NO" type="radio" />No <input type="submit" name="submit" value="Submit" /> </form> </div> </div> </div> ``` my-plugin-uninstall-executor.php ``` <?php if (isset($_POST['delete-content']) && $_POST['delete-content'] === 'YES') //delete content from user's wordpress db ```
2018/08/24
[ "https://Stackoverflow.com/questions/52008565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2383556/" ]
Unfortunately, as far as I know at least, there's no official hook available to display a custom uninstall screen. In older versions of WordPress there used to be an Uninstall confirmation screen -although I'm pretty sure there was no way to hook into it either- but nowadays WordPress simply shows a JS confirmation box ("*Are you sure you want to delete [Plugin Name] and its data?*") before running `uninstall.php` -if found- and deleting its files. What I've seen other plugin developers do in this case is include a custom Uninstall screen in the plugin's Settings / Config page which allows them to do pretty much what you described in your question. It's not an ideal solution as some users might uninstall the plugin the "traditional" way if they're unaware of your custom Uninstall screen so you won't be able to show your confirmation screen/popup, but that's the best you can do at this time. If you want to take it a step further [this answer tells you how to uninstall a plugin programatically](https://wordpress.stackexchange.com/questions/5933/how-to-delete-the-hello-dolly-plugin-automatically). It's pretty old now (2011) but if that still works then maybe you could delete your own plugin after running your custom actions.
34,939,612
Examples: * 1.99 --> $1.99 * 1.9 --> $1.90 * 1 --> $1.00 * 1.005 --> $1.01 * 1.004 --> $1.00 I am using `{{num | currency:'USD':true}}` but it does not show trailing 0s.
2016/01/22
[ "https://Stackoverflow.com/questions/34939612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1250673/" ]
Use this code. Here is a working example <http://plnkr.co/edit/xnN1HnJtTel6WA24GttR?p=preview> `{{num | currency:'USD':true:'1.2-2'}}` ***Explanation :*** ***number\_expression | number[:digitInfo]*** Finally we get a decimal number as text. Find the description. **number\_expression:** An angular expression that will give output a number. **number :** A pipe keyword that is used with pipe operator. **digitInfo :** It defines number format. Now we will understand how to use digitInfo. The syntax for digitInfo is as follows. ***{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}*** Find the description. **minIntegerDigits :** Minimum number of integer digits. Default is 1. (in our case 1) **minFractionDigits :** Minimum number of fraction digits. Default is 0. (in our case 2) **maxFractionDigits :** Maximum number of fraction digits. Default is 3. (in our case 2)
50,474,700
HI I am using nginx and apache (docker per each) Problem: when i open the site.com . i got forbidden error , and the webpage(based on php) working only if I open the following URL: /index.php . or /index . and then all other pages working as it should ``` nginx conf: events { worker_connections 4096; } http { client_max_body_size 150m; server { listen 80; location / { proxy_pass http://site:8080/; } } ``` apache -vhosts conf DocumentRoot /var/www/site ``` <Directory /var/www/site> Options Indexes FollowSymLinks MultiViews AllowOverride All Require all granted </Directory> RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^([^\.]+)$ $1.php [NC,L] ``` I tried to put this: ``` RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^([^\.]+)$ $1.php [NC,L] ``` in htacess file but it is not working
2018/05/22
[ "https://Stackoverflow.com/questions/50474700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9050897/" ]
I used like this on a local server and it loads the proper index php on doc path. Also, try this without your rewrite rule. It could be overriding this setting. ``` DocumentRoot "/var/www/site" <Directory "/var/www/site"> Options Indexes FollowSymLinks Includes AllowOverride All Require all granted </Directory> <IfModule dir_module> DirectoryIndex index.php </IfModule> ```
6,276,805
How do I get Tornado (or in general another server) to handle the .py files on my host, while Apache still handles the php files?
2011/06/08
[ "https://Stackoverflow.com/questions/6276805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/648927/" ]
Since the title and axes are div and not img or canvas I think the only solution would be to write every text in a canvas with the fillText() function. Then convert this to picture. You can write in canvas like that : fillText("Hello World!", x, y); Now you can also add this to jQplot as a plugin :) Good luck
37,864,134
``` id date value ------------------ 1 1 null 1 2 a 1 3 b 1 4 null 2 1 null 2 2 null 2 3 null 2 4 null 2 5 null ``` If value is null in all id's then max of date of that id and if we have value then max of date with value id. Required output is: ``` id date value ----------------- 1 3 b 2 5 null ```
2016/06/16
[ "https://Stackoverflow.com/questions/37864134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2673907/" ]
Typical method for this type of problem is `row_number()`. You can create a CASE expression to define a priority: ``` select id, date, value from ( select id, date, value, row_number() over (partition by id order by case when value is not null then 1 else 2 end asc, date desc) rn from UnnamedTable ) t1 where t1.rn = 1 ```
3,445,924
What is field sequential in 3D? I've been scouring the internet but no luck. The only thing I got was this: Field-Sequential.  In the context of cinema-stereoscopy, the rapid alternation of left and right perspective views projected on the screen. But isn't this the same as frame sequential??
2010/08/10
[ "https://Stackoverflow.com/questions/3445924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/381699/" ]
[reuxables](http://www.nukeation.com/reuxables.aspx) have a free theme and have just included datagrids in their styles. No I don't work there. Bought one of their themes though, and it's great :D
3,703,467
What is the best way to retrieve a custom class name? My goal is to get away from using an enum that describes each variation of my classes as follows: ``` enum { MyDataType1, MyDataType2, MyDataType3 } ``` with each class being implemented as follows: ``` MyDataType1 : IGenericDataType MyDataType2 : IGenericDataType //etc... ``` However, I sometimes need to display a user-friendly name of each class's type. Before I could get this from the enum, but now I would like to get it from class metadata if possible. So instead of MyDataType1.GetType().Name which would display the class name I'd like to use a custom name (without having to define a property in the class).
2010/09/13
[ "https://Stackoverflow.com/questions/3703467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82541/" ]
Have you considered adding a custom attribute to the class that can be then be retrieved through reflection. [Here is Microsoft's quick tutorial to give you an idea how to apply this technique.](http://msdn.microsoft.com/en-us/library/aa288454(VS.71).aspx) Using this method will allow you to add as much additional metadata to your class as needed either through using built in framework attributes or defining your own. [Here is another post that I made that also refers to using extra metadata to do dynamic class loading; which I think is what you are trying to accomplish?](https://stackoverflow.com/questions/3089607/pattern-method-for-c-plugin-functionality/3089656#3089656) Since there were a few question how to do this below is a simple console application that you can run and see first hand how it works. Enjoy! ``` using System; using System.Reflection; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Type[] _types = null; //load up a dll that you would like to introspect. In this example //we are loading the currently executing assemble since all the sample code //is constained within this simple program. In practice you may want to change //this to a string that point to a particual assemble on your file system using //Assembly.LoadFrom("some assembly") Assembly a = Assembly.GetExecutingAssembly(); //get an arrray of the types contained in the dll _types = a.GetTypes(); //loop through the type contained in the assembly looking for //particuar types. foreach (Type t in _types) { //see if this type does not contain the desired interfaec //move to the next one. if (t.GetInterface("CustomInterface") == null) { continue; } //get a reference to the attribute object[] attributes = t.GetCustomAttributes(typeof(CustomAttribute), false); CustomAttribute attribute = (CustomAttribute)attributes[0]; //do something with the attribue Console.WriteLine(attribute.Name); } } } /// <summary> /// This is a sample custom attribute class. Add addtional properties as needed! /// </summary> public class CustomAttribute : Attribute { private string _name = string.Empty; public CustomAttribute(string name) : base() { _name = name; } public string Name { get { return _name; } set { _name = value; } } } /// <summary> /// Here is a custom interface that we can search for while using reflection. /// </summary> public interface CustomInterface { void CustomMethod(); } /// <summary> /// Here is a sample class that implements our custom interface and custom attribute. /// </summary> [CustomAttribute("Some string I would like to assiciate with this class")] public class TestClass : CustomInterface { public TestClass() { } public void CustomMethod() { //do some work } } /// <summary> /// Just another class without the interface or attribute so you can see how to just /// target the class you would like by the interface. /// </summary> public class TestClass2 { public TestClass2() { } public void CustomMethod() { //do some work } } } ```
13,353,771
I have recently completely recoded my site registration form, a lot of my users were complaining that upon registration, they would fill out the form only to be told that the username was already taken, or some other error that meant they would have to retype all of that information. I set off today designing and coding the new registration page, and the resulting response from my users is that it looks more user friendly, and when the "live" validation is included, it will be just right. Anyway, here is how my registration page looks, with the location of the divs that will contain errors; ![Image showing how the design of the form looks](https://i.stack.imgur.com/puUKU.png) For each area of the form, I have added the **same div class** next to it, which I hope I can then hide / unhide depending on what the user has typed in. My issue is, surely if I use that same class for ALL of the fields, it will update ALL of the error fields when I use something like the innerHTML function? jQuery is far from my strong point, and I would really appreciate any help. I will add more information if it is requested, thanks!
2012/11/13
[ "https://Stackoverflow.com/questions/13353771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1205868/" ]
First of all, you should descend from `NSObject`. There is no tangible benefit to not doing so. `NSObject` adds nothing in terms of storage over the lowest level representation of a class but adds an awful lot of behaviour that will allow your classes to act correctly with the runloop, with the normal collections (eg, `NSArray` or `NSDictionary`) and with just about everything else. To answer your question specifically: ``` #import <objc/runtime.h> ... NSLog(@"obj size: %zd", class_getInstanceSize([NSObject class])); ``` Outputs '4' on iOS and '8' on 64-bit OS X. So the answer you're looking for is 'the natural size of an integer'. `NSProxy` is the same size, `UIView` (on iOS) is 84 bytes. Documentation for `class_getInstanceSize` is [here](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/func/class_getInstanceSize) — it explicitly returns "[t]he size in bytes of instances of the class cls", as the name says.
70,664,803
I have a function with a layer that has an import inside of it. When ran, I get the error "*No module named xhtml2pdf*" I have 2 layers that I could import, one for the PDF script and one for the xhtml2pdf module, I don't really want to import both My import of the function in the layer is: > > from PDF import convert\_html\_to\_pdf > > > Inside the layer I have the import > > from xhtml2pdf import pisa > > > Do I need to add the package into my main function using a layer or can I "nest" layers inside of each other? Or, is there a way to install the package inside the same layer as my PDF.py?
2022/01/11
[ "https://Stackoverflow.com/questions/70664803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2772911/" ]
Generally speaking, you should try and have it so the lambda layer is specific to the lambda function, meaning that the lambda function and the layer have a one to one relationship. As the lambda function changes, so does that layer to accommodate more or less libraries required. While lambda layers can indeed be reused across different lambda functions, a one to many relationship for the layer makes it trickier to effectively manage the lambda functions; it's also unlikely that the layer can be re-used as is by different lambda functions, which then means you need more layers. You can see why this could become painful. This then implies that the best solution is to install *all* dependencies your function needs into a single layer. You can find full instructions on how to do this [here](https://stackoverflow.com/a/64462403/3390419).
21,319
I have Time Machine working nicely, making snappshotted backups on a regular basis. The backed up files are easily & quickly available. I would like to make an offsite copy of these backups for ultimate safety. I already have a webhost (Dreamhost) with lots of available space. I'd like to find the best way to transfer these files. Ideally, this system should as many of the following as possible: * Fast * Low-bandwidth * Secure / encrypted on the remote end * Preserving the various snapshots / versions that TM makes * Able to browse the backed up files through standard UNIX shell commands (like "ls") * Reliable: a broken remote backup operation shouldn't render the entire backup unusable * Easy to set up
2009/06/07
[ "https://serverfault.com/questions/21319", "https://serverfault.com", "https://serverfault.com/users/883/" ]
The ideal solution is to create a sparsebundle image and to sync that. This can be most easily done by sharing the drive over the network and pointing Time Machine to it and starting a fresh backup. You can also find information on [creating a custom sparsebundle to use as a Time Machine backup](http://www.macosxhints.com/article.php?story=20080420211034137). The reason to do this is because a sparsebundle stores its data spread over a collection of files (8MB 'bands'). If you have a sparsebundle, you can rync it to the remote server, and rsync can just transfer the bands that have changed. With Time Machine, you typically just append onto the end, so you'll only usually be syncing the last few bands up. Once a given band is full and OS X creates another one, the now-full band won't be written to anymore. It gets copied up one last time, and never touched again. The new band gets copied every time rsync is run until it too fills up and stops being written to. For extra fun, there are options you can pass to hdiutil to create an encrypted disk image, so that if someone breaks into your Dreamhost machine they won't be able to harvest your files.