text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Is it possible to use SQL Server Compact Edition in an Open Source project? I am aware of other solutions like System.Data.Sqlite or Firebird through Dblinq, but since nothing beats SQL Compact Edition (integration-wise) with Visual Studio, I would like to use it and to know if its license allows its usage in Open Source projects.
Thanks.
A: One point to bear in mind is that you would presumably not be distributing the source code for the Compact Edition. This might make your project fail some definitions of "Open source" if the Compact Edition is closely integrated with the rest of your code. This in turn might make it inelligible to be hosted on certain FOSS web servers (I'm thinking of Google Code) and might result in your prtoject getting a bad name amond more zealous FOSS supporters.
A: As long as you don't need replication with a big MS SQL Server you are fine with SQL CE.
A: IANAL, and I do not know if the EULA is compatible with every open source license.
But, as long as you sign up for redistribution rights you should be fine to redistribute it with an open source project.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1153395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What classes from Jain SIP (java) should I use to make an SIP client? I am asking to create an SIP client, but I am totally lost ...
After some researches I found the Jain SIP API in java, and I think that I will use it.
However I don't really know what classes I should use and what interfaces I should implement or not.
I have read this article : http://www.oracle.com/technetwork/articles/entarch/introduction-jain-sip-090386.html
And this : http://hudson.jboss.org/hudson/job/jain-sip/lastSuccessfulBuild/artifact/javadoc/javax/sip/package-summary.html#package_description
But I don't understand which part should I implement for an SIP client ? The SipListener OR the SipStack and the SipProvider ?
Thanks.
A: You need to implement both of those classes.
The SipProvider class will connect to your endpoint (Aterisk, for example). Note that this class must be on an static context, because only one connection is allowed per client.
You cant create a SipProvider instance calling a SipStack class, on sipStack.createSipProvider(listeningPoint). After this, you be able to create transactions and send requests to you endpoint.
The SipListener is the class that will process all responses from your server. This means that every request that you send to the server (Via SipProvider) will receive a response on SipListener. So, you must have this listener to process all data returned by your endpoint.
Try to implement the code that was described on oracle article that you cite. I started to develop based on this article, and works very fine!
A: Check the examples at the Reference Implementation https://java.net/projects/jsip/sources/svn/show/trunk/src/examples?rev=2279 to help you moving forward faster
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16151352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: What folders should be git ignored in React Native project? I'm playing with Facebook/React Native, and when I run git init, I have no idea what should be ignored expect node_modules folder,
Should I commit all iOS folder?
Thanks
A: We suggest this .gitignore: react-native/Examples/SampleApp/.gitignore.
It ignores both user-specific Xcode files and the node_modules dir.
A: React Native CLI creates a .gitignore file when you start a new project:
react-native init <ProjectName>
It covers all the basics that should/can be ignored.
Source: https://github.com/facebook/react-native/blob/master/template/_gitignore
A: This is a related question:What should Xcode 6 gitignore file include?
It can be divided into three categories:
*
*IDE(Webstorm,Xcode) config
file,like:.idea/,ios/ProjectName.xcodeproj/xcuserdata
*version control tools(git,svn) file, like: .git
*other files,for example,.DS_Store is OSX dir config file
my answer is which have been inspected in practice:
### SVN template
.svn/
### Xcode template
# Xcode
#
# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
## Build generated
build/
DerivedData/
## Various settings
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata/
## Other
*.moved-aside
*.xccheckout
*.xcscmblueprint
### JetBrains template
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff:
.idea/workspace.xml
.idea/tasks.xml
.idea/dictionaries
.idea/vcs.xml
.idea/jsLibraryMappings.xml
# Sensitive or high-churn files:
.idea/dataSources.ids
.idea/dataSources.xml
.idea/dataSources.local.xml
.idea/sqlDataSources.xml
.idea/dynamic.xml
.idea/uiDesigner.xml
# Gradle:
.idea/gradle.xml
.idea/libraries
.idea
# Mongo Explorer plugin:
.idea/mongoSettings.xml
## File-based project format:
*.iws
## Plugin-specific files:
# IntelliJ
/out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
### TortoiseGit template
# Project-level settings
/.tgitconfig
*.swp
# node_modules/,Xcode and Webstorm will spend lots of time for indexing this dir
node_modules/
# ios/Pods,
ios/Pods/
# OS X temporary files that should never be committed
.DS_Store
src/components/.DS_Store
# user personal info,for example debug info
ios/ProjectName.xcodeproj/project.xcworkspace/
ios/ProjectName.xcodeproj/xcuserdata
# Podfile versions
ios/Podfile.lock
# Created by .ignore support plugin (hsz.mobi)
Hope it helps you!
A: gitignore.io suggests the following .gitignore file for react-native:
Created by https://www.gitignore.io/api/reactnative
### ReactNative ###
# React Native Stack Base
### ReactNative.Xcode Stack ###
# Xcode
#
# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
## Build generated
build/
DerivedData/
## Various settings
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata/
## Other
*.moved-aside
*.xccheckout
*.xcscmblueprint
### ReactNative.Node Stack ###
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Typescript v1 declaration files
typings/
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
### ReactNative.Buck Stack ###
buck-out/
.buckconfig.local
.buckd/
.buckversion
.fakebuckversion
### ReactNative.macOS Stack ###
*.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
### ReactNative.Gradle Stack ###
.gradle
**/build/
# Ignore Gradle GUI config
gradle-app.setting
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
!gradle-wrapper.jar
# Cache of project
.gradletasknamecache
# # Work around https://youtrack.jetbrains.com/issue/IDEA-116898
# gradle/wrapper/gradle-wrapper.properties
### ReactNative.Android Stack ###
# Built application files
*.apk
*.ap_
# Files for the ART/Dalvik VM
*.dex
# Java class files
*.class
# Generated files
bin/
gen/
out/
# Gradle files
.gradle/
# Local configuration file (sdk path, etc)
local.properties
# Proguard folder generated by Eclipse
proguard/
# Log Files
# Android Studio Navigation editor temp files
.navigation/
# Android Studio captures folder
captures/
# Intellij
*.iml
.idea/workspace.xml
.idea/tasks.xml
.idea/gradle.xml
.idea/dictionaries
.idea/libraries
# External native build folder generated in Android Studio 2.2 and later
.externalNativeBuild
# Freeline
freeline.py
freeline/
freeline_project_description.json
### ReactNative.Linux Stack ###
*~
# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*
# KDE directory preferences
.directory
# Linux trash folder which might appear on any partition or disk
.Trash-*
# .nfs files are created when an open file is removed but is still being accessed
.nfs*
# End of https://www.gitignore.io/api/reactnative
A: It's probably worth noting that react-native init <project-name> generates a .gitignore file for you. This will likely be up to date with React Native's current tooling and build outputs. So this should be a good starting point.
Using react-native-cli 1.0.0 and react-native 0.36.0 generated the following .gitignore file:
# OSX
#
.DS_Store
# Xcode
#
build/
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata
*.xccheckout
*.moved-aside
DerivedData
*.hmap
*.ipa
*.xcuserstate
project.xcworkspace
# Android/IJ
#
*.iml
.idea
.gradle
local.properties
# node.js
#
node_modules/
npm-debug.log
# BUCK
buck-out/
\.buckd/
android/app/libs
android/keystores/debug.keystore
A: If you look at the React Native examples:
https://github.com/facebook/react-native/tree/master/Examples
Each one has a directory with a contents similar to the iOS directory generated by react-native-cli. Looking further into the Xcode project file, it's referenced in there too, and look at the contents - there's things like the launch screen.
So yes, the iOS directory is needed.
Regarding node_modules, I suggest you look at this answer which provides more information:
https://stackoverflow.com/a/19416403/125680
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29294913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "63"
} |
Q: Pure CSS slider left margin accretion I am in the process of developing a site for a uni project, and I have built an automatically changing slider while only using css (it is a requirement of this project that I don't use anything else). The problem I'm experiencing is that when the slides change, the left margin begins to add up, and I can't figure out why.
I have tried making a page with just the html and css necessary for the slider to work and it works properly there, but not when incorporated into my main css page.
Any pointers would be appreciated!
The site this can be seen on is http://www.darkmatter-designs.com/
A: I can't figure out what the problem is.. The css is really messy, there is a lot of useless or overwritten properties.. You have to optimize it..
But somehow I found a workaround : set the width of the #css-slider to 864px.. It's not really a proper solution but it works anyway..
A: As you can see you have some margin between the images, which makes their widths effectively bigger a little bit. I see you applied a reset in your css, so this is probably coming from the white space in your html. A quick fix would be to put all the li and img on a single line with no spaces or carriage returns between them, like so:
<ul id="css-slider"><li><img src="http://cdn.gtm.net.au/images/catalogue/sp_image_108.jpg" alt="slider"></li><li><img src="http://cdn.gtm.net.au/images/catalogue/sp_image_62.jpg" alt="slider"></li><li><img src="http://cdn.gtm.net.au/images/catalogue/sp_image_59.jpg" alt="slider"></li><li><img src="http://cdn.gtm.net.au/images/catalogue/sp_image_66.jpg" alt="slider"></li></ul>
I know, it's weird.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23257598",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Implementing multi layer role on Django Working with django Group and Permission. Normally works fine. Now want to add sub admin who can give permission only particular model. How to implement?
A: As per our discussion below are my Steps:
*
*Override Role with company OR you can keep this at Super Admin level.
http://127.0.0.1:8000/admin/auth/role/
*Add separate table for permissions with pk, client ID, RoleID , add, edit, view, delete, model, action (URL) columns
*Add decorator for each of the action or Model and check permissions for that particular action or model.
*Check roles and permission in Admin using common function something like check_role_permissions_admin
//Add below function in separate / common function file.
def check_role_permissions_admin(request, url=None):
if not hasattr(request.user,"client"):
return {
'clientwise': False,
'add': False,
'change': False,
'delete': False,
'view': False,
'icon': ''
}
super_admin_role = Role.objects.get(pk=1)
all_roles = request.user.groups.all()
try:
action = Actions.objects.get(
url=url
)
except:
action = None
if super_admin_role in all_roles:
return {
'clientwise': False,
'add': True,
'change': True,
'delete': True,
'view': True,
'icon': str(action.icon) if action else ''
}
// Write Logic here for Role and Permissions of requested action(s)
roles = [group for group in request.user.groups.all()]
permissions = ActionPermissions.objects.filter(
client=request.user.client,
role__in=roles,
action__url=url
)
if permissions.exists():
permobj = permissions[0]
return {
'clientwise': True if permobj.client else False,
'add': True if permobj.add else False,
'change': True if permobj.change else False,
'delete': True if permobj.delete else False,
'view': True if permobj.view else False,
'icon': permobj.action.icon
}
else:
return {
'clientwise': False,
'add': False,
'change': False,
'delete': False,
'view': False,
'icon': ''
}
//Add below code in admin.py, for every admin action you need to do following //thing and need
//to make sure that similar entry is added in table permissions.
from module.function import check_role_permissions_admin
@admin.register(ConfigRuleMaster)
class ModelMasterAdmin(admin.ModelAdmin):
action_form=CustomActionForm
form = ModelMasterForm
fields=(('title','template'))
list_display=('title','template')
search_fields = ('title','template',)
list_display_links = []
def get_model_perms(self, request):
perms = decorators.check_role_permissions_admin(request, '/admin/lmt/modelmaster/')
perms['clientwise'] = False
return perms
def has_add_permission(self, request):
perms = decorators.check_role_permissions_admin(request, '/admin/lmt/modelmaster/')
return perms['add']
def has_change_permission(self, request, obj=None):
perms = decorators.check_role_permissions_admin(request, '/admin/lmt/modelmaster/')
return perms['change']
*Another work is to handle actions through decorators.
But this is very raw version of code I found in my repository, you need to make this logic at very high level to make your client happy and to have full secured code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53478559",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: WooCommerce: Add class to variation dropdown I want to add the class .form-control to the variation dropdown in the WooCommerce product pages.
It seems that there is an option to do so. I found the function wc_dropdown_variation_attribute_options.
The function has an class attribute:
function wc_dropdown_variation_attribute_options( $args = array() ) {
$args = wp_parse_args( apply_filters( 'woocommerce_dropdown_variation_attribute_options_args', $args ), array(
'options' => false,
'attribute' => false,
'product' => false,
'selected' => false,
'name' => '',
'id' => '',
'class' => '',
'show_option_none' => __( 'Choose an option', 'woocommerce' ),
) );
Is there any solution to add the class to the dropdown?
I only found the function but no code/snippet to change the class attribute.
Edit: I found a snippet that is customizing the dropdown but I don't know how to use it for only adding the class: https://stackoverflow.com/a/47189725/1788961
A: The answer is in the apply_filters( 'woocommerce_dropdown_variation_attribute_options_args', $args )
You basically need to use that filter to access the $args that are being passed. In your particular situation, this is how you would do it:
add_filter( 'woocommerce_dropdown_variation_attribute_options_args', static function( $args ) {
$args['class'] = 'form-control';
return $args;
}, 2 );
What this does, is hooks into the woocommerce_dropdown_variation_attribute_options_args filter and passes the original $args to a static function. Then you basically set the value of the class index of the $args array. Then you return the $args.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58594970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Implement realm with data binding in android I am trying to use Android's architecture component i.e.data binding with Realm database using MVVM pattern.
After exploring about the data binding and MVVM , i came across few approaches to bind model with the UI.
*
*Declare Observable primitive fields in model and directly bind them to the android xml file.
*Keep the model as it is with primitive data type and declare Observable fields in View model class
Now, as realm does not support Observable fields the option left is to use Observable
i have referred this article to use realm with data binding , but this article is pretty old one.
so my questions are
*
*What is preferable while implementing data binding in android , bind model directly to the android UI or declare obserable variables in view model and map them with the model ?
*best practices to use realm with data binding
My question is pretty specific in context of realm and data binding hence its not a generalize question.
A: I'll answer the first question only as I haven't used Realm for a while.
As you stated yourself, you cannot use Observable fields in the model that you use in Realm and you shouldn't ever do so. Model is to be kept simple.
ViewModel is exactly where Observables belong. They should be bound to the view and only them.
Consider using the new LiveData classes instead of Observables and ViewModels from the new Architecture Components. They make things even easier and are now supported in Data Binding:
LiveData Overview
LiveData with Data Binding
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50681534",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP - FPDF Multicell function does not make a new line I'm trying to make a newline inside a multicell. What I've done is:
$pdf->MultiCell(90,10,'test'.'\n'.'test',1,0,'C',1);
According to the manual the multicell should parse the '\n' character and render a newline but it does not (it prints the two byte string '\n' alongside with the actual text)
A: Try to use "\n" instead of '\n' (or even PHP_EOL predefined constant). Use double quotes.
Related:
*
*What is the difference between single-quoted and double-quoted strings in PHP?
*FPDF multicell alignment not working
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23967938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: image height based on mobile orientation I have a problem with a small mobile image gallery. When I change the orientation to portrait the images are too large to be displayed on the screen.
Is it possible with some javascript to make images fit the screen when the orientation changes to portrait? In landscape mode, everything looks fine.
A: yes, you can use CSS3 Media Queries without using JavaScript.
@media screen and (max-width: 450px) {
img {
width: 30%;
}
}
http://webdesignerwall.com/tutorials/responsive-design-with-css3-media-queries
A: Try this:
@media screen and (orientation:portrait) {
//your css code goes here
}
@media screen and (orientation:landscape) {
//your css code goes here
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10430135",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: how can I save a form with ModelMultipleChoiceField? I have a model Calendar and in a form I want to be able to create multiple instances of it.
Here are my models:
class Event(models.Model):
user = models.ForeignKey(User)
class Group(models.Model):
name = models.CharField(_('Name'), max_length=80)
events = models.ManyToManyField(Event, through='Calendar')
class Calendar(models.Model):
event = models.ForeignKey(Event)
group = models.ForeignKey(Group)
class CalendarInline(admin.TabularInline):
model = Calendar
extra = 1
class GroupAdmin(admin.ModelAdmin):
inlines = (CalendarInline,)
Here is how I try to code my form:
class AddEventToGroupForm(ModelForm):
group = ModelMultipleChoiceField(queryset=Group.objects.all(), widget=SelectMultiple())
def save(self):
for g in self:
g.save()
class Meta:
model = Calendar
fields = ('group',)
And here is a part of my view:
e = Event.objects.get(id=event_id)
calentry = Calendar(event=e)
if request.POST:
f = AddEventToGroupForm(data=request.POST, instance=calentry)
if f.is_valid():
f.save()
If I try to submit that form, I get:
AttributeError at /groups/add_event/7/
'BoundField' object has no attribute 'save'
What is the proper way to create multiple instances of Calendar in this
situation?
A: That's not how to deal with many-to-many relationships in forms. You can't iterate through fields in a form and save them, it really doesn't work that way.
In this form, there's only one field, which happens to have multiple values. The thing to do here is to iterate through the values of this field, which you'll find in the cleaned_data dictionary (when the form is valid).
So, in your view, you do something like:
if f.is_valid():
for group in f.cleaned_data['group']:
calentry.groups.add(group)
Note you're not 'saving' the AddEventToGroupForm form at all. I would make it a standard forms.Form, rather than a ModelForm, as you're not really depending on any of the ModelForm functionality.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1833275",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Dependency injection: HttpClient or HttpClientFactory? Everywhere I can see three main approaches to create clients (basic, named, typed) in DI, but I have found nowhere if to inject IHttpClientFactory or HttpClient (both possible).
Q1: What is the difference between injecting IHttpClientFactory or HttpClient please?
Q2: And if IHttpClientFactory is injected, should I use factory.CreateClient() for each call?
A: Summary
*
*HttpClient can only be injected inside Typed clients
*for other usages, you need IHttpClientFactory
*In both scenarios, the lifetime of HttpClientMessageHandler is managed by the framework, so you are not worried about (incorrectly) disposing the HttpClients.
Examples
In order to directly inject HttpClient, you need to register a specific Typed service that will receive the client:
services.AddHttpClient<GithubClient>(c => c.BaseAddress = new System.Uri("https://api.github.com"));
Now we can inject that inside the typed GithubClient
public class GithubClient
{
public GithubClient(HttpClient client)
{
// client.BaseAddress is "https://api.github.com"
}
}
You can't inject the HttpClient inside AnotherClient, because it is not typed to AnotherClient
public class AnotherClient
{
public AnotherClient(HttpClient client)
{
// InvalidOperationException, can't resolve HttpClient
}
}
You can, however:
1. Inject the IHttpClientFactory and call CreateClient(). This client will have BaseAddress set to null.
2. Or configure AnotherClient as a different typed client with, for example, a different BaseAdress.
Update
Based on your comment, you are registering a Named client. It is still resolved from the IHttpClientFactory.CreateClient() method, but you need to pass the 'name' of the client
Registration
services.AddHttpClient("githubClient", c => c.BaseAddress = new System.Uri("https://api.github.com"));
Usage
// note that we inject IHttpClientFactory
public HomeController(IHttpClientFactory factory)
{
this.defaultClient = factory.CreateClient(); // BaseAddress: null
this.namedClient = factory.CreateClient("githubClient"); // BaseAddress: "https://api.github.com"
}
A: Sadly I cannot comment, but only Post an answer. Therefore I suggest you should check out the following Links:
https://learn.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests
https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/
Regarding your Questions it more or Less boils down to this:
Q1 -> IHttpClientFactory handles the connection pools of HttpClient instances and this will help you regarding load and dispose problems as discribed in the links, if the HttpClient is used wrong.
Q2 -> yes you should use factory.create client according to microsoft docs
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59280153",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "66"
} |
Q: Is it safe to use inheritance for meta-data migration? Is it safe to create a template schema for metadata so that other schemas which contain data can inherit from it?
Advantage: Migrations will be seamless for multi tenant scenarios.
Disadvantages: ?
Example:
hello=# CREATE SCHEMA template;
hello=# CREATE TABLE template.cities (
name text,
population real,
altitude int;
hello=# CREATE SCHEMA us;
hello=# CREATE TABLE us.cities () INHERITS (template.cities);
hello=# \d us.cities;
Table "us.cities"
Column | Type | Collation | Nullable | Default
------------+--------------+-----------+----------+---------
name | text | | |
population | real | | |
altitude | integer | | |
Inherits: template.cities
hello=# CREATE SCHEMA eu;
hello=# CREATE TABLE eu.cities () INHERITS (template.cities);
hello=# \d eu.cities;
Table "eu.cities"
Column | Type | Collation | Nullable | Default
------------+--------------+-----------+----------+---------
name | text | | |
population | real | | |
altitude | integer | | |
Inherits: template.cities
hello=# ALTER TABLE cities ADD COLUMN state varchar(30);
hello=# \d us.cities;
Table "us.cities"
Column | Type | Collation | Nullable | Default
------------+-----------------------+-----------+----------+---------
name | text | | |
population | real | | |
altitude | integer | | |
state | character varying(30) | | |
Inherits: template.cities
A: I think inheritance is a good approach to this problem.
I can think of two down sides:
*
*It is possible to create additional columns to the inheritance children. If you control DDL, you can probably prevent that.
*You still have to create and modify indexes on all inheritance children individually.
If you are using PostgreSQL v11 or later, you could prevent both problems by using partitioning. The individual tables would then be partitions of the “template” table. This way, you can create indexes centrally by creating a partitioned index on the template table. The disadvantage (that may make this solution impossible) is that you need a partitioning key column in the table.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59158743",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Setting active link dynamically on static navigation I have "navigation.html" (static coded navigtaion ) file loaded on multiple pages, using jQuery .load()
Now I need to dynamically set active <li> for each page user clicking on. I can not use body id for specific reasons.
Any other ways to do this?
A: If you can identify your current page by class or id (ex: body > div#contacts) for contacts.html and this class/id is unique then you have to match it with you navigation, other way is to match window.location.href value (parsed if you want) against your navigation.
changeActiveLink is defined in JS (ex:init.js) file which you include to each page
function changeActiveLink() {
var currentLocation = window.location.href;
currentLocation = currentLocation.replace('//', '/').split('/');
var page = currentLocation[currentLocation.length - 1];
if (page == "") { page = 'index.html'; }
$('#leftNav1 a[href*="'+ page +'"]').addClass('active');
}
This line is called from each file when "init.js" is included.
$('#leftNav1').load('navigation.html', changeActiveLink);
A: Or you can use any HTML or even HTML5 tag to specify li item.
<li class="some">
or
<li title="some">
or
<li attr-specify="some-specific-in-url">
and jQuery with window.location object
$('li[title="' + window.location.path + '"]').addClass("active");
A: You could set up some jquery script to get the url and then find the href of the li that matches that. This will allow you to addClass() to that li of active.
This of course will only work if your href matches the url
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9982140",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Test if socket is connected Following on from this question, I am trying to set a variable to see if a socket is connected.
However the question's answer doesnt seem to work. If I console.log the socket variable I get this:
As you can see in the image, it says connected: true but when I run this:
console.log(socket.connected); I simply get false. The start of my code looks like this:
var socket = io('http://test.domain.net:1234', {reconnection: false});
console.log("Connected:" + socket.connected);
A: I think you should put a timer and then do the console due to the async nature of JavaScript.
var socket = io('http://test.domain.net:1234', {reconnection: false});
setTimeout(function(){
console.log("Connected:" + socket.connected);
}, 3000);
`
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37277199",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: How can I combine multiple webpages and get them as pdf? I have multiple pages that I am getting after filling a form with puppeteer. I am currently using "page.printToPDF" api of puppeteer to obtain the webpage as a pdf but the problem is that I have multiple pages and I would like to combine all of them and get a single pdf. Is there anyway I can achieve this with puppeteer and javascript?
A: Here is an alternative solution, there are many packages for merging pdf files.
Here is how you can use one of the many pdf merging packages.
const PDFMerge = require('pdf-merge');
const files = [
`${__dirname}/1.pdf`,
`${__dirname}/2.pdf`
];
const finalFile = `${__dirname}/final.pdf`;
Here is how you can print multiple pages and then merge them.
// goto first page and save pdf file
await page.goto('http://example1.com', {waitUntil: 'networkidle'});
await page.pdf({path: files[0], format: 'A4', printBackground: true})
// goto first page and save pdf file
await page.goto('http://example2.com', {waitUntil: 'networkidle'});
await page.pdf({path: files[1], format: 'A4', printBackground: true})
// merge two of them and save to another file
await PDFMerge(files, {output: finalFile);
It's all about how you take advantages of your resources.
A: var fs = require('fs');
var pdf = require('html-pdf');
var html = fs.readFileSync('https://www.google.co.in/', 'utf8');
var options = {
format: 'A4',
"border": {
"top": "0.2in", // default is 0, units: mm, cm, in, px
"bottom": "1in",
"left": "0.1cm",
"right": "0.1cm"
},
};
pdf.create(html, options).toFile('./google.pdf', function(err, res) {
if (err) return console.log(err);
console.log(res); // { filename: '/app/businesscard.pdf' }
});
You have to install html-pdf after this use above code. for more information about to convert check link. https://www.npmjs.com/package/html-pdf
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48641218",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: My sticky sidebar does not show until the user scrolls down Like the title says, I got the sticky sidebar to work. The only concern is that when the user first get to the page, the sidebar does not show at all until the user scrolls down, then it does go up and down. I was wondering if there's something wrong with the JS code or something else..? I can't seem to get it to work >-<
<script>
$( document ).ready(function() {
var $sticky = $('.sidebar');
var $stickyrStopper = $('.sticky-stopper');
if (!!$sticky.offset()) {
var generalSidebarHeight = $sticky.innerHeight();
var stickyTop = $sticky.offset().top;
var stickOffset = 0;
var stickyStopperPosition = $stickyrStopper.offset().top;
var stopPoint = stickyStopperPosition - generalSidebarHeight - stickOffset;
var diff = stopPoint + stickOffset;
$(window).scroll(function(){
var windowTop = $(window).scrollTop();
if (stopPoint < windowTop) {
$sticky.css({ position: 'absolute', top: diff });
} else if (stickyTop < windowTop+stickOffset) {
$sticky.css({ position: 'fixed', top: stickOffset });
} else {
$sticky.css({position: 'fixed', top: 'initial'});
}
});
}
});
</script>
There's nothing specific in the CSS or the html. Just a div on the right side class: sidebar and no specific CSS either except for the design of it. I thought there'd be a lot of code so I didn't post it here. Let me know if you do need it..
<!DOCTYPE html>
<div class="sidebar">
<!-- Office Reservation -->
<asp:Panel ID="pnl_In_Out" runat="server">
<div class="sidebar-sticky">
<!--<div class="container col-md-3" style="margin-top: 0px; position: relative; top:0px">-->
<%--<div class="" style="margin-left: 10px; padding-left:0px; max-width: 240px; width: 100%; position: relative; float: left;">--%>
<div class="office-reservation">
<div class="panel-main panel-primary">
<div class="panel-heading text-center" style="font-size: 15px; color: #444; font-weight: bold;">OFFICE RESERVATION</div>
<hr style="width: 50%; margin-left: auto; margin-right: auto; margin-top: 0px;">
<%--<div class="divider-line" style="width: 90px; border-top: 1px solid #ddd; text-align: center; margin: 0px 50px 0px 70px;"></div>--%>
<div class="panel-body">
<div class="row">
<div class="form-group" style="padding-left: 5px; text-align: left">
<label class="control-label" style="padding-left: 20px; text-align: left; font-size: 14px; color: #444;"><b>In</b></label>
<div class="input-group">
<div class="col-md-12">
<div class="textarea-form">
<asp:TextBox ID="txt_SearchDateFrom" CssClass="form-control form-control-inline input-small date-picker" runat="server"></asp:TextBox>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar" style="padding: 3px;"></span>
</span>
</div>
</div>
</div>
<div class="input-group">
<div class="col-md-12">
<div class="">
<asp:DropDownList ID="ddl_SearchTimeFrom" CssClass="form-control text-right" Width="145" Height="35" runat="server"></asp:DropDownList>
<span class="input-group-addon">
<span class="glyphicon glyphicon-time" style="padding: 3px; width: 20px"></span>
</span>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group" style="padding-left: 5px; text-align: left">
<label class="control-label" style="padding-left: 20px; text-align: left; font-size: 14px; color: #444;"><b>Out</b></label>
<div class="input-group">
<div class="col-md-12">
<div class="">
<asp:TextBox ID="txt_SearchDateTo" CssClass="form-control form-control-inline input-small date-picker" runat="server"></asp:TextBox>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar" style="padding: 3px"></span>
</span>
</div>
</div>
</div>
<div class="input-group">
<div class="col-md-12">
<div class="">
<%--<asp:TextBox ID="txt_SearchTimeTo" CssClass="form-control timepicker timepicker-no-seconds" Width="145" runat="server"></asp:TextBox>--%>
<asp:DropDownList ID="ddl_SearchTimeTo" CssClass="form-control" Width="145" Height="35" runat="server"></asp:DropDownList>
<span class="input-group-addon">
<span class="glyphicon glyphicon-time" style="padding: 3px; width:20px"></span>
</span>
</div>
</div>
</div>
</div>
</div>
<div class="wigdet_input_box" style="padding-top: 5px;">
<asp:Button ID="btn_Reserve" runat="server" Text="RESERVE" CssClass="btn btn-danger" Width="50%" OnClick="btn_Reserve_Time_Click" />
</div>
</div>
</div>
</div>
</div>
</asp:Panel>
<!-- QUICK CONTACT FORM -->
<asp:Panel ID="pnl_Question" runat="server">
<!--<div class="container col-md-3" style="margin-top: 0px; position: relative; top:0px">-->
<%--<div class="" style="margin-left: 10px; padding-left:0px; max-width: 240px; width: 100%; position: relative; float: left;">--%>
<div class="sidebar-sticky2">
<div class="panel-main panel-primary">
<div class="panel-heading text-center" style="font-size: 15px; color: #444; font-weight: bold;">QUESTIONS ?</div>
<hr style="width: 50%; margin-left: auto; margin-right: auto; margin-top: 0px;">
<div class="panel-body">
<div class="row">
<div class="form-group" style="padding-left: 5px; text-align: left">
<div class="input-group">
<div class="col-md-12">
<div class="">
<asp:TextBox ID="txt_Email" CssClass="form-control" Width="145" Font-Size="Small" runat="server" placeholder="Email Address"></asp:TextBox>
<span class="input-group-addon">
<span class="glyphicon glyphicon-envelope" style="padding: 3px"></span>
</span>
</div>
</div>
</div>
<div class="input-group">
<div class="col-md-12">
<div class="">
<asp:TextBox ID="txt_Message" TextMode="multiline" Rows="3" Font-Size="Small" CssClass="form-control" class="contact-message" Style="width: 100%!important; height: 70px; resize: none;" runat="server" placeholder="Enter Message"></asp:TextBox>
</div>
</div>
</div>
</div>
</div>
<div class="wigdet_input_box" style="padding-top: 5px;">
<asp:Button ID="btn_Message_Send" runat="server" Text="SEND" CssClass="btn btn-danger" Width="50%" OnClick="btn_Message_Send_Click" />
</div>
</div>
</div>
</div>
</asp:Panel>
<!-- CONTACT INFORMATION -->
<asp:Panel ID="Panel1" runat="server">
<!--<div class="container col-md-3" style="margin-top: 0px; position: relative; top:0px">-->
<%--<div class="" style="margin-left: 10px; padding-left:0px; max-width: 240px; width: 100%; position: relative; float: left;">--%>
<div class="sidebar-sticky3">
<div class="panel-main panel-primary">
<div class="panel-heading text-center" style="font-size: 15px; color: #444; font-weight: bold;">AGENT INFORMATION</div>
<hr style="width: 50%; margin-left: auto; margin-right: auto; margin-top: 0px;">
<div class="panel-body"">
<%--<div class="agent-photo">
<img src="/images/agent_face.jpg" width="80" alt="Agent" style="float: left;" />
</div>--%>
<div class="contact-info" style="text-align: center; color: #444; font-size: 14px;">
<%--<img src="/images/agent_face.jpg" width="150" alt="Agent" />--%>
<h5>Contact Number: </h5><asp:Label ID="lbl_ListingContactPhone" runat="server" Text="none"></asp:Label>
<h5>E-mail Address: </h5><asp:Label ID="lbl_ListingContactEmail" runat="server" Text="none"></asp:Label>
</div>
</div>
</div>
</div>
</div>
And the CSS
.sidebar {
float: right;
width: 245px;
margin-left: 850px;
}
.sidebar-sticky {
float: right;
}
.sidebar-sticky2 {
float: right;
}
.sidebar-sticky3 {
float: right;
}
A: Since the picture is not clear enough to reproduce the issue you described, I would only just point out aspects I observed to be out of place in the script you posted.
I have not studied the logic of the code enough to establish its correctness or a possible lack of it. But I believe some of the variables at play in the script ought to be evaluated during scroll since a change in the page content can invalidate their initial state:
$(document).ready(function() {
// 1. These variables factor in statically to the feature
// and it's appropriate that they are evaluated once
var $sticky = $('.sidebar');
var $stickyrStopper = $('.sticky-stopper');
if (!$sticky.offset()) {
return;
}
$(window).scroll(function() {
var stickOffset = 0;
// 2. These variables factor in DYNAMICALLY to the feature,
// and they must be re-evaluated in alignment with
// changing content for instance.
// --
// Therefore they deserve to be evaluated inside the scroll handler.
var generalSidebarHeight = $sticky.innerHeight();
var stickyTop = $sticky.offset().top;
var stickyStopperPosition = $stickyrStopper.offset().top;
var stopPoint = stickyStopperPosition - generalSidebarHeight - stickOffset;
var diff = stopPoint + stickOffset;
var windowTop = $(window).scrollTop();
if (stopPoint < windowTop) {
$sticky.css({
position: 'absolute',
top: diff
});
} else if (stickyTop < windowTop + stickOffset) {
$sticky.css({
position: 'fixed',
top: stickOffset
});
} else {
$sticky.css({
position: 'fixed',
top: 'initial'
});
}
});
});
See if that provides you a stepping stone.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53052248",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: git push is stuck when pushing to remote When I try to push to a remote repository,
git push origin xyz
it gets stuck. I try ssh -T [email protected] and I get a success:
You've successfully authenticated, but GitHub does not
provide shell access.
When I use the verbose option, I get a message that it is pushing:
git push -v origin xyz
Pushing to [email protected]:repo.git
and it times out after about 10 minutes with another message:
Connection to github.com closed by remote host.
And I do not get the prompt back in the shell.
I have tried the following but to no avail:
*
*including the --dry-run switch with push results the same.
*git clean -d -f -i followd by git gc --auto
I am on macOS High Sierra and using SSH authentication.
A: It turned out it was stuck due to a pre-push commit hook which was placed there (at <repository-root>/.git/hooks/pre-push) by a third-party tool.
To debug, I ran the command with GIT_TRACE on:
$ GIT_TRACE=1 git push -v origin xyz
11:47:11.950226 git.c:340 trace: built-in: git 'push' '-v' 'origin' ‘xyz’
Pushing to [email protected]:repo.git
11:47:11.951795 run-command.c:626 trace: run_command: 'ssh' '[email protected]' 'git-receive-pack ‘\’’repo.git'\'''
11:47:13.100323 run-command.c:626 trace: run_command: '.git/hooks/pre-push' 'origin' '[email protected]'
Deleting the pre-push file solved the problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48745559",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Call a controller method without loading a blank view I'm trying to call a controller method to delete a record in my database and I am using an actionlink to do this but whenever I hit the delete button, it will delete the record in the database, but it redirects me to a blank page. What I am trying to do is have it not redirect to anything but I can't seem to get that to work.
HTML/Razor
@Html.ActionLink(" ", "DeleteRecord", new { id = item.JPAppId }, new { @class = "fa fa-trash"})
Controller Method
public void DeleteRecord(Guid id)
{
JPApplication jPApplication = db.JPApplications.Find(id);
db.JPApplications.Remove(jPApplication);
db.SaveChanges();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53216847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Multiple VU in Jmeter-Only one user able to insert data Test Plan:-
-User logs in.
-Enter details in a form and save it(Which is stored in DB).
-Logs out.
When ran with 2 Virtual Users :-
-Number Of Threads(users) = 2
-Ramp Up Period = 1
-Loop Count = 1
Only 1 user is able to successfully store the details in DB.
2nd Thread/user give some URLs in response instead of JSON Data.
When one thread is used and the script is run many times, it is successfully storing data in DB.
Elements used in the Test Plan:-
-HTTP Cookie Manager
-View Result Tree
Am I missing some elements ?
What mistake I am doing ?
A: I suppose you are replaying the recorded plan for 1 user.
Most probably your issue is due to not variabilizing (Regexp Post-Processor or CSS/Jquery Post Processor to extract and variable to inject) some dynamic data that is needed for the additionnal users.
So when you put 1, it works because IDs correspond to recorded user, but when you put more, at some step you have the second users using the IDs of the first one.
Google "correlation with jmeter" to understand and fix your issue.
A: In case you have the correct script then check the business of your application. As I have experienced some applications don't allow many users submit the form at the same time. It will lock the form for the first user and the second user cannot submit, the second user will receive the response data with messages like "This form is being used by another user..." or "The data on this form is out of date, please refresh...". In that case, I use a Logic Controller, called "Critical Section Controller". It will handle the users to make sure the transaction will be executed by only one user at a time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32879319",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Migrate pinnacle cart customers data to magento1.x version I came back on stackoverflow after long time.I really need a help in migrating the pinnacle cart to magento1.x.I am migrating the customer data but I want customer can login in magento site with same credentials without reset the password.
Is it possible that customer can use the same credentials of pinnacle cart to Magento after migration.
any quick help will be appreciated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45785631",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get distinct pattern match results (substrings) from PyMongo What is the most efficient way to query a MongoDB collection for unique/distinct substrings in a given field?
Example documents:
{"_id": "1234.abc.test1", "some_key": "some_value"}
{"_id": "1234.abc.test2", "some_key": "some_value"}
{"_id": "0420.def.test3", "some_key": "some_value"}
The document IDs above follow an internal namespacing convention. I need to know what all of the distinct first elements of that namespacing are.
The desired output of the query on the above collection:
1234
0420
I am trying to avoid getting the entire dataset back only to do row['_id'].split('.')[0] on each row afterwards. Ideally, the query should return only the distinct list of those substrings.
A: The idea is actually the same as yours(i.e. splitting by . and get the first element), then $group them to get distinct records.
db.collection.aggregate([
{
$project: {
first: {
"$arrayElemAt": [
{
"$split": [
"$_id",
"."
]
},
0
]
}
}
},
{
"$group": {
"_id": "$first"
}
}
])
Here is the Mongo playground for your reference.
Here is the PyMongo implementation of the above query:
pipeline = [
{"$project": {"first": {"$arrayElemAt": [{"$split": ["$_id", "."]}, 0]}}},
{"$group": {"_id": "$first"}}
]
result = self.collection.aggregate(pipeline=pipeline, allowDiskUse=False)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70476261",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ajax get image from folder debug function ajax_json(folder){
var thumbnailbox = $('#thumbnailbox');
$.ajax({
url:"json_data.php",
dataType:"json",
type:"POST",
data: {folder: JSON.stringify(folder)},
contentType: "application/json; charset=utf-8",
success:function(d){
var temp = '';
for (var o in d) {
if (d.hasOwnProperty(o) && d[o].hasOwnProperty('src') && d[o].src !== '') {
//create image
temp += "<div class='typebox'><img id='typeImg' src=" + d[o].src + "></div>";
}
}
}, error: function (jqXHR, textStatus, errorThrown){
console.log("textStatus = " + textStatus + "\terrorThrown = " + errorThrown);
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.readyState);
alert(textStatus);
}
});
}
php
<?php
header("Content-Type: application/json");
$folder = $_POST["folder"];
$jsonData = '{';
$dir = $folder."/";
$dirHandle = opendir($dir);
$i = 0;
while ($file = readdir($dirHandle)) {
if(!is_dir($file) && preg_match("/.jpg|.gif|.png/i", $file)){
$i++;
$src = "$dir$file";
$jsonData .= '"img'.$i.'":{ "num":"'.$i.'","src":"'.$src.'", "name":"'.$file.'" },';
}
}
closedir($dirHandle);
$jsonData = chop($jsonData, ",");
$jsonData .= '}';
echo $jsonData;
?>
error
textStatus = parsererror errorThrown = SyntaxError: Unexpected token <
my intention is the get image from my folder using ajax ,it got error and i cant find what i am missing to have error , can anyone help me take a look? i cant debug it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32796396",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get Index of a Set in Swift let setOfStrings: Set<String> = ["ONE", "TWO", "THREE"];
It doesn't behave like and array, so setOfStrings[0] does not work.
Any ideas?
A: You might want to access the first element of the set as follows:
if let first = setOfStrings.first {
print(first)
}
Assuming that you are already familiar with: Set is unordered data structure, i.e: first value is not guaranteed to be "ONE".
You cannot access an element in a set via index as an integer (setOfStrings[0]), however, since Set represents a Collection (adopted by sets), SetIndex is probably what are you looking for, by using Set.Index of your current set, as follows:
let setOfStrings: Set<String> = ["ONE", "TWO", "THREE"]
// for me, it sorted as: {"THREE", "TWO", "ONE"}
let mySetIndex = setOfStrings.index(setOfStrings.startIndex, offsetBy: 1)
let secondElemnet = setOfStrings[mySetIndex] // "TWO"
Note that:
*
*By using subscript(_:), you should be able to get e specific element.
*index(_:offsetBy:):
Returns an index that is the specified distance from the given index.
*
*mySetIndex data type is SetIndex<String>.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43409009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to build server streaming via grpc and nest.js? Need to create some "channel" to which the client can subscribe and periodically receive messages.
Within the current technology stack, I'm trying to organize something like this:
proto file:
syntax = "proto3";
package testtime;
service TimeService {
rpc GetTimeStream(Empty) returns (stream TimeStreamResponse);
}
message Empty {
}
message TimeStreamResponse {
string result = 1;
}
controller:
import { Controller } from '@nestjs/common';
import { GrpcMethod } from '@nestjs/microservices';
import moment from 'moment';
import { Observable, Subject } from 'rxjs';
const timeSubject = new Subject<{ result: string }>();
setInterval(() => {
const result = moment().format('hh:mm');
timeSubject.next({ result });
}, 5000);
@Controller()
export class TestTimeController {
@GrpcMethod('testtime.TimeService', 'GetTimeStream')
public getTimeStream(): Observable<{ result: string }> {
return timeSubject.asObservable();
}
}
when I try to call the method, I get an error:
/project/node_modules/@nestjs/microservices/server/server-grpc.js:141
this.transformToObservable(await handler).subscribe(data => callback(null, data), (err) => callback(err));
^
TypeError: callback is not a function
at SafeSubscriber._next (/project/node_modules/@nestjs/microservices/server/server-grpc.js:141:73)
at SafeSubscriber.__tryOrUnsub (/project/node_modules/rxjs/src/internal/Subscriber.ts:265:10)
at SafeSubscriber.next (/project/node_modules/rxjs/src/internal/Subscriber.ts:207:14)
at Subscriber._next (/project/node_modules/rxjs/src/internal/Subscriber.ts:139:22)
at Subscriber.next (/project/node_modules/rxjs/src/internal/Subscriber.ts:99:12)
at CatchSubscriber.Subscriber._next (/project/node_modules/rxjs/src/internal/Subscriber.ts:139:22)
at CatchSubscriber.Subscriber.next (/project/node_modules/rxjs/src/internal/Subscriber.ts:99:12)
at TapSubscriber._next (/project/node_modules/rxjs/src/internal/operators/tap.ts:125:22)
at TapSubscriber.Subscriber.next (/project/node_modules/rxjs/src/internal/Subscriber.ts:99:12)
at MergeMapSubscriber.notifyNext (/project/node_modules/rxjs/src/internal/operators/mergeMap.ts:162:22)
at SimpleInnerSubscriber._next (/project/node_modules/rxjs/src/internal/innerSubscribe.ts:30:17)
at SimpleInnerSubscriber.Subscriber.next (/project/node_modules/rxjs/src/internal/Subscriber.ts:99:12)
at MergeMapSubscriber.notifyNext (/project/node_modules/rxjs/src/internal/operators/mergeMap.ts:162:22)
at SimpleInnerSubscriber._next (/project/node_modules/rxjs/src/internal/innerSubscribe.ts:30:17)
at SimpleInnerSubscriber.Subscriber.next (/project/node_modules/rxjs/src/internal/Subscriber.ts:99:12)
at SwitchMapSubscriber.notifyNext (/project/node_modules/rxjs/src/internal/operators/switchMap.ts:166:24)
What am I doing wrong?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67057765",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Azure function app, service bus and return service bus I have an azure function with a service bus input attribute and service bus output attribute set.
This means that whatever I return from this function will be returned to the ‘return’ queue.
However, i want to manually handle some messages as there is no point retrying them I just want to put them straight on the LDQ and carry on.
So i added MessageReceiver as a parameter with lockToken.
All good.
But now, if i handle the message and send to DLQ i have no way ending the function execution gracefully as it is expecting a return. So i throw an exception. But now i have numerous error logs in the output like ‘lock is invalid’.
I tried to set autocomplete to false but then i have a different issue; how do i ensure i can return the message AND log it in a transaction and handle rollback?
Any guidance??
Example:
public static class Function1
{
[FunctionName("Function1")]
[return: ServiceBus("returnQueueName", Connection = "myConnectionString")]
public static async System.Threading.Tasks.Task<ReturnMessage> RunAsync([ServiceBusTrigger("mytopic", "mysubscription", Connection = "myConnectionString")]
string mySbMsg, ILogger log,
MessageReceiver messageReceiver, string lockToken)
{
log.LogInformation($"C# ServiceBus topic trigger function processed message: {mySbMsg}");
await messageReceiver.DeadLetterAsync(lockToken);
return new ReturnMessage();
}
}
public class ReturnMessage
{
public string Payload { get; set; }
}
Hopefully you can see that the input queue and output queue are handled by the hosting system - Azure. I like this because it will look after atomcity for me.
But if I include the line:
await messageReceiver.DeadLetterAsync(lockToken);
This will move the current message to the DLQ.
GREAT!!! That's what I want.
But I am now forced to return something OR throw an exception. Is there any way out of this as seeing the error messages is misleading as there is no error to follow.
A: As far as I can see it appears that you shouldn't use an automatic return service bus binding. Instead, you should manually connect to the return topic/queue and handle the message logistics manually.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55932497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: objective-C - other methods to convert a float to string I know that you can convert a float into a string using
NSString *myString = [NSString stringWithFormat:@"%f", myFloat];
My question is what OTHER methods exist in Objective-C that can do that same?
thanks.
A: You can create your own category method. Something like
@interface NSString (Utilities)
+ (NSString *)stringWithFloat:(CGFloat)float
@end
@implementation NSString (Utilities)
+ (NSString *)stringWithFloat:(CGFloat)float
{
NSString *string = [NSString stringWithFormat:@"%f", float];
return string;
}
@end
Edit
Changed this to a class method and also changed the type from float to CGFloat.
You can use it as:
NSString *myFloat = [NSString stringWithFloat:2.1f];
A: You could use NSNumber
NSString *myString = [[NSNumber numberWithFloat:myFloat] stringValue];
But there's no problem doing it the way you are, in fact the way you have in your question is better.
A: float someVal = 22.3422f;
NSNumber* value = [NSNumber numberWithFloat:someVal];
NSLog(@"%@",[value stringValue]);
A: in a simple way
NSString *floatString = @(myFloat).stringValue;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4993231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "40"
} |
Q: How to change layers in pretrained model in Mxnet I have a pre-trained Mxnet model. I need to change last two layers and add new two layers for testing. Basically, I need to create a probability map of the image.
How can i do that ?
A: There is a tutorial on fine-tuning with MXNet. Did you check this out?
http://mxnet.incubator.apache.org/faq/finetune.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38537567",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Determining the execution time of all statements in process of FPGA I'm beginner studying FPGA. I'm confusing a problem.
I have code and the data type I use is fixed-point:
process(clk)
begin
if(clk'EVENT and clk ='1') then
r_amp := to_sfixed (amp,amp'HIGH,amp'LOW);
r_Va := resize (r_amp * to_sfixed(Va,0,-31),r_Va);
r_Vb := resize (r_amp * to_sfixed(Vb,0,-31),r_Vb);
r_Vc := resize (r_amp * to_sfixed(Vc,0,-31),r_Vc);
V_alpha := resize(r_Va/(to_sfixed (2/3,4,-27)*Udc),V_alpha);
V_beta := resize(to_sfixed(0.57735026919,4,-27)*(r_Vb-r_Vc)/(to_sfixed (2/3,4,-27)*Udc),V_beta);
tmp := resize(to_sfixed(0.57735026919,4,-27)*V_beta,tmp);
z1x := resize(V_alpha - tmp,z1x);
z1y := resize(to_sfixed (2,4,-27)*tmp,z1y);
z2x := resize(z1x+z1y,z2x);
z2y := resize(to_sfixed (-1,4,-27)*z1x,z2y);
z3x := resize(z1y,z3x);
z3y := resize(to_sfixed (-1,4,-27),z3y);
end if;
end process;
How to caculate the execution time of all statements in process? if all statements don't finish in 1 clock period, what will happen?
Thank for watching.
A: You define the clock period in ns and the synt/PR-tools tries to place the logic so this time constraint is fulfilled. If it fails you will get a timing error.
If it is not finished within 1 clk the result is undefined.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52181098",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to make separate REST controllers for nested resources? Spring Boot I have a REST controller. It processes the resource "messages". And each message can contain comments inside itself.
/api/v1/messages/1
/api/v1/messages/2
/api/v1/messages/1/comments/1
/api/v1/messages/1/comments/2
Here is a code:
@RestController
@RequestMapping("/api/v1/messages/")
public class RestControllerV1 {
@RequestMapping(value = "{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Message> getMessage(@PathVariable("id") Long messageId) {
}
@RequestMapping(value = "{messageId}/comments/{commentId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Comment> getComment(@PathVariable("messageId") Long messageId, @PathVariable("commentId") Long commentId) {
}
}
It works fine.
But I think that it is not very good to have one big controller for two resources. So I want different controllers (SOLID, S-principle).
MessageControllerV1
and
CommentControllerV1
Is it possible to divide controllers in Spring Boot application?
A: You could have something like:
@RestController
@RequestMapping("/api/v1/messages")
public class MessageController {
@RequestMapping(value = "{messageId}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Message> getMessage(@PathVariable("messageId") Long messageId) {
...
}
}
@RestController
@RequestMapping("/api/v1/messages/{messageId}/comments")
public class CommentController {
@RequestMapping(value = "{commentId}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Comment> getComment(@PathVariable("messageId") Long messageId,
@PathVariable("commentId") Long commentId) {
...
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50394327",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: I need some help detecting if a browser has access to the internet
Possible Duplicate:
Check if Internet Connection Exists with Javascript?
I have been working on a manual to be sent via CD to a customer. The owner of my company requires that the manual be split into many subsections as .doc and .docx files. The table of contents for this manual will be an HTML page, to be run by autorun when the CD is put into the computer.
I can be fairly sure that the computer is a windows computer, but that's about it. My current thinking is to use this script to take advantage of google to display the word file, but only if the computer is actually connected to the internet. That way I don't have to rely on the customer having a particular version of word (or having a compatibility pack installed).
From the research I've done, relying on a computer to correctly recognize that a link to a word document should be opened with word is problematic, and has to be resolved at the user end.
A: Have a look at window.navigator.onLine
A: You could try an ajax request to a reliable site.
// THIS IS OUR PAGE LOADER EVENT!
window.onload = function() {
testConnection();
};
function testConnection(){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
alert(xmlhttp.responseText);
} else if (xmlhttp.readyState==4){
alert("NO INTERNET DETECTED!");
}
}
xmlhttp.open("GET","http://www.w3schools.com/ajax/ajax_info.txt",true);
xmlhttp.send();
}
Now you will have to play around with it for a way to use the response because it is asynchronous, but this will work to test a connection.
A: Previously discussed here: Check if Internet Connection Exists with Javascript? and here: How to know if the network is (dis)connected?.
A: GM_xmlhttpRequest({
method: "GET",
url: "http://www.google.com/",
onload: function(response) {
if(response.responseText != null) {
alert("OK");
} else {
alert("not connected");
}
}
});
*
*second alternative
var HaveConnection = navigator.onLine;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6616009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: laravel artisan error while clearing config cache when I run php artisan cache:config the command throw the following error
PHP Warning: require(): Filename cannot be empty in /home/****/public_html/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php on line 71
PHP Fatal error: require(): Failed opening required '' (include_path='.:/usr/share/php') in /home/****/public_html/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php on line 71
I have no idea what causing this and how to fix it.
A: it turns out that there is one suspicious file inside config folder, once it's deleted the artisan command works just fine again.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64852826",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Select two columns from the sqlite which got unique column and ordered by Date, Time I have two tables which got same columns, examples
TableA
ID, Image, Date , Time
0 , 0 , 12/03, 12:33
0 , 1 , 12/03, 12:34
1 , 2 , 12/03, 12:34
1 , 3 , 12/03, 12:35
TableB
ID, Image, Date , Time
0 , 4 , 12/03, 12:33
0 , 5 , 12/03, 12:35
2 , 6 , 12/03, 12:34
2 , 7 , 12/03, 12:35
The results I need are
ID, Image, Date , Time
0 , 5 , 12/03, 12:35
1 , 3 , 12/03, 12:35
2 , 7 , 12/03, 12:35
This is easy to be done if it was one table
SELECT DISTINCT ID, Image FROM TableA GROUP BY ID ORDER BY Date DESC, Time DESC LIMIT 5
But how could I select from two tables?
A: You can use union all. This returns the most recent image from the two tables combined for each id:
with ab as (
select a.* from TableA a union all
select b.* from TableB b
)
SELECT ID, Image
FROM (SELECT ab.*,
ROW_NUMBER() OVER (PARTITION BY id ORDER BY DATE DESC, TIME DESC) as seqnum
FROM ab
) ab
WHERE seqnum = 1;
ORDER BY Date DESC, Time DESC
LIMIT 5;
A: If what you need is the rows with the latest date and time (as your expected results):
with cte as (
select * from Tablea
union all
select * from Tableb
)
select * from cte
where Date || Time = (select max(Date || Time) from cte)
order by id
I assume the dates are always in the format MM/YY and the times hh:mm.
See the demo.
Results:
| ID | Image | Date | Time |
| --- | ----- | ----- | ----- |
| 0 | 5 | 12/03 | 12:35 |
| 1 | 3 | 12/03 | 12:35 |
| 2 | 7 | 12/03 | 12:35 |
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59249173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: pip and multiple python version issues in ubuntu 16.04 I'm deploying a flask server with gulp, and after the gulp command is launched, everything goes fine until the following line:
import flask
as I get the error
ImportError: No module named flask
. Adding the lines before the import command
import sys
print(sys.executable)
I get printed
/usr/bin/python
which, launched on console, corresponds to a python 2.7.12 interpreter, and the command 'import flask' within the console doesn't give any error!!
I can find many python interpreters (2, 3 and virtenvs on my machine) but it seems each of them has flask installed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46791309",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: take minimum between column value and constant global value I would like create new column for given dataframe where I calculate minimum between the column value and some global value (in this example 7). so my df has the columns session and note and my desired output column is minValue :
session note minValue
1 0.726841 0.726841
2 3.163402 3.163402
3 2.844161 2.844161
4 NaN NaN
I'm using the built in Python method min :
df['minValue']=min(7, df['note'])
and I have this error:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
A: Use np.minimum:
In [341]:
df['MinNote'] = np.minimum(1,df['note'])
df
Out[341]:
session note minValue MinNote
0 1 0.726841 0.726841 0.726841
1 2 3.163402 3.163402 1.000000
2 3 2.844161 2.844161 1.000000
3 4 NaN NaN NaN
Also min doesn't understand array-like comparisons hence your error
A: The preferred way to do this in pandas is to use the Series.clip() method.
In your example:
import pandas
df = pandas.DataFrame({'session': [1, 2, 3, 4],
'note': [0.726841, 3.163402, 2.844161, float('NaN')]})
df['minVaue'] = df['note'].clip(upper=1.)
df
Will return:
note session minVaue
0 0.726841 1 0.726841
1 3.163402 2 1.000000
2 2.844161 3 1.000000
3 NaN 4 NaN
numpy.minimum will also work, but .clip() has some advantages:
*
*It is more readable
*You can apply simultaneously lower and upper bounds: df['note'].clip(lower=0., upper=10.)
*You can pipe it with other methods: df['note'].abs().clip(upper=1.).round()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33689714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
} |
Q: Is there a development environment 'checklist' I can run through before starting to code? I am following Michael Hartl's Rails Tutorial, and have gone through setting up my Development Environment.
I want to quickly check I have everything in order i.e. RVM, Ruby, Rails, Git, etc. all installed in the right place and correctly configured.
If you were picking up a beginner's computer and wanted to understand their development environment and spot anything missing (before running into errors later on), is there a hygiene checklist you go through?
How can I do this?
Thank you!
A: Michael hartls tutorial explains well what you need, but for a short list:
Curl
is needed to get RVM and to test HTTP requests. You will need it to install some requirements also.
Git:
You need it during the tutorial, and to get some gems directly from github.
Any JS platform:
I've choosen NODEJS because it's the easiest one to install, but you can use any of your like: rubyracer, v8...
Ruby interpreter:
Then Install a ruby version. I've always install the last one as default and then install the ones needed in the project.
The gems:
If you are using Ruby > 2.0 install byebug if not install debugger. And rails, the last version as well. If you are following a tutorial install other version.
Any editor:
If you want to learn I recommend you VIM, as you will get used to develop and will learn a nice editor. Learning a nice command line editor is allways payed. So don't be afraid. You can learn sublime or gedit at any moment, but learning VIM is hardest, so start now.
Then databases.
Install whichever you want:
MySQL.
PostgreSQL
SQlite
Or mongo, just to practice.
that should be enough to start the tutorial.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24512307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I use jQuery sortable for elements in a specific table column only? I am trying to use jQuery's draggable and sortable to sort elements listed inside of a specific column of a table.
The reason is that I essentially want to fit people into timeslots.
I have a table as such:
<table width="300" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>1:00 PM</td>
<td><div class="personSortable">Person 1</div></td>
</tr>
<tr>
<td>2:00 PM</td>
<td><div class="personSortable">Person 2</div></td>
</tr>
<tr>
<td>3:00 PM</td>
<td><div class="personSortable">Person 3</div></td>
</tr>
<tr>
<td>4:00 PM</td>
<td><div class="personSortable">Person 4</div></td>
</tr>
</table>
I want to make all the divs with the class 'personSortable' sortable into the avaliable time slots. I have looked for an answer but the closest thing i could find was to make the entire row sortable (by making the table the sortable container) - which is not ideal because I can't have the time slots change.
Another idea I had was to create two div wrappers: one with the time slots, and one containing sortable divs for the people, and using the CSS 'float' property to have them line up. Would that be a more ideal approach?
A: Found this and it seems to do the trick if anyone else was interested:
http://www.redips.net/javascript/drag-and-drop-table-content/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11149873",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to send any structure as parameter to a method and return the structure? I'm new to Go and I'm seeing if there's a way to have a method that receives any structure as parameter.
I have something like this in my code that is a function that does exactly the same for 5 structures and returns the same structure, but I don't know if I can do that. I'm wondering if I can do something like this:
type Car struct {
Model string `yaml:"Model"`
Color string `yaml:"Color"`
Wheels int `yaml:Wheels"`
Windows int `yaml:"Windows"`
}
type Motorcycle struct {
Model string `yaml:"Model"`
Color string `yaml:"Color"`
Wheels int `yaml:Wheels"`
}
type Bus struct {
Model string `yaml:"Model"`
Color string `yaml:"Color"`
Wheels int `yaml:Wheels"`
Passengers int `yaml:"Passengers"`
}
func main () {
car := GetYamlData(Car)
motorcycle := GetYamlData(Motorcycle)
Bus := GetYamlData(Bus)
}
func GetYamlData(struct anyStructure) (ReturnAnyStruct struct){
yaml.Unmarshal(yamlFile, &anyStructure)
return anyStructure
}
Is possible to do something like the code above? Actually what I have is something like this:
func main(){
car, _, _ := GetYamlData("car")
_,motorcycle,_ := GetYamlData("motorcycle")
_,_,bus := GetYamlData("bus")
}
func GetYamlData(structureType string) (car *Car, motorcycle *Motorcycle, bus *Bus){
switch structureType{
case "car":
yaml.Unmarshal(Filepath, car)
case "motorcycle":
yaml.Unmarshal(Filepath, motorcycle)
case "bus":
yaml.Unmarshal(Filepath, bus)
}
return car, motorcycle, bus
}
With the time this will be increasing and it will return a lot of values and I don't want a lot of return values, is there a way to do it with the first code that I posted?
A: You can do it the exact same way yaml.Unmarshal does it, by taking in a value to unmarshal into:
func GetYamlData(i interface{}) {
yaml.Unmarshal(Filepath, i)
}
Example usage:
func main () {
var car Car
var motorcycle Motorcycle
var bus Bus
GetYamlData(&car)
GetYamlData(&motorcycle)
GetYamlData(&bus)
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51482629",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP/MYSQL query ranking using secondary tables Working with a ranking algorithm, but I'm getting frustrated with the multiple database calls and data gyrations i'm having to go through to calculate the rank of a specific item, output it in to an array, and then sort by the rank value. Is it possible in MySQL to calculate the rank of a given row based on the data found in other tables?
SELECT key_value FROM table;
Now with the result set I need to rank each item based on various other tables information about those items. So if the output was -
|key_value|
|abcd1 |
|abcd2 |
|abcd3 |
Then based on 'abcd1' values in 3 other tables, I need to rank each entry based on the value divided by total and return the rank and then output it. Is there a way to do all this in a single SQL statement? I've thought about setting up some sql variables and storing different calls and then doing the calculation, but I'm still not sure how you would assign that to the SELECT statements output and rank it accordingly. I'm good with PHP, but i'm kind of a MySQL n00b.
This is probably confusing the way I'm describing it - I can answer more questions to help better explain what I'm trying to do.
Basically each row returned in the original statement is really only relevant to each user based on information stored about that object in 3 other tables. Need to know the best way to use the data in the 3 other tables to rank the relevancy of the data from the first table.
A: The key here is that you need to JOIN your other tables, then ORDER BY some expression on their fields.
SELECT key_value
FROM table
LEFT JOIN table_b on table_b.field = table.key_value
LEFT JOIN table_c on table_c.field = table.key_value
LEFT JOIN table_d on table_d.field = table.key_value
ORDER BY table_b.some_field DESC, (table_c.another_field / table_d.something_else) ASC
;
Depending on the join conditions, you may need to GROUP BY table.key_value or even use subqueries to attain the appropriate effect.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531266",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Keras custom loss function causes TypeError
*
*Why when I am trying to create my own loss function using Keras backend
def my_loss(y_true, y_pred):
return K.mean(K.max(y_true, y_pred) / K.min(y_true, y_pred))
and pass to the Keras neural network, I get
TypeError: Value passed to parameter 'reduction_indices' has DataType float32 not in list of allowed values: int32, int64
*As far as I know, we should use Keras backend functions in custom loss because keras have to differentiate the loss function, but how do they differentiate Max and Min functions that have no derivative?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63542710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Iterate over a directory and filter results based on file extensions I have a function that cycles through a directory and, for each folder within that directory, returns the most recent file. The problem is that the folders contain files of different formats, such as .xlsx and .csv. The file extensions may change per request, so I need to pass them as a parameter to the function, instead of hard-coding the values. How can I pass a list of file extensions as a parameter and select the file according to its extension? Here's what I'm trying to do:
var extensions = new string[] { ".xlsx", ".csv" };
var filename = FileSystemService.GetRecentFile(path, extensions.ToList<string>);
A: If you need the most recent file having one of the extensions required, then this could be a solution:
public FileInfo GetRecent(string path, params string[] extensions)
{
var list = new List<FileInfo>();
// Getting all files having required extensions
// Note that extension is case insensitive with this code
foreach (var ext in extensions)
list.AddRange(
new DirectoryInfo(path)
.EnumerateFiles("*" + ext, SearchOption.AllDirectories)
.Where(p =>
p.Extension.Equals(ext,StringComparison.CurrentCultureIgnoreCase))
.ToArray());
return list.Any()
// If list has somm file then return the newest one
? list.OrderByDescending(i => i.LastWriteTime)
.FirstOrDefault()
// else return what you please, it could be null
: null;
}
If you need the most recent file for each extension, then this could be a solution:
public Dictionary<string, FileInfo> GetRecents(string path, params string[] extensions)
{
var ret = new Dictionary<string, FileInfo>();
// Getting all files having required extensions
// Note that extension is case insensitive with this code
foreach (var ext in extensions)
{
var files = new DirectoryInfo(path)
.EnumerateFiles("*" + ext, SearchOption.AllDirectories)
.Where(p =>
p.Extension.Equals(ext, StringComparison.CurrentCultureIgnoreCase))
.ToArray();
ret.Add(ext, files.Any()
? files.OrderByDescending(i => i.LastWriteTime).FirstOrDefault()
: null);
}
return ret;
}
A: You could first enumerate the Sub-Directories in the provided path, using Directory.EnumerateDirectories. This enumeration excludes the root, so we can add it back to the Enumerable, if required, using the Prepend()1 or Append()1 methods.
Then iterate the collection of extensions, call DirectoryInfo.EnumerateFiles to get Date/Time information about the files in each Directory and filter using the FileInfo.LastWriteTime value and finally order by the most recent and yield return the first result.
I've used a public methods that calls a private worker method, so the public method can be used to provide some more filters or it could be more easily overloaded. Here it's used to provide an option to return the most recent file of all.
It can be called as:
string[] extensions = { ".png", ".jpg", "*.txt" };
var mostRecentFiles = GetMostRecentFilesByExtension(@"[RootPath]", extensions, false);
Specify false to get all the files by type and directory, or true to get the most recent file among all files that matched the criteria.
public IEnumerable<FileInfo> GetMostRecentFilesByExtension(string path, IEnumerable<string> extensions, bool returnSingle)
{
var mostRecent = MostRecentFileByExtension(path, extensions).Where(fi => fi != null);
if (returnSingle) {
return mostRecent.OrderByDescending(fi => fi.LastWriteTime).Take(1);
}
else {
return mostRecent;
}
}
private IEnumerable<FileInfo> MostRecentFileByExtension(string path, IEnumerable<string> exts)
{
foreach (string dir in Directory.EnumerateDirectories(path, "*", SearchOption.AllDirectories).Prepend(path))
foreach (string ext in exts) {
yield return new DirectoryInfo(dir)
.EnumerateFiles($"*{ext}")
.Where(fi => fi.Extension.Equals(ext, StringComparison.InvariantCultureIgnoreCase))
.OrderByDescending(fi => fi.LastWriteTime).FirstOrDefault();
}
}
(1) Both Prepend() and Append() require .Net Framework 4.7.1.
Core/Standard Frameworks all have them.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60012205",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Where should I cp oc binary to on MacOS? In this documentation it says
unpack the archive and move the oc binary to a directory on your PATH
I tried echo $PATH and it returns:
bin:/Library/Frameworks/Python.framework/Versions/3.4/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin
Clearly there are multiple path here, which one should I move cp oc binary to?
A: /usr/local/bin would be the usual choice for user or third-party executables. That way it won't get wiped out when you update the OS.
See also: Where do you keep your own scripts on OSX? - the question is about scripts rather than binaries, but the same logic applies.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44351776",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: in iOS7 how do you stop the First viewcontroller autorotating? I have an app that just needs one screen to autorotate, the first and last screens should be portrait. I can get the last screen to stop rotating using:
- (NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskPortrait;
}
But this does not work on the first screen, I am using a storyboard with a UINavigationController (I'm thinking that may have something to do with it?)
Any help would be gratefully received. Thanks
A: you may need to subset the UINavigationController and you should use it instead of the standard UINavigationController.
I have done this in my projects, so this cares of the individual UIViewController classes' custom orientations:
.h
#import <UIKit/UIKit.h>
@interface UIOrientationController : UINavigationController { }
@end
.m
@implementation UIOrientationController
- (BOOL)shouldAutorotate {
return [self.topViewController shouldAutorotate];
}
- (NSUInteger)supportedInterfaceOrientations {
return [self.topViewController supportedInterfaceOrientations];
}
@end
NOTE: you can extended this class with overriding more methods, if it becomes a requirement in your final code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24239641",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Get a clean extract from Wikipedia page I am currently exploring the Wikipedia API and am trying to understand it a bit more.
So I am starting with a Wikidata ID and can find my Wikipedia Title there. I extract the title and am then able to query Wikipedia like e.g. so:
https://en.wikipedia.org/w/api.php?action=query&format=json&titles=Los_Angeles&prop=extracts&exsentences=2&explaintext&exintro
The result would be something like the following:
Los Angeles (US: (listen) lawss AN-jəl-əs; Tongva: Tovaangar; Spanish: Los Ángeles; Spanish for "The Angels"), often spoken and written as its initialism, L.A., is the largest city in California. With a 2020 population of 3,898,747, it is the second-largest city in the United States, after New York City, and the third-largest city in North America, after Mexico City and New York City.
That way I get the extract as a plain string. Good! The problem is, that it still contains "links" or "strange things", because some links/infos are removed. E.g. the pronunciation of the text ist now gone but the link to (listen) to it is still there as plain text.
I would like to display the text of the page in an iOS App as plain text somehow. Is there a way to get that from the wikipedia API or will I have to do my own magic?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69466276",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Nested Json using retrofit i want to read sub_category > id, name from json using retrofit
But below code give failed response.
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was
BEGIN_ARRAY at line 2 column 2 path $
My Json....
[
{
"id": "1",
"name": "Invamore",
"sub_category": [
{
"id": "101",
"name": "Banner"
},
{
"id": "102",
"name": "3 sided Dangler"
},
{
"id": "103",
"name": "Leaflet"
}
]
},
{
"id": "2",
"name": "HUPS",
"sub_category": [
{
"id": "103",
"name": "Leaflet"
},
{
"id": "104",
"name": "Posters"
},
{
"id": "105",
"name": "Sunpack"
}
]
},
{
"id": "3",
"name": "Xplore",
"sub_category": [
{
"id": "101",
"name": "Banner"
},
{
"id": "103",
"name": "Leaflet"
},
{
"id": "106",
"name": "Dangler"
},
{
"id": "107",
"name": "Vertical Streamer"
}
]
},
{
"id": "4",
"name": "Xpress",
"sub_category": [
{
"id": "101",
"name": "Banner"
},
{
"id": "103",
"name": "Leaflet"
},
{
"id": "108",
"name": "Streamer"
}
]
},
{
"id": "5",
"name": "Matrix",
"sub_category": [
{
"id": "103",
"name": "Leaflet"
}
]
},
{
"id": "6",
"name": "Instabrite",
"sub_category": [
{
"id": "103",
"name": "Leaflet"
}
]
},
{
"id": "7",
"name": "Mileage",
"sub_category": [
{
"id": "107",
"name": "Vertical Streamer"
}
]
},
{
"id": "8",
"name": "Onam Posm",
"sub_category": [
{
"id": "101",
"name": "Banner"
},
{
"id": "106",
"name": "Dangler"
}
]
}]
Backend.java
public void pos_func(String user_id) {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call call = apiService.POS_MODEL_CALL(user_id);
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
}
@Override
public void onFailure(Call call, Throwable t) {
Log.d("sk_log", "Failed! Error = " + t.getMessage());
}
});
}
ApiInterface.java
@FormUrlEncoded
@POST("pos_distributed.php")
Call<ValuesPos> POS_MODEL_CALL(@Field("user_id") String user_id);
Model : from pojoschema2pojo.com for above JSON
ValuesPos.java
package com.example.shkhan.myapp.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
/**
* Created by shkhan on 14/11/16.
*/
public class ValuesPos {
@SerializedName("id")
@Expose
public String id;
@SerializedName("name")
@Expose
public String name;
@SerializedName("sub_category")
@Expose
public List<SubCategory> subCategory = new ArrayList<SubCategory>();
/**
*
* @return
* The id
*/
public String getId() {
return id;
}
/**
*
* @param id
* The id
*/
public void setId(String id) {
this.id = id;
}
/**
*
* @return
* The name
*/
public String getName() {
return name;
}
/**
*
* @param name
* The name
*/
public void setName(String name) {
this.name = name;
}
/**
*
* @return
* The subCategory
*/
public List<SubCategory> getSubCategory() {
return subCategory;
}
/**
*
* @param subCategory
* The sub_category
*/
public void setSubCategory(List<SubCategory> subCategory) {
this.subCategory = subCategory;
}
}
SubCategory.json
package com.example.shkhan.myapp.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
/**
* Created by shkhan on 14/11/16.
*/
public class SubCategory {
@SerializedName("id")
@Expose
public String id;
@SerializedName("name")
@Expose
public String name;
/**
*
* @return
* The id
*/
public String getId() {
return id;
}
/**
*
* @param id
* The id
*/
public void setId(String id) {
this.id = id;
}
/**
*
* @return
* The name
*/
public String getName() {
return name;
}
/**
*
* @param name
* The name
*/
public void setName(String name) {
this.name = name;
}
}
A: The Json contains a list of ValuesPos
The ApiInterface.java call for a single ValuesPos
EDIT
Change the ApiInterface.java to call for a list of ValuesPos
@FormUrlEncoded
@POST("pos_distributed.php")
Call<List<ValuesPos>> POS_MODEL_CALL(@Field("user_id") String user_id);
A: Here is the entire code which work for me... ( Thanks for the help )
Modified two class
ApiInterface.java
@FormUrlEncoded
@POST("pos_distributed.php")
Call<List<ValuesPos>> POS_MODEL_CALL(@Field("user_id") String user_id);
Backend.java
public void pos_func(String user_id) {
dataArrayList1 = new ArrayList<>();
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call <List<ValuesPos>> call = apiService.POS_MODEL_CALL(user_id);
call.enqueue(new Callback<List<ValuesPos>>() {
@Override
public void onResponse(Call<List<ValuesPos>> call, Response<List<ValuesPos>> response) {
Log.d("sk_log", "Status POS Code = successsss");
dataArrayList1 = response.body();
//ValuesPos valuesPos = (ValuesPos) response.body();
Log.d("sk_log", "name==="+dataArrayList1.get(0).getName());
Log.d("sk_log", "name==="+dataArrayList1.get(0).getSubCategory().get(0).getName());
CustomerCollection.spinner_pos(dataArrayList1);
}
@Override
public void onFailure(Call<List<ValuesPos>> call, Throwable t) {
Log.d("sk_log", "Failed! Error = " + t.getMessage());
}
});
}
:)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40591040",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Toogle slide on a tag and css proprety I'm trying to toggle box shadow property for a tag within #bj-pagination. I would like to achieve effect where box shadow slides from page 1 link to page 2 link when link for page 2 is clicked. Is this complicated?
<div id="bj-pagination">
<div class="pagination">
<span class="disabled"><span id="prev">PREV</span></span>
<span class="current">1</span>
<a href="pagination.php?page=2">2</a>
<a href="pagination.php?page=3">3</a>
<a href="pagination.php?page=4">4</a>
<a href="pagination.php?page=2"><span id="next">NEXT</span></a>
</div>
</div>
Here I am positioned on page 1. CSS for current page is...
#bj-pagination .current {
-moz-box-shadow: inset 0 -4px 0 #F6E128;
-webkit-box-shadow: inset 0 -4px 0 #F6E128;
box-shadow: inset 0 -4px 0 #F6E128;
background: #FFF;
border:1px solid #E4E4E4;
border-right:none;
}
I would like to when page 2 is clicked animate slide of boxshadow from page 1 link on to page 2 link
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16275074",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: A strange result in a simple pthread code I wrote the following code:
#include <pthread.h>
#include <stdio.h>
void* sayHello (void *x){
printf ("Hello, this is %d\n", (int)pthread_self());
return NULL;
}
int main (){
pthread_t thread;
pthread_create (&thread, NULL, &sayHello, NULL);
printf("HERE\n");
return 0;
}
After compiling and running I saw 3 different types of outputs.
*
*Only "Here" was printed.
*"Here" and 1 'sayHello' message.
*"Here" and 2 'sayHello' messages.
Of course I'm OK with the second option, but I don't understand why the 'sayHello' massege can be printed 0 or 2 times if I created only one thread?
A: You can't say when the thread starts to run, it might not start until
after you return from main which means the process will end and the thread with it.
You have to wait for the thread to finish, with pthread_join, before leaving main.
The third case, with the message from the thread printed twice, might be because the thread executes, and the buffer is written to stdout as part of the end-of-line flush, but then the thread is preempted before the flush is finished, and then the process exist which means all file streams (like stdout) are flushed so the text is printed again.
A: For output 1:
your main function only create a pthread, and let it run without waiting for it to finish.
When your main function return, Operating system will collect back all the resources assigned to the pprocess. However the newly created pthread might have not run.
That is why you only got HERE.
For output 2:
your newly created thread finished before main function return. Therefore you can see both the main thread, and the created thread's output.
For output 3
This should be a bug in glibc. Please refer to Unexpected output in a multithreaded program for details.
To make the program always has the same output
pthread_join is needed after pthread_create
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30375392",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Passing component as a function argument I have a function that take a component as argument, and return another, enhanced component:
import React from 'react';
import { compose } from 'recompose';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { Layout, DarkBar } from 'SharedComponents/Layouts';
const myCreationFunction = ({
component,
}) => {
const Route = (props) => {
// Some code here
return (
<Layout>
<div><Link to={props.path}>LinkTitleHere</Link></div>
{React.createElement(component, {
...props,
...someOtherPropsHere,
})}
</Layout>
);
}; // The error points here
const mapStateToProps = () => ({});
const enhance = compose(
connect(mapStateToProps, someActionsHere),
)(Route);
return enhance;
};
I invoke that function in this way:
import MyComponent from './MyComponent';
import myCreationFunction from './HOC/myCreationFunction';
const Route = myCreationFunction({
component: MyComponent,
});
When I run it in the development mode, it runs smoothly. But when trying to build the app using npm run build and going through webpack, I get:
Module parse failed: Unexpected token (35:47)
You may need an appropriate loader to handle this file type.
| function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
> var createListRoute = function myCreationFunction((_temp = _ref, _ref2 = <_Layouts.DarkBar>
| <_Breadcrumbs2.default />
| <_Layouts.RoundAddButton path={addPath} color="white" />
What am I doing wrong?
Edit #1
It seems that the <Link> is causing the problem. Removing it fixed the problem. Also, when trying to replace it with a tag, I get the same issue. Weird.
Edit #2
I have not resolved this issue because of lack of time. I was trying for 1 hour without any progress and decided to go with button tag and onClick method that uses history to push the new url.
It was and is really weird to me, that a Link or <a> tag can break something during the build process itself. I will definitely jump deeper into it in some free time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50870650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Why does my PartialView render outside the form tag? I have a view that displays an HTML table of "Room" objects. Each Room is a row (which is a PartialView) in the table.
The view contains this code:
<table>
@foreach (var item in Model)
{
using (Html.BeginForm())
{
@Html.Partial("_roomPartial", item)
}
}
</table>
Model is an IEnumerable<Room>, and _roomPartial is an HTML row containing the properties of a Room.
For some reason, the HTML of the Partial renders after the closing form tag (despite being inside the using block):
<form action="/Room/Index" method="post"></form>
<tr>
...some boring markup...
</tr>
Other things I tried to make this work:
*
*Used Html.RenderPartial("_roomPartial", item); instead of @Html.Partial.
*Moved the using (Html.BeginForm()) block inside the PartialView
I got the same HTML results each time.
Why does the Partial render outside the form tag? And how can I get it to render properly?
View:
@model IEnumerable<PatientAssigner.Models.Room>
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.ID)
</th>
<th>
@Html.DisplayNameFor(model => model.isOccupied)
</th>
<th>
@Html.DisplayNameFor(model => model.patientComplexityLevel)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
using (Html.BeginForm())
{
@Html.Partial("_roomPartial", item)
}
}
</table>
_roomPartial:
@model PatientAssigner.Models.Room
<tr>
<td>
@Html.DisplayFor(room => room.ID)
@Html.HiddenFor(room => room.ID)
</td>
<td>
@Html.EditorFor(room => room.isOccupied)
@Html.ValidationMessageFor(room => room.isOccupied)
</td>
<td>
@Html.DropDownListFor(room => room.patientComplexityLevel,
new SelectList(Enum.GetValues(typeof(PatientAssigner.Models.PatientComplexityLevel)),
Model.patientComplexityLevel),
"")
@Html.ValidationMessageFor(room => room.patientComplexityLevel)
</td>
<td>
<input type="submit" value="Save" class="btn btn-default" id="saveBtn" />
</td>
</tr>
A: form tags are not valid between table and tr tags. I suggest changing your view to not have the tr or td tags and do this outside:
<table>
@foreach (var item in Model)
{
<tr><td>
@using (Html.BeginForm())
{
@Html.Partial("_roomPartial", item)
}
</td></tr>
}
</table>
If you need to have a form for every row but want your inputs spread across cells, your only option is to have nested tables like this:
<table>
<tr>
<td>
<form>
<table>
<tr>
<td>cell1</td>
<td>cell2</td>
<td>cell3</td>
</tr>
</table>
</form>
</td>
</tr>
<tr>
<td>
<form>
<table>
<tr>
<td>cell1</td>
<td>cell2</td>
<td>cell3</td>
</tr>
</table>
</form>
</td>
</tr>
</table>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24842418",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: python webserver socket programming error # Import socket module
from socket import *
#from socket import AF_INET, SOCK_STREAM, socket
import sys # In order to terminate the program
# Create a TCP server socket
#(AF_INET is used for IPv4 protocols)
#(SOCK_STREAM is used for TCP)
ipadress=socket.gethostbyname(socket.gethostname())
subnetAdress = '.'.join(ipadress.split('.')[:3]) + '.0'
print(f"ipadress : {ipaddress}")
print(f"subnetAdress : {subnetAdress}")
file = open("permit.txt", 'r', encoding="UTF-8")
permitList = file.readlines()
#
serverSocket = socket(AF_INET, SOCK_STREAM)
# Assign a port number
serverPort = 6789
# Bind the socket to server address and server port
serverSocket.bind(("", serverPort))
# Listen to at most 1 connection at a time
serverSocket.listen(1)
# Server should be up and running and listening to the incoming connections
while True:
print('The server is ready to receive')
# Set up a new connection from the client
connectionSocket, addr = serverSocket.accept()
# If an exception occurs during the execution of try clause
# # the rest of the clause is skipped
# # If the exception type matches the word after except
# # the except clause is execute
if subnetAdress+'\n' in permitList:
print("Warning!!\n it's not permitted")
continue
try:
# Receives the request message from the client
message = connectionSocket.recv(1024).decode()
print(message)
# Extract the path of the requested object from the message
# # # The path is the second part of HTTP header, identified by [1]
# filename = message.split()[1]
print(filename)
# Because the extracted path of the HTTP request includes
# # # a character '\', we read the path from the second character
file = open(filename[1:], 'rb')
# Store the entire contenet of the requested file in a temporary buffer
# outputdata = file.read()
# # Send the HTTP response header line to the connection socket
header = 'HTTP/1.1 200 OK\n'
if(filename.endswith(".jpg")):
filetype = 'image/jpg'
elif(filename.endswith(".mp4")):
filetype = 'video/mp4'
elif(filename.endswith(".wmv")):
filetype = 'video/wmv'
elif(filename.endswith(".gif")):
filetype = 'video/gif'
elif(filename.endswith(".html")):
filetype = 'text/html'
else:
raise IOError
header += 'Content-Type: '+str(filetype)+'\n\n'
print(header)
connectionSocket.send(header.encode())
# Send the content of the requested file to the connection socket
# # # for i in range(0, len(outputdata)):
# # # # connectionSocket.send(outputdata[i].encode())
# # # connectionSocket.send(outputdata)
connectionSocket.send("\r\n".encode())
# Close the client connection socket
# connectionSocket.close()
except IOError:
# Send HTTP response message for file not found
header = 'HTTP/1.1 404 Not Found \n\n'
connectionSocket.send(header.encode())
connectionSocket.send(
"<html><head></head><body><h1>404 Not Found</h1></body></html>\r\n".encode())
# Close the client connection socket
connectionSocket.close()
serverSocket.close()
sys.exit()
#Terminate the program after sending the corresponding data
I did this for socket programming
it's hard to explain but I had this error. and I put from socket import
please help me out. I don't know why
I will be dying ..
AttributeError Traceback (most recent call last)
c:\Users\taek\python\탐색\네트워크\과제3\IPwebServer.py in <module>
9 #(SOCK_STREAM is used for TCP)
10
---> 11 ipadress=socket.gethostbyname(socket.gethostname())
12 subnetAdress = '.'.join(ipadress.split('.')[:3]) + '.0'
13
AttributeError: type object 'socket' has no attribute 'gethostbyname'
** **
ㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠ
A: If you use
from socket import *
then you have to use without socket.
gethostbyname(...)
gethostname()
socket(AF_INET, SOCK_STREAM)
If you use
import socket
then you have to use with socket.
socket.gethostbyname(...)
socket.gethostname()
socket.socket(AF_INET, SOCK_STREAM)
BTW: import * is not preferred - see PEP 8 -- Style Guide for Python Code
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70243284",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: problems with opening vegan I Installed the package "vegan" but cant seem to run it. When I use the command library(vegan) I get this message
.
Any ideas? I normally just use R cmdr so excuse me if this is a silly question.
Also: Is there any plugin to cmdr for NMDS ordination that I can use instead?
A: That wasn't a "problem". It was only a "message" and not even a particularly dangerous message. It was telling you that the vegan package had a function of the same name as another function in the pls package. If you know that you will be using the scores function with the syntax of the pls::scores function at a later time, then you will need to use it with that form. If you just use scores you will get the function as it exists in pkg:vegan.
I'm being mute about the second part (although it may be premised incorrectly on your anxiety about the message, in which case the question is moot). Multipart questions are discouraged on SO.
A: To answer your question about Rcmdr plugin for NMDS: check BiodiversityR package that provides an Rcmdr GUI to a part of vegan (plus more).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50238438",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using ManagementObjectSearcher to get an exact BitLocker WMI value Good Day All,
I am having an issue with ManagementObjectSearcher. I am trying to query the exact value that i want but cannot find any reference to the precise syntax requirements and I continually receive an error when trying to finish out the code to be what I need it to be.
the specific portion of code that is presenting the issue is when I check for the drives Encryption state(I know for a fact that my disk is not encrypted on this machine, which is why that is the only value i have if'd currently). Any assistance in getting this code to pull the correct value would be greatly appreciated.
I've tried both the "=" method and the "LIKE" method with no change in output.
using Microsoft.Win32;
using System;
using System.Drawing;
using System.IO;
using System.Management;
using System.Windows.Forms;
public Form1()
{
InitializeComponent();
// Check for OS Version
string OSVer = Convert.ToString(Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "ProductName", null));
OSDialog.Text = OSVer;
// Check Architecture
if (Directory.Exists("C:\\Program Files (x86)"))
{
ArchitectureDialog.Text = "64 Bit";
}
else
{
ArchitectureDialog.Text = "32 Bit";
}
// Check Encryption
ManagementObjectSearcher Collect = new ManagementObjectSearcher("SELECT ProtectionStatus FROM Win32_EncryptableVolume WHERE DriveLetter = 'C:'");
string Encryption = Collect.ToString();
if (Encryption == "0")
{
EncryptionDialog.Text = "Disk is not Encrypted";
EncryptionDialog.ForeColor = Color.Green;
}
}
private void Cancel_Click(object sender, EventArgs e)
{
Close();
}
A: Getting BitLocker information from WMI requires elevated permissions. Your code has to be running as an admin and you have to ask for elevated privileges. So, I don't use ManagementObjectSearcher to obtain BitLocker info. Instead, I do something similar to the following (modified to your scenario - but not tested as shown):
ManagementObject GetBitLockerManager( string driveLetter )
{
var path = new ManagementPath( );
path.Server = string.Empty;
path.NamespacePath = @"\ROOT\CIMV2\Security\MicrosoftVolumeEncryption";
path.ClassName = "Win32_EncryptableVolume";
var options = new ConnectionOptions( );
options.Impersonation = ImpersonationLevel.Impersonate;
options.EnablePrivileges = true;
options.Authentication = AuthenticationLevel.PacketPrivacy;
var scope = new ManagementScope( path, options );
var mgmt = new ManagementClass( scope, path, new ObjectGetOptions( ) );
mgmt.Get( );
return mgmt
.GetInstances( )
.Cast<ManagementObject>( )
.FirstOrDefault
( vol =>
string.Compare
(
vol[ "DriveLetter" ] as string,
driveLetter,
true
) == 0
);
}
A: OK so I figured it out, thank you for all of the assistance provided. Code is below.
ManagementObjectSearcher Encryption = new ManagementObjectSearcher(@"root\cimv2\Security\MicrosoftVolumeEncryption", "SELECT * FROM Win32_EncryptableVolume");
foreach (ManagementObject QueryObj in Encryption.Get())
{
string EncryptionStatus = QueryObj.GetPropertyValue("ProtectionStatus").ToString();
if (EncryptionStatus == "0")
{
EncryptionDialog.Text = "Unencrypted";
}
else if (EncryptionStatus == "1")
{
EncryptionDialog.Text = "Encrypted - SysPrep will not complete";
}
else if (EncryptionStatus == "2")
{
EncryptionDialog.Text = "Cannot Determine Encryption";
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42984048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Where i can edit this price element woocommerce? I want to replace the word "De: " of all products, but I do not know where
Link to website
A: You can change the "From" text via the woocommerce_get_price_html_from_text filter.
You would do so, like this:
add_filter( 'woocommerce_get_price_html_from_text', 'so_43054760_price_html_from_text' );
function so_43054760_price_html_from_text( $text ){
return __( 'whatever', 'your-plugin-textdomain' );
}
Keep in mind this is WooCommerce 3.0-specific code. I'm not sure it is back-compatible with WC 2.6.x.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43054760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: User Registration setting missing in Joomla This is my first experience in Joomla V3.3.6
I have a requirement where there would be 2 user types.
-> User Type 1
-> User Type 2
1) I am looking out for registration module in Joomla. Searched and looks there are lots of plugins. But also understood that Joomla by default has default Registration module as per the below link:
*
*http://docs.joomla.org/Allowing_user_registration
*http://docs.joomla.org/Setting_user_registration_policy
The issue is, I do not see a place in Global Settings where there is User Settings as defined by the above link. Hence not able to see the registration page.
2) I see in admin dashboard, User Manager, User Groups. I guess, I could use these user groups to define the User Types. Please confirm if this is how it is in Joomla?
Kindly Help! Thanks in advance.
A: From the administrator, go to User Manager
At the top right, you'll see Options
That's where you set the user/registration options
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26702419",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Chart.Js Doughnut not calculating JSON data properly When using static data, the Doughnut chart appear perfectly, example:
$.ajax({
url: 'includes/stats.php?show',
dataType: 'json',
success: function (response)
{
console.log(response['CARS']); //I see 2
console.log(response['MOTORS']); //I see 0
console.log(response['BOATS']); //I see 0
var autoData = [
{
value: 2,
color: "#4286f4",
highlight: "#4d6fa5",
label: "Cars"
},
{
value: 0,
color: "#3fe276",
highlight: "#51a36d",
label: "Motor Homes"
},
{
value: 0,
color: "#bde234",
highlight: "#87964e",
label: "Boats"
}
];
var ctx = document.getElementById("onChart").getContext("2d");
var myNewChart = new Chart(ctx).Doughnut(autoData);
}
});
I'm doing the JSON call, but on the callback, I'm filling autoData variable with static data [2, 0, 0], this way the chart appears and calculate 100% for "Cars", because it is the only with some value (2), others are 0's...
When I do:
$.ajax({
url: 'includes/stats.php?show',
dataType: 'json',
success: function (response)
{
console.log(response['CARS']); //I see 2
console.log(response['MOTORS']); //I see 0
console.log(response['BOATS']); //I see 0
var autoData = [
{
value: response['CARS'],
color: "#4286f4",
highlight: "#4d6fa5",
label: "Cars"
},
{
value: response['MOTORS'],
color: "#3fe276",
highlight: "#51a36d",
label: "Motor Homes"
},
{
value: response['BOATS'],
color: "#bde234",
highlight: "#87964e",
label: "Boats"
}
];
var ctx = document.getElementById("onChart").getContext("2d");
var myNewChart = new Chart(ctx).Doughnut(autoData);
}
});
I get just what looks like a 2% slice of the chart filled... What's happening here?
A: I was constructing the JSON from PHP, something like:
$data = $autoQuery->fetch_array();
$autoData = array('CARS' => $data['CARS'],
'MOTORS' => $data['MOTORS'],
'BOATS' => $data['BOATS']);
echo json_encode($autoData);
This wasn't working. When I put intval() before each $data variable, it worked!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45333611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: I want to add list view new items (Except old ones) to array I have two list views, list one contains hotel service items that are fixed to a specific room and the other on is optional services, when i click on optional service list view item it will be added into services items. at the end all services will be viewed in list services(fixed + additional), and the price of only optional service will be saved in a db table which is optional service of the specified room
i tried on adding to delete old values and then adding optional services till the size of the added items but it doesn't work, some times it gives an error and other it prints or add only the old services and first one from the optional
`
for(int i=0;i<(lst1Count);i++){
lst1.getItems().remove(i);
}
for(int i=0;i<(lst1.getItems().size());i++){
try {
String queryServicePrice = "select Serviceprice from services where ServiceName ='"+lst1.getItems().get(i)+"'";
ResultSet rsRoomService = stmt.executeQuery(q`ueryServicePrice);
rsRoomService.next();
Serviceprice[i] = rsRoomService.getBigDecimal(
"Serviceprice");
System.out.println("price"+i+" : "+Servicepric
e[i]);}
`
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56870393",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Enforce NTP Time Sync on boot - raspberrypi 3 I have a setup a raspberrypi to sync time from a NTP server as it does not have a HW clock on it, however this update does not happen immediately and takes a while (~15 mins). Is there a way I can enforce the NTP Client to sync datetime with the NTP server before starting up other user processes. If anyone has been able to achieve this please let me know. cheers!
Update: The rPi does not have internet connectivity
A: You might want to try this service from the NIST:
NIST Internet Time Service. They have a list of servers here. and tips on how to engage with their system from Windows, OSX, and Linux. The response might be quick enough to hold you over until your NTP client can receive its response.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45122822",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to get running total column sir i have query that show RUNNING TOTAL but not show me exect Dr_amount and Cr_amount as per transaction how to get Dr_amount and Cr_amount as per single transaction
SELECT
V_DATE,FLAG,V_NUM,V_NARATION,
sum(DR_AMOUNT) AS DEBIT,
sum(CR_AMOUNT) AS CRIDIT,
sum(dr_amount)-sum(cr_amount) as total
FROM VOUCHARDETAIL AS VDTL
INNER JOIN VOUCHARMASTER AS VMST
ON VDTL.DTL_NUM <=VMST.MST_NUM
WHERE (V_DATE BETWEEN '12-03-2017' AND '13-03-2017') AND (FLAG='IV' OR FLAG='BR'
OR FLAG='CP' OR FLAG='CR' OR FLAG='JV') AND (AC_CODE=60030002)
GROUP BY
V_DATE,FLAG,V_NUM,V_NARATION
ORDER BY
V_DATE
Example Image
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42802550",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Running Transient services in background (.NET Core) I am attempting to write a customer order tracker using Blazor Server.
What I'd like to do is launch on the background an order management service for every new order created. The service would keep track of various live information associated with the order, and it should be disposed of when the order is completed.
I am able to do that through registering the service as:
services.AddTransient();
I can then dependency-inject this into a razor component:
@inject OrderManagementService om_service
This creates a new instance for each order, which is good. The problem is that I can't expect the user to keep the page open in order to keep the the Transient service's scope alive.
From my observation, the instance continues to run, but its lifetime is not well-defined. It could terminate indefinitely soon (not long enough to finish the job), or run indefinitely long (thus robbing the server of resources). As I have no reference to it.
How can this problem be solved? If Transient services are not the solution, then what would it be?
Thank you!
A: Check out hosted background services in .NET Core, sounds like it could work for you.
Hosted background services continue running on your server even if the user navigates away from your site. You could have an OrderManager hosted service that guides each order through the process and keeps the order status updated in the database, email the user status updates, or push changes to the front-end.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67325621",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Auto refresh/reload four iframes in Wordpress I'm pretty NEW
so on the question:
I have 4 iframes on one page in WordPress showing some stats. I want to make them auto refresh (not the whole page) on certain amount of time, like every 3 second.
I've managed to do that for one only but whenever I try to add another one it doesn't work. I hope there's a simple solution.
Here's the iframe:
<iframe id="idcw" src="http://web.ubercounter.com/charts/chart5?f=jsn&ext=1&pid=01edabc9-dd3c-41db-949b-9b6ee52e0af5&cid=&fromD=2018-06-26&toD=&fromT=16:48:14&toT=<=&lg=&r=0&fh=0&th=24&u=0&rt="></iframe>
And the JS I''ve putt in the Header:
<script>
window.setInterval("reloadIFrame1();", 60000);
function reloadIFrame1() {
document.frames["idcw"].location.reload();
}
window.setInterval("reloadIFrame2();", 60000);
function reloadIFrame2() {
document.getElementById('idcw').src = document.getElementById('idcw').src;
}
</script>
PS: That was the only code I found on the internet working as it had to work. I tried with my very basic knowledge to add another 3 iframes to reload but only one refreshed.
Thanks in advance!
A: Try this code
setInterval(function(){ reloadIFrame2(); }, 5000);
function reloadIFrame2() {
var elements = document.getElementsByClassName("idcw");
for (var i = 0, len = elements.length; i < len; i++) {
elements[i].src = elements[i].src;
}
}
<iframe class="idcw" src="http://web.ubercounter.com/charts/chart5?f=jsn&ext=1&pid=01edabc9-dd3c-41db-949b-9b6ee52e0af5&cid=&fromD=2018-06-26&toD=&fromT=16:48:14&toT=<=&lg=&r=0&fh=0&th=24&u=0&rt="></iframe>
<iframe class="idcw" src="http://web.ubercounter.com/charts/chart5?f=jsn&ext=1&pid=01edabc9-dd3c-41db-949b-9b6ee52e0af5&cid=&fromD=2018-06-26&toD=&fromT=16:48:14&toT=<=&lg=&r=0&fh=0&th=24&u=0&rt="></iframe>
<iframe class="idcw" src="http://web.ubercounter.com/charts/chart5?f=jsn&ext=1&pid=01edabc9-dd3c-41db-949b-9b6ee52e0af5&cid=&fromD=2018-06-26&toD=&fromT=16:48:14&toT=<=&lg=&r=0&fh=0&th=24&u=0&rt="></iframe>
<iframe class="idcw" src="http://web.ubercounter.com/charts/chart5?f=jsn&ext=1&pid=01edabc9-dd3c-41db-949b-9b6ee52e0af5&cid=&fromD=2018-06-26&toD=&fromT=16:48:14&toT=<=&lg=&r=0&fh=0&th=24&u=0&rt="></iframe>
Run this fiddle
http://phpfiddle.org/main/code/asn7-zfvq
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51154351",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Installing Maven and creating a maven project in eclipse I am new to using maven project and i am trying to create a maven project and i followed the instructions to create one in eclipse and i gave the groupId and artifact id to it and clicked Finish, for which it gave me an error stating
"No marketplace entries found to handle
maven-compiler-plugin:3.1:compile in Eclipse. Please see Help for
more information."
For this issue i tried googling and stack overflow and i saw people asking other people to change the installation directory of maven inside
Window-> Preferences -> Maven-> Installation
I tried that and tried to update the maven project but still i have some errors, i am not able to setup my project, Could someone please help?
I am attaching the errors herewith.
A: If a Maven project is configured to use ecj compiler, the following errors appear when importing the project into eclipse:
*
*No marketplace entries found to handle maven-compiler-plugin:2.3.2:compile in Eclipse. Please see Help for more information.
*No marketplace entries found to handle maven-compiler-plugin:2.3.2:testCompile in Eclipse. Please see Help for more information.
A fix should be trivial.
http://git.eclipse.org/c/m2e/m2e-core.git/tree/org.eclipse.m2e.jdt/lifecycle-mapping-metadata.xml reads:
<parameters>
<compilerId>javac</compilerId>
</parameters>
It should read:
<parameters>
<compilerId>javac</compilerId>
<compilerId>eclipse</compilerId>
</parameters>
Reproducible: Always
Steps to Reproduce:
1. Unpack example zip provided
2. Try to import it to Eclipse: File->Import->Maven->Existing Maven Projects
A: First you can try to install maven globaly. follow the steps.
*
*Download maven from maven download link
*Create or export M2_HOME="MAVEN ROOT LOCATION". Ex. : E:\SoftwareRepo\building tools\apache-maven-3.5.2
*Create or export MAVEN bin folder location to PATH variable.
For example: E:\SoftwareRepo\building tools\apache-maven-3.5.2\bin
*Open terminal or cmd and run mvn --version to confirm maven is installed or not.
Then go to eclipse. and setup project.follow this steps
*
*Import existing maven project or create a maven project
*Goto project explorer and Right click on your pom.xml
*then select Run As maven install.
*and then what you want.
Hope it will serve your purpose. You can download a sample spring boot project from sample spring boot project
Or you can run a maven project from terminal or cmd. Just goto project root folder and then run a maven task like maven clean install .
Happy Coding :)
A: First install Java and then create the maven project.
Install the stable Java version in the system.
If Java is not installed then these types of errors will be displayed.
No marketplace entries found to handle
maven-compiler-plugin:3.1:compile in Eclipse.
Take a look at Help for more information.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53330113",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: java.lang.ClassCastException: cannot cast class com.ibm.WsnOptimizedNaming._NamingContextStub to interface Created a remote EJB project and deployed in the IBM websphere server as Jar.
Now, i created a EJB Client project in my local and trying to connected as Remote call.
but it is throwing an exception: java.lang.ClassCastException
client Program:
package ejb3.test;
import java.util.Properties;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
public class TestEJBClient {
public static void main(String[] args) {
// TODO Auto-generated method stub
Properties props = new Properties();
props.put(javax.naming.Context.PROVIDER_URL, "iiop://(ip of remote ejb server):2809");
ITestEJBRemoteInterface loEJB = null;
Object lobj;
try {
InitialContext ctx = new InitialContext(props);
System.out.println(ctx.getEnvironment());
lobj = ctx.lookup("ejb3/test/ITestEJBRemoteInterface");// look up of corba
System.out.println("--------" + lobj);
loEJB = (ITestEJBRemoteInterface) PortableRemoteObject.narrow((org.omg.CORBA.Object) lobj, ITestEJBRemoteInterface.class);
String lsName = "Kevin";
// Invoke the Method using bean object ;
System.out.println("Is " + lsName + " present in the list:: " + loEJB.checkNames(lsName));
System.out.println("EJB run successful");
}
catch (NamingException e) {
e.printStackTrace();
}
}
}
exception:
{com.ibm.websphere.naming.hostname.normalizer=com.ibm.ws.naming.util.DefaultHostnameNormalizer, java.naming.factory.initial=com.ibm.websphere.naming.WsnInitialContextFactory, com.ibm.websphere.naming.name.syntax=jndi, com.ibm.websphere.naming.namespace.connection=lazy, com.ibm.ws.naming.ldap.ldapinitctxfactory=com.sun.jndi.ldap.LdapCtxFactory, com.ibm.websphere.naming.jndicache.cacheobject=populated, com.ibm.websphere.naming.namespaceroot=defaultroot, com.ibm.ws.naming.wsn.factory.initial=com.ibm.ws.naming.util.WsnInitCtxFactory, com.ibm.websphere.naming.jndicache.maxcachelife=0, com.ibm.websphere.naming.jndicache.maxentrylife=0, com.ibm.ws.naming.wsn.localonly=false, com.ibm.websphere.naming.jndicache.cachename=providerURL, java.naming.provider.url=iiop://10.176.106.207:2809, java.naming.factory.url.pkgs=com.ibm.ws.naming:com.ibm.ws.naming:com.ibm.ws.naming:com.ibm.ws.naming:com.ibm.ws.naming}
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
INFO: Client code attempting to load security configuration
Feb 18, 2016 7:39:53 PM null null
AUDIT: security.LoadSCI
Feb 18, 2016 7:39:53 PM null null
AUDIT: security.GettingConfig
Feb 18, 2016 7:39:53 PM null null
WARNING: ssl.default.password.in.use.CWPKI0041W
Feb 18, 2016 7:39:53 PM null null
INFO: ssl.disable.url.hostname.verification.CWPKI0027I
Feb 18, 2016 7:39:53 PM null null
AUDIT: security.AuthTarget
Feb 18, 2016 7:39:53 PM null null
AUDIT: security.ClientCSI
--------com.ibm.WsnOptimizedNaming._NamingContextStub:IOR:00bdbdbd0000003149444c3a636f6d2e69626d2f57736e4f7074696d697a65644e616d696e672f4e616d696e67436f6e746578743a312e3000bdbdbd0000000100000000000000f4000102bd0000000a6c6f63616c686f737400238c0000006b4a4d4249000000124773e3aa37643062633737336533616166633334000000240000004749454a500200f76a838007736572766572311a57736e44697374436f734f626a65637441646170746572574c4d00000016434c45564449434d2d3134334e6f6465303143656c6cbd00000007000000010000001400bdbdbd0501000100000000000101000000000049424d0a0000000800bd00011600000100000026000000020002bdbd49424d04000000050005020102bdbdbd0000001f0000000400bd0003000000200000000400bd0001000000250000000400bd0003
Exception in thread "P=592906:O=0:CT" java.lang.ClassCastException: cannot cast class com.ibm.WsnOptimizedNaming._NamingContextStub to interface ejb3.test.ITestEJBRemoteInterface
at com.ibm.rmi.javax.rmi.PortableRemoteObject.narrow(PortableRemoteObject.java:396)
at javax.rmi.PortableRemoteObject.narrow(PortableRemoteObject.java:148)
at ejb3.test.TestEJBClient.main(TestEJBClient.java:38)
How could i resolve that error?
Can any one please share your thoughts.
A: ClassCastException - if narrowFrom cannot be cast to narrowTo.
Seems that corba.object and itestejbrremoteinterface are not related by inheritance
A: The relevant lines from the dumpNameSpace are:
168 (top)/nodes/CLEVDICM-143Node01/servers/server1/ejb3.test.ITestEJBRemoteInterface
168 ejb3.test.ITestEJBRemoteInterface
192 (top)/nodes/CLEVDICM-143Node01/servers/server1/ejb/TestEJB(1)_jar/TestEJB(1).jar/TestEJB#ejb3.test.ITestEJBRemoteInterface
192 ejb3.test.ITestEJBRemoteInterface
The root of the server context is (top)/nodes/CLEVDICM-143Node01/servers/server1/, which means you should use one of these strings:
*
*ejb3.test.ITestEJBRemoteInterface
*ejb/TestEJB(1)_jar/TestEJB(1).jar/TestEJB#ejb3.test.ITestEJBRemoteInterface
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35484304",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to reliably determine the width of a character in C#? I'm writing a C# program and I'm using a fixed-width font to display everything. Under this font, every Unicode character either occupies 1 character width or 2 character width. In the program, there is a feature that needs to determine a particular character occupies 1 character width or 2 character width. At first I use the regex [^\x00-\xFF] to solve the problem. If a character matches it, it occupies 1 character width, otherwise it's 2 character width. But later I found this is not correct. For example, these characters ┌─┬┐│├┼┤┴┘ don't fall in the range of [^\x00-\xFF] but they all just occupies 1 character width. I want to know in C# how to determine a specific character occupies 1 character width or 2 when using fixed-width font?
A: I'm also searching for the same question's answer... but I haven't found it.
by the way, I finally write a library to get length of character (generate a range information which shows character length use Console.Write() and Console.CursorLeft, and then convert to C# code, when get character length, use binary search for higher speed)
nuget: NullLib.ConsoleEx
Project: https://github.com/SlimeNull/NullLib.ConsoleEx
A: According to .NET documentation, if you know the font used1, you could use the GlyphTypeface API to get the "AdvanceWidths" of each glyph of your font.
You still have to map the character with glyph index in your font. You can use CharacterToGlyphMap to do that.
var character = 'x';
GlyphTypeface glyphTypeface = new GlyphTypeface(new Uri("file:///C:\\WINDOWS\\Fonts\\Kooten.ttf"));
var index = glyphTypeface.CharacterToGlyphMap[character];
var width = glyphTypeface.AdvanceWidths[index];
[1] To get current console's font details I would recommend to read following question: Get current console font info
Related question: How to find exact size for an arbitrary glyph in WPF?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65410411",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Mule http connector encoding I am posting xml string use mule http connector to my client.
The xml has string "Grubišić". It works fine if I post data to client from anypoint studio. If run on production or testing server, my client received "GrubiÅ¡iÄ" instead of "Grubišić".
I tried to specify content-type = "application/xml;charset=UTF-8" from http request header, payload property.. none of them worked.
<set-payload value="#[flowVars.myXML]" encoding="UTF-8" mimeType="application/xml" doc:name="Set Payload"/>
<http:request config-ref="HTTP_Request_Configuration" path="/api/upload" method="POST" doc:name="HTTP" >
<http:request-builder>
<http:header headerName="Content-Type" value="application/xml;charset=UTF-8"/>
</http:request-builder>
</http:request>
I am using 3.9CE runtime.
Am I missing any config? or it could be a bug in 39CE standalone?
Thanks
-Susan
A: There a lot of context missing in the question to be sure, but setting the encoding in the set-payload operation or in the Content-Type header doesn't actually transform the payload to or from UTF-8. A common mistake is to assume because the configurations, or even the XML declaration says UTF-8, to assume that the data is UTF-8 automatically. It is the data that is in UTF-8 or not. Most probably you are using a payload that is in a local encoding (Windows-1252 or something similar) when you test locally, but your server uses UTF-8 by default so it doesn't appear as you are expecting. "GrubiÅ¡iÄ" looks very similar to how the UTF-8 encoding of "Grubišić" would look.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71133250",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Does the 'Supporting Files' folder increase launch time/CPU consumption? If I have a lot of images/etc in the Supporting Files folder does that increase CPU consumption and slow the launch time of the app? Does the app have to load all these files on launch.
Thanks in Advance :)
A: No. In general these are copied into the apps bundle at compile time, letting the app access them when it needs them (by finding the files).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23649478",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to make chromium/chrome only reloads the modifled files? My site has a lot of img, js, css files. If one file is modified by developer its url will be changed too, otherwise the url will not be changed.
I wish chromium/chrome only reloads the modified files according to the url, but actually it often reloads all files with some unknown rules without using cache.
How to solve this?
A: It's a vague and broad question, but I guess you use different URLs to prevent retrieving old, cached versions of changed resources (that's one sure way anyway, although not necessarily the best way) and have a problem with Chromium-based browsers not caching resources that are unchanged.
Chromium respects caching directives as per spec, so it seems you're not sending the appropriate caching directives (headers) in the first place or have a problem testing the caching behavior (e.g. testing with caching disabled). Determine which is the problem and fix it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57638661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Update sharepoint user profile property with SPSecurity.RunWithElevatedPrivileges I try to change user profile property with next code
SPSecurity.RunWithElevatedPrivileges(delegate(){
SPSite currentSite = new SPSite(SPContext.Current.Web.Url);
SPServiceContext serviceContext = SPServiceContext.GetContext(currentSite);
UserProfileManager upm = new UserProfileManager(serviceContext);
UserProfile up1 = upm.GetUserProfile("DOMAIN\\User3");
up1["CustomProperty"].Value=10;
up1.Commit();
currentSite.Dispose();
});
And it's all right when i open page with account User1, which have permissions to change all user profiles. But when i open page with User2(with no permissions) - i get 403 error. In debugger up1["CustomProperty"].Value is null.
Why SPSecurity.RunWithElevatedPrivileges have no effect and how can i solve this problem?
Thanks
A: I found description of my problem in next article
Impersonation does not work with UserProfileManager
As a reason you can clear HttpContext each time you get or set user profile properties. For example next code works fin for me.
SPSecurity.RunWithElevatedPrivileges(delegate()
{
HttpContext tempCtx = HttpContext.Current;
HttpContext.Current = null;
UserProfile userProfile = GetUserProfile(user);
userProfile["SomeProperty"].Value = points;
userProfile.Commit();
HttpContext.Current = tempCtx;
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32047472",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to iterate through a list of URLs and make a GET request I am trying to take a list of URLs from Google Sheets and then make an API request for each URL and return data in JSON format. I currently am able to retrieve the list from Google sheets as well as make a Request for a single URL that I manually enter.
So far everything is working as expected. I am more or less asking for guidance on what my next steps would be. I am a novice in Python so not sure what to do next.
Here is an example of the output for the API request of the single URL in JSON:
{"date":"2019-02-07T00:00:00+0000","clicks":7},{"date":"2019-02-06T00:00:00+0000","clicks":7},{"date":"2019-02-05T00:00:00+0000","clicks":5}
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 6 18:47:58 2018
@author: Dylan
"""
import requests
import json
import gspread
from oauth2client.service_account import ServiceAccountCredentials
#scope is just telling google what API you want to use because they have so
many
scope = ['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name('Bitly Click
Data-a892fb027ee3.json', scope)
gc = gspread.authorize(credentials)
wks = gc.open("Bit.ly Links & General Links").get_worksheet(0)
values_list = wks.col_values(2)
wks = json.dumps(str(wks))
print(wks.get_all_records())
url = "https://api-ssl.bitly.com/v4/bitlinks/THIS NEEDS TO BE THE URL LIST
HERE/clicks"
payload = ""
headers = {'authorization': 'Bearer ACCESS TOKEN HERE'}
response = requests.request("GET", url, data=payload, headers=headers)
print(response.text)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54700823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Having trouble wrapping my head around how to handle dates I'm working on a scheduling system for music venues. The basic idea is that there's an "Create new schedule" page, on which there is a DatePicker calendar (using AngularUI Bootstrap). The user selects a Date, then adds performers into timeslots. The built object looks something like this:
{
date: 2017-6-22 00:00:00.000-5:00
venue: VenueID
performances: [
{
performer: performerID,
time: 2017-06-22 22:00:23.231-5:00
},{
perfomer: performer2ID,
time: 2017-06-22 23:00:42.523-5:00
}
]
}
There's a couple of problems here. For the original date selection, I set the time (using myDate.setHours(0,0,0,0)) to midnight because the time doesn't really matter, I only care about the actual date. Likewise for the timeslots, their date doesn't matter (since they belong to the schedule for that day), so I only care about the time. Then in another project, we have a node/mongo app that saves these schedules, and returns them to a page in the angular project that lets you select a schedule for editing/etc. It selects which ones to return by grabbing all the schedules for a specific venue, and doing "if (schedule.date >= new Date().setHours(0,0,0,0)) { add schedule to return list }"
Anyway, on to the actual problem. The angular app does all of the date calculations client side. What I mean is, I'm in CST. If I select a Date on the calendar and save a schedule for that date, then someone in EST selects the same day on the calendar and saves a schedule, they have different dates in the database. For example, when I make the schedule, the date in the DB is "2017-06-22 00:00:00.000-5:00". When the EST friend makes a schedule on the same date, it gets saved as "2017-06-22 00:00:00.000-4:00".
In the "Select a schedule to view/edit" page, I do something like this:
<select ng-model="schedule" ng-options="s.date|date:'fullDate' for s in schedules" ng-show="schedules.length>=1"></select>
Of course this doesn't work because when my EST friend looks at the list, he sees the correct date. But when I look at one that he created, the date is one day off because "2017-06-22 00:00:00.000-4:00" converted to local timezone is "2017-06-21 23:00:00.000-5:00".
I guess TL;DR is I'm not sure how to handle it since the venue and anyone creating/editing the schedules may not share the same time zone. I want all of the dates/times to show up in the timezone of the venue (which I have the address for. I guess I could geolocate to find timezone?). I'm just not sure how to go about it.
A: The DatePicker gives you a date object. Instead of storing the entire value string just grab the day month and year Date(value).getYear() + '-' + Date(value).getMonth() + '-' + Date(value).getDate(). As for the times do the same as the dates. Store those values in the DB and then when you get them back you will have to convert them back to a date object so that the date picker can understand them.
Ultimately with this solution your just trying to store dates without the timezones. Make sure to state in your app that the times are for those areas.
A: You have to distinguish between the format the date/time is transported, saved vs. how the date will be shown to the user.
*
*For transportation and saving use UTC in a format that is easy computable (eg. ISO8601).
*For visualization to the user convert this value to the timezone and desired user format by using some helper library.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44713525",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to poll a resource using jersey service i have a jersey service which generates a response. what i want to do is to poll a resource (in my case, a singleton class instance) for a success value, and as soon as i get the success value, perform some action
@Path("/generate")
class Generation{
@POST
@Produces("javax.ws.rs.core.MediaType.TEXT_PLAIN")
public String generateAndPoll(){
//Generate response
/*Polling to start
*/
return someValue;
}
}
what may be a good way to accomplish that? Would timer be of any use?
A: As of Jersey 2.3.1, a new feature has been added to support server-sent events. For your use-case, you might want to read more into the Jersey documentation
A: If you don't mind using an external library, I have been using atmosphere for a few years and it is a great server push / comet implementation. It has support for just about ever server and yes it will depend on the server. They support long poll and websockets natively. Almost the entire service can be configured with just a couple of annotations. Here is an example of how to use it on a jersey 2 service.
https://github.com/Atmosphere/atmosphere-samples/blob/master/samples/jersey2-chat/src/main/java/org/atmosphere/samples/chat/jersey/Jersey2Resource.java
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19152221",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Point out location in Google Map I am developing an application in PHP. I have latitude and longitute of few locations in Google Map. I want to point it those locations on google map.
How can i point it?
A: http://code.google.com/apis/maps/index.html take a look at the google api its very easy to work with
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4332142",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why solr RemoveDuplicatesTokenFilterFactory dont work? My schema.xml is splitting product name and then uses RemoveDuplicate to remove duplicated words after split.
<fieldType name="type_name" class="solr.TextField">
<analyzer type="index">
<tokenizer class="solr.PatternTokenizerFactory" pattern="\|| " />
<filter class="solr.LowerCaseFilterFactory"/>
<filter class="solr.RemoveDuplicatesTokenFilterFactory"/>
And in query analyzer I see that RemoveDuplicatesTokenFilterFactory did absolutely nothing to duplicated words. Why?
A: If you read Wiki you will see that it only removes duplicates at the same position, which is not the case here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10329470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Deploying angular build utilising the azure event hub js sdk fails to run If I run the project locally with
ng serve -o
everything works as expected
However, once I build it (either dev or prod build) and deploy it to either an Azure web app or a local web server on my machine I get the error of
connectionContext.js:20 Uncaught TypeError: os__WEBPACK_IMPORTED_MODULE_2__.type is not a function - within connectionContext.js (from the azure event hubs SDK)
I performed
npm install
and all modules install but I still get the same error each time.
I am assuming something is added when running locally via the ng server but is not included within a build.
Is there anything to check for that I may have missed?
UPDATE:
I have this running now by removing the functions that were causing the issue, not a fix more a hack to try and get progression. However, if I deploy to a local web server on my machine or to a raspberry pi it runs as expected. But when I deploy it to an azure web app it does not work as expected and states it cannot find 2 files (even though they can be seen via the FTP)
A: You need to create a web.config file in your wwwroot folder and add the MIME config like below to serve the JSON and WOFF files on Azure. You can check this similar thread.
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<system.webServer>
<staticContent>
<remove fileExtension=".json" />
<remove fileExtension=".woff" />
<remove fileExtension=".woff2" />
<mimeMap fileExtension=".json" mimeType="application/json" />
<mimeMap fileExtension=".woff" mimeType="application/font-woff" />
<mimeMap fileExtension=".woff2" mimeType="application/font-woff" />
</staticContent>
</system.webServer>
</configuration>
You can check angular deployment document fore more information,
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60055497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to load 1000+ items to a asp:GridView from SQL Server DB with high efficiency I have a function like below that I use to return a gridview (id: dgmenu) to the end users based on their role. Note that I am not allowed to apply pagination to the gridView, all items must be seen in one page.
protected DataTable MenuForUserRole(string userRole) {
DataTable dtMenus = new DataTable();
string connectionString = constr;
try {
using(SqlConnection cnn = new SqlConnection(connectionString)) {
cnn.Open();
string query = @"Select mycolumn1, mycolumn2, mycolumn3, mycolumn4m mycolumn5
From mytable
Where mykey = (select thekey from anothertable where role = @role)
order by myOrderColumn;
";
SqlCommand oCmd = new SqlCommand(query, cnn);
oCmd.Parameters.AddWithValue("@role", userRole);
using(SqlDataAdapter a = new SqlDataAdapter(oCmd)) {
a.Fill(dtMenus);
}
cnn.Close();
}
} catch (Exception ex) {
throw;
}
return dtMenus;
}
Usage:
dgMenu.DataSource = MenuForUserRole(ddlUserRoles.SelectedItem.Value.ToString());
dgMenu.DataBind();
My issue is performance-related: some of the GridViews returned has more than 1000 items, so it takes 5-6 seconds to load the complete gridView for those users, which is unacceptable. When I search online, I couldn't find more efficient code to load a gridView from SQL Server Database. Any help or advice that might increase the load speed when there is high amount of data to the gridview would be appreciated.
Used -> Visual Studio 2017 & SQL Server 2017
A: The most efficient way would be to realize that it is a bad idea.
1000 records is too much for any user to deal with. 1-2 Orders of Magnitude to much. There is no human on this planet, that could work with that much data at once. This data needs to be filtered, grouped or paginated way more before it comes in front of a user.
And those are all operations you should not be doing past the query. Those should be done in the query itself. Retrieving data you do not want to do filtering later just adds a tone of network load, adds race conditions, Database locks and is propably slower anyway (DBMS are really good at their job!). Worse, with ASP.Net and it's shared memory it can quickly lead to memory issues.
A: Profile your code. Understand where most of the time is spent. It could be SQL Server, it could be transmission over network, it could be binding the data to the control[s]. If it is SQL Server, we would need to see your schema to tell you how performance could be improved. Like, do you have an index on mykey? BTW, don't call it a key, key is something that uniquely identifies the record, which is obviously not the case here.
A: Use reporting (e.g. Reporting Services) and create a link to export the data into an excel spreadsheet.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58140308",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: mailmerge in word from c# opens multiple instances I'm trying to automate mailmerge using a .net program. There's a one page letter in word document addressed to a particular person with a mailmerge field by name 'Person'. Our database has got multiple persons and each person name has to go into a copy of the letter. We want the one-page letters to be concatenated one after the other. Currently this code tries to use two persons with - name1 & name2. The code below opens a separate instance of word for every person name.
object oMissing = System.Reflection.Missing.Value;
//CREATING OBJECTS OF WORD AND DOCUMENT
Word.Application oWord = new Word.Application();
Word.Document oWordDoc = new Word.Document("C:\\Test\\AddressTemplate.docx");
//SETTING THE VISIBILITY TO TRUE
oWord.Visible = true;
//THE LOCATION OF THE TEMPLATE FILE ON THE MACHINE
Object oTemplatePath = "C:\\Test\\AddressTemplate.docx";
oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
foreach (Microsoft.Office.Interop.Word.Field field in oWordDoc.Fields)
{
if (field.Code.Text.Contains("Person"))
{
field.Select();
oWord.Selection.TypeText(name1);
}
}
oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
foreach (Microsoft.Office.Interop.Word.Field field in oWordDoc.Fields)
{
if (field.Code.Text.Contains("Person"))
{
field.Select();
oWord.Selection.TypeText(name2);
}
}
Question: How can I change the code to open just one instance of word, fill in the mailmerge field and concatenate one letter at the end of the other?
A: If you call new Word.Application you're creating a new instance, if what you want is to create a new instance if there is none, but reuse one if there is already one open you can do the following:
Application app;
try
{
app = (Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
}
catch
{
app = new Application();
}
Based on your comment i think you actually only have 1 instance of word open, it just opens both documents in different Windows (but a single application). Windows aren't the same as applications.
If you want it all in a single window you could reuse the previous document or else close it before you open a new one
A: Ronan's code above did the trick for me. I was doing new Application() every time, adding WINWORD instances (I know, should've known better). I speak both C# and VB, but here's the VB version I used in this project:
' Use same winword instance if there; if not, create new one
Dim oApp As Application
Try
oApp = DirectCast(Runtime.InteropServices.Marshal.GetActiveObject("Word.Application"), Application)
Catch ex As Exception
' Word not yet open; open new instance
Try
' Ensure we have Word installed
oApp = New Application()
Catch eApp As Exception
Throw New ApplicationException(String.Format("You must have Microsoft Word installed to run the Top Line report"))
End Try
End Try
oApp.Visible = True
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19501285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to change html href attribute value with jQuery? I am trying to change html href attribute value ?post=55 to ?post=44 with button click using jQuery, but don't know how.
HTML
<button class="button">button</button>
<a href="posts.php?post=55" class="post-link">Post</a>
JAVASCRIPT
$('.button').on('click', function() {
});
This is what I have
<a href="posts.php?post=55" class="post-link">Post</a>
This is what I want when clicking button
<a href="posts.php?post=44" class="post-link">Post</a>
A: A Jquery function allows you to change an attribute of a tag. It is written as $("tag").attr('attr','newvalue').
In your case, you can do $("a").attr('href','posts.php?post=44') inside the click function (you should probably give the a tag an id too)
A: "on-click" handler has $(this) that you can use to navigate in the DOM tree if you know that the object you want to alter is relatively placed (from what I see you have <a/> following <button/>.
$('.button').on('click', function() {
$(this).parent().find('.post-link').attr('href', '#hello-world')
})
JSFiddle
If you want to change a link of the element that is somewhere on the page, I would suggest searching by id value (the id should be unique). Let's say you have <a id="my-id" href="...">...</a>, then:
$('.button').on('click', function() {
$('#my-id').attr('href', '#hello-world')
})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72930714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Trying to create a new page when horizontal pos. of i extends past right margin I am trying add a page when horizontal or the x position is greater than a counter in order to keep a right side margin. When I run the code I end up in an infinate loop of hundreds of pages all displaying the same first page graphics. Thinking it might have to do with my lack of understanding HasMorePages. I could use some help. Thanks.
public static class PrintWave
{
public static void PrintPreWave()
{
PrintDocument pd = new PrintDocument();
if (WaveTools.MySettings == null)
{
pd.DefaultPageSettings.Landscape = true;
}
else
{
pd.DefaultPageSettings = WaveTools.MySettings;
}
pd.OriginAtMargins = true;
pd.PrintPage += new PrintPageEventHandler(OnPrintPage);
PrintDialog dlg = new PrintDialog();
PrintPreviewDialog printPreviewDlg = new PrintPreviewDialog();
printPreviewDlg.Document = pd;
Form p = (Form)printPreviewDlg;
p.WindowState = FormWindowState.Maximized;
printPreviewDlg.ShowDialog();
}
private static void OnPrintPage(object sender, PrintPageEventArgs e)
{
string MyTag = string.Empty;
MyTag = WaveActions.ActiveId;
Wave MyWave = WaveHolder.FindWave(MyTag);
int MyCount = 0;
int xOffset = e.MarginBounds.Location.X;
int yOffset = e.MarginBounds.Location.Y;
if (MyWave != null)
{
Graphics g = e.Graphics;
g.SetClip(e.PageBounds);
Pen MyPen = new Pen(WaveTools.WaveColor, WaveTools.PenWidth);
float dx = (float)e.PageBounds.Width / MyWave.NumSamples;
float dy = (float)e.PageBounds.Height / 255;
if (MyWave.Normal == false)
{
g.ScaleTransform(dx, dy);
}
for (int i = 0; i < MyWave.NumSamples - 1; i++)
{
g.DrawLine(MyPen, i, MyWave.Data[i], i + 1, MyWave.Data[i + 1]);
MyCount = MyCount + 1;
if (MyCount > e.MarginBounds.Width)
{
e.HasMorePages = true;
MyCount = 0;
return;
}
else
{
e.HasMorePages = false;
return;
}
}
}
}
}
}
A: for (int i = 0; i < MyWave.NumSamples - 1; i++)
That's the core problem statement, you start at 0 every time PrintPage gets called. You need to resume where you left off on the previous page. Make the i variable a field of your class instead of a local variable. Implement the BeginPrint event to set it to zero.
The else clause inside the loop need to be deleted.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10263250",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Strange behaviour when calling VB6.0 COM-component in C# (in python all is ok) I have some problems when working with COM-component in C#.
I have old (~2001-2003year developed) VB6 COM component, and unfortunately there is no source code for it. The component interacting with a service program (no source too). The main Application is written in VB6, and now I'm rewriting it on .Net.
I have imported (with TblImp) component into C# and calling it:
using System;
using System.Threading;
using System.Collections.Generic;
using System.Text;
using System.Runtime.CompilerServices;
using SrvCommDCG;
class Program
{
[STAThread]
static void Main(string[] args)
{
if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA)
{
System.Console.WriteLine("calling com");
clsCommDCGService srv = new clsCommDCGService();
srv.Check();
System.Console.ReadKey();
}
}
}
When I'm running it on Windows 7, nothing happens (the component should show a messagebox when check is finished).
When I'm running it on Windows 8, program crashes without any exception.
I've tried different thread models: MTA, STA (using either [STAThread], or SetApartmentState()), calling DisableComObjectEagerCleanup() -- nothing helped.
After week of no result, I've tried to use my component in Python, and:
import win32com.client
tst = win32com.client.Dispatch("SrvCommDCG.clsCommDCGService")
tst.Check()
All is working, check is ok and MessageBox appeared.
Ofc, it works from VB 6.0 too.
I think, the problem is that python is single-threaded win32 app, and C# is multithreaded managed code. And I'm missing some point to understand what I should add to C# code, to make it work? Unfortunately I need to call it from .Net.
edit #1: I've tried on .Net 4.0 and 4.5, and also on .Net 2.0 frameworks
edit #2: when program crashing on Windows 8 there aren't any useful messages (even if i ran program from VS C# debugger), it's just write "Program occured a problem and will be closed" (have russian Win8, can't tell you the exact message in Windows). The Event log in Win8 says: Process was killed due to unhandled exception c0000005 at address 012E72CC. It's simple Access Violation.
edit#3: While C# program works bad on Win7/8, it works normal on Windows XP. Mysterios things.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16882579",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Get BoundingBox of ONLY visible area of map in osmdroid I am using osmdroid version 4 and I want to have BoundingBox of visible map. It seems that MapView.getBoundingBox method returns bounding box of all tiles that are visible or partially visible. Take a look at this picture:
Black rectangles are tiles, red rectangle with rounded corners is device display.
I want to have only diagonal area shown by green line. What should I do?
A: I believe you are mistaken. getBoundingBox() returns the lat/long boundaries of what is visible on the screen. The code will take the pixel x,y value of the two corners and covert that into lat/long and that is what is used. It is not "snapped" to actual map tiles. The result of getBoundingBox() should return the area of the red box.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20757480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Opens the map with a certain position of the camera I'm new to java, I installed Google maps in my application, but when you open the card, open a very large scale of the map, a function I need to use for that would map opened at a certain city? And just a second question - please tell me what the name of the function is responsible for determining the location the user
A: This question is rather vague but the API documentation should be able to help you here.
https://developers.google.com/maps/documentation/api-picker
Just pick out which API you need. It should be something like setLocation(Coordinates) in all of them.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26482006",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I eliminate duplicates using MAX function? I have these tables
recommendation_object_id, exhibitor_name, event_edition_id, timestamp
I want to hide/remove the duplicates in recommendation_object_id to make it a primary key.
I successfully removed most of the dups, but a few recommendation id's have a different event edition id so some id's are still duplicating as a result.
A colleague of mine said I could eliminate those further by using max(timestamp) but I could not pull it off :(
My current query is this:
SELECT DISTINCT r.recommended_object_id, ed.exhibitor_name, sd.event_edition_id, r.object_type, max(r.timestamp)
FROM recommendations r
left join show_details sd on r.event_edition_id = sd.event_edition_id
left join exhibitor_details ed on r.recommended_object_id = ed.exhibitor_id
group by r.recommended_object_id, ed.exhibitor_name, sd.event_edition_id, r.object_type
order by r.recommended_object_id
A: If you want one row per recommended_object_id, the one with the most recent timestamp, then use window functions:
select r.*
from (select r.recommended_object_id, ed.exhibitor_name, sd.event_edition_id, r.object_type,
row_number() over (partition by recommended_object_id order by r.timestamp desc) as seqnum
from recommendations r left join
show_details sd
on r.event_edition_id = sd.event_edition_id left join
exhibitor_details ed
on r.recommended_object_id = ed.exhibitor_id
) r
where seqnum = 1
order by r.recommended_object_id;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65629024",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to get img alt text and data-src using Beautifulsoup? HTML snippet :
<span class="photo_tooltip" id="__w2_YFXobXt_link">
<a href="/profile/Smit-Soni-2" id="__w2_GDetCwt_link">
<img class="profile_photo_img" src="https://assets.ec.quoracdn.net/-images.placeholder_img.png96cbdb37c749e493.png" height="50" width="50" data-src="https://assets.ec.quoracdn.net/main-thumb-18048885-50-ujrumofdevpkaarfisuvjdtbihztxnta.jpeg" alt="Smit Soni" />
</a></span>
I want to extract all the alt text and data-src from the img class="profile_photo_img. My code:
ele = soup.find_all('img', class_='profile_photo_img')
for i in ele:
print i["data-src"]
print i["alt"]
But it is printing nothing. How can I get the desired result?
A: Try the following code:
elements = soup.findAll('img', attrs={'class':'profile_photo_img'})
for element in elements:
print element['data-src']
print element['alt']
Also make sure that the soup is right parsed from the html by printing it before you are searching for elements
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40284002",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to get custom headers from axios post response? i'm using nuxt/axios with laravel as my backend. in my responses from laravel i send a custom header named _msg but i cant access it. in my console.log(response) i get only this:
but in my brower network i get the header:
how can i access it?
UPDATED
added this to my laravel middleware:
this is an example if request is from manager and admin
<?php
namespace App\Http\Middleware;
use Closure;
use App\Traits\UtilsTrait;
class ManagerPlus
{
use UtilsTrait;
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// return $next($request);
if($this->isMoreManager()){
$request->panelType = $this->addPanelType();
$response = $next($request);
$response->headers->set('Access-Control-Expose-Headers', 'Content-Disposition');
return $response;
}
return $this->permissionDenied();
}
}
UPDATE AFTER EXPOSE:
i did as told with my laravel/fruitcake setting and middleware and this is my new header that i get from axios. but still not getting my _msg
A: What I think you need to do is:
if you are using the package https://github.com/fruitcake/laravel-cors you will have config/cors.php and there is where you should add
'exposed_headers' => ['_msg'],
and you have to create the middleware as it's explained in the issue https://github.com/fruitcake/laravel-cors/issues/308#issuecomment-490969761
$response->headers->set('Access-Control-Expose-Headers', '_msg');
I hope it works
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63152522",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to accept an array parameter in a GET request in Flask using Connexion I am using connexion to create a REST API via Flask. At the moment I am passing a single identifier in.
/read/maa_valid_product_id/{drug_product_id}:
get:
operationId: registrations.read_maa_valid_product_id
tags:
- Marketing Applications
summary: Read the entire list of non-passive marketing application registrations for a specified drug_product_id, which have a valid authorisation status
description: Read the entire list of non-passive marketing application registrations for a specified drug_product_id, which have a valid authorisation status
parameters:
- in: path
name: drug_product_id
required: true
schema:
type: integer
description: Numeric ID of the user to get
- in: query
name: length
required: false
schema:
type: integer
description: Numeric ID of the user to get
- in: query
name: offset
required: false
schema:
type: integer
description: Numeric ID of the user to get
responses:
'200':
description: Successfully commpleted the list operation for non-passive valid MAAs, for the specified drug_product_id
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/marketing_application'
I need to pass an array of id values in, based on selections in a table. Is this possible?
If it is possible, how would I access the array, the existing method call is:
def read_maa_valid_product_id(drug_product_id, length=0, offset=0):
"""
This function responds to a request for /api/products
with the complete lists of people
:return: json string of list of people
"""
# conn_ariel = pool.acquire()
conn_ariel = get_connection()
cursor_ariel = conn_ariel.cursor()
# Create the list of products from our data
sql = """
SELECT A.DRUG_PRODUCT_ID,
B.PREFERRED_TRADE_NAME,
B.PRODUCT_LINE,
B.PRODUCT_TYPE,
B.FLAG_PASSIVE AS PRODUCT_FLAG_PASSIVE,
A.REGISTRATION_UID,
A.COUNTRY_DISPLAY_LABEL,
A.FLAG_PASSIVE,
A.AUTHORIZATION_STATUS,
A.DISTRIBUTION_TYPE AS PROCEDURE_TYPE,
A.MAH_COMPANY,
A.DOSSIER_REF_NUMBER AS REGISTRATION_NAME_DETAILS,
A.APPLICATION_STAGE,
A.APPLICATION_TYPE,
A.RENEWAL_NOT_REQUIRED,
TO_CHAR(A.NEXT_RENEWAL_DATE,'YYYY-MM-DD') AS NEXT_RENEWAL_DATE
FROM DIM_REGISTRATION_SET A, DIM_DRUG_PRODUCT B, v_rep_az_183_01_reg_includes C
WHERE A.DRUG_PRODUCT_ID = B.DRUG_PRODUCT_ID AND A.VERSION_SEQ = C.VERSION_SEQ
AND A.DATA_STATE = 'C'
AND A.FLAG_PASSIVE = '0'
AND A.APPLICATION_TYPE = 'Marketing Application'
AND A.AUTHORIZATION_STATUS LIKE 'Valid%'
AND A.DRUG_PRODUCT_ID = :id
ORDER BY B.PREFERRED_TRADE_NAME, A.COUNTRY_DISPLAY_LABEL ASC
"""
cursor_ariel.execute(sql,{"id":drug_product_id})
registrations = []
names = [c[0] for c in cursor_ariel.description]
cursor_ariel.rowfactory = collections.namedtuple("registrations", names)
i = 0
j = 0
start = None
if offset == 0:
start = True
else:
start = False
for row in cursor_ariel.fetchall():
if start == True:
registration = {
"drug_product_id": row.DRUG_PRODUCT_ID,
"preferred_trade_name": row.PREFERRED_TRADE_NAME,
"product_line": row.PRODUCT_LINE,
"product_type": row.PRODUCT_TYPE,
"product_flag_passive": row.PRODUCT_FLAG_PASSIVE,
"registration_uid": row.REGISTRATION_UID,
"country_display_label": row.COUNTRY_DISPLAY_LABEL,
"flag_passive": row.FLAG_PASSIVE,
"authorization_status": row.AUTHORIZATION_STATUS,
"procedure_type": row.PROCEDURE_TYPE,
"mah_company": row.MAH_COMPANY,
"registration_name_details": row.REGISTRATION_NAME_DETAILS,
"application_stage": row.APPLICATION_STAGE,
"application_type": row.APPLICATION_TYPE,
"renewal_not_required": row.RENEWAL_NOT_REQUIRED,
"next_renewal_date": row.NEXT_RENEWAL_DATE
}
# logging.info("Adding Registration: %r", registration)
registrations.append(registration)
if length > 0:
if i == length - 1:
break
i += 1
else:
if j == offset - 1:
start = True
j += 1
pool.release(conn_ariel)
return registrations
A: Got there in the end:
yaml config:
/read/products_many/{drug_product_ids}:
get:
operationId: products.read_products_many
tags:
- Product
summary: Read multiple drug products for the provided drug_product_ids
description: Read multiple drug products for the provided drug_product_ids
parameters:
- name: drug_product_ids
in: path
required: true
schema:
type: array
items:
type: integer
minItems: 1
style: simple
explode: false
description: drug_product_ids primary keys of the required products
responses:
'200':
description: Successfully retrieved product
content:
application/json:
schema:
$ref: '#/components/schemas/product'
Based on:https://swagger.io/docs/specification/serialization/#uri-templates
Then in my method, I see a list coming in as a parameter, so I am converting to string and then creating the SQL using string formatting.
def read_products_many(drug_product_ids):
conn_ariel = get_connection()
cursor_ariel = conn_ariel.cursor()
print(drug_product_ids) # --> [4670, 4671]
print(type(drug_product_ids)) # --> List
# convert to string for use in IN clause in SQL
drug_product_ids = [str(x) for x in drug_product_ids]
print("read_many product, id", drug_product_ids)
# Create the list of products from our data
sql = """
SELECT DRUG_PRODUCT_ID, PREFERRED_TRADE_NAME, PRODUCT_LINE, PRODUCT_TYPE, FLAG_PASSIVE , PRODUCT_NUMBER
FROM DIM_DRUG_PRODUCT
WHERE DRUG_PRODUCT_ID in ({0})
AND PREFERRED_TRADE_NAME NOT LIKE '%DO NOT USE%'
AND UPPER(PREFERRED_TRADE_NAME) NOT LIKE '%DELETE%'
AND UPPER(PREFERRED_TRADE_NAME) NOT LIKE '%TEST%'
""".format(",".join(drug_product_ids))
print("SQL")
print(sql)
cursor_ariel.execute(sql)
product = None
products = []
for row in cursor_ariel.fetchall():
r = reg(cursor_ariel, row, False)
product = {
"drug_product_id" : r.DRUG_PRODUCT_ID,
"preferred_trade_name" : r.PREFERRED_TRADE_NAME,
"product_line" : r.PRODUCT_LINE,
"product_type" : r.PRODUCT_TYPE,
"flag_passive" : r.FLAG_PASSIVE,
"product_number" : r.PRODUCT_NUMBER
}
products.append(product)
pool.release(conn_ariel)
return products
SQL being returned when I enter this URL:
localhost:5000/api/read/products_many/4671,4670
is correct as:
SELECT DRUG_PRODUCT_ID, PREFERRED_TRADE_NAME, PRODUCT_LINE, PRODUCT_TYPE, FLAG_PASSIVE , PRODUCT_NUMBER
FROM DIM_DRUG_PRODUCT
WHERE DRUG_PRODUCT_ID in (4671,4670)
AND PREFERRED_TRADE_NAME NOT LIKE '%DO NOT USE%'
AND UPPER(PREFERRED_TRADE_NAME) NOT LIKE '%DELETE%'
AND UPPER(PREFERRED_TRADE_NAME) NOT LIKE '%TEST%'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64472274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Mounted Volumes for IBM Bluemix CF Apps IBM Containers on Bluemix has the support for mounting volumes and use across containers. Is there any way we can have a similar shared volumes kind w.r.t Bluemix CF Apps?
A: Cloud Foundry applications on IBM Bluemix can use Bluemix's Object Storage service for shared storage between applications.
Cloud Foundry does not support sharing volumes across instances and discourages users from writing the the filesystem as storage.
Using Object Storage, you have an API to access and share files between applications.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40173476",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I disable rails form_with update functionality I have the following form to add somebody to a waiting list.
<%= form_with(model: waitinglist, url: '/join', local: true) do |form| %>
<div class="field">
<%= form.text_field :email %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
This works fine and it will post and add somebody to the waiting list. However when the page reloads the form goes into some sort of automatic resource mode that where the submit button magically changes to update and then the form submit magically changes to the HTTP Patch method.
I'm trying to understand what is doing this and I can't find anything in the docs.
How do I create a regular form that just posts to an end point but still validates the model? (and removes this update functionality).
edit added controller
class WaitinglistsController < ApplicationController
before_action :set_waitinglist, only: [:show, :edit, :update, :destroy]
# GET /waitinglists/new
def new
@waitinglist = Waitinglist.new
end
# POST /waitinglists
# POST /waitinglists.json
def create
@waitinglist = Waitinglist.new(waitinglist_params)
if @waitinglist.save
flash[:notice] = "You have been added to the waiting list"
render :new
else
render :new
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_waitinglist
@waitinglist = Waitinglist.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def waitinglist_params
params.require(:waitinglist).permit(:email)
end
end
A: You are keeping a copy of your persisted waitinglist variable around between page loads. When your new page is rendered for the second time, since the waiting list has already been persisted, it is doing all the magical default Rails behaviours, which include updating labels for the submit button (create vs update), and the form's method (post vs patch).
You will want to create a new waitinglist if you are going to re-render the new page:
def create
@waitinglist = Waitinglist.new(waitinglist_params)
if @waitinglist.save
@waitinglist = Waitinglist.new #
flash[:notice] = "You have been added to the waiting list"
render :new
else
render :new
end
end
A: I think what u should do is if the waiting list is saved, redirect to new instead of render new. When u redirect to action it will call the action so a new object will be created. When u do render it render the view and I will have your persisted object, that’s why it is trying to update.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57815789",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cretate multiple shared secrets in a (selfmade) public/privavte key infrastructure I just try to understand cryptography, please be concern. Its not meant to be secure or professional. I create 3 numbers for each party. a public key, a secret key and a modulus. The first party (A) creates his keys
let pri = 133
let mod = 256
let pub = mod - pri
and shares "mod" and "pub" to other partys (B, C). When B want to encrypt a string he takes A's public key and modulus and do
// B encrypts
let enc = ( input + pubA ) % modA
A on his side is doing
// B decrypts
let dec = ( enc + priA) % modA
to decrypt it. My problem is, i can create multiple keypairs but only 1 associated public key to each secret key because i have to share the modulus of each pair for en/decryption.
Is it possible (in this situation) to create multiple publics numbers for a single private number? And if so, how can i do it?
Thank you (and sorry if this is a poor question)
EDIT Even if its not "good" to create your own cipher i want to do so..
I recognized that i missed the secret exponent d so that phi divides (e * expo)-1.
/* Pseude code */
p = q = primes()
n = p * q
phi = (p-1) * (q-1)
e = 3
d = ? // <-- have to find my own secret exponent!
if( gcd(e, p-1) != gcd(e, q-1) ) exit(0)
expo = 0
for(expo < 100000)
if( (e * expo)-1 == phi ) ) d = expo
And therefore i could have
public(n,e)
private(n,d)
so i can share (n,e). Is that correct?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53947979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: WebDeploy with MSdeploy.exe fails to sync GAC Assembly because dll(s) locked by another process I'm having this problem using msdeploy to sync GAC assembly to many Application Servers.
When I run this command
msdeploy -verb:sync -source:gacAssembly="'MyAssembly'" -dest:gacAssembly,computername=DESTINATIONSERVER
I obtain this error:
*Microsoft.Web.Deployment.DeploymentException:
(28/09/2010 16.46.37) An error occurred when the request was processed on the remote computer.
---> Microsoft.Web.Deployment.DeploymentClientServerException: An error was encountered when processing 'INPS.DNA.dll'.
---> Microsoft.Web.Deployment.DeploymentException: The error code was 0x80070020.
---> System.IO.IOException: The process cannot access 'C:\Windows\assembly\GAC_MSIL\MYASSEMBLY\1.0.0.0__a31fe99d2f98435c\MYASSEMBLY.dll' because it is being used by another process.
at Microsoft.Web.Deployment.Win32Native.RaiseIOExceptionFromErrorCode(Win32ErrorCode errorCode, String maybeFullPath)
at Microsoft.Web.Deployment.FileStreamEx.CreateInstance(String path, FileMode fileMode, FileAccess fileAccess)
at Microsoft.Web.Deployment.FilePathProvider.Add(DeploymentObject source, Boolean whatIf)
--- End of inner exception stack trace ---
--- End of inner exception stack trace ---
at Microsoft.Web.Deployment.DeploymentObject.Update(DeploymentObject source,DeploymentSyncContext syncContext)
at Microsoft.Web.Deployment.DeploymentSyncContext.HandleUpdate(DeploymentObject destObject, DeploymentObject sourceObject)
at Microsoft.Web.Deployment.DeploymentSyncContext.SyncDirPathChildren(DeploymentObject destRoot, DeploymentObject sourceRoot)
at Microsoft.Web.Deployment.DeploymentSyncContext.SyncChildrenNoOrder(DeploymentObject dest, DeploymentObject source)
at Microsoft.Web.Deployment.DeploymentSyncContext.SyncChildrenOrder(DeploymentObject dest, DeploymentObject source)
at Microsoft.Web.Deployment.DeploymentSyncContext.ProcessSync(DeploymentObject destinationObject, DeploymentObject sourceObject)
at Microsoft.Web.Deployment.DeploymentObject.SyncToInternal(DeploymentObject
destObject, DeploymentSyncOptions syncOptions, PayloadTable payloadTable, Conten
tRootTable contentRootTable)
at Microsoft.Web.Deployment.DeploymentAgent.HandleSync(DeploymentAgentWorkerR
equest workerRequest)
--- End of inner exception stack trace ---
at Microsoft.Web.Deployment.StatusThreadHandler.CheckForException()
at Microsoft.Web.Deployment.AgentClientProvider.RemoteDestSync(DeploymentObje
ct sourceObject, DeploymentSyncContext syncContext)
at Microsoft.Web.Deployment.DeploymentObject.SyncToInternal(DeploymentObject
destObject, DeploymentSyncOptions syncOptions, PayloadTable payloadTable, Conten
tRootTable contentRootTable)
at Microsoft.Web.Deployment.DeploymentObject.SyncTo(DeploymentProviderOptions
providerOptions, DeploymentBaseOptions baseOptions, DeploymentSyncOptions syncO
ptions)
at MSDeploy.MSDeploy.ExecuteWorker()
Error count: 1.*
If I execute IISRESET on DESTINATIONSERVER the error doesn't occur!
My question is:
It's possible to unlock DLL without perform an IISRESET command?
I think I can avoid to restart entire Web Server.
Can you help me'
Thanks a lot!
Best regards.
A: What about using the recyleApp provider to stop and start the app pool?
msdeploy.exe -verb:sync -source:recycleApp -dest:recycleApp="Default Web Site",recycleMode="StopAppPool",computerName=remote-computer
... do your real deployment ...
msdeploy.exe -verb:sync -source:recycleApp -dest:recycleApp="Default Web Site",recycleMode="StartAppPool",computerName=remote-computer
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3785385",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to reduce the time of curl call? For some reason my curl call is very slow. Here is the code I used.
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER,array('Expect:','Accept: application/xml'));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//curl_setopt(curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HEADER, 1);
//curl_setopt($ch, CURLOPT_NOBODY, !($options['return_body']));
curl_setopt($ch, CURLOPT_SSLVERSION, 3);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)');
curl_setopt($ch,CURLOPT_TIMEOUT_MS,0);
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0);
$result = curl_exec($ch);
$curl_errno = curl_errno($ch);
$curl_error = curl_error($ch);
curl_close($ch);
we have 9000 records to fetch
its taking 56 mins
To check execution time for each record I use curl_getinfo() function;
and each record take ~0.46 seconds!!
I want to reduce this seconds.
any luck it can reduce to 15 mins?
A: Try to set one more cURL option.
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
Also try to use curl_multi_exec.
A: Use file_get_contents($url)
example with User Agent
<?php
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.example.com/', false, $context);
?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24119521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Realm from JSON in async in background I'd like to work to write Realm from JSON in async in background, but I can't understand why my code isn't work as must.
override func viewDidLoad() {
super.viewDidLoad()
myFunc()
}
and myFunc():
func myFunc() {
let realm = try! Realm()
// get file JSON from local device and write data from it to RealmDB
if realm.isEmpty {
//local file JSON
let file = Bundle.main.path(forResource: "file", ofType: "json")!
let url = URL(fileURLWithPath: file)
let jsonData = NSData(contentsOf: url)!
//Serialization JSON
let json = try! JSONSerialization.jsonObject(with: jsonData as Data, options: [])
DispatchQueue.main.async {
realm.beginWrite()
//Create data from JSON to our objects
realm.create(DataRoot.self, value: json, update: true)
try! realm.commitWrite()
}
}
}
DB is creating, but next step (as I see) is in error:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (transport.filter("id == 1").first?.routes.count)!
}
So, I'd like to wait full writing DB in background (show progress view, for example) and go next step.
A: You have to check for optional in numberOfRows Method and do it like this
func myFunc() {
let queue1 = DispatchQueue(label: "com.appname.queue")
queue1.async {
let realm = try! Realm()
// get file JSON from local device and write data from it to RealmDB
if realm.isEmpty {
//local file JSON
let file = Bundle.main.path(forResource: "file", ofType: "json")!
let url = URL(fileURLWithPath: file)
let jsonData = NSData(contentsOf: url)!
//Serialization JSON
let json = try! JSONSerialization.jsonObject(with: jsonData as Data, options: [])
realm.beginWrite()
//Create data from JSON to our objects
realm.create(DataRoot.self, value: json, update: true)
try! realm.commitWrite()
DispatchQueue.main.async {
self.tableview.reloadData()
}
}
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let routes = transport.filter("id == 1").first?.routes {
return routes.count
}
return 0
}
A: To generally answer your question: the high level Realm feature you want to be using here is notifications.
You should be architecting your app in such a way that the data you want to use to back a view controller can be represented in a Realm query or notification, so that when the underlying data for a view or controller changes, you can perform the relevant view update actions.
There are some other problems with your code, such as potentially accessing a Realm instance from a different thread than the one on which it was created. I suggest you read more about this in Realm's Threading documentation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40977288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I change the Created By for my crossrider plugin? When users install my browser it shows the plugin created by the name listed under my crossrider dev account. I'd like to change that to my company name but the site won't let me change the name. How can I change it to show my company name vs my first and last name? Thanks
A: Email [email protected] from the email address currently associated with the account. In the email, provide:
*
*Current Account Name: the name currently associated with the account
*Extension ID(s): One or more IDs of extensions in the account
*New Account Name: the desired name for the account
[Disclosure: I am a Crossrider employee]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29777217",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get device ID in angular js? I need to find the device ID on which my app is running. I am using angular js and ionic. Is there any way to obtain the device ID?
A: Option 1: Use AngularJS run
// Calling the rootScope to handle the ondevice ready
angular.module('myApp').run(['$rootScope', function($rootScope) {
document.addEventListener('deviceready', function() {
$rootScope.$apply(function() {
$rootScope.myVariable = "variable value";
try {
$rootScope.uuid = device.uuid; //always use device object after deviceready.**
alert($rootScope.uuid);
//onapploginx(uuid);
} catch (e) {
alert(e);
}
// Register the event listener
document.addEventListener("backbutton", onBackKeyDown, false);
});
});
}]);
Option 2: Use JS only
define the onLoad in the body
<body id="main_body" ng-app='myApp' ng-controller='DemoController' onload="onLoad()">
call addEventListener for device ready and then call the function of onDeviceReady
function onLoad() {
console.log("i am onload");
document.addEventListener("deviceready", onDeviceReady, false);
}
// device APIs are available
//
function onDeviceReady() {
try {
var uuid = device.uuid; //always use device object after deviceready.**
alert("uuidx:",uuid);
} catch (e) {
alert(e);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37427907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: HttpWebResponses: How efficient is MemoryStream.CopyTo vs chunking? I'm running into a problem with downloading large JSON objects from an API. Usually, this documents are small in size, but occasionally they are quite large (100k+). This puts the large object heap into play and there are some performance concerns.
Here is the guts of the downloader method that returns the response bytes.
using (var httpWebResponse = (HttpWebResponse)request.GetResponse())
{
byte[] responseBytes;
using (var responseStream = httpWebResponse.GetResponseStream())
{
using (var memoryStream = new MemoryStream())
{
if (responseStream != null)
{
responseStream.CopyTo(memoryStream);
}
responseBytes = memoryStream.ToArray();
}
}
return responseBytes;
}
If the end goal is to get the contents of the webresponse into a byte array, is this the most efficient way to do this? In the past I would just read the stream in chunks. I've been told that this is less efficient than CopyTo for the 90% of the time (when the JSON response is sub-85k), but better for the other 10%.
I cannot seem to find a general consensus on this. Any input would be appreciated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33926576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: python-shell problem with sync inside javascript I'm using python-shell to run a Python code that return some messages inside a JavaScript environment, but the messages come out of sync. The first message returns at the right moment, but then all other messages comes out together at the end, not one by one.
When I run the test.py alone the messages come in the right way, which possibly means that is not a problem with my python code. Despite all other messages is logged together, the time when they are executed inside the python code is right, what can be seeing by the time: inside each message.
But what happens in my browser environment is the message <2>FIRST TEST logged first, and then <3>TEST and <4>MORE TEST are logged together after 10 seconds.
This is my python code test.py:
import sys
import time
import threading
def test():
start = time.time()
end1 = time.time()
print("<2>FIRST TEST time: {}".format(end1 - start))
time.sleep(5)
end2 = time.time()
print("<3>TEST time: {}".format(end2 - start))
time.sleep(5)
end3 = time.time()
print("<4>MORE TEST time: {}".format(end3 - start))
x = threading.Thread(target=test)
x.start()
sys.stdout.flush()
This is my JavaScript code execPyShell.ts:
const exec: () => void = () => {
console.log('Start')
let pyshell = new PythonShell('./engine/test.py');
let newLogs: string[] = [];
pyshell.on('message', function(message: string) {
console.log(message);
})
pyshell.end(function (err: any) {
if (err){
throw err;
};
console.log('Finished');
});
}
A: Solved! I forgot that I had to add
sys.stdout.flush()
After every print() called to force it to flush the buffer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73838952",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to create google play menu in xamarin I'm new to Xamarin. How can i design a pop up menu that looks like google play menu in Xamarin ? I.e see the image below :
A: There are several ways to go about making a fly-out menu, which is what I believe you are after. The very basic approach, is to add something similar to the following to your AXML:
<?xml version="1.0" encoding="utf-8"?>
<flyoutmenu.FlyOutContainer xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<include
layout="@layout/MenuLayout" />
<include
layout="@layout/ContentLayout" />
</flyoutmenu.FlyOutContainer>
Source: http://blog.neteril.org/blog/2013/04/19/fly-out-menu-xamarin-android/
Another Source: http://www.appliedcodelog.com/2016/01/navigation-drawer-using-material-design.html
I hope this helps!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37659722",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: AWS Elastic BeanStalk Security Group I am trying to create Worker Environmenton EBS with Sample Application of Node js which should use existing Security group on VPC.
I create this environment inside VPC (Virtual Private Cloud).
When I create this environment, I keep following configuration for VPC.
Security Group which is selected here is already exist.
In the next screen, I also select instance profile and service role which also exist.
While I create Environment with this setting, It does create Environment fine but it always create new Security group instead of using existing security group.
Why it always create new Security group and not use existing one ?
I want to reuse Security group and not create separate for each worker environment.
Appreciate if someone can guide me in right direction.
Thanks in advance.
A: Beanstalk uses the security group you asked for, but on creation it also creates a unique one for that configuration. If you launch your instance it will be in the security group as expected.
A: Instead of stopping it from being created, was able to modify its rules such that I changed to just allow port 22 access only from my private security group.
Namespace: aws:autoscaling:launchconfiguration
OptionName: SSHSourceRestriction
Value: tcp, 22, 22, my-private-security-group
Visit : https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/command-options-general.html#SSHSourceRestriction
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33680906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I get an entity from Doctrine Fixture reference? I have added data fixtures in my project that relies on referencing entity objects from each other.
In data fixture one, I have added entity references such as:
// GroupEntity_Fixtures.php file
$this->addReference('GROUP_USER', $groupUser);
$this->addReference('GROUP_ADMIN', $groupAdmin);
Where $groupAdmin and $groupUser are both Group() entities. In my second fixtures file I want to add those entities to my User entity via:
//UserEntity_Fixtures.php file
$userActive->addGroup($this->getReference('GROUP_USER'));
$userActive is a User entity with a Many to Many relationship to Group Entity. Unfortunately it seems that I am only passing in a proxy of the entity and not the entity itself which renders the following error:
[Symfony\Component\Debug\Exception\ContextErrorException]
Catchable Fatal Error: Argument 1 passed to Blogger\BlogBundle\Entity\User:
:addGroup() must be an instance of Blogger\BlogBundle\Entity\groups, instan
ce of Proxies\__CG__\Blogger\BlogBundle\Entity\Group given, called in /home
/na/Practice/src/Blogger/BlogBundle/DataFixtures/ORM/CreateUserController_S
ignUpForm_UserEntity_Fixtures.php on line 27 and defined in /home/na/Practi
ce/src/Blogger/BlogBundle/Entity/User.php line 305
How do I convert the reference from a proxy to the entity it expects?
Code for Group Fixture:
<?php
// DataFixtures/ORM/GroupEntity_Fixtrues.php
namespace Blogger\BlogBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;
use Blogger\BlogBundle\Entity\User;
use Blogger\BlogBundle\Entity\Group;
class GroupEntity_Fixtures extends AbstractFixture implements OrderedFixtureInterface
{
/**
* {@inheritDoc}
*/
public function load(ObjectManager $manager)
{
$groupUser = new Group();
$groupUser->setName('GROUP_USER');
$groupUser->setRole('ROLE_USER');
$manager->persist($groupUser);
$groupAdmin = new Group();
$groupAdmin->setName('GROUP_ADMIN');
$groupAdmin->setRole('ROLE_USER,ROLE_ADMIN');
$manager->persist($groupAdmin);
$manager->flush();
$this->addReference('GROUP_USER', $groupUser);
$this->addReference('GROUP_ADMIN', $groupAdmin);
}
public function getOrder()
{
return 1;
}
}
Code for User Fixture
<?php
// DataFixtures/ORM/CreateUserController_SignUpForm_UserEntity_Fixtrues.php
namespace Blogger\BlogBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;
use Blogger\BlogBundle\Entity\User;
use Blogger\BlogBundle\Entity\Group;
class CreateUserController_SignUpForm_UserEntity_Fixtures extends AbstractFixture implements OrderedFixtureInterface
{
/**
* {@inheritDoc}
*/
public function load(ObjectManager $manager)
{
$groupUser2 = new Group();
$groupUser2->setName('GROUP_USER');
$groupUser2->setRole('ROLE_USER');
$manager->persist($groupUser2);
// This person represents an active (email verified) user.
$userActive = new User();
$userActive->setPassword("passwordActive");
$userActive->setEmail("[email protected]");
$userActive->setUserName("testActive");
$userActive->setPassword(crypt($userActive->getPassword(),$userActive->getSalt()));
$userActive->setEmailToken(md5(uniqid(rand(), true)));
$userActive->addGroup($groupUser2);
//$userActive->getGroups()->add($groupRepository->getGroupByName("BASIC_USER"));
// This person represents an unactive (email not verified) user.
$userUnactive = new User();
$userUnactive->setPassword("passwordUnactive");
$userUnactive->setEmail("[email protected]");
$userUnactive->setUserName("testUnactive");
$userUnactive->setPassword(crypt($userUnactive->getPassword(),$userUnactive->getSalt()));
$userUnactive->setEmailToken(md5(uniqid(rand(), true)));
// Persist objects into the database
$manager->persist($userActive);
$manager->persist($userUnactive);
$manager->flush();
}
public function getOrder()
{
return 2;
}
}
Code for Group Entity:
/**
* @ORM\ManyToMany(targetEntity="User", inversedBy="groups")
*/
private $users;
Code for User Entity:
/**
* @ORM\ManyToMany(targetEntity="Group", mappedBy="users")
*/
protected $groups;
Added Group Methos:
/**
* Add groups
*
* @param \Blogger\BlogBundle\Entity\groups $groups
* @return User
*/
public function addGroup(\Blogger\BlogBundle\Entity\groups $groups)
{
$this->groups[] = $groups;
return $this;
}
A: The addGroup method has the wrong type hint:
It should be:
/**
* Add groups
*
* @param \Blogger\BlogBundle\Entity\Group $groups
* @return User
*/
public function addGroup(\Blogger\BlogBundle\Entity\Group $groups)
{
$this->groups[] = $groups;
return $this;
}
Notice \Blogger\BlogBundle\Entity\Group instead of \Blogger\BlogBundle\Entity\groups.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17264758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: how to print more than one rows through PL/SQL procedure? How to write a procedure where user will give department number, and the procedure will show the list of those employees who are working in that department.
My procedure:
create or replace procedure p1(
dno in number,
name out varchar2 )
is
begin
select ename
into name
from emp
where deptno=dno;
end;
PLSQL:
declare
dno emp.deptno%type:=:dept;
name emp.ename%type;
begin
p1(dno,name );
dbms_output.put_line(name);
end;
But this is showing an error:
ORA-01422: exact fetch returns more than requested number of rows
How can I print multiple values through procedure?
A: I haven't tried your code, but you seen to call the procedure p1(dno,name ); and insert name in it.
But name can only be output becuase of the OUT, you need to use IN OUT in your procedure at least.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31372377",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I secure a SQL Server 2005 database? I have a database for a web application that is home to some personal information about my users.
What should I do to make sure the data is secure?
Encrypting the data makes sense, of course... but what about stopping somebody from getting on the machine to begin with?
What do I do about the developers that need access to the data, to make fixes, etc...?
Is there a document or best practice site that I can use as a guide?
A: Depending on the type of data I'm not sure that encryption is necessary providing you secure access to the system and the database itself. All of our production database servers are behind a firewall. Only systems that are on the administrative network are allowed access through the firewall and then only on specific, required ports. Database servers don't host web servers.
Access to the database servers themselves is strictly limited to DBAs and platform support personnel. They use administrative logins, not their personal login ids. That way if their personal account is compromised the database servers aren't.
For web servers only web admins and platform support have access (I happen to wear two hats, web developer and web admin, although that is rare in our organization).
Developers have access to shares where they can publish their application, usually coordinated with the web admin for any setup/configuration. Some senior developers are given administrator access to databases in order to create/modify schemas.
Usually, what happens is you develop using a locally installed database server, upload code to QA servers that have a little looser access policy, but are only accessible from company networks, then have the DBAs copy the database schema and roles to production and publish your app to the production web server.
Web apps are often configured to run under limited credential service accounts which have read/write, but not admin, access to the database. I typically encrypt any part of my web.config that contains connection information as well.
The general idea is to give enough access to get your job done without too much bother, but limit access to the minimum required.
Oh. And no "real" data on development or QA servers.
[EDIT] We don't keep SSNs or credit card numbers. If you do, you'll need to be even more careful. Most of my apps do access logging, some are required to due to HIPPA, but I find that it is a good practice for just about anything meaningful
A: Well the developers should probably do all their work on a development database that doesn't contain sensitive information to start with.
A: Here in the UK we have legislation known as the Data Protection Act. If you worked for a UK company I would advise you to speak to your company's 'data controller' (being the individual whom the Information Commissioner's Office can pursue legally in instances of non-compliance) and they will be able to furnish you with a definitive answer about what 'secure' means as regards the data in question, probably enshrined in a written company policy.
If you are in the US I'd guess your corporation might have a bunch of highly paid lawyers who will be able to similarly give a definitive answer :)
I'm no legal expert but would suggest that obfuscating data does not make it fit for any purposes other than that for which it was obtained e.g. integration testing by developers using obfuscated 'real life' data is probably a no-no.
A: You need to pratice standard security for a windows server. A good place to start is to use integrated logins rather that SQL logins.
You will need to study the books on-line. You can give some users read-only access. Others can be denied access to sensitive tables.
A: I would use Active Directory to control access to SQL Server or any network resource. By grouping the users and applying security to the group, it will make it so much easier to make changes in the future.
Here is a guide from Microsoft on SQL Server 2005 Security Best Practices:
http://download.microsoft.com/download/8/5/e/85eea4fa-b3bb-4426-97d0-7f7151b2011c/SQL2005SecBestPract.doc
*Note: it downloads a Word document, so you will need MS Word or the MS Word viewer
This document has a lot of detail so you may want to grab some coffee first :).
However, I agree with the others, active development shouldn't happen against production data. We currently use a process of cleaning production data before it gets to the QA or Dev environments.
Another option we explored is developing a solution to generate data for Dev and QA.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/210832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can;t install lxml package on windwos 11 "PS D:\Complete-Python-3-Bootcamp-master\12-Advanced Python Modules\puzzle_unzip> pip install lxml
Collecting lxml
Using cached lxml-4.9.1.tar.gz (3.4 MB)
Preparing metadata (setup.py) ... done
Installing collected packages: lxml
DEPRECATION: lxml is being installed using the legacy 'setup.py install' method, because it does not have a 'pyproject.toml' and the 'wheel' package is not installed. pip 23.1 will enforce this behaviour change. A possible replacement is to enable the '--use-pep517' option. Discussion can be found at https://github.com/pypa/pip/issues/8559
Running setup.py install for lxml ... error
error: subprocess-exited-with-error
× Running setup.py install for lxml did not run successfully.
│ exit code: 1
╰─> [96 lines of output]
Building lxml version 4.9.1.
Building without Cython.
Building against pre-built libxml2 andl libxslt libraries
running install
C:\Users\lohar\AppData\Local\Programs\Python\Python311\Lib\site-packages\setuptools\command\install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
warnings.warn(
running build
running build_py
creating build
creating build\lib.win-amd64-cpython-311
creating build\lib.win-amd64-cpython-311\lxml
copying src\lxml\builder.py -> build\lib.win-amd64-cpython-311\lxml
copying src\lxml\cssselect.py -> build\lib.win-amd64-cpython-311\lxml
copying src\lxml\doctestcompare.py -> build\lib.win-amd64-cpython-311\lxml
copying src\lxml\ElementInclude.py -> build\lib.win-amd64-cpython-311\lxml
copying src\lxml\pyclasslookup.py -> build\lib.win-amd64-cpython-311\lxml
copying src\lxml\sax.py -> build\lib.win-amd64-cpython-311\lxml
copying src\lxml\usedoctest.py -> build\lib.win-amd64-cpython-311\lxml
copying src\lxml\_elementpath.py -> build\lib.win-amd64-cpython-311\lxml
copying src\lxml\__init__.py -> build\lib.win-amd64-cpython-311\lxml
creating build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\__init__.py -> build\lib.win-amd64-cpython-311\lxml\includes
creating build\lib.win-amd64-cpython-311\lxml\html
copying src\lxml\html\builder.py -> build\lib.win-amd64-cpython-311\lxml\html
copying src\lxml\html\clean.py -> build\lib.win-amd64-cpython-311\lxml\html
copying src\lxml\html\defs.py -> build\lib.win-amd64-cpython-311\lxml\html
copying src\lxml\html\diff.py -> build\lib.win-amd64-cpython-311\lxml\html
copying src\lxml\html\ElementSoup.py -> build\lib.win-amd64-cpython-311\lxml\html
copying src\lxml\html\formfill.py -> build\lib.win-amd64-cpython-311\lxml\html
copying src\lxml\html\html5parser.py -> build\lib.win-amd64-cpython-311\lxml\html
copying src\lxml\html\soupparser.py -> build\lib.win-amd64-cpython-311\lxml\html
copying src\lxml\html\usedoctest.py -> build\lib.win-amd64-cpython-311\lxml\html
copying src\lxml\html\_diffcommand.py -> build\lib.win-amd64-cpython-311\lxml\html
copying src\lxml\html\_html5builder.py -> build\lib.win-amd64-cpython-311\lxml\html
copying src\lxml\html\_setmixin.py -> build\lib.win-amd64-cpython-311\lxml\html
copying src\lxml\html\__init__.py -> build\lib.win-amd64-cpython-311\lxml\html
creating build\lib.win-amd64-cpython-311\lxml\isoschematron
copying src\lxml\isoschematron\__init__.py -> build\lib.win-amd64-cpython-311\lxml\isoschematron
copying src\lxml\etree.h -> build\lib.win-amd64-cpython-311\lxml
copying src\lxml\etree_api.h -> build\lib.win-amd64-cpython-311\lxml
copying src\lxml\lxml.etree.h -> build\lib.win-amd64-cpython-311\lxml
copying src\lxml\lxml.etree_api.h -> build\lib.win-amd64-cpython-311\lxml
copying src\lxml\includes\c14n.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\config.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\dtdvalid.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\etreepublic.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\htmlparser.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\relaxng.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\schematron.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\tree.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\uri.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\xinclude.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\xmlerror.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\xmlparser.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\xmlschema.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\xpath.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\xslt.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\__init__.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\etree_defs.h -> build\lib.win-amd64-cpython-311\lxml\includes
copying src\lxml\includes\lxml-version.h -> build\lib.win-amd64-cpython-311\lxml\includes
creating build\lib.win-amd64-cpython-311\lxml\isoschematron\resources
creating build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\rng
copying src\lxml\isoschematron\resources\rng\iso-schematron.rng -> build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\rng
creating build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\xsl
copying src\lxml\isoschematron\resources\xsl\RNG2Schtrn.xsl -> build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\xsl
copying src\lxml\isoschematron\resources\xsl\XSD2Schtrn.xsl -> build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\xsl
creating build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\xsl\iso-schematron-xslt1
copying src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\iso_abstract_expand.xsl -> build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\xsl\iso-schematron-xslt1
copying src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\iso_dsdl_include.xsl -> build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\xsl\iso-schematron-xslt1
copying src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\iso_schematron_message.xsl -> build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\xsl\iso-schematron-xslt1
copying src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\iso_schematron_skeleton_for_xslt1.xsl -> build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\xsl\iso-schematron-xslt1
copying src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\iso_svrl_for_xslt1.xsl -> build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\xsl\iso-schematron-xslt1
copying src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\readme.txt -> build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\xsl\iso-schematron-xslt1
running build_ext
building 'lxml.etree' extension
creating build\temp.win-amd64-cpython-311
creating build\temp.win-amd64-cpython-311\Release
creating build\temp.win-amd64-cpython-311\Release\src
creating build\temp.win-amd64-cpython-311\Release\src\lxml
"C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.34.31933\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -DCYTHON_CLINE_IN_TRACEBACK=0 -Isrc -Isrc\lxml\includes -IC:\Users\lohar\AppData\Local\Programs\Python\Python311\include -IC:\Users\lohar\AppData\Local\Programs\Python\Python311\Include "-IC:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.34.31933\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\VS\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22000.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\um" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\shared" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\winrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\cppwinrt" /Tcsrc\lxml\etree.c /Fobuild\temp.win-amd64-cpython-311\Release\src\lxml\etree.obj -w
cl : Command line warning D9025 : overriding '/W3' with '/w'
etree.c
C:\Users\lohar\AppData\Local\Temp\pip-install-v8_cypj7\lxml_b1e7951ab83046e384fffcd4610d3736\src\lxml\includes/etree_defs.h(14): fatal error C1083: Cannot open include file: 'libxml/xmlversion.h': No such file or directory
Compile failed: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\BuildTools\\VC\\Tools\\MSVC\\14.34.31933\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2
creating Users
creating Users\lohar
creating Users\lohar\AppData
creating Users\lohar\AppData\Local
creating Users\lohar\AppData\Local\Temp
"C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.34.31933\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -I/usr/include/libxml2 "-IC:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.34.31933\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\VS\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22000.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\um" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\shared" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\winrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\cppwinrt" /TcC:\Users\lohar\AppData\Local\Temp\xmlXPathInituop21067.c /FoUsers\lohar\AppData\Local\Temp\xmlXPathInituop21067.obj
xmlXPathInituop21067.c
C:\Users\lohar\AppData\Local\Temp\xmlXPathInituop21067.c(1): fatal error C1083: Cannot open include file: 'libxml/xpath.h': No such file or directory
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\BuildTools\\VC\\Tools\\MSVC\\14.34.31933\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2
*********************************************************************************
Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?
*********************************************************************************
[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.
error: legacy-install-failure
× Encountered error while trying to install package.
╰─> lxml
note: This is an issue with the package mentioned above, not pip.
hint: See above for output from the failure.
PS D:\Complete-Python-3-Bootcamp-master\12-Advanced Python Modules\puzzle_unzip> "
*
*im trying to install lxml library by pip install lxml.
*i also installed vs build tools 2022 .
*after that i stuck on this error i tryed multiple things but they dont work
*thigs that i tried manually installing packages.
*multiple internet solutions
im expecting a solution to install lxml on W11 machine.and also im using vs code and pycharm python version 3.11 and pip version 22.3.1
A: The Python lxml module is a language-binding / wrapper for two C libraries.
For Windows they provide binary builds that include these libraries. Otherwise it will be pain and suffering getting it installed and running on Windows. Because it's Windows. "Developers, developers, developers".. (As lxml developers put it: "users of that platform usually fail to build lxml themselves")
Normally you should get the binary distribution when doing install through pip but in this case you don't.
*
*Try to pin an older version, maybe binaries are available for it:
pip install lxml==4.9.0
*Try to download the lxml binary distribution by Christoph Gohlke available here.
You can install the wheel file also via pip.
Sources:
*
*Where are the binary builds?
*Source builds on MS Windows
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74666576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Reliable Ways to Send Large Files to Clients we have a need to regularly provide large files to clients on a daily or weekly basis. Currently our process is this:
*
*Internal process creates the file and places it in a specific folder
*Our client connects via SFTP and downloads the file
This work well when the files are small. As they get bigger (50-100 GB in size), we keep getting network interruptions and internal disk space related issues.
What I'd like to see is the following:
*
*Our internal process creates the file.
*This file is copied to an intermediary service (similar to something like FileDropper).
*Our client will download the file from this intermediary service.
I'd like to know if other people had similar issues and what possible solutions are in place. File Dropper works great for non-business related files but obviously I won't be putting client data on there. We also have an Office 365 subscription. I tried to see what I could use with that but I haven't found anything yet that would help solve this.
Any hints, suggestions or feedback is much appreciated!
A: Consider Amazon S3.
I have used it several times in the past and it is very reliable both for processing a lot of files and for processing large files
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45844912",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Subsets and Splits