id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23532700
|
A: That project is created for use with Gradle for Android. Eclipse does not support that yet. It is also distributed as an AAR, which Eclipse does not support. There are recipes for converting AARs into Eclipse-friendly Android library projects that you can try. Otherwise, you will need to reorganize the project code yourself to support the classic Eclipse-style project structure. Mostly, that will involve moving the contents of library/src/main/ into a regular Eclipse Android library project:
*
*The res/ directory and AndroidManifest.xml file would go in the library project root directory
*The java/ directory would be renamed src/ and also go in the library project directory
However, you will have to repeat this process each and every time the library's author updates the library, at least for those updates that you are interested in.
You may wish to see if there is an alternative library that meets your needs but is better packaged for use with Eclipse.
A: Basically there are some changes to be done to eclipse project before importing it to eclipse like src folder.
The project you posted may contains many error since it have two more android project dependency.
I tired to convert above project with its dependency :
Checkout Complete Source Code
There is one more project lib u need to add LIB
| |
doc_23532701
|
const [page, setPage] = useState(1);
const handleSetPage = () => {
setPage(2);
};
return (
<div>
{page === 1 && <ChildPage1 handleSetPage={handleSetPage} /> }
{page === 2 && <ChildPage2 /> }
</div>
)
}
const ChildPage1 = ({handleSetPage}) => {
return (
<button onClick={handleSetPage}>Next page</button>
)
}
it('Continues to next page on button click', () => {
render(<CreateDuty />);
fireEvent.click(screen.getByText('Next page'));
expect('Page 2 text').toBeInTheDocument();
});
Im trying to test that the pages change when button is clicked, but in the test handleSetPage() isnt being called.
How do I pass/wrap/mock the function so it gets called?
A: First of all user events are async, which means you need to wrap your test function in an async function and await the user events.
import React, { useState } from 'react'
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
const Parent = () => {
const [page, setPage] = useState(1);
const handleSetPage = () => {
setPage(2);
};
return (
<div>
{page === 1 && <ChildPage1 handleSetPage={handleSetPage} />}
{page === 2 && <ChildPage2 />}
</div>
)
}
const ChildPage1 = ({ handleSetPage }) => {
return (
<button onClick={handleSetPage}>Next page</button>
)
}
const ChildPage2 = () => {
return (
<div>Page 2 text</div>
)
}
it('Continues to next page on button click', async () => {
render(<Parent />);
const button = screen.getByRole('button');
userEvent.click(button);
const page2Text = await screen.findByText('Page 2 text');
expect(page2Text).toBeInTheDocument();
});
second, you need to find the element that you looking for and expect it. If you expect a string you will get this error:
received value must be an HTMLElement or an SVGElement.
Received has type: string
Received has value: "Page 2 text"
in this example, I get the button by role because there is only one button on the screen. In real-world examples, you can give id's to components that you want to test and use that id to get the component you want.
| |
doc_23532702
|
<script type="text/javascript">
window.print();
window.close();
</script>
A: Try adding a delay before calling window.close()
<script type="text/javascript">
window.print();
setTimeout(window.close, 10000);
</script>
A: I don't think you will get it to work this way. For example in IE the print function will prevent the close function and in many versions of Chrome window.close doesn't work.
There are 2 other ways of doing this:
*
*If possible try to use a print style-sheet by specifying an own stylesheet with media="print". In this stylesheet you can hide things such as navigation menus and choose appropriate colors for printing. details on selfhtml
*If that does not work let the user understand what you are doing: rename your current print-button to "print preview" and let the user close this window when he is done printing. I have seen many other websites do it this way too. You can still call window.print if you like.
| |
doc_23532703
|
Best,
Arno
A: I found the fix myself: explicitly setting the character set to "latin1" when connecting to the database (I had omitted it before). Still wondering why this was changed and why I missed it in the release notes.
| |
doc_23532704
|
What I would like to do is use this Raspberry Pi to forward a TCP traffic to a specific interface:
*
*Open the 127.0.0.1:3100 and use the eth0 interface
*Open the 127.0.0.1:3200 and use the eth1 interface
An application using a proxy trough 127.0.0.1:3100 will have a different IP from the one using the Proxy at 127.0.0.1:3200
Can it be done ? I tried with Squid & Dante, open a Socket5 or HTTP Proxy but I couldn't successfully use one or another connection, always the default.
| |
doc_23532705
|
Here is the code that I have:
RoundedRectangle(cornerRadius: 25, style: .continuous)
.stroke(Color.black, lineWidth: 1)
.frame(width: 100, height: 20, alignment: Alignment.top)
.overlay(
Text(item.category)
.font(.caption.weight(.semibold))
.foregroundColor(.accentColor)
)
This created the following rounded rectangle:
Does anyone know how to make the rounded rectangle the size of the Text inside? So basically, instead of passing a width, I want the RoundedRectangle to expand based on the width of the Text automatically, but also leave some padding.
A: You can try this
Text(item.category)
.font(.caption.weight(.semibold))
.foregroundColor(.accentColor)
.padding(10) // your preference
.overlay(
RoundedRectangle(cornerRadius: 25, style: .continuous)
.stroke(.black, lineWidth: 1)
)
| |
doc_23532706
|
import cv2
# Choose an image to detect faces in
img = cv2.imread('RDJ.png')
# Must convert to grayscale
grayscaled_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#
cv2.imshow('Face Detector', img)
cv2.waitKey()
I have tried to fix it using different things but I cant figure out any solutions.
A: You need to change the penultimate line of your code:
cv2.imshow('Face Detector', grayscaled_img)
Because the image showed is the original.
| |
doc_23532707
|
Example code:
import requests,re
from bs4 import BeautifulSoup
res = requests.get('https://www.example.com')
soup = BeautifulSoup(res.text,'lxml')
links = soup.find_all('a', href=True)
# example_of_affiliate_links = ['http://example.com/click/click?p=1&t=url&s=IDHERE&url=https://www.mywebsite.com/920&f=TXL&name=electronic/ps4/','https://example.net/click/camref:IDhere/destination:https://www.mywebsite.com/product/138/sony-ps4.html']
I want to collect all affiliated links for "mywebsite.com", using the following regex pattern, but it is not capturing any links.
pattern = re.compile(r'([http,https]://www.mywebsite.com\S[\.html,\.php,\&]$)')
Is there a better way to do this?
A: Here's the regex you're looking for:
https?://www.mywebsite.com\S*$
What's wrong with your regex?
([http,https]://www.mywebsite.com\S[\.html,\.php,\&]$)
*
*The braces on each sides are useless
*[] means any of those characters, so in [http,https], you're looking of one character, which might be "h", "t", "t", "p", "s" or ","
*\S only captures one character, your need to add a multiplier after it
*Same thing goes for the [\.html,\.php,\&] part
| |
doc_23532708
|
*
*Start transaction
*Fetch object A
*Update A
*Commit transaction
*Perform a long task with A
*Update A (not necessary within transaction, but it would be nice)
How to accomplish that? I do not want to have locked table during step 5. Steps 1-4 are expected to behave like "SELECT FOR UPDATE". Below is my current code. The method I'm executing is execute(). I'm testing it by executing it from different application instances and I'm checking, if instance A is able to do operations on table while instance B is executing executeJob(job).
@Service
@Slf4j
@Transactional
public class JobExecutionService {
private final Environment environment;
private final TestJobRepository testJobRepository;
private final TestJobResultRepository testJobResultRepository;
@Autowired
public JobExecutionService(Environment environment, TestJobRepository testJobRepository, TestJobResultRepository testJobResultRepository) {
this.environment = environment;
this.testJobRepository = testJobRepository;
this.testJobResultRepository = testJobResultRepository;
}
public void execute() {
TestJob job = getJob();
executeJob(job);
finishJob(job);
}
@Transactional
public TestJob getJob() {
TestJob testJob = testJobRepository.findFirstByStatusOrderByIdAsc(
0
);
testJob.setStatus(1);
testJobRepository.save(testJob);
return testJob;
}
public void executeJob(TestJob testJob) {
log.debug("Execution-0: {}", testJob.toString());
Random random = new Random();
try {
Thread.sleep(random.nextInt(3000) + 1000);
} catch (InterruptedException e) {
log.error("Error", e);
}
log.debug("Execution-1: {}", testJob.toString());
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void finishJob(TestJob testJob) {
testJobResultRepository.save(
new TestJobResult(
null,
testJob.getId(),
environment.getProperty("local.server.port")
)
);
}
}
public interface TestJobRepository extends PagingAndSortingRepository<TestJob, Long>, QueryDslPredicateExecutor<TestJob> {
@Lock(LockModeType.PESSIMISTIC_WRITE)
TestJob findFirstByStatusOrderByIdAsc(Integer status);
}
A: @Transactional on private methods does not work in proxy mode: Does Spring @Transactional attribute work on a private method? The only one public method you have here is execute(), so you could either annotate it or the class as a whole.
(By the way, if you make getJob() and finishJob() public, @Transactional will still not work for them as they are called from execute() method via this and not via proxy generated by transaction management infrastructure).
You could drop @Transactional from your JobExecutionService, move getJob() and finishJob() (or whatever methods should run in independent transactions) as public methods to a new service like TransactionalJobExecutionService and annotate that new service as @Transactional.
| |
doc_23532709
|
It will always be the case that whenever one of the fields has a value, the other one will be null. I know I could create
two different classes, each of them with only one field. Is there a better alternative than creating two different classes?
Here's an example of what I'm trying to accomplish:
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class Foo
{
private Foo(int x, bool asAList = false)
{
if (asAList)
{
Baz = new List<int> { x };
}
else
{
Bar = x;
}
}
public static JObject Get(int x, bool asAList = false)
{
Foo foo = new Foo(x, asAList);
return JObject.FromObject(foo);
}
[JsonProperty(PropertyName = "qwerty", NullValueHandling = NullValueHandling.Ignore)]
public int? Bar { get; set; } = null;
[JsonProperty(PropertyName = "qwerty", NullValueHandling = NullValueHandling.Ignore)]
public List<int> Baz { get; set; } = null;
}
And I'd like to be able to do this:
JObject a = Foo.Get(1);
JObject b = Foo.Get(2, true);
A: You could have one private JToken JsonProperty that is being used for serializing/deserializing to either of the two public facing properties. On a set operation, that would then determine based on the JToken type if it's a JArray or not and then based on that determine which of the other properties to set. On a get operation, it would use the property that isn't null and convert that to the JToken. In order to deserialize you'll want a constructor that can be used the [JsonConstructor] can be added. Since you don't want to serialize/deserialize the other properties directly, the [JsonProperty] attribute can be removed because of the MemberSerialization.OptIn.
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class Foo
{
[JsonConstructor]
private Foo()
{ }
private Foo(int x, bool asAList = false)
{
if (asAList)
Baz = new List<int> { x };
else
Bar = x;
}
public static JObject Get(int x, bool asAList = false)
{
Foo foo = new Foo(x, asAList);
return JObject.FromObject(foo);
}
[JsonProperty(PropertyName = "qwerty", NullValueHandling = NullValueHandling.Ignore)]
private JToken Qwerty
{
get
{
return Bar.HasValue ? JToken.FromObject(Bar) : Baz != null ? JToken.FromObject(Baz) : null;
}
set
{
if (value != null && value.Type == JTokenType.Array)
Baz = value?.ToObject<List<int>>();
else
Bar = value?.ToObject<int?>();
}
}
public int? Bar { get; set; }
public List<int> Baz { get; set; }
}
| |
doc_23532710
|
The login and register forms are there http://localhost:8000/login but after login if I go to my route (http://localhost:8000/api/categories) inside the middleware I am redirected to the home page. If I have the route outside the middleware it works but without requiring a login.
** Works ** (at least the 'Category' view shows)
Route::controller(App\Http\Controllers\API\CategoryController::class)->group(function(){
Route::get('categories', 'index')->name('categories.index')
});
** Does Not work ** (redirects to home view)
Route::group(['middleware' => 'auth:api'], function(){
Route::controller(App\Http\Controllers\API\CategoryController::class)->group(function(){
Route::get('categories', 'index')->name('categories.index')
});
});
** CategoryController**
<?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Category;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
class CategoryController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$cat = $this->getCategories();
return response()->json($cat);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$cat = $this->getCategories();
return view('create-category',compact('cat'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
return Auth::user();
$category = Category::firstOrCreate(
['name' => $role_name],
['guard_name' => 'api']
);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$cat = $this->getCategories($id);
// $cat = Category::where('id', $id)->get()->keyBy('id');
return response()->json($cat);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
public function getParentCategory($id) {
$cat = Category::where('id', $id)->get()->keyBy('id');
return $cat;
}
public function getChildCategory($id, $keyBy = null) {
// return $keyBy;
$cat = Category::where('parent_id', $id)->get()->keyBy('id');
return $cat;
}
private function setKeyBy($collection, $name) {
$collection = $collection->keyBy($name);
return $collection;
}
public function getCategories($category_id = null) {
$cat = Category::where('id', '>', 0);
if(!is_null($category_id)) {
$cat = $cat->where('id', $category_id)->get()->keyBy('id');
} else {
$cat = $cat->whereNull('parent_id')->get()->keyBy('id');
foreach($cat as $catID=>$catArray) {
$subCat = $this->getChildCategory($catID, 'id');
// $subCat = $subCat->keyBy('id');
if ($subCat->first()) {
$cat[$catID]['subcat'] = $subCat;
}
}
}
return $cat;
}
public function createCategoryForm() {
$cat = $this->getCategories();
return view('create-category',compact('cat'));
}
public function categoryDropown($child_id = null) {
$cat = $this->getCategories();
}
public function categoryChildDropown($child_id) {
$cat = Category::where('parent_id', $child_id)->get();
return $cat;
}
}
I have used Laravel for a while now but this is the first time creating an app from scratch with Auth. I do not know what I am missing. TIA
A: You can try this:
$router->group(['middleware' => 'auth'], function() use ($router) {
Route::controller(App\Http\Controllers\API\CategoryController::class)->group(function(){
Route::get('categories', 'index')->name('categories.index')
});
});
A: Thanks to Dream Bold for pointing me in the right direction. I should have posted the web.php and api.php files. I found the answer here https://stackoverflow.com/a/35162656/1198563
I had the route in the api.php Once I moved it into web.php, into the web middleware group and in the api middleware group it works.
Route::group(['middleware' => 'web'], function () {
Route::auth();
// Moving here will ensure that sessions, csrf, etc. is included in all these routes
Route::group(['prefix' => 'api', 'middleware' => 'auth'], function () {
Route::controller(App\Http\Controllers\API\CategoryController::class)->group(function () {
Route::get('categories', 'index')->name('categories.index');//->middleware('auth');
});
});
});
| |
doc_23532711
|
A: To get the "anchor part" of the current page, you can use:
var hash = window.location.hash;
Then, based on your question link, you want to send it to a PHP script. You can do this with a JavaScript redirect like so:
window.location = "myscript.php?hash=" + encodeURIComponent(hash);
However, this won't work for users without JavaScript enabled, so be sure to have a <noscript> message ready!
A: You could use a regular expression:
var url = "http://nhs/search-panel.php#?patientid=2";
var hash = url.match(/^[^#]*#(.*)/)[1];
See also doing substring in window.location.hash
| |
doc_23532712
|
my_rhs = [1.0, 1.0, 0.0, 0.0, 0.0,\ #comment1
-1.0, -1.0, -1.0,\ #comment2
0.0, 0.0, 0.0]
but when I do this Python gives an error. How can I comment in the places shown? I tried defining each line as a new list and using + to append but that doesn't seem to work either. Like below
my_rhs = [1.0, 1.0, 0.0, 0.0, 0.0]+\ #comment1
[-1.0, -1.0, -1.0]+\ #comment2
[0.0, 0.0, 0.0]
How can I comment in the shown locations without Python giving an error?
A: You simply need to remove the backslash characters:
my_rhs = [1.0, 1.0, 0.0, 0.0, 0.0, # comment1
-1.0, -1.0, -1.0, # comment2
0.0, 0.0, 0.0]
Below is a demonstration:
>>> my_rhs = [1.0, 1.0, 0.0, 0.0, 0.0, # comment1
... -1.0, -1.0, -1.0, # comment2
... 0.0, 0.0, 0.0]
>>> my_rhs
[1.0, 1.0, 0.0, 0.0, 0.0, -1.0, -1.0, -1.0, 0.0, 0.0, 0.0]
>>>
The \ character tells Python that the following line is part of the current line. So, it interprets this:
my_rhs = [1.0, 1.0, 0.0, 0.0, 0.0,\ #comment1
-1.0, -1.0, -1.0,\ #comment2
0.0, 0.0, 0.0]
As being equivalent to this:
my_rhs = [1.0, 1.0, 0.0, 0.0, 0.0, #comment1 -1.0, -1.0, -1.0, #comment2 0.0, 0.0, 0.0]
It is noteworthy that PEP 8, the official style-guide for Python code, has a section on wrapping long lines:
The preferred way of wrapping long lines is by using Python's implied
line continuation inside parentheses, brackets and braces. Long lines
can be broken over multiple lines by wrapping expressions in
parentheses. These should be used in preference to using a backslash
for line continuation.
This excerpt from Explicit Line Joining is also relevant:
A line ending in a backslash cannot carry a comment. A backslash does
not continue a comment. A backslash does not continue a token except
for string literals (i.e., tokens other than string literals cannot be
split across physical lines using a backslash). A backslash is illegal
elsewhere on a line outside a string literal.
| |
doc_23532713
|
EDIT:
Here's some code
class Spider(CrawlSpider):
name = 'spider'
user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'
def __init__(self, mode, *args, **kwargs):
if mode == 'scan':
self.start_urls = ['https://www.example.com/']
self.rules = (Rule (callback="parse_obj", follow=False),
)
self.custom_settings = {
'COMPRESSION_ENABLED': True,
'URLLENGTH_LIMIT': 100,
'DOWNLOAD_DELAY': 1
}
elif mode == 'crawl':
# something else
super(Spider, self).__init__(*args, **kwargs)
| |
doc_23532714
|
I'm getting the error Type Mismatch: cannot convert from Map<Long,Program> to TreeMap<Long,Firefox>. Doesn't matter if Program is an interface or superclass.
How do I overcome this issue?
A: Try this one
class MyMap<K,T extends Program> extends TreeMap<K,Program>{
private static final long serialVersionUID = 1L;
}
interface Program{
}
class Firefox implements Program{
}
And here is your code
Map<Long, Program> map=new MyMap<Long,Firefox>();
map.put(1L, new Firefox());
| |
doc_23532715
|
char[] model, float version, int price, char[] color;
I am reading from a file that has lines where each line fills one struct. Here is an example of a couple lines from the file:
F150 5.4 28000 white
RAM1500 5.7 32000 orange
So if I'm reading the first line, I want to save F150 in char[] model, 5.7 in float version, 28000 in int price, and white in char[] color all in the struct stored in the first spot of the array.
I am unsure as to how to traverse the text file and assign the different variables to each struct in the array, any help would be greatly appreciated.
My current code for the accessing and reading of this file is here:
void accessFile(char *fn) {
struct vehicle *array;
int count = 0;
char line[100];
FILE *fp = fopen(fn, "r");
while(fgets(line, sizeof(line), fp) != 0) {
count++;
}
array = (struct vehicle *) malloc(count * sizeof(struct vehicle));
rewind(fp);
while(fgets(line, sizeof(line), fp) != 0) {
count++;
}
}
I ran through the file the first time to find the lines in the file in order to know how large to create the array. My plan is to assign each line with their corresponding variables in each struct, but I'm struggling with the syntax for how to differentiate between the individual parts of each line.
A: You can sscanf() to split the line.
Since I was bored, I did this:
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
char* model;
float version;
int price;
char* color;
}
vehicle;
bool vehicle_create( vehicle* v, const char* model, float version, int price, const char* color )
{
v->model = strdup( model );
if (!(v->model)) return false;
v->version = version;
v->price = price;
v->color = strdup( color );
if (v->color) return true;
free( v->model );
return false;
}
void vehicle_destroy( vehicle* v )
{
if (!v) return;
if (v->model) free( v->model ); v->model = NULL;
if (v->color) free( v->color ); v->color = NULL;
}
bool read_vehicle( FILE* f, vehicle* v )
{
char model[ 50 ];
char color[ 50 ];
char line[ 200 ];
float version;
int price;
if (!fgets( line, sizeof(line), f ))
return false;
if (4 != sscanf( line, "%50s %f %d %50s", model, &version, &price, color ))
return false;
return vehicle_create( v, model, version, price, color );
}
size_t read_vehicle_inventory( FILE* f, vehicle* vs, size_t n )
{
size_t count = 0;
while (count < n
&& read_vehicle( f, vs + count ))
count += 1;
return count;
}
int main()
{
const size_t MAX_INVENTORY_SIZE = 100;
vehicle inventory[ MAX_INVENTORY_SIZE ];
size_t inventory_size = 0;
// Load inventory from file
inventory_size = read_vehicle_inventory( stdin, inventory, MAX_INVENTORY_SIZE );
printf( "inventory size = %d\n", (int)inventory_size );
// Display the inventory
for (size_t n = 0; n < inventory_size; n++)
printf( "%s %s %f is $%d\n",
inventory[ n ].color,
inventory[ n ].model,
inventory[ n ].version,
inventory[ n ].price );
// Free inventory
for (size_t n = 0; n < inventory_size; n++)
vehicle_destroy( inventory + n );
return 0;
}
Enjoy.
| |
doc_23532716
|
I need a generic stored procedure for a given table which can be used to process updates to a row. I want to build it so that if I am only updating a few columns (of potentially many), then I only send in those few parameters (reducing payload to the db, reducing lines of code, etc). If any parameters are not present then the column doesn't get updated.
Currently, all parameters (e.g. 1 for each column) default to NULL. Then, if the value is NULL, then the column doesn't get updated. If the parameter is not null, e.g. a value was passed, the column is updated with the new value.
Given this, How can I handle instances where the app needs to do an update to a column which currently has a value, but it needs to be set to Null, while still keeping the ability to only pass in parameters for columns which need to change?
I don't want to pass every parameter every time an update needs to occur, for reasons explained above.
Here is what I have. As you can see, currently, if the input value for a column is null, we don't set a new value.
CREATE PROCEDURE [dbo].[bfsp_update_MEMBER]
(
@IN_id INT = NULL,
@IN_orig_id INT = NULL,
@IN_flags INT = NULL,
@IN_member_flags INT = NULL,
@IN_role_flags INT = NULL,
@IN_validation_flags INT = NULL,
@IN_login_id VARCHAR(150) = NULL,
@IN_email VARCHAR(255) = NULL,
@IN_password_crypt VARCHAR(65) = NULL
)
AS
BEGIN
DECLARE @iNewestIdentity as INT;
/* convert '' to null on char and varchar cols */
SET @IN_login_id = CASE WHEN LTRIM(RTRIM(@IN_login_id)) = '' THEN NULL ELSE @IN_login_id END
SET @IN_email = CASE WHEN LTRIM(RTRIM(@IN_email)) = '' THEN NULL ELSE @IN_email END
SET @IN_password_crypt = CASE WHEN LTRIM(RTRIM(@IN_password_crypt)) = '' THEN NULL ELSE @IN_password_crypt END
/* log the data */
INSERT INTO MEMBERS
(
--ID,
ORIG_ID,
SEQ,
SRC_MEMBER_ID,
FLAGS,
MEMBER_FLAGS,
ROLE_FLAGS,
VALIDATION_FLAGS,
LOGIN_ID,
EMAIL,
PASSWORD_CRYPT
)
SELECT
M.ORIG_ID,
M.SEQ + 1 SEQ,
M.SRC_MEMBER_ID,
ISNULL(@IN_flags, M.FLAGS) | 8 FLAGS,
ISNULL(@IN_member_flags, M.MEMBER_FLAGS) MEMBER_FLAGS,
ISNULL(@IN_role_flags, M.ROLE_FLAGS) ROLE_FLAGS,
ISNULL(@IN_validation_flags, M.VALIDATION_FLAGS) VALIDATION_FLAGS,
ISNULL(@IN_login_id, M.LOGIN_ID) LOGIN_ID,
ISNULL(@IN_email, M.EMAIL) EMAIL,
ISNULL(@IN_password_crypt, M.PASSWORD_CRYPT) PASSWORD_CRYPT
FROM
bfv_MEMBERS M
WHERE
M.FLAGS & 8 = 8 AND
M.ORIG_ID = @IN_orig_id
--AND M.ID = @IN_id /* dont really need this right? e.g. can pass in orig_id and use that since it only looks for the current row */
;
SET @iNewestIdentity = SCOPE_IDENTITY();
/* set old row to inactive */
UPDATE
MEMBERS
SET
FLAGS = FLAGS &~ 8
WHERE
ID = @IN_id /* need the id here as opposed to orig_id */
;
RETURN
END
| |
doc_23532717
|
Here is the code:
plt.figure()
plt.scatter(x[:2], y[:2], s=100, c='red', label='Tall students')
plt.scatter(x[2:], y[2:], s=100, c='blue', label='Short students')
plt.show()
My problem is that if I run the code twice I get two images like this:
If I run it again, I get only a single plot.
Is there any way to make sure I get only 1 plot here?
A: plt.clf() will clear the current figure. plt.cla() will clear all subplots.
| |
doc_23532718
|
Source: https://testdriven.io/blog/built-in-permission-classes-drf/
In this blog there is statement:
DEFAULT_PERMISSION_CLASSES will only work for the views or objects that don't have permissions explicitly set.
You don't necessarily need to use built-in classes here. You can use your own custom classes as well.
Question: What does set permissions explicitly means?
A: it means telling django which permission class it should use for this specific view
in this example I'm telling django to use the IsAuthenticated class rather
than using the default permissions class which is defined in the settings.py file
class ExampleView(APIView):
permission_classes = [IsAuthenticated]
def get(self, request, format=None):
content = {
'status': 'request was permitted'
}
return Response(content)
| |
doc_23532719
|
NOTE: These two DFs are not aligned and I am also curious what happens if some values are missing.
Thanks and Cheers:
DF1:
Chromosome;RXN;ID
1009250;q9hxn4;NA
1010820;p16256;NA
31783;p16588;"PNTOt4;PNTOt4pp"
203;3-DEHYDROQUINATE-DEHYDRATASE-RXN;"DHQTi;DQDH"
DF2:
Chromosome;Count1;Count2;Count3;Count4;Count5
203;1;31;1;0;0;0
1010820;152;7;0;11;4
1009250;5;0;0;17;0
31783;1;0;0;0;0;0
Expected Result:
Chromosome;RXN;Count1;Count2;Count3;Count4;Count5
1009250;q9hxn4;5;0;0;17;0
1010820;p16256;152;7;0;11;4
31783;p16588;1;0;0;0;0
203;3-DEHYDROQUINATE-DEHYDRATASE-RXN;1;31;1;0;0;0
A: If I understand your request correctly, this should do it in Python. I've made the Chromosome column into the index of each DataFrame.
from io import StringIO
txt1 = '''Chromosome;RXN;ID
1009250;q9hxn4;NA
1010820;p16256;NA
31783;p16588;"PNTOt4;PNTOt4pp"
203;3-DEHYDROQUINATE-DEHYDRATASE-RXN;"DHQTi;DQDH"'''
txt2 = """Chromosome;Count1;Count2;Count3;Count4;Count5;Count6
203;1;31;1;0;0;0
1010820;152;7;0;11;4
1009250;5;0;0;17;0
31783;1;0;0;0;0;0"""
df1 = pd.read_csv(
StringIO(txt1),
sep=';',
index_col=0,
header=0
)
df2 = pd.read_csv(
StringIO(txt2),
sep=';',
index_col=0,
header=0
)
DF1:
RXN ID
Chromosome
1009250 q9hxn4 NaN
1010820 p16256 NaN
31783 p16588 PNTOt4;PNTOt4pp
203 3-DEHYDROQUINATE-DEHYDRATASE-RXN DHQTi;DQDH
DF2:
Count1 Count2 Count3 Count4 Count5 Count6
Chromosome
203 1 31 1 0 0 0.0
1010820 152 7 0 11 4 NaN
1009250 5 0 0 17 0 NaN
31783 1 0 0 0 0 0.0
result = pd.concat(
[df1.sort_index(), df2.sort_index()],
axis=1
)
print(result)
RXN ID Count1 Count2 Count3 Count4 Count5 Count6
Chromosome
203 3-DEHYDROQUINATE-DEHYDRATASE-RXN DHQTi;DQDH 1 31 1 0 0 0.0
31783 p16588 PNTOt4;PNTOt4pp 1 0 0 0 0 0.0
1009250 q9hxn4 NaN 5 0 0 17 0 NaN
1010820 p16256 NaN 152 7 0 11 4 NaN
The concat command also handles mismatched indices by simply filling in NaN values for columns in e.g. df1 if df2 doesn't have have the same index, and vice versa.
A: As bash was mentioned in the text body, I offer you an awk solution. The dataframes are in files df1 and df2:
$ awk '
BEGIN {
FS=OFS=";" # input and output field delimiters
}
NR==FNR { # process df1
a[$1]=$2 # hash to an array, 1st is the key, 2nd the value
next # process next record
}
{ # process df2
$2=(a[$1] OFS $2) # prepend RXN field to 2nd field of df2
}1' df1 df2 # 1 is output command, mind the file order
The 2 last lines could be written perhaps more clearly:
...
{
print $1,a[$1],$2,$3,$4,$5,$6
}' df1 df2
Output:
Chromosome;RXN;Count1;Count2;Count3;Count4;Count5
203;3-DEHYDROQUINATE-DEHYDRATASE-RXN;1;31;1;0;0;0
1010820;p16256;152;7;0;11;4
1009250;q9hxn4;5;0;0;17;0
31783;p16588;1;0;0;0;0;0
Output will be in the order of df2. Chromosome present in df1 but not in df2 will not be included. Chromosome in df2 but not in df1 will be output from df2 with empty RXN field. Also, if there are duplicate chromosomes in df1, the last one is used. This can be fixed if it is an issue.
| |
doc_23532720
|
I get a lot of things to work, but I always have one problem and can´t find the source.
Here is the basis of my Code written in C++Builder 10 on Windows 10.
> //---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#define Characteristic_UUID "{6e400003-b5a3-f393-e0a9-e50e24dcca9e}"
#define Service_UUID "{6e400001-b5a3-f393-e0a9-e50e24dcca9e}"
#pragma resource "*.dfm"
TForm1 *Form1;
TBluetoothLEDevice* device;
TBluetoothGattCharacteristicList* characteristic ;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
BluetoothLE1->DiscoverDevices(100);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::BluetoothLE1EndDiscoverDevices(TObject * const Sender, TBluetoothLEDeviceList * const ADeviceList)
{
device = ADeviceList->First();
BluetoothLE1->DiscoverServices(device);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::BluetoothLE1ServicesDiscovered(TObject * const Sender, TBluetoothGattServiceList * const AServiceList)
{
GUID AGuid;
CLSIDFromString(TEXT(Service_UUID), &AGuid);
TBluetoothGattService* service = BluetoothLE1->GetService(device,AGuid);
//TBluetoothGattServiceList* abcd = BluetoothLE1->GetServices(device);
CLSIDFromString(TEXT(Characteristic_UUID), &AGuid);
characteristic = BluetoothLE1->GetCharacteristics(service);
while(characteristic->First()->UUID != AGuid)
{
characteristic->Delete(0);
}
if(characteristic->First()!= NULL);
BluetoothLE1->SubscribeToCharacteristic(device,characteristic->First());
}
//---------------------------------------------------------------------------
void __fastcall TForm1::BluetoothLE1CharacteristicRead(TObject * const Sender, TBluetoothGattCharacteristic * const ACharacteristic,
TBluetoothGattStatus AGattStatus)
{
static long i;
Label1->Caption = i;
i++;
}
//---------------------------------------------------------------------------
After exactly 86303 Notifys (calling BluetoothLE1CharacteristicRead) I get a Stack Overflow. So there must be something wrong.
At the beginning i wrote the program in Visual Studio in C++ with the Windows Drivers Functions, but same thing.
A: I have found the problem.
It is a bug in the Win32 Bluetooth APIs.
With Windows Update KB3156421 every program crashes after one notification and Mircosoft gives a workaround. Link
That workaround fixes my problem above too.
| |
doc_23532721
|
{
"_id": "29763f342ab34fd7b579fd4546aaed93",
"_rev": "3-f56dccaa214f3e9fce1e1e3e32e710a2",
"client_id": "sse",
"outcomes": [
{
"contact": "phone",
"type": "phone_outbound",
"attempt": "1",
"provider_id": "123456789",
"status_outbound": "noanswer"
},
{
"contact": "phone",
"type": "phone_outbound",
"attempt": "1",
"provider_id": "123456789",
"status_outbound": "noanswer"
}
]
}
and a map function like this:
function(doc) {
for(i=0;i<doc.outcomes.length;i++)
{
emit(null, {'client_id':doc.client_id,'outcome':doc.outcomes[i]});
}
}
the result i get per generated row is:
{client_id: "sse", outcome: { contact: "phone", type: "phone_outbound",
attempt: "1", provider_id: "123456789", status_outbound: "noanswer" }}
rather than
{client_id: "sse", contact: "phone", type: "phone_outbound",
attempt: "1", provider_id: "123456789", status_outbound: "noanswer"}
see the extra 'outcome:' and parenthesis in the first example output? Thats what I don't want. Obviously my view is wrong but I cant work out how to achieve my goal. Can anyone assist? The key needs to remain null.
The reason I'm not referencing each field by name ie doc.contact is that I'd like to take advantage of the schemaless nature of it all. If I add an extra field to 'outcomes' i'd like to able to report on it without adding it explicitly to the map function.
A: doc.outcomes[i].client_id = doc.client_id;
emit(null, doc.outcomes[i]);
| |
doc_23532722
|
please see the formula in B3, and pls put the array formula in C3. that must give the same result in Col B.
Thank you
here is the sheet
https://docs.google.com/spreadsheets/d/10fxGKhiBwFfv1osdwTI3wu8i3knqmKQKHC8V1ffca5M/edit#gid=107749899
A: try:
=ARRAYFORMULA(IFNA(VLOOKUP(A3:A,
SORTN(SORT({Individual!C3:C,
ROW(Individual!C3:C),
Individual!A3:E}, 2, 0), 9^9, 2, 2, 0), 7, 0)))
| |
doc_23532723
|
Can anyone review my section of code and tell me what my error is? I'm pulling my hair-out on this.
This is a simple school project. I don't care to change the code to use mysqli
Error: syntax error , unexpected "", expecting identifier (t_string)
or variable (t_variable) or number (t_num_string)
Thanks!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
form{
width: 400px;
height: 600px;
border: 1px solid black;
display: block;
margin: 0 auto;
}
span{
display: block;
}
</style>
</head>
<body>
<?php
// A simple PHP script demonstrating how to connect to MySQL.
// Provides a form for adding, and deleting a student record to the database
$servername = getenv('IP');
$username = getenv('JSMITH');
$password = "1234";
$database = "JSMITH";
$dbport = 3306;
// Create connection
$db = new mysqli($servername, $username, $password, $database, $dbport);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
echo "Connected successfully (".$db->host_info.")";
$thisPHP = $_SERVER['PHP_SELF'];
echo <<<EOE
<form action="$thisPHP" method="POST">
Name:</span>
<input type="text" name="Name"><br>
<span>Address:</span>
<input type="text" name="Address"><br>
<span>Phone:</span>
<input type="number" name="Phone_number"><br>
<span>Email:</span>
<input type="text" name="Email">
<span>Avaliability:</span>
<input type="radio" name="Avaliable" value="Now">Now: (< 1 Month) <br>
<input type="radio" name="Avaliable" value="Soon" >Soon: (1-3 months)<br>
<input type="radio" name="Avaliable" value="Exploring">Upcoming: (3+ months)<br>
<span>Company:</span>
<input type="text" name="Company"><br>
<span>Job:</span>
<input type="text" name="Job"><br>
<span>Description:</span>
<input type="text" name="Description"><br>
<span>Skills</span>
<select name="Skill">
<option value="SQL">SQL</option>
<option value="Java">Java</option>
<option value="HTML">HTML</option>
<option value="Javascript">Javascript</option>
<option value="C++">C++</option>
<option value="C#">C#</option>
<option value="XML">XML</option>
<option value="C">C</option>
<option value="Perl">Perl</option>
<option value="Python">Python</option>
<option value="PHP">PHP</option>
</select>
<span>Experience:</span>
<select name="Period">
<option value="0" >0</option>
<option value="1-3">1-3</option>
<option value="3-5">3-5</option>
<option value="5-10">5-10</option>
<option value="10+">10+</option>
</select>
<br>
<span>Position:</span>
<input type="radio" name="Position" value="Team-Member" >Team-Member<br>
<input type="radio" name="Position" value="Team Leader">Team Leader<br>
<input type="radio" name="Position" value="Executive">Executive<br>
<input type="submit" name="Add" value="Add"><br>
</form>
EOT;
// Start executing the script
{
$Name = $_POST["Name"];
$Address = $_POST["Address"];
$Phone = $_POST["Phone"];
$Email = $_POST["Email"];
$Availability = $_POST['Availability'];
$Company = $_POST["Company Name"];
$Job = $_POST['Job Title'];
$description = $_POST['Description'];
$Skill = $_POST['Skill'];
$Period = $_POST['Period'];
$Position = $_POST['Position'];
$Update=$_POST["Update"];
if(!empty($Name)){
$sql="INSERT INTO employee(Name, Address, Phone, Email, Availability, Company Name, Job Title, Description, Skill, Period, Position)
VALUES ('$Name','$Address','$Phone','$Email','$Avaliabilty','$Company','$Job','$Description','$Period','$Skill','$Position')";
if($db->query($sql) == TRUE){
echo ("Record added");
}
}
if (isset($Update)){
$sql="UPDATE employee SET Address='$Address',Phone='$Phone',Email='$Email',Availability='$Availability',Company='$Company',Job='$Job',Description='$Description',Skill = '$Skill',Period='$Period',Position='$Position' WHERE Name='$Name' ";
$db->query($sql);
}
$db->close();
?>
A: add ?> before <form action="$thisPHP" method="POST"> and add <?php before the line // Start executing the script and check what happens!
A: Check below code I have corrected the form and removed the `{' which was causing the error
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
form{
width: 400px;
height: 600px;
border: 1px solid black;
display: block;
margin: 0 auto;
}
span{
display: block;
}
</style>
</head>
<body>
<?php
// A simple PHP script demonstrating how to connect to MySQL.
// Provides a form for adding, and deleting a student record to the database
$servername = getenv('IP');
$username = getenv('JSMITH');
$password = "1234";
$database = "JSMITH";
$dbport = "3306";
// Create connection
$db = new mysqli($servername, $username, $password, $database, $dbport);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
echo "Connected successfully (".$db->host_info.")";
$thisPHP = $_SERVER['PHP_SELF'];
?>
<form action="$thisPHP" method="POST">
Name:</span>
<input type="text" name="Name"><br>
<span>Address:</span>
<input type="text" name="Address"><br>
<span>Phone:</span>
<input type="number" name="Phone_number"><br>
<span>Email:</span>
<input type="text" name="Email">
<span>Avaliability:</span>
<input type="radio" name="Avaliable" value="Now">Now: (< 1 Month) <br>
<input type="radio" name="Avaliable" value="Soon" >Soon: (1-3 months)<br>
<input type="radio" name="Avaliable" value="Exploring">Upcoming: (3+ months)<br>
<span>Company:</span>
<input type="text" name="Company"><br>
<span>Job:</span>
<input type="text" name="Job"><br>
<span>Description:</span>
<input type="text" name="Description"><br>
<span>Skills</span>
<select name="Skill">
<option value="SQL">SQL</option>
<option value="Java">Java</option>
<option value="HTML">HTML</option>
<option value="Javascript">Javascript</option>
<option value="C++">C++</option>
<option value="C#">C#</option>
<option value="XML">XML</option>
<option value="C">C</option>
<option value="Perl">Perl</option>
<option value="Python">Python</option>
<option value="PHP">PHP</option>
</select>
<span>Experience:</span>
<select name="Period">
<option value="0" >0</option>
<option value="1-3">1-3</option>
<option value="3-5">3-5</option>
<option value="5-10">5-10</option>
<option value="10+">10+</option>
</select>
<br>
<span>Position:</span>
<input type="radio" name="Position" value="Team-Member" >Team-Member<br>
<input type="radio" name="Position" value="Team Leader">Team Leader<br>
<input type="radio" name="Position" value="Executive">Executive<br>
<input type="submit" name="Add" value="Add"><br>
</form>
<?php
// Start executing the script
if (!empty($_POST))
{
$Name = $_POST["Name"];
$Address = $_POST["Address"];
$Phone = $_POST["Phone"];
$Email = $_POST["Email"];
$Availability = $_POST['Availability'];
$Company = $_POST["Company Name"];
$Job = $_POST['Job Title'];
$description = $_POST['Description'];
$Skill = $_POST['Skill'];
$Period = $_POST['Period'];
$Position = $_POST['Position'];
$Update=$_POST["Update"];
if(!empty($Name)){
$sql="INSERT INTO employee(Name, Address, Phone, Email, Availability, Company Name, Job Title, Description, Skill, Period, Position)
VALUES ('$Name','$Address','$Phone','$Email','$Avaliabilty','$Company','$Job','$Description','$Period','$Skill','$Position')";
if($db->query($sql) == TRUE){
echo ("Record added");
}
}
if (isset($Update)){
$sql="UPDATE employee SET Address='$Address',Phone='$Phone',Email='$Email',Availability='$Availability',Company='$Company',Job='$Job',Description='$Description',Skill = '$Skill',Period='$Period',Position='$Position' WHERE Name='$Name' ";
$db->query($sql);
}
$db->close();
}
?>
| |
doc_23532724
|
Object.getOwnPropertyNames(window.__proto__)
But in IE10 window.__proto__ is not defined. As in all other browthers
Object.getOwnPropertyNames(window)
does contain many functions, but not all (including the two mentioned above).
How do I enumerate those in IE10?
A: You can get enumerable and non-enumerable properties of the Window object with:
var properties = Object.getOwnPropertyNames(Object.getPrototypeOf(window))
the getPrototypeOf method is available in IE9+.
| |
doc_23532725
|
Here's my code
Loader::library('file/types');
$ih = Loader::helper('image');
$names = explode("||",$this->tName);
$urls = explode("||",$this->tUrl);
$fIDs = explode("||",$this->fID);
Loader::model('file');
$i = Loader::helper('image');
$v = array();
$cc = 0;
foreach ($names as $k=>$n){
if (intval($fIDs[$k]) > 0 ) :
$img = $test = File::getByID($fIDs[$k]);
$fv = $img->getExtension();
$ft = FileTypeList::getType($fv);
$img = $ft->type == 1 ? $img : false;
else :
$img = false;
endif;
$v[$cc]['name'] = $n;
$v[$cc]['url'] = $urls;
$v[$cc]['src'] = $img ? $ih->getThumbnail($img,100,100)->src : false;
$cc ++;
}
return $v;
And what i'm having issues with is getting the array values from $urls within this code. (5th last one)
foreach ($names as $k=>$n){
if (intval($fIDs[$k]) > 0 ) :
$img = $test = File::getByID($fIDs[$k]);
$fv = $img->getExtension();
$ft = FileTypeList::getType($fv);
$img = $ft->type == 1 ? $img : false;
else :
$img = false;
endif;
$v[$cc]['name'] = $n;
$v[$cc]['url'] = $urls;
$v[$cc]['src'] = $img ? $ih->getThumbnail($img,100,100)->src : false;
$cc ++;
}
return $v;
Thanks for all your help. Appreciate it.
A: I think you have to do something like this:
$i = 0;
foreach ($names as $k=>$n){
if (intval($fIDs[$k]) > 0 ) :
$img = $test = File::getByID($fIDs[$k]);
$fv = $img->getExtension();
$ft = FileTypeList::getType($fv);
$img = $ft->type == 1 ? $img : false;
else :
$img = false;
endif;
$v[$cc]['name'] = $n;
$v[$cc]['url'] = $urls[$i]; //changed
$v[$cc]['src'] = $img ? $ih->getThumbnail($img,100,100)->src : false;
$cc ++;
$i++; //changed
}
return $v;
A: Since you are looping through the names array using $k as the index, you can access the matching url with the same index. So you could change the line to:
$v[$k]['url'] = $urls[$k];
There's no need to keep track of the index using the $cc variable since $k already represents the current index in the names array. You are already accessing the fIDs array the same way (using $k).
| |
doc_23532726
|
It works the way I did for cells with value but not when the cells are empty.
This is the code I Did :
if(DateGridView1.Rows[selectedRow].Cells[2].Value.ToString() != "NULL")
DateTimePicker1.Value = (DateTime)DateGridView1.Rows[selectedRow].Cells[2].Value;
When I click on empty cells this is the error shown :
http://i.gyazo.com/273416fc2c2975fdf8902ad9bbb4caca.png
Here are the proprieties of the datatimeicker :
http://i.gyazo.com/0296eef11d258823904a4db0db379c04.png
Thanks
A: How about trying with String.IsNullOrEmpty()?
If it is not NULL or Empty, check the range values. If the ranges are ok, then put the value on the control.
if(!String.IsNullOrEmpty(DateGridView1.Rows[selectedRow].Cells[2].Value.ToString())
{
DateTime dateTime = DateGridView1.Rows[selectedRow].Cells[2].Value;
if (dateTime > DateTimePicker1.MinValue && dateTime < DateTimePicker1.MaxValue)
{
DateTimePicker1.Value = (DateTime)DateGridView1.Rows[selectedRow].Cells[2].Value;
}
}
| |
doc_23532727
|
The second reason I don't really like overriding SavingChanges is that it seems very messy and gets full of code quickly. When you have a complex object graph that method is going to get very messy VERY quickly with a lot of
if (entity is MyType)
{
//perform MyType validation
}
Third reason I don't really like this is all the extra validator objects that I would have to pass in the constructor of the object context. I am using a DI framework but it still feels messy.
I suppose I only have this problem because I am letting people use the repositories. I could add a layer of indirection and then they would have to use some sort of DTO. The downside here is it seems like a lot of extra work. Also the constant mapping that would have to take place.
Is there anyway that you could give access to repositories and to do validation without sticking everything into one SavingChanges method?
A: If your code is ugly, write nicer code. :)
var entities = context.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified))
.Select(ose => ose.Entity);
var errors = entities.OfType<IMyValidationInterface>()
.SelectMany(e => e.Validate());
...and done!
| |
doc_23532728
|
<form action="upload_file.php" method="post" enctype="multipart/form-data">
Select a file: <input type="file" name="upload">
<input type="submit">
</form>
Here's my php:
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
session_start();
$allowedExts = array("doc", "docx");
$extension = pathinfo( $_FILES["upload"]["name"],PATHINFO_EXTENSION);
if (($_FILES["upload"]["size"] < 200000)
&& in_array($extension, $allowedExts)) {
if ($_FILES["upload"]["error"] > 0)
{
echo "Return Code: " . $_FILES["upload"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["upload"]["name"] . "<br />";
echo "Type: " . $_FILES["upload"]["type"] . "<br />";
echo "Size: " . ($_FILES["upload"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["upload"]["tmp_name"] . "<br />";
$dir_exists = is_dir("Proposals/". $_SESSION["FirstName"] ."/");
$file_exists = file_exists("Proposals/".$_SESSION["FirstName"] ."/" . $_FILES["upload"]["name"]);
$folderName=$_SESSION["FirstName"];
$baseDir = "Proposals" ;
//var_dump($_FILES);
//die();
// Create directory if it does not exist
if (! $dir_exists) {
if(!is_dir($baseDir))
mkdir($baseDir);
mkdir($baseDir . DIRECTORY_SEPARATOR . $_SESSION["FirstName"]);
}
if ($file_exists) {
echo $_FILES["upload"]["name"] . " already exists. ";
} else {
move_uploaded_file($_FILES["upload"]["tmp_name"],
"Proposals/". $_SESSION["FirstName"] ."/". $_FILES["upload"]["name"]);
echo "Stored in: " . "Proposals/". $_SESSION["FirstName"] ."/". $_FILES["upload"]["name"];
}
}
} else {
echo "Invalid file";
}
?>
The file outputted:
Type: application/msword
Size: 124.9296875 Kb
Temp file: /tmp/phpUWDc3s
The var_dump outputted this on a test file:
array(1) { ["upload"]=> array(5) {
["name"]=> string(18) "Test.doc"
["type"]=> string(18) "application/msword"
["tmp_name"]=> string(14) "/tmp/phpUWDc3s"
["error"]=> int(0)
["size"]=> int(127928) } }
And the warnings/errors it gives me are:
Strict Standards: Only variables should be passed by reference in /disks/vhosts/***/***/upload_file.php on line 6 Upload: Test.doc
WITHOUT the mkdir code it gives me:
Warning: move_uploaded_file(Proposals/Test.doc): failed to open stream: Permission denied in /disks/vhosts/***/***/upload_file.php on line 40 Warning: move_uploaded_file(): Unable to move '/tmp/phpQmgxdO' to 'Proposals/Test.doc' in /disks/vhosts/***/***/upload_file.php on line 40 Stored in: Proposals/Test.doc
For some reason with or without the mkdir, no file is being put in the Proposals paper even if it's the right file type. Is this just a permission issue with the server or is there something I have to add/change to make this all work?
A: A. The first Error
Strict Standards: Only variables should be passed by reference in /disks/vhosts///upload_file.php on line 6 Upload: Test.doc
Change
$extension = end(explode(".", $_FILES["upload"]["name"]));
To
$extension = path_info( $_FILES["upload"]["name"],PATHINFO_EXTENSION);
B. The second error
Warning: move_uploaded_file(Proposals/Test.doc): failed to open stream: Permission denied in /disks/vhosts///upload_file.php on line 40 Warning: move_uploaded_file(): Unable to move '/tmp/phpQmgxdO' to 'Proposals/Test.doc' in /disks/vhosts///upload_file.php on line 40 Stored in: Proposals/Test.doc
Use something like this with full path /disks/vhosts/***/***/
$baseDir = __DIR__ ; // or /disks/vhosts/***/***/ has applicable
if (! $dir_exists) {
if (is_writable("$baseDir/Proposals/")) {
mkdir("$baseDir/Proposals/" . $_SESSION["FirstName"]);
} else {
trigger_error("Proposals/ is not writeable");
}
}
A: You currently have this code...
if(!$dir_exists) {
mkdir("Proposals/". $_SESSION["FirstName"]);
} elseif ($file_exists) {
echo $_FILES["upload"]["name"] . " already exists. ";
} else {
move_uploaded_file($_FILES["upload"]["tmp_name"],
"Proposals/". $_SESSION["FirstName"] ."/". $_FILES["upload"]["name"]);
echo "Stored in: " . "Proposals/". $_SESSION["FirstName"] ."/". $_FILES["upload"]["name"];
}
Which will ONLY move_uploaded_file if the directory you're looking for exists. Move that line below your if statement, and it should then create the directory if needed, then upload the file.
| |
doc_23532729
|
[!] You need Java 11 or higher to build your app with this version of Gradle. │
│ │
│ To get Java 11, update to the latest version of Android Studio on https://developer.android.com/studio/install. │
│ │
│ To check the Java version used by Flutter, run `flutter doctor -v`.
I dont understand why I need to update Android Studio to the latest version when I am using VS Code for flutter. Can someone help me fix this problem?
A: It's so weird. I installed jdk-11 from oracle but it didnt work. But when I updated Android Studio and then running the flutter program in VS Code, it run without any problem. I still dont understand why it worked but the solution was to just update android studio.
| |
doc_23532730
|
# LIBRARY IMPORTS
from datetime import datetime
import random
# VARIABLES
date = datetime.now()
dateFormat = str(date.strftime("%d-%m-%Y %H:%M:%S"))
lowerCase = "abcdefghijklmnopqrstuvwxyz"
upperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
numbers = "0123456789"
symbols = "!?%&@#+*/()=<>-_"
passwordConstructor = lowerCase + upperCase + numbers + symbols
minPasswordLength: int = 8
maxPasswordLength: int = 20
# FUNCTIONS
def getUsername():
global userName
userName = str(input("Enter Username:"))
def getPasswordLength():
global passwordLength
passwordLength = input("Enter the length of password: ")
def generatePassword():
global password
password = "".join([random.choice(passwordConstructor) for i in range(passwordLength)])
print("1." + password)
password = ''.join(random.sample(password,len(password)))
print("2." + password)
password = ''.join(random.sample(password, len(password)))
print("3." + password)
def generateTextFile():
if userName != "":
f = open(userName.upper() + " - " + dateFormat + ".txt", "w+")
f.write("USERNAME: " + userName + "\nPASSWORD: " + password + "\n\nGENERATED ON: " + dateFormat)
else:
f = open("Password generated on " + dateFormat + ".txt", "w+")
f.write("PASSWORD: " + password + "\n\nGENERATED ON: " + dateFormat)
f.close()
def printPassword():
generatePassword()
print(password)
if getPasswordLength() == '':
print("Please enter a value. This cannot be empty.")
else:
if not getPasswordLength().isdigit():
print("Length of password must be a number.")
else:
if getPasswordLength() > maxPasswordLength:
print('Length of password is limited to ' + maxPasswordLength)
elif getPasswordLength() < minPasswordLength:
print('Length of password must be grater than ' + minPasswordLength)
else:
generatePassword()
But condition doesn't work and end up in an error. What I am doing wrong?
Conditions for User Input which should be covered:
*
*Cannot be empty.
*Must be number.
*Greater than minPasswordLength (8).
*Smaller than maxPasswordLength (20).
A: When you add the max and min password length to the string at the end you must declare them to be a string. It should look like this:
print('Length of password is limited to ' + str(maxPasswordLength))
That's the only immediate issue that I can see, however from my experience I know that it has to be done every time an integer or numeric value is added to a string so you will have to amend any other instances where this happens.
Hope this works :)
A: There are a couple issues here in your code, as others have mentioned, including issues of comparisons between different types, namely comparing the input provided by the user and the min and max password lengths.
You also do not have a loop to re-prompt the user to enter a password length again if it does not satisfy the constraints, which I am not sure was your intended aim. I have adapted your existing code below and enclosed the modified logic in a while loop so that the user will continue to be prompted to enter a password length that satisfies the constraints.
# LIBRARY IMPORTS
from datetime import datetime
import random
# VARIABLES
date = datetime.now()
dateFormat = str(date.strftime("%d-%m-%Y %H:%M:%S"))
lowerCase = "abcdefghijklmnopqrstuvwxyz"
upperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
numbers = "0123456789"
symbols = "!?%&@#+*/()=<>-_"
passwordConstructor = lowerCase + upperCase + numbers + symbols
minPasswordLength: int = 8
maxPasswordLength: int = 20
# FUNCTIONS
def getUsername():
global userName
userName = str(input("Enter Username:"))
def getPasswordLength():
global passwordLength
passwordLength = input("Enter the length of password: ")
def generatePassword():
global password
password = "".join([random.choice(passwordConstructor) for i in range(passwordLength)])
print("1." + password)
password = ''.join(random.sample(password,len(password)))
print("2." + password)
password = ''.join(random.sample(password, len(password)))
print("3." + password)
def generateTextFile():
if userName != "":
f = open(userName.upper() + " - " + dateFormat + ".txt", "w+")
f.write("USERNAME: " + userName + "\nPASSWORD: " + password + "\n\nGENERATED ON: " + dateFormat)
else:
f = open("Password generated on " + dateFormat + ".txt", "w+")
f.write("PASSWORD: " + password + "\n\nGENERATED ON: " + dateFormat)
f.close()
def printPassword():
generatePassword()
print(password)
while True:
getPasswordLength()
if passwordLength == "":
print("Please enter a value. This cannot be empty.")
continue
try:
passwordLength = int(passwordLength)
except ValueError:
print("Length of password must be an integer.")
continue
if passwordLength > maxPasswordLength:
print(f"Length of password is limited to {maxPasswordLength}")
elif passwordLength < minPasswordLength:
print(f'Length of password must be grater than {minPasswordLength}')
else:
generatePassword()
break
As mentioned by other users, global variables should be avoided if possible, and for your code the same result can be achieved in perhaps a more "pythonic" way without using global variables. I have not changed it in my answer but could be something to think about.
A: I switched from global variable to return and ended up with:
# Simple password generator created by akatsuki
# LIBRARY IMPORTS
from datetime import datetime
import random
# VARIABLES
date = datetime.now()
dateFormat = str(date.strftime("%d-%m-%Y %H:%M:%S"))
lowerCase = "abcdefghijklmnopqrstuvwxyz"
upperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
numbers = "0123456789"
symbols = "!?%&@#+*/()=<>-_"
passwordConstructor = lowerCase + upperCase + numbers + symbols
minPasswordLength: int = 8
maxPasswordLength: int = 20
# FUNCTIONS
def getUsername():
userName = str(input("Enter Username:"))
return userName
def getPasswordLength():
passwordLength: str = input("Enter the length of password: ")
return passwordLength
def generatePassword():
password = "".join([random.choice(passwordConstructor) for i in range(getPasswordLength())])
print("1." + password)
password = ''.join(random.sample(password,len(password)))
print("2." + password)
password = ''.join(random.sample(password, len(password)))
print("3." + password)
return password
def generateTextFile():
if getUsername() != "":
f = open(getUsername().upper() + " - " + dateFormat + ".txt", "w+")
f.write("USERNAME: " + getUsername() + "\nPASSWORD: " + generatePassword() + "\n\nGENERATED ON: " + dateFormat)
else:
f = open("Password generated on " + dateFormat + ".txt", "w+")
f.write("PASSWORD: " + generatePassword() + "\n\nGENERATED ON: " + dateFormat)
f.close()
def printPassword():
generatePassword()
print(generatePassword())
while True:
getUsername()
getPasswordLength()
if getPasswordLength() == "":
print("Please enter a value. This cannot be empty.")
continue
try:
getPasswordLength() = int(getPasswordLength())
except ValueError:
print("Length of password must be an integer.")
continue
if getPasswordLength() > maxPasswordLength:
print(f"Length of password is limited to {maxPasswordLength}")
elif getPasswordLength() < minPasswordLength:
print(f'Length of password must be grater than {minPasswordLength}')
else:
generatePassword()
generateTextFile()
break
But in line:
try:
getPasswordLength() = int(getPasswordLength())
I got following error:
"Cannot assign to function call"
How this can be solved?
| |
doc_23532731
|
I have a NSTimer that changes the background image of a UIButton.
Once this is complete, it will trigger the same action again (reset the NSTimer) for a predetermined number of times.
My problem is that if my NSTimer is set to execute more than once per second. (0.75, say) The background image wont change.
I am using NSLog to check that the event fires. But the button image will just remain in its original state.
Is there any way to change the background image more often than once per second?
This is my timer :
[NSTimer scheduledTimerWithTimeInterval: tmpLvlSpeed
target: self
selector: @selector(simPressRed:)
userInfo: nil
repeats: NO];
And the code to change the image:
[btnRed setImage:[UIImage imageNamed:@"btn_red.png"] forState:UIControlStateNormal];
if tmpLvlSpeed is less than 1.0, the button image will never change. Even though the simPressRed function will still fire.
Any clues? Is there an update cycle I can modify?
A: Have you tried to use setNeedsDisplay?
[button setNeedsDisplay];
A: how many images do you have? From what you gave us, you only have one image, so no duh the image won't change. Please post the code you have so we can further help you
| |
doc_23532732
|
I am playing with pyPEG2 by Volker Birk and I am stuck with a very trivial case:
from pypeg2 import *
text = 'f(x)'
grammar = name, '(' , word,')'
print parse(text, grammar)
The exception I am getting looks like:
Traceback (most recent call last): File "test.py", line 5, in
print parse(text, grammar) File "/home/yy/dev/python/len/len/lang/pypeg2/init.py", line 539, in
parse
t, r = parser.parse(text, thing) File "/home/yy/dev/python/len/len/lang/pypeg2/init.py", line 644, in
parse
t, r = self._parse(t, thing, pos) File "/home/yy/dev/python/len/len/lang/pypeg2/init.py", line 814, in
_parse
t2, r = self._parse(t, e, pos) File "/home/yy/dev/python/len/len/lang/pypeg2/init.py", line 962, in
_parse
raise GrammarTypeError("in grammar: " + repr(thing)) pypeg2.GrammarTypeError: in grammar: '('
parse() fails on parsing opening round bracket which supposed to be a Symbol(). Surely I am missing something obvious, but what?
A: from __future__ import unicode_literals, print_function
from pypeg2 import *
text = 'f(x)'
grammar = name(), '(' , attr('Param',word),')'
print(parse(text, grammar))
outputs
[Attribute(name=u'name', thing=Symbol(u'f'), subtype=None), Attribute(name=u'Param', thing=u'x', subtype=None)]
Why? RTFM!!
Caveat: pyPEG 2.x is written for Python 3. You can use it with Python
2.7 with the following import (you don't need that for Python 3)
A: I updated the documentation because of people having such problems. pyPEG2 is written for Python 3. That means, it uses Unicode strings all the way. For Python 2.7, this would require strings of the form i.e. u'f(x)'. Because I don't want to have the documentation twice, I'm recommending from __future__ import unicode_literals, print_function
VB.
| |
doc_23532733
|
Obviously, I know that I can define String color , but is there a better way to do this ?
A: Define an enum
public enum Color {
RED, BLACK, ORANGE;
}
and use it like this:
Color red = Color.RED;
You can define in or outside of the enclosing class.
If you wish to define it inside the class, the enum will be implicitly static (by default) and will be accessible it like this
SomeClass.Color red = SomeClass.Color.RED;
A: You can use an Enum.
It allows only to use specific Objects.
Enum Color { RED, GREEN, BLUE };
Color var = Color.RED;
A: If you want a simple way to define a color with no particular meaning:
public enum Color {
RED, BLACK, ORANGE;
}
If you want to define a variable which can allows real java.awt.Color:
import java.awt.Color;
public enum MyColor
{
RED (Color.RED),
BLACK (Color.BLACK),
ORANGE (Color.ORANGE);
private Color value;
private MyColor(Color value) {
this.value = value;
}
public Color getValue() {
return value;
}
}
A: Enum-variables/fields can hold null aswell, so you will have 4 possible values, BLACK,RED,ORANGE and null. Try to use null as BLACK.
enum Color {RED,ORANGE;
static boolean isBlack(Color c){
return c == null;
}
static boolean isRed(Color c){
return c == RED;
}
static boolean isOrange(Color c){
return c == ORANGE;
}
};
| |
doc_23532734
|
for file in /Volumes/USB_AIB/DICOMFunCurrentBatch/MOVr1unzip/s*/*
do
mv $file dicom${file%%}
done
but got thousands of lines of the following error (once for each file within each folder--this is just an example of one of them):
mv: rename /Volumes/USB_AIB/DICOMFunCurrentBatch/MOVr1unzip/s307_1/29217684 to dicom/Volumes/USB_AIB/DICOMFunCurrentBatch/MOVr1unzip/s307_1/29217684: No such file or directory
Any ideas on how to fix it?
A: I don't you have a valid path as dicom/Volumes/USB_AIB/DICOMFunCurrentBatch/MOVr1unzip/s307_1/, why do you add dicom at the beginning?
maybe you want to append dicom to the end of the $file?
mv "$file" "${file}_dicom"
or something like that.
A: *
*the following variable expansion ${file%%} is strange because it does nothing:
${parameter%%word} : remove the longest matching suffix pattern.
*to move the file into a directory the path should exists, to create the path:
mkdir -p "$(dirname "${newfilename}")"
Maybe what you are trying to do:
for file in /Volumes/USB_AIB/DICOMFunCurrentBatch/MOVr1unzip/s*/*
do
mv "$file" "${file%/*}/dicom${file##*/}"
done
| |
doc_23532735
|
Meteor.methods({
getResponseFromServer:function(latlong){
lng = parseFloat(latlong.lng);
lat = parseFloat(latlong.lat);
//return 'hello';
//this hello i got in my client side code.
console.log(Centers.find({ coordinates: { $near: { $geometry: { type: "Point", coordinates: [lat,lng] }, $maxDistance: 10000 } } }).fetch());
//getting data from server
var getObject = Centers.find({ coordinates: { $near: { $geometry: { type: "Point", coordinates: [lat,lng] }, $maxDistance: 10000 } } }).fetch();
//getting data from server and store it in an object and return it
return getObject;
}
});
and i have my client side code simple.
Template.searchlist.onRendered(function(){
this.searchedString = Router.current().params.name;
searchedParams = this.searchedString;
searchedParams = searchedParams.split('-');
var lat = searchedParams.pop();
var lng = searchedParams.pop(1);
lng = Number(lng).toFixed(6);
console.log(lng);
lat = Number(lat).toFixed(6);
var latlong = {'lat':lat,'lng':lng};
Meteor.call("getResponseFromServer",latlong,function(error,success){
console.log(error+' see sucess here');
console.log(success+' see failure here');
});
});
please give me solution about it if anyone have idea.
| |
doc_23532736
|
I have added .checkboxradio("refresh") to the radio group and to the individual radiobutton to no avail. A demo is here: http://jsfiddle.net/mckennatim/a9jx9/
.button("refresh") causes an error.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Tax</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0-rc.1/jquery.mobile-1.1.0-rc.1.min.css" />
<link href="css/tax.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.1.0-rc.1/jquery.mobile-1.1.0-rc.1.min.js"></script>
</head>
<body>
<div id="page2" data-role="page" data-add-back-btn="true">
<div data-role="content">
<div id="proCG">
<fieldset data-role="controlgroup" data-mini="true">
<legend>Tax Capital Gains </legend>
<input type="radio" name="choProCG" id="radProCG1" value="1" />
<label for="radProCG1">as ordinary income</label>
<input type="radio" name="choProCG" id="radProCG2" value="0" />
<label for="radProCG2">at a separate rate</label>
</fieldset>
</div>
<div id="txthere"></div>
</div>
</div>
</body>
</html>
<script>
$('#page2').live('pageinit', function(event) {
console.log('here');
$("#radProCG2").prop("checked", true).checkboxradio("refresh");
$('input[name=choProCG]').checkboxradio("refresh");
$('#txthere').append('duck');
$('#txthere').append($('input[name=choProCG]:checked').val());
$('input[name=choProCG]').change( function(e){
$('#txthere').append(this.value);
$('#txthere').append('frog');
});
});
</script>
A: Try this http://jsfiddle.net/CGpGD/2/
OR
the Code Below
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Tax</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0-rc.1/jquery.mobile-1.1.0-rc.1.min.css" />
<link href="css/tax.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.1.0-rc.1/jquery.mobile-1.1.0-rc.1.min.js"></script>
</head>
<body>
<div id="page2" data-role="page" data-add-back-btn="true">
<div data-role="content">
<div id="proCG">
<fieldset data-role="controlgroup" data-mini="true">
<legend>Tax Capital Gains </legend>
<input type="radio" name="choProCG" id="radProCG1" value="1" />
<label for="radProCG1">as ordinary income</label>
<input type="radio" name="choProCG" id="radProCG2" value="0" />
<label for="radProCG2">at a separate rate</label>
</fieldset>
</div>
<div id="txthere"></div>
</div>
</div>
</body>
</html>
<script>
$('#page2').live('pageinit', function(event) {
console.log('here');
$("#radProCG2").attr("checked", true).checkboxradio("refresh");
$('input[name=choProCG]').checkboxradio("refresh");
$('#txthere').append('duck');
$('#txthere').append($('input[name=choProCG]:checked').val());
$('input[name=choProCG]').change( function(e){
$('#txthere').append(this.value);
$('#txthere').append('frog');
});
});
</script>
A: try this code in html..
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<legend>Choose a pet:</legend>
<input type="radio" name="radio-choice-1" id="radio-choice-1" value="choice-1" checked="checked" />
<label for="radio-choice-1">Cat</label>
<input type="radio" name="radio-choice-1" id="radio-choice-2" value="choice-2" />
<label for="radio-choice-2">Dog</label>
<input type="radio" name="radio-choice-1" id="radio-choice-3" value="choice-3" />
<label for="radio-choice-3">Hamster</label>
<input type="radio" name="radio-choice-1" id="radio-choice-4" value="choice-4" />
<label for="radio-choice-4">Lizard</label>
</fieldset>
</div>
| |
doc_23532737
|
LaunchTemplate:
Type: AWS::EC2::LaunchTemplate
Properties:
LaunchTemplateData:
ImageId: ami-xxxxxxxxxxxxxxx
What's the best way to update LaunchTemplate to always use the latest imageId built by codepipe line?
A: Use
Parameters:
Amiid:
Type: AWS::SSM::Parameter::Value<String>
Default: /aws/...<ssm parameter name for your AMI family>
This way CFN will fetch the latest AMI ID from SSM
Then use this parameter in
ImageId: !Ref Amiid
| |
doc_23532738
|
/var/www/html/src/gorm.io/gorm/utils/utils.go:46:30: reflect.ValueOf(val).IsZero undefined (type reflect.Value has no field or method IsZero)
this is my code:
package main
import (
"gorm.io/gorm"
"gorm.io/driver/sqlite"
)
type Product struct {
gorm.Model
Code string
Price uint
}
func main() {
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
// Migrate the schema
db.AutoMigrate(&Product{})
// Create
db.Create(&Product{Code: "D42", Price: 100})
}
A: The Value.IsZero() method was added in Go 1.13. You have to use Go 1.13 or a later version if your code relies on this "feature".
You can check your go version by running go version.
| |
doc_23532739
|
I have a classic website that's written in HTML & JS (based on bootstrap). The user navigates through it and when the user decides to sign-in I need show the login modal dialog that's in React and if the login is successful then I need to load the react app. The react app is a full application with nav bar, etc. - that means the current site needs to be unloaded / disappear. (The URL could continue to be the same, no restriction; it's just that the first website is used for marketing and when the user signs-in I need to load the actual application).
How can I achieve this? I have been searching the internet for the last few hours but not solution so far.
This question is regarding JS & React integration has NOTHING TO DO WITH OAUTH. This is for moderators who don't understand coding.
Thanks in advance for any info that could help.
A: It is the process.
I do not see any issue doing this in the same URL. In your solution, you can create two projects. setup startup page and then redirect to the original application, for security you should use O-Auth authentication. OAuth is explained Here
| |
doc_23532740
|
I also have a Password field, which, in editing mode, is write-only.
Meaning- the password is not displayed, but if a user inserts a value for this field- then the password is changed.
My issue is that when editing an existing user, I obviously want the password field to be optional. But when adding a new user, I want to make this field required.
How can this be acheived?
thanks
A: I use method "setColProp" for this
......
{ //Edit dialog options
beforeCheckValues: function(postdata, formid, mode) {
grid.setColProp('Password', {editrules: {required: false}});
},
{ //Add dialog options
beforeCheckValues: function(postdata, formid, mode) {
grid.setColProp('Password', {editrules: {required: true}});
}
A: for your problem you can use different validation methods when editing and adding.
example:
function validate_add(posdata, obj)
{
if(posdata.PASSWORD==null || posdata.PASSWORD=="" || posdata.PASSWORD==undefined)
return [false, "Please enter the pasword"];
return [true, ""];
}
function validate_edit(posdata, obj)
{
//you can ignore this because you dont want to verify password
}
// in jqgrid
grid.navGrid('#pager',{add:true,addtext:'Add',edit:true,edittext:'Edit',del:true,deltext:'Del', search:true,searchtext:'Find',refresh:true}, //options
{width:700,reloadAfterSubmit:true, beforeSubmit:validate_edit}, // edit options
{width:700,reloadAfterSubmit:true, beforeSubmit:validate_add}, // add options
{}, //del options
{} //search options
);
A: Sandeep posted correct code because beforeSubmit can be used for the custom validation.
There are alternative approach to do what you want. One can't define different editrules, but one can change the value of the editrules objects inside of beforeCheckValues method for example or inside of some other form edit events called before validation check.
Here is the schema of the code which can change the editrules:
var grid = $("#list"),
getColumnIndexByName = function(columnName) {
var cm = grid.jqGrid('getGridParam','colModel'), // grid[0].p.colModel
i=0, l=cm.length;
for (; i<l; i++) {
if (cm[i].name===columnName) {
return i; // return the index
}
}
return -1;
},
addEditrulesPassword={required:true /*some other settings can follow*/},
editEditrulesPassword={required:false /*some other settings can follow*/};
// ... first of all we define the grid
grid.jqGrid({
// all parameters including the definition of the column
// with the name 'Password' inside of `colModel`
});
grid.jqGrid(
'navGrid','#pager',{/*navGrid options*/},
{//Edit dialog options
},
{//Add dialog options
beforeCheckValues:function(postdata,$form,oper) {
// get reference to the item of colModel which correspond
// to the column 'Password' which we want to change
var cm = grid[0].p.colModel[getColumnIndexByName('Password')];
cm.editrules = addEditrulesPassword;
},
onclickSubmit:function(ge,postdata) {
// get reference to the item of colModel which correspond
// to the column 'Password' which we want to change
var cm = grid[0].p.colModel[getColumnIndexByName('Password')];
cm.editrules = editEditrulesPassword;
}
}
);
A: I found a bit dirty solution for inline edit:
function inlineCustomValidation(value, colname) {
var savedRow = jQuery("#grid").getGridParam("savedRow");
if (savedRow[0].some_required_field == "")
//add operation validation
} else {
//edit operation validation
}
};
savedRow array. This is a readonly property and is used in inline and cell editing modules to store the data, before editing the row or cell. See Cell Editing and Inline Editing.
A: The below script is to validate jqgrid inline edit cell, it won't allow user to enter any special characters except dot(.) used to specify decimal separator
{ name: 'Amount', width: 22, label: 'Cost', editable: true, align: "right", sorttype: 'int', search: false, formatter: 'currency', formatoptions: { prefix: "$", thousandsSeparator: ",", decimalPlaces: 2, defaultValue: '0.00' },
editoptions: {
dataInit: function(element) {
$(element).keypress(function (e) {
if (e.which != 8 && e.which != 0 && e.which != 46 && (e.which < 48 || e.which > 57 )) {
return false;
}
});
}
}
},
| |
doc_23532741
|
When I Manually move the pre- and postbuild event configuration in the generated .csproj file further downwards, then msbuild recognizes these variables correctly.
Adding the buildevent to the project is the last thing I do before saving the project.
This is how I add it:
using Microsoft.Build.Construction;
using Microsoft.Build.Evaluation;
private const string PreBuildEventFixture = "PreBuildEvent";
private const string PostBuildEventFixture = "PostBuildEvent";
private const string PreBuildEvent = "attrib -R \"$(ProjectDir)app.config\"";
private const string PostBuildEvent = "copy \"$(ProjectDir)app.config.$(ConfigurationName)\" \"$(TargetDir)\\$(ProjectName).dll.config\" \r\n attrib -R \"$(ProjectPath)\"";
public void AddBuildEvents(Project project)
{
ProjectPropertyGroupElement propertyGroupElement = project.Xml.AddPropertyGroup();
propertyGroupElement.AddProperty(PreBuildEventFixture, PreBuildEvent);
propertyGroupElement.AddProperty(PostBuildEventFixture, PostBuildEvent);
}
The error I get when running the generated project through msbuild is this:
The command "copy "app.config." "\.dll.config"" exited with code 1
When I then manually edit the .csproj file (with notepad or another text editor), cut the pre-and postbuild event, and paste it below the <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> element, then msbuild builds the generated .csproj file fine.
What is the best way to add the build events to the .csproj file so it ends up after the Import element in the resulting XML?
Apparently, my current way of using [ProjectPropertyGroupElement][1] by requesting it from AddPropertyGroup of the the Xml property of the Microsoft.Build.Evaluation.Project is not.
Example Project:
using System.IO;
using Microsoft.Build.Construction;
using Microsoft.Build.Evaluation;
class Program
{
private const string PreBuildEventFixture = "PreBuildEvent";
private const string PostBuildEventFixture = "PostBuildEvent";
private const string PreBuildEvent = "attrib -R \"$(ProjectDir)app.config\"";
private const string PostBuildEvent = "copy \"$(ProjectDir)app.config.$(ConfigurationName)\" \"$(TargetDir)\\$(ProjectName).exe.config\" \r\n attrib -R \"$(ProjectPath)\"";
private const string ProjectFile = @"C:\test\TestProject\TestProject.csproj";
static void Main(string[] args)
{
if (!File.Exists(ProjectFile))
throw new FileNotFoundException("ProjectFile not found");
ProjectCollection collection = new ProjectCollection();
Project project = collection.LoadProject(ProjectFile);
ProjectPropertyGroupElement propertyGroupElement = project.Xml.AddPropertyGroup();
propertyGroupElement.AddProperty(PreBuildEventFixture, PreBuildEvent);
propertyGroupElement.AddProperty(PostBuildEventFixture, PostBuildEvent);
project.Save();
collection.UnloadAllProjects();
}
}
Steps to reproduce
*
*Create a new project
*Manually add app.config.debug file which should be different to the app.debug file
*Add the postbuildevent: copy "$(ProjectDir)app.config.$(ConfigurationName)" "$(TargetDir)\$(ProjectName).exe.config
*See that the project build and the correct config file is applied
*Remove the pre- and postbuild events using notepad (so not to leave any traces)
*Run the example project
*Reload and build the project you created.
*Output window will now say The system cannot find the file specified.
A: var propertyGroupElement = project.Xml.CreatePropertyGroupElement();
project.Xml.AppendChild(propertyGroupElement);
propertyGroupElement.AddProperty(PreBuildEventFixture, PreBuildEvent);
propertyGroupElement.AddProperty(PostBuildEventFixture, PostBuildEvent);
A: Project related macros are not parsed if they are added before the project is actually constructed (constructing a project includes adding references). Instead of using $(ProjectName), the path can be constructed using solution variables (that already exist) like this :
copy "$(SolutionDir)ProjectName\app.config.$(Configuration)" "$(SolutionDir)ProjectName\bin\$(Configuration)\ProjectName.dll.config"
Note that ProjectName is the actual name of the project hardcoded, but since you are generating a project this should be easy to add.
| |
doc_23532742
|
{
HomeFolderListing = new List<string>();
ReportingServiceSoapClient rs = new ReportingServiceSoapClient();
rs.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;
CatalogItem[] HomeFolders = null;
string reportPath = "/";
rs.ListChildren(reportPath, true, out HomeFolders);
foreach (var homeF in HomeFolders)
{
if (homeF.Name.ToString().ToLower().Contains("base"))
{
if (homeF.Path.ToString().ToLower().Contains("/data sources/"))
{
}
else
{
Console.WriteLine("Adding reporting folder: " + homeF.Name.ToString());
HomeFolderListing.Add(homeF.Path.ToString());
}
}
}
}
public static void PublishReport()
{
foreach (string HomeFold in HomeFolderListing)
{
ReportingServiceSoapClient rs = new ReportingServiceSoapClient();
rs.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;
BatchHeader bh = new BatchHeader();
string batchID = null;
rs.CreateBatch(out batchID);
bh.BatchID = batchID;
Byte[] definition = null;
Warning[] warnings = null;
try
{
FileStream stream = File.OpenRead(ReportInformation.Report2Deploy);
definition = new Byte[stream.Length];
stream.Read(definition, 0, (int)stream.Length);
stream.Close();
}
catch (Exception ex)
{
}
try
{
string filename = ReportInformation.ReportDeployNameOnly;
Console.WriteLine("Deploying Report: " + filename + " to: " + HomeFold);
rs.CreateReport(bh, filename, HomeFold, true, definition, null, out warnings);
if (warnings != null)
{
foreach (Warning warning in warnings)
{
Console.WriteLine(warning.Message);
}
}
else
Console.WriteLine("Report: {0} created successfully with no warnings", filename);
}
catch (Exception ex)
{
}
}
}
when i execute rs.CreateReport() it comes back as if it was successful with no warning, however, when i view the server it just isn't there. And yes I've looking in all the folders.
A: Are you sure there is no error? There's an empty catch block. The documenation says to catch a SoapException. Try this in the catch:
catch (SoapException e)
{
//Do something with the error, sample code write to console
Console.WriteLine(e.Detail.InnerXml.ToString());
}
Taken from:
http://msdn.microsoft.com/en-us/library/aa225813(v=sql.80).aspx
| |
doc_23532743
|
A: Most of the times it's a broken package.
Try to install reportlab using pip
pip install --upgrade --force-reinstall reportlab
Then you need to restart idle or pycharm ..etc
| |
doc_23532744
|
The text aligns centrally in its grid area but the image (in .area1) stays top left (the image is 150x150, so there should be scope for it being centered).
Does anybody know what I am doing wrong.
Below is the CSS and the HTML.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Grid Area Test</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<img class="area1" src="https://source.unsplash.com/150x150">
<p class="area2">Area 2</p>
<p class="area3">Area 3</p>
<p class="area4">Area 4</p>
<p class="area5">Area 5</p>
</body>
</html>
* {
box-sizing: border-box;
margin: 0;
}
body {
background: #9A9696;
}
body {
display: grid;
grid-template-columns: repeat(6, 100px);
grid-template-rows: repeat(6, 100px);
grid-template-areas:
"area1 area1 ..... ..... area2 area2"
"area1 area1 ..... ..... area2 area2"
"..... ..... area3 area3 ..... ....."
"..... ..... area3 area3 ..... ....."
"area4 area4 ..... ..... area5 area5"
"area4 area4 ..... ..... area5 area5";
justify-content: center;
}
.area1, .area2, .area3, .area4, .area5 {
background: #DE6449;
display: grid;
align-items: center;
justify-content: center;
}
.area1 {grid-area: area1;}
.area2 {grid-area: area2;}
.area3 {grid-area: area3;}
.area4 {grid-area: area4;}
.area5 {grid-area: area5;}
.area6 {grid-area: area6;}
A: Quick answer: use margin: auto
.area1 {
grid-area: area1;
margin: auto;
}
Detailed answer: Centering in CSS Grid
| |
doc_23532745
|
The issue i am having is with the div "logofoxfont" as I want the letter 'f' to be in the same position in all broswers but it appears to be different in firefox.
How can I sort this?
<html>
<head>
</head>
<link href="fw.css" rel="stylesheet" type="text/css">
<body>
<div class="topbox">
<div class="logobox"><div class="logoboxfont">
f</div></div>
<div class="logotext"></div>
</div>
<div class="midbox">
<div class="menubox"><div class="menuboxfont">Home<br>About Us<br>Staff<br>News<br></div>
<div class="menubox2"><div class="menuboxfont2">Appointments<br>
Price Guide<br>Emergency Services<br>Feedback<br></div></div></div>
</div>
</body>
</html>
And the css is:
#logo{
background-image:url(40.jpg);
height:100px;
width:100px;
}
.topbox {
margin: 0px auto;
height:100px;
width:900px;
margin-top:0px;
background: #ffffff;
}
.logobox {
height:90px;
width:70px;
margin-top:10px;
background-color:#2FB2F4;
}
.logotext {
color: #333333;
font-family: Cambria;
font-size: 18px;
margin-top: -90px;
margin-left: 75px;
position:absolute;
}
#logotext1 {
margin-left:10px;
}
#logotext2 {
color: #00AAF5;
font-family: georgia;
font-size: 22px;
margin-top: -35px;
margin-left:10px;
}
.logoboxfont {
font-family:Cambria;
color: #ffffff;
font-size: 126px;
position:absolute;
margin-top:-20px;
margin-left:0px;
-moz-transform:rotate(10deg);
-webkit-transform:rotate(10deg);
-o-transform:rotate(10deg);
-ms-transform:rotate(10deg);
}
.midbox {
margin: 0px auto;
height:700px;
width:900px;
margin-top:0px;
background: #ffffff;
border-top: 1px solid #333333;
}
.menubox {
height:230px;
width:150px;
margin-top:10px;
background: #E6E6E6;
}
.menuboxfont {
color: #333333;
font-family:lucida grande;
font-size: 12px;
margin-top: 4px;
margin-left: 4px;
position:absolute;
}
.menubox2 {
height:160px;
width:150px;
margin-top:70px;
background: #FAFAFA;
position:absolute;
}
.menuboxfont2 {
color: #333333;
font-family:lucida grande;
font-size: 12px;
margin-top: 4px;
margin-left: 4px;
position:absolute;
}
Thanks for the help!
James
A: See fiddle for code and demo:
Fiddle: http://jsfiddle.net/kHtmf/1/
Demo: http://jsfiddle.net/kHtmf/1/embedded/result/
SS of Firefox:
SS of chrome:
SS of Safari:
| |
doc_23532746
|
<p>Hello {{name}}</p>
and at bottom, there is script
return {
data: function(){
return{
name: "Peter"
}
}
}
Now when the page is accessed, it displays - Hello Peter
Question is I want to fetch name from real database from my server. So I made this changes -
app.request.post(
'http://domain-name/page.php',
{userid: 2},
function(response){
var response = JSON.parse(response);
console.log(response); //console log shows {name: "Peter"}
return response
}
);
return {
data: function(){
return response //console log shows response is not defined
}
}
Now when try to access the page, it throws errors (in console) - ReferenceError: response is not defined. In console my request query is OK, it show - {name: "Peter"}
I did return response as well as tried replacing the position of function as well as tried many other possible fix suggested on stackoverflow.
I think one function is running before other one make finish database queries. I am not expert (just average). So please someone suggest.
I have also tried to access the page through routes.js as example given in request-and-load.html but still reference error.
A: I think you have to pass by async routeto load page context (c.f. F7 doc)
You will be able to load datas via resolve callback
Maybe an example can help : async data for page
A: return response is inside the data: section. The request is not, and they cannot reach each other.
Put the gathering of data inside the data function. You also want to save the response outside of the request function. To make sure the response variable is reachable. I'd also personally move the request itself to be defined in a separate location for usage outside of this one instances.
File: custom.js
requests = {
GetName: function () {
app.request.post(
'http://domain-name/page.php',
{ userid: 2 },
function (response) {
var response = JSON.parse(response);
console.log(response); //console log shows {name: "Peter"}
return response
}
);
},
GetNameDynamic: function (id) {
app.request.post(
'http://domain-name/page.php',
{ userid: id},
function (response) {
var response = JSON.parse(response);
console.log(response);
return response
}
);
}
}
Then inside the data: section call that function and save as a variable. Pass that in the data return.
data: function () {
// Must return an object
var result = requests.GetName();
return {
name: result.name,
}
},
There are other ways/locations to accomplish this. One being the async in the route as the other user mentioned.
In the routes array, just change the path and componentUrl to the correct ones.
{
path: '/post-entity-group/:type/:group/:public/',
async: function (routeTo, routeFrom, resolve, reject) {
var result = requests.GetName();
resolve(
{
componentUrl: './pages/post-entity.html',
},
{
context: {
name: result.name,
}
}
)
}
},
| |
doc_23532747
|
I have the following json structure:
{
library:[{
libraryphone: 9898989898,
location:{
address:{
street:123 garden ave,
city: Dublin
}
},
{
libraryphone: 9090909090,
location:{...}
}, {
libraryphone: 9797979797,
location: {...}
}
}]
}
In the json above, I have multiple library phones and addresses. So I need to collect all the phone numbers on the condition that the city exists.
I have tried:
$.library[?(@.location.address.city)].libraryphone
I understand to get the libraryphones, all I need to do is
$.library[*].libraryphone
But, I need to have the condition of checking if the city exists or not.
| |
doc_23532748
|
<body class="{{ bodyClass }}">
I would like it to be "login" on page load. Any strategy for this? Or do I just have to fudge it and load it as 'login' and manually use javascript to to tweak the DOM just for this instance.
A: What you are looking for is ng-cloak.
You have to add it like this:
<body class="{{ bodyClass }}" ng-cloak>
and this will prevent unwanted flashing.
Link to docs about this.
Edit:
It is also advisable to put the snippet below into your CSS file, according to docs.
"For the best result, the angular.js script must be loaded in the head
section of the html document; alternatively, the css rule above must
be included in the external stylesheet of the application."
[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
display: none !important;
}
A: There is a solution to the flash problem in plain CSS which is bulletproof. For the class of your app root element add the following. This solution works by order of processing: everything is hidden in CSS, angular is loaded, and then CSS shows the app root. I like to use this so if there are other non-angular elements on the page they will render first making the page appear to load faster.
/* in your CSS file in head */
.myApp {
display:none;
}
<div class="myApp" ng-app="myApp"></div>
Just before the body ends add your script references and some inline CSS:
<script language="javascript" type="text/javascript" src="angular.min.js"></script>
<style>
.myApp {
display:block;
}
</style>
</body>
A: Instead of using class, you should use ng-class
<body ng-class="{{ bodyClass }}">
A: One of the problems that you're facing is that the browser will display the <body> element before AngularJS has loaded and started manipulating the DOM. What other people said about ng-class is correct, it will do the right class applying but you still need to not show anything before Angular is ready.
In previous versions of Angular you could do this:
<body style="display:none" ng-show="true" ng-class="{{bodyClass}}">
In recent versions this doesn't work however because ng-show does its visibility by adding and removing the ng-hide class (which is less specific than an element attribute)
What I've been doing recently is this:
<head>
...
<style> <!-- Or you could include this in an existing style sheet -->
.ng-cloak {
display: none !important;
}
</style>
</head>
<body class="ng-cloak" ng-cloak ng-class="{{bodyClass}}">
Doing it this way means that the <body> will be immediately hidden by the style for the ng-cloak class. When Angular does start up it will process all of the directives include ng-class and ng-cloak, so your <body> element will then have the right class and be visible.
Read more here ng-cloak directive
A: I've noticed sometimes even ng-cloak doesn't seem to actually work. Maybe I am doing something wrong.
<body ng-cloak class="{{ bodyClass }}">
I also do one more small thing similar to @mbokil you can hide the element by default. By using an attribute selector targeting any elements with the attribute ng-cloak you're able to utilize angular directives. This has several benefits, but the main benefit is once angular fires it removes this attribute which will trigger a redraw.
<style>
[ng-cloak] {
display:none;
}
</style>
| |
doc_23532749
|
CREATE TABLE [dbo].[soft] (
[img_pk] [int] IDENTITY (1, 1) NOT NULL ,
[name] [varchar] (50) NULL ,
[img_data] [image] NULL ,
[img_contenttype] [varchar] (50) NULL,
[file_data] [image] NULL ,
[file_contenttype] [varchar] (50) NULL
)
ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[soft] WITH NOCHECK ADD
CONSTRAINT [PK_image] PRIMARY KEY NONCLUSTERED
(
[img_pk]
) ON [PRIMARY]
GO
No problem with the first part, it's solved like
string query1 = "CREATE TABLE soft" +
"(pk int IDENTITY (1, 1) NOT NULL," +
"name VARCHAR(50) NULL, img_data IMAGE NULL, img_contenttype VARCHAR(50) NULL, file_data IMAGE NULL, file_contenttype VARCHAR(50) NULL)"
But no ideas how to work with the next part. Can anyone help me?
A: You can combine the table and primary key definitions:
CREATE TABLE [dbo].[soft]
(
[img_pk] [int] IDENTITY (1, 1) NOT NULL
CONSTRAINT PK_Image PRIMARY KEY CLUSTERED,
[name] [varchar] (50) NULL ,
[img_data] [image] NULL ,
[img_contenttype] [varchar] (50) NULL,
[file_data] [image] NULL ,
[file_contenttype] [varchar] (50) NULL
)
GO
You can dispense with the extra 'ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] ' if that's your default FileGroup, which it is in many (most?) cases
Also, I have created the PK as Clustered, which is more usual for an auto-inc column.
Also:
ntext, text, and image data types will
be removed in a future version of
Microsoft SQL Server. Avoid using
these data types in new development
work, and plan to modify applications
that currently use them. Use
nvarchar(max), varchar(max), and
varbinary(max) instead.
A: You mean just load the query into a string? You can use the @"" multi-line string syntax:
string query2 = @"
ALTER TABLE [dbo].[soft] WITH NOCHECK ADD
CONSTRAINT [PK_image] PRIMARY KEY NONCLUSTERED
(
[img_pk]
) ON [PRIMARY]
";
(The 'ON PRIMARY .. GO' is part of the first query, by the way.)
To execute this you'd use something like
var command2 = dbConnection.CreateCommand();
command2.CommandText = query2;
command2.ExecuteNonQuery();
as usual.
A: Any problems you face when you use single line queries ??
string query = "ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER TABLE [dbo].[soft] WITH NOCHECK ADD CONSTRAINT [PK_image] PRIMARY KEY NONCLUSTERED ( [img_pk] ) ON [PRIMARY] GO";
| |
doc_23532750
|
A: Well, my answer will not go far from 'nothing at all', but maybe it'll be of some use.
GtkD is basically a wrapper around GTK+. That means, that there's almost a one-to-one correspondence between its functions. Also, this means that the object models are exactly the same.
E.g. there are such entities like windows, buttons, etc. Those have some relations, like, button can be placed on a window. Conceptually, all of those objects and relations are exactly the same for both GtkD and GTK+ (v3.x).
And for a GUI toolkit this object model is the most important thing to study and understand. Also, it's the biggest thing. So, if you understand this model: what objects there are and how they can be used together - you'll be successful in writing GUI apps using either GTK+ or GtkD.
The syntactical difference you'll need to overcome is pretty trivial compared to this.
I would suggest to use the GTK+ documentation when looking for how-to-do-stuff and use the GtkD documentation to understand how those concepts are implemented in D. E.g. in GTK+ v2.x to add a button on a window you use something like
gtk_container_add (GTK_CONTAINER (window), button);
and in GtkD you can do the same by
window.add(button);
In other situations it can be a bit more complex and not that straightforward at first, but will be more and more easy when you get some experience.
A: Upon further digging, I discovered this (very handy!) series of tutorials on GtkD here.
| |
doc_23532751
|
Group
+----+-----------+----------------+
| Id | GroupId | GroupName |
+----+-----------+----------------+
| 1 | 10 | Grp1@abc.com |
| 2 | 20 | Grp2@abc.com |
| 3 | 30 | Grp3@xyz.com |
| 4 | 40 | Grp4@def.com |
+----+-----------+----------------+
Customer
+---+-----------------+------------+----------+---------------+
| Id | GroupAliasName | Domain | GroupId | CustomerName |
+---+-----------------+------------+----------+---------------+
| 1 | Grp1 | abc.com | null | Cust1 |
| 2 | Grp2 | abc.com | null | Cust2 |
| 3 | Grp3 | xyz.com | null | Cust3 |
| 4 | Grp4 | def.com | null | Cust4 |
+---+-----------------+------------+----------+---------------+
Now from Customer table 'GroupAliasName' and 'Domain' when concatenated as 'GroupAliasName@Domain' is equivalent to 'GroupName' in Group table.
Using the concatenated value from Customer table, I need to pull the 'GroupId' from the Group table and populate the same in Customer table's 'GroupId' as below
Customer
+----+----------------+------------+----------+---------------+
| Id | GroupAliasName | Domain | GroupId | CustomerName |
+----+----------------+-----------+---------+-----------------+
| 1 | Grp1 | abc.com | 10 | Cust1 |
| 2 | Grp2 | abc.com | 20 | Cust2 |
| 3 | Grp3 | xyz.com | 30 | Cust3 |
| 4 | Grp4 | def.com | 40 | Cust4 |
+----+----------------+------------+----------+---------------+
The query which I tried is as below
UPDATE Customer SET GroupId =
(SELECT GroupId FROM Group G
WHERE GroupName =
(SELECT CONCAT(GroupAliasName, '@', Domain) AS GroupName
FROM Customer
WHERE Domain IS NOT NULL) AND G.GroupName = GroupName);
But I get error as 'Subquery returns more than 1 row'.
Please suggest or provide your inputs.
A: Try with somethings like this
UPDATE Customer as c
INNER JOIN Group as g on ( CONCAT(c.GroupAliasName, '@', c.Domain) = g.GroupName)
SET c.GroupId = g.GroupId;
A: Try this:
update customer as cust
inner join `group` grp on concat(cust.groupaliasname, '@', cust.domain) = grp.groupname
set cust.groupId = grp.groupId;
| |
doc_23532752
|
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) ->UICollectionViewCell
{
if indexPath.row == arrayProducts.count - 1
{
loadNextPage(collectionView, forIndexPath: indexPath)
}
}
internal func loadNextPage(view: UICollectionView, forIndexPath indexPath: NSIndexPath){
self.collectionFooter.hidden = false;
self.pageNumber! = self.pageNumber! + 1
self.getProductsByCategoryId()//this is my api call,
}
| |
doc_23532753
|
How I can do that fast?
All I can think of is this:
int start_x = 512, start_y = 600;
int end_x = 1024, end_y = 1200;
byte[,] new_arr = byte[end_x - start_x, end_y - start_y];
for (int x = start_x; x < end_x; x++)
for (int y = start_y; y < end_y; y++)
new_arr[x - start_x, y - start_y] = arr[x, y];
but that's a lot of assign operations. Is there any faster way?
A: You can use Buffer.BlockCopy to copy a block of contiguous memory from one array to another. For example:
// Names changed to be more conventional
int originalHeight = ...; // Original "height" in array
int newHeight = endY - startY;
for (int x = startX; x < endX; x++)
{
Buffer.BlockCopy(
array, x * height + startY, // Copying from here...
newArray, x * newHeight, // To here...
newHeight); // A whole column
}
If you're copying complete columns (i.e. startY is 0, and endY is originalHeight) then you could just call Buffer.BlockCopy once, with the appropriate values.
If you're really thinking about copying lines rather than columns, you might want to consider reordering your arrays so that the y value comes first - currently you have the whole of the first column, followed by the whole of the second column etc.
A: You can make it a little bit more efficient by removing un-necessary re-calculation of x - start_x:
int start_x = 512, start_y = 600;
int end_x = 1024, end_y = 1200;
byte[,] new_arr = byte[end_x - start_x, end_y - start_y];
for (int x = start_x; x < end_x; x++)
{
int target_x = x - start_x;
for (int y = start_y; y < end_y; y++)
new_arr[target_x, y - start_y] = arr[x, y];
}
| |
doc_23532754
|
public class Main {
public static void main(String[] args) {
double d = 1;
switch (d) {
case 0.0: System.out.println("The value is zero");
case 1.0: System.out.println("The value isn't zero");
default: System.out.println("It's something else");
}
}
}
Here's the complete error:
Exception Details:
Location:
Main.main([Ljava/lang/String;)V @3: tableswitch
Reason:
Type double_2nd (current frame, stack[1]) is not assignable to integer
Current Frame:
bci: @3
flags: { }
locals: { '[Ljava/lang/String;', double, double_2nd }
stack: { double, double_2nd }
Bytecode:
0000000: 0f48 27aa 0000 0025 0000 0000 0000 0001
0000010: 0000 0015 0000 001d b200 1012 16b6 0018
0000020: b200 1012 1eb6 0018 b200 1012 20b6 0018
0000030: b1
Stackmap Table:
append_frame(@24,Double)
same_frame(@32)
same_frame(@40)
Does this mean switch statements cannot be used at all on doubles? When I try the same code but using an int instead of a double it works as it should.
(using Java 17 in VSCode 1.6.4 on Windows 10 64 bit)
A: The problem is in double representation in computer. Floating point are not very good for switch.
For example even this if would not work in Java:
if(0.1 + 0.2 == 0.3)
If you really need to compare them, you can use something called threshold comparison method. Where you do something like this:
double epsilon = 0.000000000000001d;
if(Math.abs(d1 - 0.0) < epsilon) {
System.out.println("The value is zero");
}
else if(Math.abs(d1 - 1.0) < epsilon) {
System.out.println("The value isn't zero");
}
else {
System.out.println("It's something else");
}
If you dont like this solution, you can try to look at https://www.baeldung.com/java-comparing-doubles there are more solutions.
| |
doc_23532755
|
I do not want to query the api each time a new page is loaded but also want to retain the location information that views and controllers and use it.
A: To pass a gobal variable from a controller to a view you need to use @ in front of your variables (e.g. @geodata being your object).
To save the information you should either add some field location to your User model or create a new Geowhatever model and assign it to each user (and maybe to other models via polymorphism).
This way you can do @user.location or @user.geowhatever.location in your views.
The only caveat when doing caching is to keep the cache up to date. Here an observer UserObserver can do the task.
| |
doc_23532756
|
thx!
<?php global $post;
$categories = get_the_category();
foreach ($categories as $category) :
?>
<h3 class="naslovostalih">Ostali članci iz ove kategorije:</h3>
<ul class="clanciostalih">
<?php
$posts = get_posts('numberposts=15&category='. $category->term_id);
foreach($posts as $post) :
$title = get_the_title($ID);
$link = get_permalink();
printf('<a class="linkpost" title="%s" href="%s">%s</a>', $title, $link, $title);
the_post_thumbnail('thumb-232');
the_excerpt();
?>
<p class="more-link-wrapper2"><a href="<?php the_permalink(); ?>" class="read-more button"><?php _e( 'Opširnije »', 'fearless' ); ?></a></p>
<?php endforeach; ?>
<?php endforeach; ?>
</ul>
I've tried this :
Ostali članci iz ove kategorije:
<?php
$posts = get_posts('numberposts=15&category='. $category->term_id);
foreach($posts as $post) :
echo ('<div class="onepost">');
$title = get_the_title($ID);
$link = get_permalink();
printf('<a class="linkpost" title="%s" href="%s">%s</a>', $title, $link, $title);
the_post_thumbnail('thumb-232');
the_excerpt();
?>
<p class="more-link-wrapper2"><a href="<?php the_permalink(); ?>" class="read-more button"><?php _e( 'Opširnije »', 'fearless' ); ?></a></p>
echo ('</div>');
<?php endforeach; ?>
<?php endforeach; ?>
</ul>
A: `
<?php global $post;
$categories = get_the_category();
foreach ($categories as $category) :
?>
<h3 class="naslovostalih">Ostali clanci iz ove kategorije:</h3>
<ul class="clanciostalih">
<?php
$posts = get_posts('numberposts=15&category='. $category->term_id);
foreach($posts as $post) :
?>
<li>
<?php
$title = get_the_title($ID);
$link = get_permalink();
printf('<a class="linkpost" title="%s" href="%s">%s</a>', $title, $link, $title);
the_post_thumbnail('thumb-232');
the_excerpt();
?>
<p class="more-link-wrapper2"><a href="<?php the_permalink(); ?>" class="read-more button"><?php _e( 'Opširnije »', 'fearless' ); ?></a></p>
</li>
<?php endforeach; ?>
</ul>
<?php endforeach; ?>
`
I think your code had tag opening and closing issues. Try this code. :)
| |
doc_23532757
|
@Override
protected String doInBackground(String... credentials) {
// TODO Auto-generated method stub
oAuth_ConsumerKey = credentials[0];
oAuth_ConsumerSecret = credentials[1];
accessToken = credentials[2];
accessTokenSecret = credentials[3];
System.out.println("Credentials -------- " + oAuth_ConsumerKey
+ "\n" + oAuth_ConsumerSecret + "\n" + accessToken + "\n"
+ accessTokenSecret);
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(oAuth_ConsumerKey)
.setOAuthConsumerSecret(accessTokenSecret);
builder.setOAuthAccessToken(accessToken);
builder.setOAuthAccessTokenSecret(accessTokenSecret);
TwitterFactory twitterFactory = new TwitterFactory(builder.build());
Twitter twitter = twitterFactory.getInstance();
try {
List<twitter4j.Status> statuses;
String user = "@pagename";
statuses = twitter.getUserTimeline(user);
for (int i = 0; i < statuses.size(); i++) {
twitter4j.Status status = statuses.get(i);
Log.i("Tweet Count " + (i + 1), status.getText() + "\n\n");
}
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
(The above code is being done in the doInBackground method of the AsyncTask. Just thought you should know)
And I am getting an error saying: No authentication challenges found. Relevant discussions can be found on the Internet at: ...
I viewed previous posts and it said to check my date and time. I did that and they are all correct and set to automatic. (Since i have a slow internet connection) I also tried running it on a faster internet connection. I now think that there is something wrong with my code.
I am new to integrating twitter to my android app so explanatory guidance would also be helpful along with the answer.
Thanks...
A: Twitter4j adapts singletone and it maintains its login/authentication status and raises exceptions everytime you try to login/authenticate
What you have to do is separate the authentication login from the rest of API calls. in your case you need something like this:
private Twitter mTwitter;
private void login(String[] credentials){
String oAuth_ConsumerKey = credentials[0];
String oAuth_ConsumerSecret = credentials[1];
String accessToken = credentials[2];
String accessTokenSecret = credentials[3];
System.out.println("Credentials -------- " + oAuth_ConsumerKey
+ "\n" + oAuth_ConsumerSecret + "\n" + accessToken + "\n"
+ accessTokenSecret);
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(oAuth_ConsumerKey)
.setOAuthConsumerSecret(accessTokenSecret);
builder.setOAuthAccessToken(accessToken);
builder.setOAuthAccessTokenSecret(accessTokenSecret);
TwitterFactory twitterFactory = new TwitterFactory(builder.build());
mTwitter = twitterFactory.getInstance();
}
private List<Status> getTimeLine(){
List<twitter4j.Status> statuses = null;
try {
String user = "@pagename";
statuses = mTwitter.getUserTimeline(user);
for (int i = 0; i < statuses.size(); i++) {
twitter4j.Status status = statuses.get(i);
Log.i("Tweet Count " + (i + 1), status.getText() + "\n\n");
}
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return statuses;
}
Make sure you call both methods from background thread and call login once every run.
| |
doc_23532758
|
How could make this possible?.
A: You should share your views.py code.
anyway you can use HttpResponseRedirect
Example :
from django.http import HttpResponseRedirect
def index(request):
# you logic to check login
return HttpResponseRedirect('/') # it will redirect you to "/"
| |
doc_23532759
|
java.lang.InstantiationError: org.apache.axis2.databinding.ADBDataSource
org.wso2.carbon.um.ws.api.stub.Authenticate.getOMElement(Authenticate.java:126)
org.wso2.carbon.um.ws.api.stub.RemoteUserStoreManagerServiceStub.toEnvelope(RemoteUserStoreManagerServiceStub.java:9387)
org.wso2.carbon.um.ws.api.stub.RemoteUserStoreManagerServiceStub.authenticate(RemoteUserStoreManagerServiceStub.java:4030)
org.wso2.sample.LoginServlet.authenticate(LoginServlet.java:77)
org.wso2.sample.LoginServlet.doPost(LoginServlet.java:38)
javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.wso2.sample.AuthenticationFilter.doFilter(AuthenticationFilter.java:42)
| |
doc_23532760
|
I have a problem when executing the following code is shows "Commands Completed successfully" but no result from my SELECT PROBLEM 1, and also when executed seperayly it works but the result change the whole time*PROBLEM 2* e.g result1: 10:41 executed again 20:82. I just need it to be 10:41 (* I am counting how many 'Jobs' are open and closed
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[p_GetSocre]
@AUD_ID BIGINT,
@RowCounter BIGINT,
@DistinctCounter BIGINT,
@NACounter BIGINT,
@Total BIGINT,
@Status NVARCHAR(10)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
CREATE TABLE #tmp1
(
AUD_ID BIGINT,
RowCounter BIGINT,
DistinctCounter BIGINT,
NACounter BIGINT,
Total BIGINT,
[Status] VARCHAR(MAX)
)
INSERT INTO #tmp1
EXEC [p_GetCompleteIncompleteNaOverviewSCORE]
END
SELECT [Status] AS [Open/Closed], COUNT(*) AS [Status] FROM #tmp1
GROUP BY [Status]
--DROP TABLE #tmp1
The other stored proc [p_GetCompleteIncompleteNaOverviewSCORE] only counts if all parts of the job are done before it gives it a status of open/closed
Thanx
A: Please try below... Drop temp table is not necessary as Proc automatically drops temp table..
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[p_GetSocre]
@AUD_ID BIGINT,
@RowCounter BIGINT,
@DistinctCounter BIGINT,
@NACounter BIGINT,
@Total BIGINT,
@Status NVARCHAR(10)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
CREATE TABLE #tmp1
(
AUD_ID BIGINT,
RowCounter BIGINT,
DistinctCounter BIGINT,
NACounter BIGINT,
Total BIGINT,
[Status] VARCHAR(MAX)
)
INSERT INTO #tmp1
EXEC [p_GetCompleteIncompleteNaOverviewSCORE]
SELECT [Status] AS [Open/Closed], COUNT(*) AS [Status] FROM #tmp1
GROUP BY [Status]
END
| |
doc_23532761
|
My above table has ~10L data. While using EXPLAIN, it shows as,
From this, type shows ALL, Extra shows Using where and rows not in O(1). But, for searching on primary key, the type should be const, rows be in O(1) ?? I can't able to figure out the issue, which results in slowing the queries.
A: Your id field is varchar while you pass the value you are looking for as a number.
This means that mysql has to perform an implicit data conversion and will not be able to use the index for looking up the value:
For comparisons of a string column with a number, MySQL cannot use an
index on the column to look up the value quickly. If str_col is an
indexed string column, the index cannot be used when performing the
lookup in the following statement:
SELECT * FROM tbl_name WHERE str_col=1;
The reason for this is that
there are many different strings that may convert to the value 1, such
as '1', ' 1', or '1a'.
Either convert your id field to number or pass the value as string.
A: As your id column is varchar, you need to provide it String while searching.
Try, id= '123456'
Reason:
Since you are comparing a varchar column to Int, it will first convert all rows to Int, and then match it with 123456(int).
| |
doc_23532762
|
A: See below example
// Bind
$( "#members li a" ).on( "click", function( e ) {} );
$( "#members li a" ).bind( "click", function( e ) {} );
// Live
$( document ).on( "click", "#members li a", function( e ) {} );
$( "#members li a" ).live( "click", function( e ) {} );
// Delegate
$( "#members" ).on( "click", "li a", function( e ) {} );
$( "#members" ).delegate( "li a", "click", function( e ) {} );
For Reference
http://www.elijahmanor.com/differences-between-jquery-bind-vs-live-vs-delegate-vs-on/
A: The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers. For help in converting from older jQuery event methods, see .bind(), .delegate(), and .live(). (Quote from jQuery .on page.)
A: The mainly pros is on() work in dynamic elements (instead of live()).
Read more: http://api.jquery.com/on/
| |
doc_23532763
|
Where can I configure that in Idea properties?
It's not defined in pom.xml files and I'd prefer not to.
A: Not sure if it will work also on Idea Intellij ( I am using spring source studio - eclipse clon) , but should because maven configuration is in settings.xml in .M2 directory which is located in your home directory. Just use something like this ( my server is running on nexus-server:8081):
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
<servers>
<server>
<id>releases</id>
<username>user-name</username>
<password>your-password</password>
</server>
<server>
<id>snapshots</id>
<username>user-name</username>
<password>your-password</password>
</server>
</servers>
<mirrors>
<mirror>
<!--This sends everything else to /public -->
<id>nexus</id>
<mirrorOf>*</mirrorOf>
<url>http://nexus-server:8081/nexus/content/groups/public</url>
</mirror>
</mirrors>
<profiles>
<profile>
<id>nexus</id>
<!--Disable snapshots for the built in central repo to direct -->
<!--all requests to nexus via the mirror -->
<repositories>
<repository>
<id>central</id>
<url>http://central</url>
<releases>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>central</id>
<url>http://central</url>
<releases>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</profile>
</profiles>
<activeProfiles>
<!--make the profile active all the time -->
<activeProfile>nexus</activeProfile>
</activeProfiles>
</settings>
| |
doc_23532764
|
getData(id) {
if(isInCache(id)) return getFromCache(id) // already in cache?
data = fetchComplexDataStructureFromDatabase(id) // time consuming!
setCache(id, data) // update cache
return data
}
updateData(id, data) {
storeDataStructureInDatabase(id, data)
clearCache(id)
}
In the above implementation, there is a problem with concurrency, and we might end up with outdated data in the cache: consider two parallel executions running getData() and updateData(), respectively. If the first execution fetches data from the cache exactly in between the other execution's call to storeDataStructureInDatabase() and clearCache(), then we will get an outdated version of the data. How would you get around this concurrency problem?
I considered the following solution, where the cache is invalidated just before data is committed:
storeDataStructureInDatabase(id, data) {
executeSql("UPDATE table1 SET...")
executeSql("UPDATE table2 SET...")
executeSql("UPDATE table3 SET...")
clearCache(id)
executeSql("COMMIT")
}
But then again: If one execution reads the cache in between the other execution's call to clearCache() and COMMIT, then an outdated data will be fetched to the cache. Problem not solved.
A: In the cache way of thinking you cannot prevent retrieving outdated data.
For example, when someone start sending an HTTP request (if your application is a web application) that will later render the cache invalid, should we consider the cache invalid when the POST request start? when the request is handled by your server? when you start the controller code?. Well no. In fact the cache is invalid only when the database transaction ends. Not even when the transaction start, only at the end, on the COMMIT phase of the transaction. And any working process working with previous data has very few chances of being aware that the data as changed, in a web application what about html pages showing outdated data in a browser, do you want to flush theses pages?
But let's just think your parallel process are not just there for the web, but for real concurrency critical parallel jobs.
One problem is that your cache is not handled by the database server, so it's not in the transaction COMMIT/ROLLBACK. You cannot decide to clear the cache first but rebuild it if you rollback. So you can only clear and rebuild the cache after the transaction is commited.
And that lead the possibility to get an outdated version of the cache if your get comes between the database commit and the cache clear instruction. So :
*
*is it really important that you have an outdated version of the cache? Let's say your parallel process made something just a few milliseconds before you would have retrieve this new version (so it's the old one) and work with it for maybe 40ms, and then build final report on that without noticing the cache have been flush 15ms before the end of the work. If your process response cannot contain any outdated data, then you'll have to check data validity before outputing it (so you should recheck that all data used in the work process are still valid at teh end).
*So if you don't want to recheck data validity that mean your process should have put some lock (semaphore?) when starting and should release the lock only at the end of the work, your are serializing your work. Databases can speed up serialization by working on pseudo-serialization levels for transactions and breaking your transaction if any changes make this pseudo-serialization hasardous. But here you're not only working with a database so you should do the serialization on your own side.
*Process serialization is slow, but you may try to do the same as the database, that is runing jobs in parallel and invalidating any job running when data is altered (so having something that detect your cache clear and kill and rerun all existing parallel jobs, implying you have something mastering all the parallel jobs)
*or simply accept you can have small past-invalid-outdated data. If we talk of web application the time your response walks on TCP/IP to the client browser it may be already invalid.
Chances are that you will accept to work with outdated cache data. The only really important point is that if you cannot trust your cache data for a really critical thing then you should'nt use a cache for that. If your are manipulating Accounting data for example. The only way to get a serialization of parallel tasks is to do:
*
*in the Writing process: all the important reads (the one that will get some writes) and all the write things in a transaction with a high isolation level (level 4) and with all necessary row locks. That's something hard to do working only with a database, it's quite impossible if you add an external cache for read operations.
*in parallel read process: do what you want (read from external cache), if the read data won't be used for write operations. If one of the read data will later be use for a write operation this data validity will have to be checked in the write transaction (so in the Writing process). Why not adding a timestamp watermark on the data, so that when it will come back for a write operation you'll be able to know if it is still valid.
| |
doc_23532765
|
I have these type of array in javascript.Now i want to remove the value from array which name is "PropertyType[]".How to do it.Here i upload the picture of array.Here in Newremoveurl array i get the array value.
var Newremoveurl = [];
var Parant_name = 'PropertyType';
$.each(Removeurl_array, function( key, value){
var decoded_key = decodeURI(value);
if ($.inArray(Parant_name, Newremoveurl)!='-1') {
}
Newremoveurl[key]=decoded_key;
});
A: you can filter your array to remove these with standard javascript
for an exact match - you can remove like this
const filteredResults = myArray.filter(item => item === "PropertyType[]")
or for values which contain a string
const filteredResults = myArray.filter(item => item.indexOf("PropertyType[]") ===-1)
A: for (var i=myArr.length; i--;) {
if (myArr[i].indexOf("PropertyType")>=0) break;
}
Value of i will be -1 if PropertyType* does not exist, or else it would be the index of the element.
Then cut the element from the array with
if (index > -1) {
myArr.splice(index, 1);
}
You can run this solution till the value of i becomes -1, then your array would hopefully be free of the element you do not require.
| |
doc_23532766
|
generic-usb: probe of 0003:099A:2620.000F failed with error -22
and i never get to connect to the device. It seems like the systems drivers are overriding my driver in some way?
My code is registering & unregistering correctly using insmod / rmmod:
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/usb.h>
#include <linux/slab.h>
MODULE_DEVICE_TABLE (usb, id_table);
struct usb_device_id id_table[] =
{
{USB_DEVICE(0x099a, 0x2620)}, //Zippy Technology Corp. Digi Tablet
{0}
};
void dt_disconnect(struct usb_interface *interface)
{
printk("dt_disconnect called\n");
}
int dt_probe(struct usb_interface *interface, const struct usb_device_id *id)
{
printk("dt_probe called\n");
return 0;
}
static struct usb_driver dt_driver =
{
.name = "Zippy Technology Corp. Digi Tablet",
.probe = dt_probe,
.disconnect = dt_disconnect,
.id_table = id_table
};
static int __init dt_init(void)
{
//0 means success
int error = usb_register(&dt_driver);
if(error)
printk("dt_init failed\n");
return 0;
}
static void __exit dt_exit(void)
{
//void
usb_deregister(&dt_driver);
}
module_init(dt_init);
module_exit(dt_exit);
MODULE_LICENSE("GPL");
dt_probe is never called. I'm using Linux 2.6.40 (Fedora 15's version of 3.0) and most documentation about this stuff is very old so I thought I'd ask here. Any thoughts?
A: Yes, usbhid driver overrides your driver. You need to remove the usbhid driver from the running kernel. First deattach your device from the system and use "modprobe -r usbhid" to remove the usbhid module. Now insert your module and attach the device, then your driver will be taken.
| |
doc_23532767
|
php code
$symbol = $request->symbol;
$ticker = $api->prices();
foreach ($symbol as $ticker => $pairname)
{
echo $pairname;
}
in postman I send request like this
{
"symbol":"BTCUSDT"
}
When I var_dump $ticker variable the response I get is as follows
array(147) {
["XRPBUSD"]=>
string(6) "0.5881"
["MKRUSDT"]=>
string(7) "2003.70"
["SRMUSDT"]=>
string(6) "2.2300"
["BTCUSDT"]=>
string(6) "37173.34" ... } and etc.
I need when I send symbol value in postman that it prints that value in foreach loop from that $ticker variable. Currently I get NULL value.
A: You are sending a string and not a json array, it is normal that the foreach does not read.
Try this :
"symbol": [
{
"BTCUSDT"
}]
| |
doc_23532768
|
Exception of type 'Microsoft.SharePoint.SoapServer.SoapServerException' was thrown.
<detail><errorstring xmlns="http://schemas.microsoft.com/sharepoint/soap/">
List does not exist.
The page you selected contains a list that does not exist. It may have been deleted by another user.
</errorstring><errorcode xmlns="http://schemas.microsoft.com/sharepoint/soap/">0x82000006</errorcode></detail>
Please let me know if there is a way to fix it.
A: I recently ran into the exact same error message. In my case, the InfoPath Form was created with InfoPath 2010 and migrated to Sharepoint 2013. Editing with InfoPath 2013 yields the error message above. Editing with Infopath 2010 I can edit the form without any issue.
A: Perhaps its because you have a lookup field in your list, and during import process the link to lookup list is broken
| |
doc_23532769
|
I have a huge xml file, and need to first check the value of "status" tag in the root. It eat even double of the memory than when processing tag = item. And I have no idea why.
I use lxml version 2.3.2, and python 2.7.3 in ubuntu 14.04.
Structure of the xml is as below:
<root>
<status>s_value</status>
<count>c_value</count>
<items>
<item>***</item>
<item>***</item>
...
</items>
</root>
I try to process the file as below (ignore the namespace):
from lxml import etree
status = etree.iterparse('file.xml', tag='status')
for event, element in status:
value = element.text
element.clear()
del status
This code still eat a lot memory and also take long time (15s).
I tried to use a "break", and it gets the same result, but is much faster (1s), can not see the memory usage, as it is fast.
from lxml import etree
status = etree.iterparse('file.xml', tag='status')
for event, element in status:
value = element.text
element.clear()
break
del status
It seems something happen after run the first status, but as there is only one element in status, I am wondering what is processed?
Dose any one has any idea what is happening? Thanks very much
A:
It seems something happen after run the first status
Yes. It is vainly searching for the second status.
Without the break, your loop must process the entire file. The loop searches for all of the <status> tags. Without reading the file to the end, it cannot know if it has found the final tag.
Alternatively, with the break, the loop stops immediately.
Consider these two loops:
for i in range(1000000):
if i == 1:
print(i)
for i in range(1000000):
if i == 1:
print(i)
break
Hopefully, you can see that the first loop must run one million times, even though it will find the one-and-only 1 immediately.
Similarly with your code, your non-break loop must run over a bajillion lines, even though it will find the one-and-only <status> immediately.
| |
doc_23532770
|
public MainWindow()
{
InitializeComponent();
Closing += (x, y) =>
{
y.Cancel = true;
_discard = true;
CheckSettings();
};
}
public void CheckSettings(bool x)
{
if(x)
Close();
}
on the Close line I get:
cannot set visibility or call show or showdialog after window has closed
why??
A: (as requested in you comment...)
You cannot call Close from a Closing event handler.
If the logic determining if the form can be closed is implemented in CheckSettings:
public MainWindow()
{
InitializeComponent();
Closing += (sender, args) =>
{
args.Cancel = !CheckSettings();
...
};
}
public bool CheckSettings()
{
// Check and return true if the form can be closed
}
A: Until you return from your event handler (that's made the call to CheckSettings), the UI framework you're using may not evaluate the content of the EventArgs that you've named as y and set Cancel = true on.
If you're using WPF, for example, the Close method eventually calls down into another method called VerifyNotClosing (via InternalClose) which at the time of writing looks like this:
private void VerifyNotClosing()
{
if (_isClosing == true)
{
throw new InvalidOperationException(SR.Get(SRID.InvalidOperationDuringClosing));
}
if (IsSourceWindowNull == false && IsCompositionTargetInvalid == true)
{
throw new InvalidOperationException(SR.Get(SRID.InvalidCompositionTarget));
}
}
The relevant bit there is the first if that checks a member variable called _isClosing and throws an exception if the form is in the process of closing.
The InternalClose method reacts to the state of the Cancel property of the EventArgs after the event handlers have been called:
CancelEventArgs e = new CancelEventArgs(false);
try
{
// The event handler is called here
OnClosing(e);
}
catch
{
CloseWindowBeforeShow();
throw;
}
// The status of the .Cancel on the EventArgs is not checked until here
if (ShouldCloseWindow(e.Cancel))
{
CloseWindowBeforeShow();
}
else
{
_isClosing = false;
// 03/14/2006 -- hamidm
// WOSB 1560557 Dialog does not close with ESC key after it has been cancelled
//
// No need to reset DialogResult to null here since source window is null. That means
// that ShowDialog has not been called and thus no need to worry about DialogResult.
}
The code above (from the InternalClose method) is after the call to VerifyNotClosing which is why the subsequent call to Close, before the first one has finished, results in the exception being thrown.
| |
doc_23532771
|
This is installed libstdc++ detail :
>yum list | grep libstdc++
compat-libstdc++-33.x86_64 3.2.3-69.el6 @base
libstdc++.x86_64 4.4.7-4.el6 @base
libstdc++-devel.x86_64 4.4.7-4.el6 @base
compat-libstdc++-296.i686 2.96-144.el6 base
compat-libstdc++-33.i686 3.2.3-69.el6 base
libstdc++.i686 4.4.7-4.el6 base
libstdc++-devel.i686 4.4.7-4.el6 base
libstdc++-docs.x86_64 4.4.7-4.el6 base
A: You can replace your unrar version to x64. So, you can find the download version in: Rarlab website (as sudo):
tar -xvzf rarlinux-x64-5.5.b4.tar.gz
--Move the rar folder to /usr/local:
mv rar /usr/local/
--Go to /usr/local/bin:
cd /usr/local/bin
--Create a link for unrar:
ln -s /usr/local/rar/unrar
--in command, type:
unrar x filename.rar
Best Regards,
José Junior
| |
doc_23532772
|
I am getting type initialization exception at below line.
var path = InputOptions.downloadsPath;
InputOptions is a class I wrote. It contains this:
public static readonly string parentpath = Directory.GetParent(Directory.GetCurrentDirectory()).ToString();
public static readonly string downloadsPath = parentpath + @"\DATA\Download";
| |
doc_23532773
|
A: You can do that, but typically it is easier to host the backend on a subdomain, e.g. you'd host the backend on something like backend.domain.com and the frontend on domain.com and/or www.domain.com. You can configure a setup like this relatively easy with nginx for example, by setting up two location blocks, one pointing to your Laravel installation, the other one to your vue 3 application.
To get back to your question, you can also set it up like you wanted, e.g. in a subfolder instead of via a subdomain. You can also do that via location blocks with nginx, but then you'd have to make sure that the routes from your backend and your frontend never have any overlap, so I wouldn't recommend to go that way.
| |
doc_23532774
|
<input type="text" name="FirstName" mydirectivename />
Into something like this:
<span><input type="text" name="FirstName" /></span>
It was easy enough to get here:
<span type="text" name="FirstName"><input/><span>
But now I'm down in the weeds writing a compile function doing things that the documentation says "you should rarely need to do" and I'm thinking I'm off track. Is there a simple way to indicate that a specific element in a template should be the target of copied attributes?
Thanks
A: For your simple example here you can use something like this: http://plnkr.co/edit/BbwBLa?p=preview
The plunker will transclude the original element and reinsert it inside the wrapping element.
Alternatively you follow the other answer and specify everything you want to copy, for more control.
If you need to copy all attributes and you have a recent enough angular version (1.1.4 onwards, looking through the docs http://code.angularjs.org/1.1.4/docs/guide/directive) then you can try template functions which are described in the the link. These are given all of the original element's attributes and can use them to write a new template with the original attributes. I wouldn't recommend using template functions this way though as its a little too fiddly for my liking.
Edit
This does what you want in your simple example, very simply, in the link function. This should really go in the compile I think, but plunker went crazy when I put it in there. http://plnkr.co/edit/PLfSU6?p=preview
A: Try:
.directive("myDirective", function ($state) {
return {
restrict: "E",
replace: true,
controller: function(){},
template: function (element, attrs) {}
A: what about :
.directive("mydirectivename", function ($state) {
return {
restrict: "A",
replace: true,
template: '<span ng-transclude></span>',
| |
doc_23532775
|
I have using OpenTLD c++ version, but I have some problem with it, since it loses the object very easy. I have change some of the "Settings" trying to get it work better but without any success. I have also noticed that it has problems with interlaced videos.
My project is base on tracking a running person from behind, like this pic:
http://s14.postimg.org/5fac8v88x/Ejemplo5.png
I set the roi in the dorsal, it moves in every axis and has scale change a little bit faster than the OpenTLD can track.
I have looked everywhere for some information about tracking with fast scale changes but it seems to be not too much documentation.
The main changes of the code have been:
m_thetaP(0.95),
m_thetaN(0.35),
m_minSize(15),
m_camNo(0),
m_fps(30),
m_seed(0),
m_threshold(0.7),
m_proportionalShift(0.1),
Any idea of another code for tracking or where I should look for getting this more accurate?
Thanks!
PS:
I am also using HOG for the people detection when OpenTLD loses the tracking, but it works pretty bad too, I use the opencv sample code.
| |
doc_23532776
|
docker network create pgnet
docker run -it --rm \
--name pgdockerdb \
--network pgnet \
-p 5436:5432 \ # postgres is running in 5432 locally
-v /local/path/to/pgdb:/var/lib/postgresql/data \
-e POSTGRES_DB=pgdb \
-e POSTGRES_USER=pguser \
-e POSTGRES_PASSWORD=sstrongggpass \
postgres_image
I receive following answer (translated from spanish to english -> I don't know exact words that postgresql should write in english):
...first lines trying to create a new db...
initdb: error: directory «/var/lib/postgresql/data» exists but it is not empty
If you wan to create a new database cluster, erase or empty
the directory «/var/lib/postgresql/data», or exec initdb
with a different argument than «/var/lib/postgresql/data».
db exited with code 1
I tried to include a sh with pg_ctl start -D . in volume /docker-entrypoint-initdb.d/
I tried to include PUID and PGID enviroment variables in docker-compose.yml from id $user (root, user or 999 [because docker y chowning files to that user])
Worst thing is that one time worked but when y copied the up-to-date db, never worked again.
A: Finally, I realized that PG_VERSION wasn't in my directory so I created it. Then Postgres asked for more missing folders so, finally I suggest to create a new database to compare data structure to find if your directory is well formed.
I had a problem translating the files indeed, so I restored a previous version and it's working flawlessly.
| |
doc_23532777
|
Observable.cachedDefer(() -> createExpensiveFiniteObservable().cache(), 5, TimeUnit.MINUTES);
I have data sets that are expensive to construct and I want them cached long enough to support a process, but let them expire approximately between each run.
A: I've added the functionality to do this to rxjava-extras. The code below depends on rxjava-extras 0.6.8-RC2 or later (which is on Maven Central).
Run the main method below and you will see these results which seem to match the behaviour you desire (a reset of the cache whenever the time gap to next subscribe is >=5 seconds):
source emits Tue Oct 13 21:00:16 AEDT 2015
Tue Oct 13 21:00:16 AEDT 2015
Tue Oct 13 21:00:16 AEDT 2015
Tue Oct 13 21:00:16 AEDT 2015
Tue Oct 13 21:00:16 AEDT 2015
Tue Oct 13 21:00:16 AEDT 2015
source emits Tue Oct 13 21:00:31 AEDT 2015
Tue Oct 13 21:00:31 AEDT 2015
Tue Oct 13 21:00:31 AEDT 2015
Tue Oct 13 21:00:31 AEDT 2015
Tue Oct 13 21:00:31 AEDT 2015
Tue Oct 13 21:00:31 AEDT 2015
source emits Tue Oct 13 21:00:46 AEDT 2015
Tue Oct 13 21:00:46 AEDT 2015
Tue Oct 13 21:00:46 AEDT 2015
...
Main method:
public static void main(String[] args) throws InterruptedException {
Observable<Date> source = Observable
.defer(() ->
Observable
.just(new Date())
.doOnNext(
d -> System.out.println("source emits " + d)));
CloseableObservableWithReset<Date> cached =
Obs.cache(source, 5, TimeUnit.SECONDS, Schedulers.computation());
Observable<Date> o = cached
.observable()
.doOnSubscribe(() -> cached.reset());
for (int i = 0; i < 30; i++) {
o.doOnNext(System.out::println).subscribe();
Thread.sleep((i % 5 + 1)*1000);
}
cached.close();
}
Note that to reset the cache on every emission as well then where you see
.doOnSubscribe(() -> cached.reset())
put
.doOnSubscribe(() -> cached.reset())
.doOnNext(x -> cached.reset())
| |
doc_23532778
|
from how to cast the hexadecimal to varchar(datetime)?
code:
SELECT CAST(
'1900-01-01 00:00:00' +
INTERVAL CAST(CONV(substr(HEX(BinaryData),1,8), 16, 10) AS SIGNED) DAY +
INTERVAL CAST(CONV(substr(HEX(BinaryData),9,8),16,10) AS SIGNED)* 10000/3 MICROSECOND
AS DATETIME) AS converted_datetime
FROM
(
SELECT 0x0000A34900BD693D AS BinaryData
) d
But i need to convert CAST date CAST(0xA2380B00 AS Date) to varchar date
Is any possible?
A: Well, i don't really understand why you need to convert it to varchar, because if i'm not mistaken datetime behaving like string in most if not all of the situations.
However, you can use the DATE_FORMAT function. It outputs string, and you can format the datetime if you want.
| |
doc_23532779
|
It was this:
numpy.empty(100,100)
instead of
numpy.empty([100,100])
As I'm not really used to numpy, so I forgot the brackets. The code happily crunched the numbers and at the end, just before saving results to disk, it crashed on that line.
Just to put things in perspective I code on remote machine in shell, so IDE is not really an option. Also I doubt IDE would catch this.
Here's what I already tried:
*
*running pylint - well pylint kinda works. After I've disabled everything apart of errors and warnings, it even seem to be usefull. But pylint have serious issue with imported modules. As seen on official bug tracker devs know about it, but cannot/won't do anything about it. There is suggested workaround, but ignoring whole module, would not help in my case.
*running pychecker - if I create code snippet with the mistake I made, the pychecker reports error - same error as python interpreter. However if I run pychecker on the actual source file (~100 LOC) it reported other errors (unused vars, unused imports, etc.); but the faulty numpy line was skipped.
At last I have tried pyflakes but it does even less checking than pychecker/pylint combo.
So is there any reliable method which can check code in advance? Without actually running it.
A: Do you use unit tests? There is really no better way.
A: A language with stronger type checking would have been able to save you from this particular error, but not from errors in general. There are plenty of ways to go wrong that pass static type checking. So if you have computations that takes a long time, it makes sense to adopt the following strategies:
*
*Test the code from end to end on small examples (that run in a few seconds or minutes) before running it on big data that will consume hours.
*Structure long-running computations so that intermediate results are saved to files on disk at appropriate points in the computation. This means that when something breaks, you can fix the problem and restart the computation from the last save point.
*Run the code from the interactive interpreter, so that in the event of an exception you are returned to the interactive session, giving you a chance of being able to recover the data using a post-mortem debugging session. For example, suppose I have some long-running computation:
def work(A, C):
B = scipy.linalg.inv(A) # takes a long time when A is big
return B.dot(C)
I run this from the interactive interpreter and it raises an exception:
>>> D = work(A, C)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "q22080243.py", line 6, in work
return B.dot(C)
ValueError: matrices are not aligned
Oh no! I forgot to transpose C! Do I have to do the inversion of A again? Not if I call pdb.pm:
>>> import pdb
>>> pdb.pm()
> q22080243.py(6)work()
-> return B.dot(C)
(Pdb) B
array([[-0.01129249, 0.06886091, ..., 0.08530621, -0.03698717],
[ 0.02586344, -0.04872148, ..., -0.04853373, 0.01089163],
...,
[-0.11463087, 0.15048804, ..., 0.0722889 , -0.12388141],
[-0.00467437, -0.13650975, ..., -0.13894875, 0.02823997]])
Now, unlike in Lisp, I can't just set things right and continue the execution. But at least I can recover the intermediate results:
(Pdb) D = B.dot(C.T)
(Pdb) numpy.savetxt('result.txt', D)
| |
doc_23532780
|
waits for the server to respond. I've read about receive and congestion windows and I've set initcwnd to 400 on both endpoints. I also set
net.ipv4.tcp_window_scaling to 1. And both sockets are opened with TCP_NODELAY option to disable Nagle algorithm.
The RTT latency between endpoints is about 35ms.
It's clear from tcpdump trace below that at 14:02:46.310155 client sends its last packet and then it waits for ack from the server that arrives ~31ms after. Once it arrives it continues sending the data.
14:02:46.268179 IP client > server: Flags [S], seq 2645621234, win 28400, options [mss 1420,sackOK,TS val 6178563 ecr 0,nop,wscale 9], length 0
14:02:46.305282 IP server > client: Flags [S.], seq 339254367, ack 2645621235, win 28160, options [mss 1420,sackOK,TS val 4865788 ecr 6178563,nop,wscale 9], length 0
14:02:46.305343 IP client > server: Flags [.], ack 1, win 56, options [nop,nop,TS val 6178573 ecr 4865788], length 0
14:02:46.305592 IP client > server: Flags [P.], seq 1:44, ack 1, win 56, options [nop,nop,TS val 6178573 ecr 4865788], length 43
14:02:46.305954 IP client > server: Flags [.], seq 44:1452, ack 1, win 56, options [nop,nop,TS val 6178573 ecr 4865788], length 1408
14:02:46.306023 IP client > server: Flags [.], seq 1452:2860, ack 1, win 56, options [nop,nop,TS val 6178573 ecr 4865788], length 1408
14:02:46.306258 IP client > server: Flags [.], seq 2860:4268, ack 1, win 56, options [nop,nop,TS val 6178573 ecr 4865788], length 1408
14:02:46.306445 IP client > server: Flags [.], seq 4268:5676, ack 1, win 56, options [nop,nop,TS val 6178573 ecr 4865788], length 1408
14:02:46.306586 IP client > server: Flags [.], seq 5676:7084, ack 1, win 56, options [nop,nop,TS val 6178573 ecr 4865788], length 1408
14:02:46.306914 IP client > server: Flags [.], seq 7084:8492, ack 1, win 56, options [nop,nop,TS val 6178573 ecr 4865788], length 1408
14:02:46.307082 IP client > server: Flags [.], seq 8492:9900, ack 1, win 56, options [nop,nop,TS val 6178573 ecr 4865788], length 1408
14:02:46.307251 IP client > server: Flags [.], seq 9900:11308, ack 1, win 56, options [nop,nop,TS val 6178573 ecr 4865788], length 1408
14:02:46.307411 IP client > server: Flags [.], seq 11308:12716, ack 1, win 56, options [nop,nop,TS val 6178573 ecr 4865788], length 1408
14:02:46.307620 IP client > server: Flags [.], seq 12716:14124, ack 1, win 56, options [nop,nop,TS val 6178573 ecr 4865788], length 1408
14:02:46.307760 IP client > server: Flags [.], seq 14124:15532, ack 1, win 56, options [nop,nop,TS val 6178573 ecr 4865788], length 1408
14:02:46.307931 IP client > server: Flags [.], seq 15532:16940, ack 1, win 56, options [nop,nop,TS val 6178573 ecr 4865788], length 1408
14:02:46.308059 IP client > server: Flags [.], seq 16940:18348, ack 1, win 56, options [nop,nop,TS val 6178573 ecr 4865788], length 1408
14:02:46.308216 IP client > server: Flags [.], seq 18348:19756, ack 1, win 56, options [nop,nop,TS val 6178573 ecr 4865788], length 1408
14:02:46.308373 IP client > server: Flags [.], seq 19756:21164, ack 1, win 56, options [nop,nop,TS val 6178573 ecr 4865788], length 1408
14:02:46.309622 IP client > server: Flags [.], seq 21164:22572, ack 1, win 56, options [nop,nop,TS val 6178574 ecr 4865788], length 1408
14:02:46.309852 IP client > server: Flags [.], seq 22572:23980, ack 1, win 56, options [nop,nop,TS val 6178574 ecr 4865788], length 1408
14:02:46.310023 IP client > server: Flags [.], seq 23980:25388, ack 1, win 56, options [nop,nop,TS val 6178574 ecr 4865788], length 1408
14:02:46.310155 IP client > server: Flags [.], seq 25388:26796, ack 1, win 56, options [nop,nop,TS val 6178574 ecr 4865788], length 1408
14:02:46.341579 IP server > client: Flags [.], ack 44, win 55, options [nop,nop,TS val 4865797 ecr 6178573], length 0
14:02:46.341612 IP client > server: Flags [.], seq 26796:28204, ack 1, win 56, options [nop,nop,TS val 6178582 ecr 4865797], length 1408
A: In the three way handshake a window scale of 2^9 is negotiated for the receiver, and the receiver advertises a window of 55 = 55*2^9 = 28160 bytes.
The sender then sends a 43 byte packet, immediately followed by 19 with 1408 bytes for a total of 26795 bytes.
Clearly, the default initial congestion window has be modified, for otherwise the 20 packets would not have been sent without receiving an ACK.
However, the 26795 bytes have nearly filled the receivers advertised window; there is not enough room to send another full MTU.
When the ACK from the receiver finally arrives acknowleging receipt of the 43 byte packet and advertising a window of 55, we know the 43 bytes from the initial packet have been consumed, and we now calculate that there is exactly enough room available to send one more 1408 byte packet (28160-26795+43=1408).
So the problem is that your receiver is not advertising a window big enough to hold the 400*1408 bytes in your initial congestion window. You must similarly adjust the receivers receive window.
Note that if you had been looking at the capture in Wireshark, the "zero window" condition of the receiver would have been highlighted.
(Actually, it is a little more complicated than this. I can't fully explain why it doesn't send a partial MTU to fully fill the advertised receive window. If Nagle's algorithm is enabled, this explains it; you can turn it off by setting socket option TCP_NODELAY. If Nagle is off, it might reflect an implementation detail of slow start for your TCP stack.)
A: There are two main reasons for such behaviour:
*
*Slow-start. Happens when the connection is just established or after a congestion has been detected.
*Nagle algorithm. Happens when sending TCP segments shorter than MSS.
In your scenario, the client sends 20 TCP segments and waits for an acknowledgement. Having received one (for the first segment) it sends more (your trace only shows one segment).
A: From the dump of your tcp communication I see the following:
-We cannot assure Nagle is off but since the client is sending full MSS messages, this doesn't seem to be a problem here
-The connection is using window scaling: you can see wscale is 9 in options in the SYN and SYN+ACK messages
However, I see that just before passing 28160 Bytes (window published by server), client stops and waits for server ACK. That could be because it is not taking window scale into account or the initcwnd is in 20 (you said you set it to 400) or the application sent 26796 Bytes and then the rest of the Bytes.
| |
doc_23532781
|
But, when one container outputs access logs and error logs, logs are mixed.
example
# rails access log
2017-04-07 12:10:01 +0000 6a51e389e724: {"log":"I, [2017-04-07T12:10:01.825923 #7] INFO -- : Started GET \"/users/new\" for 172.21.0.1 at 2017-04-07 12:10:01 +0000","container_id":"6a51e389e724c67be4e714402b69da192db4a304cbfdf638594de6cff9774c23","container_name":"/app","source":"stdout"}
# rails error log
2017-04-07 12:10:01 +0000 6a51e389e724: {"container_id":"6a51e389e724c67be4e714402b69da192db4a304cbfdf638594de6cff9774c23","container_name":"/app","source":"stdout","log":"E, [2017-04-07T12:10:01.830039 #7] ERROR -- : Invoke logger error"}
# rails access log
2017-04-07 12:10:03 +0000 6a51e389e724: {"log":"I, [2017-04-07T12:10:01.825923 #7] INFO -- : Started POST \"/users/create\" for 172.21.0.1 at 2017-04-07 12:10:01 +0000","container_id":"6a51e389e724c67be4e714402b69da192db4a304cbfdf638594de6cff9774c23","container_name":"/app","source":"stdout"}
Can I add a label for each log type?
Please tell me if you have a good solution.
Thanks you and best regards.
A: As your app's access and error logs are sent to STDOUT of container, then you have no way to separate them by logging driver. As solution you can send access log to STDOUT, error log to STDERR of container, then later differentiate logs by "source" field of each json message (this can be done if you connect fluentd to elasticsearch+kibana).
| |
doc_23532782
|
Consider the following scenario:
I have 3 classes as shown below:
public class Computer {
public int compStatus = 0; //0 means off, 1 means on.
public void turnOn(){
this.compStatus = 1;
}
public void turnOff(){
this.compStatus = 0;
}
public void restart(){
if(compStatus ==1){
System.out.println("Turning off");
compStatus = 0;
System.out.println("Turning on");
compStatus = 1;
System.out.println("Restart successful");
}
}
}
Now the sub-class:
public class Macintosh extends Computer {
public void openXCode(){
if(compStatus == 1){
System.out.println("XCode Compiler opened.");
}
else{
System.out.println("Mac is off.");
}
}
public void restart(){
System.out.println("Mac restarted");
}
}
The tester class:
public class CompTest {
public static void main(String[] args){
Computer testObj = new Macintosh();
testObj.turnOn();
testObj.restart(); ///ERROR HERE
}
}
I am aware that the compiler checks if the restart method is in the class of the reference variable 'Computer' not the class of the actual object at the other end of the reference 'macintosh'. So if what I have said is true, why is the restart method not invoked?
A: You have to call the base class method in order to actually restart. Your method is just hiding the base method. You should override the method and then call it base.restart to do what you want.
| |
doc_23532783
|
BufferedReader input =
new BufferedReader(new InputStreamReader(connectionsocket.
getInputStream()));
DataOutputStream output =
new DataOutputStream(connectionsocket.getOutputStream());
...
output.writeChars("some random text");
output.close();
Also I have index.php file with some jQuery:
$(document).ready(function()
{
$("#send_data").click(function(){
$.ajax({
type: 'get',
dataType: 'text',
url: 'http://localhost:1024/'+$("#command").val(),
success: function(data) {console.log(data);},
error: function() { console.log("Error"); }
})
});
});
The command is sent correctly and received in Java side correctly. Then the request from java to ajax is 200 OK too. The output is also working. (For example if I remove output.close(), I do see in the firebug, that it is waiting for the output to be closed.)
The only problem is, no matter what I do I get no response text. It's always an empty string :(
A: cross-site ajax to java data transaction
and
index.php
and
Java
Implies you are violating same origin policy. You must use same host:port combination to retrieve the webpage (or at least the javascript version of the code that does AJAX) and send AJAX requests.
In other words, if your JS comes from localhost:80 and you are trying to send AJAX request to localhost:1024, you are violating security policies.
There are ways to do cross-domain AJAX like jsonp, but do you really need that? I would suggest serving jQuery code from the servlet, or eliminate PHP at all, or, even better, rewrite everything in Scala or Erlang. :)
A: in your code you create dataType:"xml"
try to use with text.because in your response i don't see the xml format,you're create response with format text.
$.ajax({
type: 'get',
dataType: 'text',
url: 'http://localhost:1024/'+$("#command").val(),
success: function(data) {console.log(data);},
error: function() { console.log("Error"); }
read this for option ajax request http://api.jquery.com/jQuery.ajax/
| |
doc_23532784
|
now is there any limit for VARCHAR column to be index-able? or dose it depend on Storage Engines?
A: Yes, there is a limitation:
From the documentation - All storage engines support at least 16 indexes per table and a total index length of at least 256 bytes. Most storage engines have higher limits.
More information - Column Indexes.
In this case you can specify a prefix length for the index, e.g. -
CREATE TABLE table1 (
column1 VARCHAR(255) DEFAULT NULL,
UNIQUE KEY UK_table1_column1 (column1(10))
);
| |
doc_23532785
|
c:\java\jdk-17.0.2
I've set up JAVA_HOME to it and added to path:
JAVA_HOME\bin
in cmd when I type java -version it works.
But when I run it from VS code or powershell it says following:
Error: could not open C:\java\jdk-17.0.2\lib\jvm.cfg'
Has anybody faced similar issue?
Thanks,
M.
UPDATE #1:
here are my env variable settings:
path:
and still not working:
PS
A: Here are 5 steps you can follow to fix the issue:
*
*In the run dialog box, enter sysdm.cpl
*In the window that came up, navigate to Advanced tab.
*Click on the Environment Variables button.
*Add the location of your java installation (the bin directory) to the PATH variable.
;%ProgramFiles%/Java/jre%version%/bin
followed by a semi-colon ;
*Do the following and check again with a new PowerShell prompt
5.1. Add a JAVA_HOME variable equal to something like: C:\Java\JDK-17.0.2
5.2. Add %JAVA_HOME%\bin to the beginning of your
PATH variable.
| |
doc_23532786
|
I have a table:
CREATE TABLE my_table (
id int(11) unsigned NOT NULL AUTO_INCREMENT,
column int(200) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
With two sample rows:
INSERT INTO my_table (id, column)
VALUES
(1, '^S[[:digit:]]{10}$'),
(2, '^M[[:digit:]]{8}$');
In mysql one can do:
SELECT id FROM my_table WHERE 'S1803020001' REGEXP my_table.column;
+----+
| id |
+----+
| 1 |
+----+
I am looking for a way to do it in SQLAlchemy.
That's how I use literal regexp with my model:
MyTable.query.filter(MyTable.column.op('regexp')(r'pattern'))
but this time I am looking for a way to swap 'pattern' and 'MyTable.column'.
I am aware it might not be supported due to various underlying database backends, as not all backends support non-literal regexp patterns. Nonetheless I am curious if and how can it be achieved.
A: Using literal() simply reverse the operation:
literal('foo').op('regexp')(MyTable.column)
| |
doc_23532787
|
vector<vector<double>> DataChannel1(2533136, vector<double>(8));
I want to take FFT from this Vector with fastest solution but I don not How!
can you help me How can I do that?
In addition to I used FFTW library but with my dimension(ROW=2533136 and COL=8) Take long time to calculate.
const auto ROWS = 2533136;
const auto COLS = 8;
fftw_complex in[ROWS][COLS], out[ROWS][COLS];
fftw_plan g;
g = fftw_plan_dft_2d(ROWS, COLS, *in, *out, FFTW_FORWARD, FFTW_MEASURE);
A: My Problem Solved And I am very thanksful from @G.M., He/She is considering my problem.
In My problem most of time spent in fftw_plan_dft_2d, I saw the FFTW documentation and understood the last input of this function is Planner Flags :
fftw_plan fftw_plan_dft_2d(int n0, int n1,
fftw_complex *in, fftw_complex *out,
int sign, unsigned flags)
All of the planner routines in FFTW accept an integer flags argument, which is a bitwise OR (‘|’) of zero or more of the flag constants defined below. These flags control the rigor (and time) of the planning process, and can also impose (or lift) restrictions on the type of transform algorithm that is employed.
Planning-rigor flags
FFTW_ESTIMATE specifies that, instead of actual measurements of different algorithms, a simple heuristic is used to pick a (probably sub-optimal) plan quickly. With this flag, the input/output arrays are not overwritten during planning.
FFTW_MEASURE tells FFTW to find an optimized plan by actually computing several FFTs and measuring their execution time. Depending on your machine, this can take some time (often a few seconds). FFTW_MEASURE is the default planning option.
| |
doc_23532788
|
Note: I have not tried anything yet.
A:
I am trying this way. Hopefully it will work. If not please show me the path.
A: You can use a sqlite in you Web, only you need a correct driver.
For example, if you web use PHP:
$db = sqlite_open('myfile.sqlite', 0666, $sqliteerror);
$result = sqlite_query($db, 'select * from foo');
var_dump(sqlite_fetch_array($result));
| |
doc_23532789
|
<android.support.design.widget.TabLayout
android:id="@+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabContentStart="57dp"
app:tabMode="scrollable" />
What I want to do now is to change this value in the code in some if/else statement?
I couldn't find out how to achieve this. There doesn't seem to be an equivalent method for this in the TableLayout class.
Thanks for any help in advance.
A: You can use setPadding or setTranslationX to get the desired effect.
| |
doc_23532790
|
Process ExplorerWindowProcess = new Process();
ExplorerWindowProcess.StartInfo.FileName = "explorer.exe";
ExplorerWindowProcess.StartInfo.Arguments = ConfigFile.File.FullName;
ExplorerWindowProcess.Start();
... but that opens the file (in my case an XML file) with the default application in Windows Explorer, which I very much don't want. I know that the Aptana tools available for Eclipse allow you the ability to select a file in the Eclipse project browser and show the file in Explorer exactly as I want, but I need a way to implement this in my WPF app.
A: Explorer Command Line Arguments
http://support.microsoft.com/kb/152457
Explorer [/n] [/e] [(,)/root,<object>] [/select,<object>]
/n Opens a new single-pane window for the default
selection. This is usually the root of the drive Windows
is installed on. If the window is already open, a
duplicate opens.
/e Opens Windows Explorer in its default view.
/root,<object> Opens a window view of the specified object.
/select,<object> Opens a window view with the specified folder, file or
application selected.
You will also want to put quotes around the filename like so:
startInfo.FileName = "explorer.exe";
startInfo.Arguments = "/select,\"" + ConfigFile.File.FullName + "\"";
| |
doc_23532791
|
File inputPropertiesFile = new File("/Users/adrian/Documents/workspace/Ronan/src/watermarker/test");
InputStream propertiesStream = new FileInputStream(inputPropertiesFile);
but I get this exception:
java.io.FileNotFoundException: /Users/adrian/Documents/workspace/Ronan/src/watermarker/test (No such file or directory) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(FileInputStream.java:120)
But the file is at that location fooor suure.And is not empty.What is wrong there?
Thank you
A: Maybe you can check if the File is accessible for the Program?
If the File is not accessible, it also cannot be found and hence raises this exception.
A: Yeah, if you try using /Users/adrian in explorer, you won't get to that path. If you use C:/Users/adrian, you will. I'm sure java is having the same problem
A: Is the file readable by your process? Try changing its permissions
chmod 777 thefile
and rerunning. If that works, then you know its a permissions issue. changing the permissions like that is probably not a permanent solution, and can be a security risk if you are on a multi-user system. But that's a different problem...
A: On Windows? Maybe you run your code on D: instead C:. If so put full path "c:\Users\adrian..."
It looks like default path to Eclipse workspace on Win7. If so, I have no "/Documents/" in the path. I have "/Users/myname/workspace/projectName/src....".
A: surround it by a try-catch block
try {
inputStream = new FileInputStream(propertiesFile);
prop.load(inputStream);
} catch (FileNotFoundException e1) {
getLog().error(e1);
} catch (IOException e) {
getLog().error(e);
}
| |
doc_23532792
|
A: openURL has not been deprecated. At least not according to the API documentation.
Just use a UIAlertView to ask whether the user would like to add an account. If they say yes, call the following line:
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=TWITTER"]];
| |
doc_23532793
|
*
*data
*repositories
Data belongs to repositories. Unlike a typical ActiveRecord application I don't use HTML forms to create these resources. Instead both entities are serialized in YAML files which I upload to persist them into my database.
Since a small import page does not take up much space and for convenience I would like to put both importer on one page.
+------------------------------+
| <Import Repositories> |
+------------------------------+
+------------------------------+
| Repository A - <Import Data> |
+------------------------------+
| Repository B - <Import Data> |
+------------------------------+
| ... |
But what is the appropriate route in this case here?
Just /repositories/new or something like repositories/data/new ?
How would I go for this, respectively what is the shortest way of defining this in routes.rb. The repositories are moddeled through classes, the data not (to keep it general). So maybe
resource repositories
is just fine?
A: As for me it is ok. Repository is a main entity, data belongs to it. It is similar to view with accept_nested_attributes form.
| |
doc_23532794
|
@if (item.Details.Length < 100)
{
<span>@item.Details</span>
}
else
{
<span>@item.Details.Substring(0, 99) ...</span>
}
But then I thought I could use the conditional operator:
<span>@{item.Details.Length < 100 ? item.Details : item.Details.Substring(0, 99);}</span>
I'm guessing this doesn't work for the same reason this doesn't work:
@if (item.Details.Length < 100)
{
item.Details;
}
else
{
item.Details.Substring(0, 99);
}
i.e. the syntax needs to be broken into html and cs parts, but is there any syntax I can use to assign and display the variable in the one-liner using the conditional operator?
Please don't tell me that all the display logic should be done in the ViewModel. I know that might be the best option but that's not what I'm asking!
A: Currently, you're trying to use a conditional ?: expression as a statement - but it's not a statement expression. However, it is a valid expression in itself. So you need to:
*
*Remove ; which is only valid after a statement
*Change the {} (used for a block body) to () (used to tell Razor how much text is the expression)
<span>@(item.Details.Length < 100 ? item.Details : item.Details.Substring(0, 99))</span>
Note that in C# 8, you can use the range operator for more brevity:
<span>@(item.Details.Length < 100 ? item.Details : item.Details[..99])</span>
| |
doc_23532795
|
Console.Read()
I asked this before,,, what is inside empty default parentheses, does any one know?
A: The first says:
This is a subroutine called Main and it takes no Parameters.
The second says;
Please call the Read subroutine/function and don't pass it any parameters
so () implies no parameters and is simply a syntactic construct to allow the programmer to pass the intention above to the compiler.
A: Nothing is inside. the parentheses are there to show the member is a method. A property would not have the parentheses.
| |
doc_23532796
|
In this project I use Serilog with Microsoft.Extensions.Logging and also Auofac for DI.
Using ILogger< T> logger with DI in the controller constructor works perfectlly and I also get logs.
The fun starts when in the API I need to use another project the use Microsoft.Extensions.Logging and Autofac and expects to receive ILogger< T> in some constructors.
I've installed the same version of Microsoft.Extensions.Logging in both projects.
I get the fallowing exception:
Autofac.Core.DependencyResolutionException: 'An exception was thrown while activating Microsoft.Extensions.Logging.Logger1[[Microsoft.AspNetCore.Hosting.Internal.WebHost, Microsoft.AspNetCore.Hosting, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]] -> Microsoft.Extensions.Logging.LoggerFactory -> λ:Microsoft.Extensions.Logging.ILoggerProvider[] -> Microsoft.Extensions.Logging.Console.ConsoleLoggerProvider -> Microsoft.Extensions.Options.OptionsMonitor1[[Microsoft.Extensions.Logging.Console.ConsoleLoggerOptions, Microsoft.Extensions.Logging.Console, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]] -> Microsoft.Extensions.Options.OptionsFactory1[[Microsoft.Extensions.Logging.Console.ConsoleLoggerOptions, Microsoft.Extensions.Logging.Console, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]] -> λ:Microsoft.Extensions.Options.IConfigureOptions1[[Microsoft.Extensions.Logging.Console.ConsoleLoggerOptions, Microsoft.Extensions.Logging.Console, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]][] -> Microsoft.Extensions.Logging.Console.ConsoleLoggerOptionsSetup -> Microsoft.Extensions.Logging.Configuration.LoggerProviderConfiguration`1[[Microsoft.Extensions.Logging.Console.ConsoleLoggerProvider, Microsoft.Extensions.Logging.Console, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].'
Inner Exception1:
DependencyResolutionException: An exception was thrown while invoking the constructor 'Void .ctor(Microsoft.Extensions.Logging.Configuration.ILoggerProviderConfigurationFactory)' on type 'LoggerProviderConfiguration`1'.
Inner Exception2:
MethodAccessException: Attempt by method 'Microsoft.Extensions.Logging.Configuration.LoggerProviderConfigurationFactory.GetConfiguration(System.Type)' to access method 'Microsoft.Extensions.Logging.ProviderAliasUtilities.GetAlias(System.Type)' failed.
These are the packages for the API:
<PackageReference Include="Autofac" Version="4.9.4" />
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="5.0.1" />
<PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Hosting.WindowsServices" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.HttpsPolicy" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="3.0.1" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="3.0.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.0.1" />
<PackageReference Include="Serilog.Extensions.Logging.File" Version="1.1.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.1.0" />
And these are the packages from the other project:
<PackageReference Include="Autofac" Version="4.9.4" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="3.0.1" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="3.0.1" />
A: ! do not believe this is Autofac specific. I am not using autofac, but sreilog. This occurred immediately following updating to 3.0.1 for me.
*
*Microsoft.EntityFrameworkCore
*Microsoft.EntityFrameworkCore.SqlServer
*Microsoft.EntityFrameworkCore.Tools
*Microsoft.Extensions.DependencyInjection
*Microsoft.Extensions.Logging.Debug
Rolling back Microsoft.Extensions.Logging from v 3.0.1 to 3.0.0 git me operational again.
Not sure root cause yet, but that should get you back in business.
If you are using EF Core and went from 3.0.0 to 3.0.1 you will need to roll those back as well to 3.0.0.
A: Looks like you might have a mismatched Microsoft.Extensions.Logging.Configuration behind the scenes; try adding:
<PackageReference Include="Microsoft.Extensions.Logging.Configuration" Version="3.0.1" />
To both projects.
| |
doc_23532797
|
I have created one target for each version in xcode.
But I have a problem with my Main Interface, when I am running the iphone app in the ipad-simulator or real ipad, it is showing the ipad main interface. This is of course not working since the resources for the ipad interface is not included in the iphone target.
The nib files describing the ipad main interface is also not included in the iphone target. But when I browse the iphone application package the ipad nib files are there?
Any clues?
A: Go to your project -> Target (select one) -> Build phases -> Copy bundle resources and see what your copying into each bundle.
A: I had same issue. I fixed by specifying the nib in the Info.plist :
Assuming that your xib files are: MainWindow_iPhone.xib and MainWindow_iPad.xib
*
*For the key: NSMainNibFile (Main nib file base name), give the value as MainWindow_iPhone
*For the key: NSMainNibFile~ipad (Main nib file base name (iPad)), give the value as MainWindow_iPad
| |
doc_23532798
|
PLEASE SEE CODE BELOW:
def ask_phone_number(correct, phone_number):
while correct == False:
phone_number = [input("Enter your phone number >>> ")]
for ch in phone_number:
if ("+1" not in ch):
print("Make sure to enter '+1' and your 10 digit US or Canada phone number")
elif (phone_number.count(ch) < 12):
print("Your phone number is incomplete")
else:
correct = True
else:
return phone_number
if __name__ == "__main__"
ask_phone_number(False, "")
A: Some issues:
*
*Your code creates phone_number as a list. Drop the square brackets.
*Once the above is fixed, your loop takes every character in the phone number and then counts how many times that character occurs in the phone number. So that will be at least 1 (because you took that character from it), but has obviously nothing to do with the number of digits in the phone number.
*I don't see the utility to pass correct and phone_number as argument. The goal of the function is to ask the user for the phone number, so it should not be an argument. And whether it is correct or not is up to the function to determine, not an argument.
So:
def ask_phone_number():
while True:
phone_number = input("Enter your phone number >>> ")
if not phone_number.startswith("+1"):
print("Make sure to enter '+1' and your 10 digit US or Canada phone number")
elif len(phone_number) < 12:
print("Your phone number is incomplete")
else:
return phone_number
A: phone_number.count(ch)
counts the number of times the string ch is in the list phone_number. This is always 1.
You should use
elif len(ch) < 12:
| |
doc_23532799
|
For $config/session.php I am using a default file that comes with Laravel 5.4
Below is my Kernel file:
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* @var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\DomainRouter::class,
\App\Http\Middleware\SetSubscr::class,
\App\Http\Middleware\VerifyCsrfToken::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
/**
* The application's route middleware.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
}
A: The problem was due to session related middleware were both available in general and 'web' group.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.