_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d1501 | train | Try this:
notStrong = True
while notStrong:
digits = False
upcase = False
lowcase = False
alnum = False
password = input("Enter a password between 6 and 12 characters: ")
while len(password) < 6 or len(password)>12:
if len(password)<6:
print("your password is too short")
elif len(password) > 12:
print("your password is too long")
password = input("Please enter a password between 6 and 12 characters.")
for i in range(0,len(password)):
if password[i].isupper():
upcase = True
if password[i].islower():
lowcase = True
if password[i].isalnum():
alnum = True
if password[i].isdigit():
digits = True
if digits and alnum and lowcase and upcase and digits:
print("Your password is strong")
notStrong = False
elif (digits and alnum) or (digits and lowcase) or (digits and upcase) or (alnum and lowcase) or (alnum and upcase) or (lowcase and upcase):
print("Your password is medium strength")
else:
print("Your password is weak")
A: You don't have to make use of a loop, you can simply call the function within itself if the password is weak or medium, like so:
def Password():
digits = False
upcase = False
lowcase = False
alnum = False
password = input("Enter a password between 6 and 12 characters: ")
while len(password) < 6 or len(password)>12:
if len(password)<6:
print("your password is too short")
elif len(password) > 12:
print("your password is too long")
password = input("Please enter a password between 6 and 12 characters.")
for i in range(0,len(password)):
if password[i].isupper():
upcase = True
if password[i].islower():
lowcase = True
if password[i].isalnum():
alnum = True
if password[i].isdigit():
digits = True
if digits and alnum and lowcase and upcase and digits:
print("Your password is strong")
elif (digits and alnum) or (digits and lowcase) or (digits and upcase) or (alnum and lowcase) or (alnum and upcase) or (lowcase and upcase):
print("Your password is medium strength")
Password()
else:
print("Your password is weak")
Password()
Password()
This is a very useful technique and can be used to simplify many problems without the need for a loop.
Additionally, you can put in another check so that you can adjust the required strength of the password as needed in the future - this is not as easy to do (or rather, cannot be done as elegantly) if you use a while loop.
EDIT - To add to the advice given in the comments:
How does a "stack overflow" occur and how do you prevent it?
Not deleting the answer because I now realize that it serves as an example of how one shouldn't approach this question, and this may dissuade people from making the same mistake that I did. | unknown | |
d1502 | train | You could use the $.after() method:
$(".test3").closest(".divouter").after("<div>Foo</div>");
Or the $.insertAfter() method:
$("<div>Foo</div>").insertAfter( $(".test3").closest(".divouter") );
A: .divouter:parent
A: I think you want the "after()" method:
$('input.test3').focus(function() {
$(this).closest('div.divouter').after('<div>Hi!</div>');
}); | unknown | |
d1503 | train | subprocess.call() returns the exit code, not the stdout. You can use the Popen class directly:
nslookup_data = subprocess.Popen(["nslookup", clean_host], stdout=subprocess.PIPE).communicate()[0]
The .communicate()[0] at the end is important. That tells Popen that we are done, and it returns a tuple: (stdout, stderr). The first item in the tuple [0] is the stdout.
You could also use subprocess.check_output():
nslookup_data = subprocess.check_output(["nslookup", clean_host]) | unknown | |
d1504 | train | You are looking for _.indexBy() http://lodash.com/docs#indexBy
Example from the docs:
var keys = [
{ 'dir': 'left', 'code': 97 },
{ 'dir': 'right', 'code': 100 }
];
_.indexBy(keys, 'dir');
// → { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } | unknown | |
d1505 | train | Personally i don't think you have much of an issue here - just apply the latest updates to the build server. The main reasons i say this are:
*
*it is highly unlikely that your code or any of the dependencies on the build server are so tightly coupled to the OS version that installing regular updates is going to affect anything, let alone break it. There can be minor differences between window messages etc between Windows versions, but those are few and far between, and are usually quite well documented out there on teh interweb. If you are using managed technology stacks like WPF/Silverlight or ASP.Net and even mostly Winforms then you will be isolated from these changes - they should only affect you if you are doing hardcore stuff using the WinAPI directly to create your windows or draw your buttons.
*it is a good practice to always engineer your product against the latest version of the OS, because you need to encourage your customer to implement those updates too - IOW you should not be in a position where you have to say to your client to not install update xyz because your application will not run against it - especially if that update is a critical security update
*testing for differences between OS versions should be done by the QA team and should independant of what is on the build server
*you do not want your build server to get in to such a state that it has been so isolated from the company update process that when you finally do apply them all it barfs and spits molten silicon everywhere. IOW, the longer you wait to update, the higher the risk of something going wrong and doing so catastrophically. Small and frequent/incremental updates are lower risk than mass updates once per decade :)
The build server updates that you do have to be cautious about are third party controls or library updates - they can frequently contain breaking changes or considerably altered behavior. They really should be scheduled, and followed up by a round of testing looking for any changes.
A: Virtualize!
Using stuff like VMWare Server you can script the launch and suspend of virtual machines. So you can script VM resume, SSH to launch build, copy, VM suspend, repeat. (I say this, but I abandoned my work on this. Still, I was making progress at the time.)
Also, you can trust your OS vendors. Can't you?
They have an interest in compatibility. If you build on Windows XP it is almost certain to work on XP SP3 and Vista and Windows 7.
If you build on RedHat Enterprise 5, it had better work on 5.1, 5.2, 5.3, 5.4, etc.
In my experience this has worked out OK so far for me and I recommend building on your lowest patch OS versions. With the Linux stuff in particular I have found newer releases linking to more recent libraries not available on older versions.
Of course it doesn't hurt to test your code on a copy of the deployment server. It all depends on how certain you want to be.
A: Take the build server off the network, that way you do not need to worry about installing security updates. Only load the source from CD, thumb drive or whatever other means.
Plug it back in at the end of your release cycle and then let all the updates take place.
A: Well, for the most stable process, I would have two build servers, "Build with Initial config, Build with update config", and two autotest test servers with similar differences. Use virtualization to do this effectively and scriptably. | unknown | |
d1506 | train | You should use a Decoder, which is able to maintain state between calls to GetChars - it remembers the bytes it hasn't decoded yet.
using System;
using System.Text;
class Test
{
static void Main()
{
string str = "Hello\u263AWorld";
var bytes = Encoding.UTF8.GetBytes(str);
var decoder = Encoding.UTF8.GetDecoder();
// Long enough for the whole string
char[] buffer = new char[100];
// Convert the first "packet"
var length1 = decoder.GetChars(bytes, 0, 6, buffer, 0);
// Convert the second "packet", writing into the buffer
// from where we left off
// Note: 6 not 7, because otherwise we're skipping a byte...
var length2 = decoder.GetChars(bytes, 6, bytes.Length - 6,
buffer, length1);
var reconstituted = new string(buffer, 0, length1 + length2);
Console.WriteLine(str == reconstituted); // true
}
} | unknown | |
d1507 | train | Hi you can add user company details using.
Javascript. example
var x =people.getPerson("admin");
logger.log(x.properties["companyemail"]);
//getting the current Company email
x.properties["companyemail"]="[email protected]";
//setting new company email
logger.log(x.properties["companyemail"]);
//getting the new Company email
companytelephone
companyaddress2
companyaddress1
companyfax
companyemail
companypostcode
These are the some properties of user comapny
A: To add a field which is already a property of user model.
In case of adding company field, follow below steps:
*
*In users.get.properties file - Add below line.
label.companyname=Company
*In users.js file - Added fields company property for not null check and getting it's value followed with clearing the value after a valid entry.
form.addValidation(parent.id + "-create-companyname",Alfresco.forms.validation.mandatory, null, "keyup"); // Add validation
organisation: fnGetter("-create-companyname"), // Get company value
fnClearEl("-create-companyname"); // Clear company field
*In users.get.html.ftl file - Added div for company
<div class="field-row">
<span class="crud-label">${msg("label.companyname")}: *</span> </div> <div class="field-row">
<input class="crud-input" id="${el}-create-companyname" type="text" maxlength="100" />
</div> | unknown | |
d1508 | train | You have put the boolean out of the loops. So, once it is false, it will never be true in other loops and this cause the issue.
int primes = 0;
Console.WriteLine("Enter a number");
int N = int.Parse(Console.ReadLine());
for (int i = 2; i <= N; i++)
{
bool isPrime = true;
for (int j = 2; j <= Math.Sqrt(i); j++)
{
if (i % j == 0)
{
isPrime = false;
}
}
if (isPrime)
{
Console.WriteLine(i + " is a prime number");
primes++;
}
}
Console.WriteLine("Between 1 to " + N + " there are " + primes + " prime numbers");
A: First define this class:
public static class PrimeHelper
{
public static bool IsPrime(int candidate)
{
if ((candidate & 1) == 0)
{
if (candidate == 2)
{
return true;
}
else
{
return false;
}
}
for (int i = 3; (i * i) <= candidate; i += 2)
{
if ((candidate % i) == 0)
{
return false;
}
}
return candidate != 1;
}
}
then call it in your application:
var finalNumber = int.Parse(Console.ReadLine());
for (int i = 0; i < finalNumber; i++)
{
bool prime = PrimeHelper.IsPrime(i);
if (prime)
{
Console.Write("Prime: ");
Console.WriteLine(i);
}
} | unknown | |
d1509 | train | You are differentiating the self and other user by some uniqueness right, say for example uniqueness is user email or user id.
Solution 1:
On making socket connection, send the user id/email also and you can store that as part of socket object itself. So that when ever player1 did some move, on emit send the id also along with whatever data you are sending.
Solution 2:
When player1 did some move, you will send data to server, while sending the data, send the user id/email also. And in server again emit along with user id.
In client you can check - if id is self, then update at bottom. If id is not self then update the top. Note: If you have multiple opponent player, still you can handle with this.
EXAMPLE:
In client:
<script>
var socket = io();
var selfId;
socket.on('playerinfo', function(data){
selfId = data.name;
playerInfo = data.players;
$('.top').html(playerInfo);
$('.bottom')html(selfId);
});
socket.on('move', function(data){
if(data.uid == selfId)
{
$('.top').html(data.card);
}
else
{
$('.bottom')html(data.card);
}
});
socket.emit('move', {card:A, uid:56836480193347838764});
</script>
In server:
var players = [];
io.on('connection', function(socket){
//player is given 'P' with random number when connection is made to represent username
socket.name = "P" + Math.floor(Math.random() * (20000));
// Here may be you can assign the position also where the user is sitting along with the user name.
//players will be an array of object which holds username and their position
//So that in client you can decide where the user will sit.
players.push(socket.name);
io.emit('playerinfo', {'players':players, 'name':socket.name);
socket.on('move', function (data) {
socket.emit('move', data);
});
}
A: Take a look into this 7 part tutorial. I think it gives you a good picture about what needs to be done in a typical multiplayer game by Socketio:
http://www.tamas.io/online-card-game-with-node-js-and-socket-io-episode-1/
http://www.tamas.io/online-card-game-with-node-js-and-socket-io-episode-2/
http://www.tamas.io/online-card-game-with-node-js-and-socket-io-episode-3/
http://www.tamas.io/online-card-game-with-node-js-and-socket-io-episode-4/
http://www.tamas.io/online-card-game-with-node-js-and-socket-io-episode-5/
http://www.tamas.io/online-card-game-with-node-js-and-socket-io-episode-6/
http://www.tamas.io/online-card-game-with-node-js-and-socket-io-episode-7
A: You need to give each client some kind of id, and tell each client when they connect, what their id is. When a client connects, generate a random unique id for them, and then send this back to them so they know their id. When you send back the data of other players, the client can figure out which data is theirs based on the id and display it in the right area. | unknown | |
d1510 | train | *
*Right-click on the labels and choose "Format Axis from the drop down menu
*Under "Number", choose the number format you want (Time)
This should give you the desired result: | unknown | |
d1511 | train | I managed to get this to work, by using a separate queryset that gets the group ids. This way the prefetch filter will not use the requesting user id to filter, which resulted in empty lists for all other users.
group_ids = user.groups.values('pk')
User.objects.exclude(id=user.id).filter(
groups__in=group_ids
).prefetch_related(
Prefetch('groups', Group.objects.filter(id__in=group_ids), to_attr='related_groups'),
) | unknown | |
d1512 | train | The way systemctl communicates with systemd to get service status is through a d-bus socket. The socket is hosted in /run/systemd. So we can try this:
docker run --privileged -v /run/systemd:/run/systemd -v /sys/fs/cgroup:/sys/fs/cgroup test-docker:latest
But when we run systemctl status inside the container, we get:
[root@1ed9d836a142 /]# systemctl status
Failed to connect to bus: No data available
It turns out that for this to work, systemctl expects systemd to be pid 1, but inside the container, pid 1 is something else. We can resolve this by running the container in the host PID namespace:
docker run --privileged -v /run/systemd:/run/systemd --pid=host test-docker:latest
And now we're able to successfully communicate with systemd:
[root@7dccc711a471 /]# systemctl status | head
● 7dccc711a471
State: degraded
Jobs: 0 queued
Failed: 2 units
Since: Sun 2022-06-26 03:11:44 UTC; 5 days ago
CGroup: /
├─kubepods
│ ├─burstable
│ │ ├─pod23889a3e-0bc3-4862-b07c-d5fc9ea1626c
│ │ │ ├─1b9508f0ab454e2d39cdc32ef3e35d25feb201923d78ba5f9bc2a2176ddd448a
... | unknown | |
d1513 | train | There are many challenges mixing different compilers, like:
*
*Name mangling (the way symbols are exported), especially when using C++
*Different compilers use different standard libraries, which may cause serious problems. Imagine for example memory allocated with GCC/MinGW malloc() being released with MSVC free(), which will not work.
With static libraries it is especially hard (e.g. malloc() can be linked to the wrong standard library).
With shared libraries there may be possibilities to solve these issues and get it to work, at least when sticking to C. For C++ it may be a lot more challenging. | unknown | |
d1514 | train | Yes, it is possible but your code would not work because x inside the loop will be unknown:
for i in test_rng:
my_fun1(i)
print(x)
my_fun2(x)
Possibly, you want to do something like:
for i in test_rng:
x = my_fun1(i)
print(x)
my_fun2(x)
You may also want to double-check the code in my_fun1():
def my_fun1(i):
x=+i
return x
as the use of x=+i may suggest you are trying to do something different from x = i, which is essentially what your code is doing: x=+i -> x = (+i) -> x = i
A: Your code contains a wrong logic and I am also assuming that the variable x is globally defined. See below.
def my_fun1(i):
x=+i#I am assuming you want this x+=i
return x
def my_func2(x1)
print(x1)
test_rng=range(124,124+100)
for i in test_rng:
my_fun1(i)
print(x)
my_fun2(x) | unknown | |
d1515 | train | Disable ligatures to make them show properly. Worked for me.
-moz-font-feature-settings: "liga" off;
https://developer.mozilla.org/en/CSS/font-feature-settings | unknown | |
d1516 | train | Simplest will be bubble sort.
item* sort(item *start){
item *node1,*node2;
int temp;
for(node1 = start; node1!=NULL;node1=node1->next){
for(node2 = start; node2!=NULL;node2=node2->next){
if(node2->draw_number > node1->draw_number){
temp = node1->draw_number;
node1->draw_number = node2->draw_number;
node2->draw_number = temp;
}
}
}
return start;
} | unknown | |
d1517 | train | The server socket can bind only to an IP that is local to the machine it is running on (or, to the wildcard IP 0.0.0.0 to bind to all available local IPs). Clients running on the same network can connect to the server via any LAN IP/Port the server is bound to.
However, when the server machine is not directly connected to the Internet, but is running behind a router/proxy, the server socket cannot bind to the network's public IP. So, for what you are attempting, you need to bind the server socket to its local LAN IP (or wildcard) and Port, and then configure the network router to port-forward inbound connections from its public WAN IP/Port to the server's private LAN IP/Port. Then, clients running on other networks can connect to your public WAN IP/Port, and then be forwarded to the server.
If the router supports UPnP (Universal Play-by-play) and it is enabled, the server code can programmably setup the port forwarding rules dynamically. Otherwise, the rules need to be configured manually in the router's configuration by an admin. | unknown | |
d1518 | train | ASP.NET MVC uses a different IDependencyResolver than ASP.NET WebAPi namelly Sytem.Web.Mvc.IDependencyResolver.
So you need a new NinjectDependencyResolver implementation for the MVC Controllers (luckily the MVC and WepAPi IDependencyResolver almost has the same members with the same signatures, so it's easy to implement)
public class NinjectMvcDependencyResolver : NinjectDependencyScope,
System.Web.Mvc.IDependencyResolver
{
private readonly IKernel _kernel;
public NinjectDependencyResolver(IKernel kernel)
: base(kernel)
{
_kernel = kernel;
}
}
And then you can register it in the Global.asax with:
DependencyResolver.SetResolver(new NinjectMvcDependencyResolver(kernel)); | unknown | |
d1519 | train | my $result = qx(some-shell-command @{[ get_value() ]});
# or dereferencing single scalar value
# (last one from get_value if it returns more than one)
my $result = qx(some-shell-command ${ \get_value() });
but I would rather use your first option.
Explanation: perl arrays interpolate inside "", qx(), etc.
Above is array reference [] holding result of function, being dereferenced by @{}, and interpolated inside qx().
A: Backticks and qx are equivalent to the builtin readpipe function, so you could explicitly use that:
$result = readpipe("some-shell-command " . get_value()); | unknown | |
d1520 | train | I just tried it with this:
class Thing < ActiveRecord::Base
after_save :test_me
def test_me
puts self.id
end
end
and in the console:
$ rails c
Loading development environment (Rails 3.0.4)
>> x=Thing.new
=> #<Thing id: nil, name: nil, created_at: nil, updated_at: nil>
>> x.save
2
=> true
>> y=Thing.create
3
=> #<Thing id: 3, name: nil, created_at: "2011-04-27 15:57:03", updated_at: "2011-04-27 15:57:03">
What else is going on in your model?
A: if you call reload() after saving the object, the self.id will be populated | unknown | |
d1521 | train | Currently this is working for me -- making a socket rather than a shared memory connection.
>jdb –sourcepath .\src -connect com.sun.jdi.SocketAttach:hostname=localhost,port=8700
Beforehand you need to do some setup -- for example, see this set of useful details on setting up a non-eclipse debugger. It includes a good tip for setting your initial breakpoint -- create or edit a jdb.ini file in your home directory, with content like:
stop at com.mine.of.package.some.AClassIn:14
and they'll get loaded and deferred until connection.
edit: forgot to reference Herong Yang's page.
A: Try quitting Android Studio.
I had a similar problem on the Mac due to the ADB daemon already running. Once you quit any running daemons, you should see output similar to the following:
$ adb -d jdwp
28462
1939
^C
$ adb -d forward tcp:7777 jdwp:1939
$ jdb -attach localhost:7777 -sourcepath ./src
Set uncaught java.lang.Throwable
Set deferred uncaught java.lang.Throwable
Initializing jdb ...
>
See my other answer to a similar question for more details and how to start/stop the daemon.
A: Answer #1: Map localhost in your hosts file, as I linked to earlier. Just to be sure.
Answer #2: If you're using shared memory, bit-size could easily become an issue. Make sure you're using the same word width everywhere.
A: In order to debug application follow this steps:
Open the application on the device.
Find the PID with jdwp (make sure that 'android:debuggable' is set to true in the manifest):
adb jdwp
Start JVM with the following parameters:
java -agentlib:jdwp=transport=dt_shmem,server=y,address=<port> <class>
Expected output for this command:
Listening for transport dt_shmem at address: <port>
Use jdb to attach the application:
jdb -attach <port>
If jdb successful attached we will see the jdb cli.
Example:
> adb jdwp
12300
> java -agentlib:jdwp=transport=dt_shmem,server=y,address=8700 com.app.app
Listening for transport dt_shmem at address: 8700
> jdb -attach 8700
main[1] | unknown | |
d1522 | train | My favourite trick is to use the keyboard:
options.add_argument("--incognito")
options.add_extension('Google-Translate.crx')
driver.get("chrome://extensions")
time.sleep(1)
action = ActionChains(driver)
# Open the extension:
for _ in range(2):
action.send_keys(Keys.TAB).perform()
action.send_keys(Keys.RETURN).perform()
# Flip the switch that enables it in incognito
for _ in range(4):
action.send_keys(Keys.TAB).perform()
action.send_keys(Keys.RETURN).perform() | unknown | |
d1523 | train | Hi have a try with this code.
following code is for camera button click works :
imgviewCamera.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//define the file-name to save photo taken by Camera activity
String fileName = "new-photo-name.jpg";
//create parameters for Intent with filename
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,"Image capture by camera");
//imageUri is the current activity attribute, define and save it for later usage (also in onSaveInstanceState)
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
//create new Intent
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, PICK_Camera_IMAGE);
}
});
OnActivityresult code will be like below
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Uri selectedImageUri = null;
String filePath = null;
switch (requestCode) {
case PICK_Camera_IMAGE:
if (resultCode == RESULT_OK) {
//use imageUri here to access the image
selectedImageUri = imageUri;
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
}
break;
}
if(selectedImageUri != null){
try {
// OI FILE Manager
String filemanagerstring = selectedImageUri.getPath();
// MEDIA GALLERY
String selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}
if (filePath != null) {
Toast.makeText(getApplicationContext(), " path" + filePath,
Toast.LENGTH_LONG).show();
Intent i = new Intent(getApplicationContext(), EditorActivity.class);
// passing array index
i.putExtra("id", filePath);
startActivity(i);
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Internal error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
dont forget to add camera permission in manifest file.
hope this will help you. | unknown | |
d1524 | train | Try to use a UIToolBar instead of a UIVisualEffectView as the background of the segment. The navigation bar has translucent background rather than blur effect. UIToolBar has the same translucent background as navigation bar, so it would look seamless at the edge.
A: Looking to your picture it seems your issue is not attributable to UINavigationBar but to a view where you have added UISegmentedControl.
I don't know your structure but it could be the tableHeaderView (self.tableView.tableHeaderView) so a reasonable way to solve this problem is to change the header color:
Code example:
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
var headerView: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
header.contentView.backgroundColor = UIColor.clearColor()
return header
} | unknown | |
d1525 | train | import matplotlib.pyplot as plt
import pandas as pd
data = {'2013': {1:25,2:81,3:15}, '2014': {1:28, 2:65, 3:75}, '2015': {1:78,2:91,3:86 }}
df = pd.DataFrame(data)
df.plot(kind='bar')
plt.show()
I like pandas because it takes your data without having to do any manipulation to it and plot it.
A: You can access the keys of a dictionary via dict.keys() and the values via dict.values()
If you wanted to plot, say, the data for 2013 you can do:
import matplotlib.pyplot as pl
x_13 = data['2013'].keys()
y_13 = data['2013'].values()
pl.bar(x_13, y_13, label = '2013')
pl.legend()
That should do the trick. More elegantly, do can simply do:
year = '2013'
pl.bar(data[year].keys(), data[year].values(), label=year)
which woud allow you to loop it:
for year in ['2013','2014','2015']:
pl.bar(data[year].keys(), data[year].values(), label=year)
A: You can do this a few ways.
The Functional way using bar():
data = {'2013': {1: 25, 2: 81, 3: 15}, '2014': {1: 28, 2: 65, 3: 75}, '2015': {1: 78, 2: 91, 3: 86}}
df = pd.DataFrame(data)
X_axis = np.arange(len(df))
plt.bar(X_axis - 0.1,height=df["2013"], label='2013',width=.1)
plt.bar(X_axis, height=df["2014"], label='2014',width=.1)
plt.bar(X_axis + 0.1, height=df["2015"], label='2015',width=.1)
plt.legend()
plt.show()
More info here.
The Object-Oriented way using figure():
data = {'2013': {1: 25, 2: 81, 3: 15}, '2014': {1: 28, 2: 65, 3: 75}, '2015': {1: 78, 2: 91, 3: 86}}
df = pd.DataFrame(data)
fig= plt.figure()
axes = fig.add_axes([.1,.1,.8,.8])
X_axis = np.arange(len(df))
axes.bar(X_axis -.25,df["2013"], color ='b', width=.25)
axes.bar(X_axis,df["2014"], color ='r', width=.25)
axes.bar(X_axis +.25,df["2015"], color ='g', width=.25) | unknown | |
d1526 | train | I don't know the topic, I had to read it up. So I'm not entirely sure the code is works right (for every input), though I checked it for some examples I found on the net.
function mapAB(a,b,fn){
var k=0, out = Array(a.length*b.length);
for(var i=0; i<a.length; ++i)
for(var j=0; j<b.length; ++j)
out[k++] = fn(a[i], b[j]);
return out;
}
function kroneckerProduct(a,b){
return Array.isArray(a)?
Array.isArray(b)?
mapAB(a,b, kroneckerProduct):
a.map(v => kroneckerProduct(v, b)):
Array.isArray(b)?
b.map(v => kroneckerProduct(a, v)):
a*b;
}
function mapAB(a, b, fn) {
var k = 0,
out = Array(a.length * b.length);
for (var i = 0; i < a.length; ++i)
for (var j = 0; j < b.length; ++j)
out[k++] = fn(a[i], b[j]);
return out;
}
function kroneckerProduct(a, b) {
return Array.isArray(a) ?
Array.isArray(b) ?
mapAB(a, b, kroneckerProduct) :
a.map(v => kroneckerProduct(v, b)) :
Array.isArray(b) ?
b.map(v => kroneckerProduct(a, v)) :
a * b;
}
function compute() {
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
var text;
try {
text = JSON.stringify(kroneckerProduct(
JSON.parse(a.trim()),
JSON.parse(b.trim())
), null, 2);
} catch (err) {
text = err;
}
document.getElementById("out").innerHTML = text;
}
<input id=a value=[1,2]><br>
<input id=b value=[3,4]><br>
<input type=button value=compute onclick=compute()>
<div id=out></div> | unknown | |
d1527 | train | boost::mpl::_1 and boost::mpl::_2 are placeholders; they can be used as template parameters to differ the binding to an actual argument to a later time. With this, you can do partial application (transforming a metafunction having an n-arity to a function having a (n-m)-arity), lambda expressions (creating a metafunction on-the-fly where it is needed), etc.
An expression containing at least a placeholder is a placeholder expression, which can be invoked like any other metafunction, with some arguments that will replace the placeholders.
In your example, assuming the following typedef
typedef boost::flyweights::hashed_factory_class<
boost::mpl::_1,
boost::mpl::_2,
boost::hash<boost::mpl::_2>,
std::equal_to<boost::mpl::_2>,
std::allocator<boost::mpl::_1>
> hashed_factory;
we can assume that at some other point in the code, the hashed_factory will be invoked with some parameter:
typedef typename
boost::mpl::apply<
hashed_factory,
X,
Y
>::type result; // invoke hashed_factory with X and Y
// _1 is "replaced" by X, _2 by Y
I did not look in Flyweight code, but we can suppose that _1 will be bound to the value type of the flyweight, and _2 to the key type (since it is used for hashing and testing equality). In this case, I think both will be std::string since no key type is specified.
I'm not sure my explanation about MPL's placeholders is quite clear, feel free to read the excellent MPL tutorial that explains very well metafunctions, lambda expressions and other template metaprogramming features. | unknown | |
d1528 | train | For version ^0.8.2 following solutions work for me.
iOS
in ios/Podfile add following to end of file.
post_install do |installer|
installer.pods_project.targets.each do |target|
flutter_additional_ios_build_settings(target)
target.build_configurations.each do |build_configuration|
build_configuration.build_settings['EXCLUDED_ARCHS[sdk=iphonesimulator*]'] = 'arm64 i386'
end
end
end
Then clean your project and follow these steps as santoshakil mentioned santoshakilsanswer; (Those steps work for me if not follow all steps mentioned in link)
flutter clean && flutter pub get
cd ios
arch -x86_64 pod update
arch -x86_64 pod install
then at the top of your Pod file, paste this line platform :ios, '10.0'
right click on ios folder and open in xcode and then set all deployment target to 10
Android
Your android/app/build.gradle look like below as webrtcflutterdemo
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}
apply plugin: 'com.android.application'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
android {
compileSdkVersion 28
lintOptions {
disable 'InvalidPackage'
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.cloudwebrtc.flutterwebrtcdemo"
minSdkVersion 21
targetSdkVersion 28
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.debug
useProguard true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
packagingOptions {
exclude 'META-INF/proguard/androidx-annotations.pro'
}
}
flutter {
source '../..'
}
dependencies {
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
android/app/AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cloudwebrtc.flutterwebrtcdemo">
<!-- The INTERNET permission is required for development. Specifically,
flutter needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<!-- io.flutter.app.FlutterApplication is an android.app.Application that
calls FlutterMain.startInitialization(this); in its onCreate method.
In most cases you can leave this as-is, but you if you want to provide
additional functionality it is fine to subclass or reimplement
FlutterApplication and put your custom class here. -->
<application
android:label="flutter_webrtc_demo"
android:icon="@mipmap/ic_launcher">
<meta-data
EDIT
For Android side, i can not build for compilesdk and targetsdk 31. Temporary solution is downgrading compilesdk to 30. It is about jdk version on your mac device. | unknown | |
d1529 | train | I figured out that it was a bug in my code
this code was giving me always the same name
String neteworkName = vdc.getAvailableNetworkRefs().iterator().next().getName();
it should be
String neteworkName = networkConnection.getNetwork(); | unknown | |
d1530 | train | Can you show an example of code that does not work? It looks OK to me:
> Container = require "Container"
> c = Container.create(5)
> c:add(2, 42)
> =c:getAt(2)
42 | unknown | |
d1531 | train | There seems to be a mathematical error. If you want your last animate to move the element to the start position, change it to:
.animate({
'top': '-=200',
'left': '-=300'
}
But if you want it to move to start after you current last animation then add the following animate after that:
.animate({
'top': '-=250'
} | unknown | |
d1532 | train | You need to make sure that you #include the right headers, in this case:
#include <stdlib.h> // rand(), srand()
#include <time.h> // time()
When in doubt, check the man pages:
$ man rand
$ man time
One further problem: time() requires an argument, which can be NULL, so your call to srand() should be:
srand(time(NULL));
A: Note that time() function uses current time (expressed in seconds since 1970) both in its return value and in its address argument.
A: I had this issue, and the problem was that in windows you need to include sys/time.h, but in linux you need time.h and I didn't notice.
I fixed this by adding a simple platform check:
#ifdef _WIN32
#include <sys/time.h>
#else
#include <time.h>
#endif
Note that this is for windows and linux, because that's what I needed for my program. | unknown | |
d1533 | train | person['age'] = age
The 'age' inside the brackets is the key, the value 'age' is where your value is assigned.
The person dictionnary becomes:
{'first': first_name, 'last': last_name,'age': age}
A: Here, person[age] = age
works only when age is given as argument when calling this function.
person is dictionary, age in person[age] is key, and the age which is at right side of assignment operator(=) is value passed as argument in function.
for e.g :
for the given code below in last line i have given age as argument.
def build_person(first_name, last_name, age=None):
person = {'first': first_name, 'last': last_name}
if age:
person['age'] = age
print(person)
return person
build_person("yash","verma",9)
Output for above code is :
{'first': 'yash', 'last': 'verma', 'age': 9}
now,
if i don't give age as a argument then,
def build_person(first_name, last_name, age=None):
person = {'first': first_name, 'last': last_name}
if age:
person['age'] = age
print(person)
return person
build_person("yash","verma")
output will be:
{'first': 'yash', 'last': 'verma'} | unknown | |
d1534 | train | If a variable is declared, but not initialized, its value will be Empty, which you can check for with the IsEmpty() function:
Dim banners
If IsEmpty(banners) Then
Response.Write "Yes"
Else
Response.Write "No"
End If
' Should result in "Yes" being written
banners will only be equal to Nothing if you explicitly assign it that value with Set banners = Nothing.
You will have problems, though, with this technique if you have Option Explicit turned on (which is the recommendation, but isn't always the case). In that case, if banners hasn't been Dimed and you try to test IsEmpty(banners), you will get a runtime error. If you don't have Option Explicit on, you shouldn't have any problems.
edit: I just saw this related question and answer which might help, too.
A: @Atømix: Replace
If Not banners Is Nothing then
and use
If IsObject(banners) Then
Your other code you can then place into an include file and use it at the top of your pages to avoid unnecessary duplication.
@Cheran S: I tested my snippets above with Option Explicit on/off and didn't encounter errors for either version, regardless of whether Dim banners was there or not. :-)
A: IsObject could work, but IsEmpty might be a better option - it is specifically intended to check if a variable exists or has been initialised.
To summarize:
*
*IsEmpty(var) will test if a variable exists (without Object Explicit), or is initialised
*IsNull(var) will test if a variable has been assigned to Null
*var Is Nothing will test if a variable has been Set to Nothing, but will throw an error if you try it on something that isn't an object
*IsObject(var) will test if a variable is an object (and will apparently still return False if var is Empty).
A: Somewhat related is IsMissing() to test if an optional parameter was passed, in this case an object, like this:
Sub FooBar(Optional oDoc As Object)
'if parameter is missing then simulate it
If IsMissing(oDoc) Then Dim oDoc as Object: oDoc = something
...
A: You need to have at least dim banners on every page.
Don't you have a head.asp or something included on every page?
A: Neither of IsEmpty, Is Object, IsNull work with the "Option Explicit" Setting, as stealthyninja above has misleadingly answered.
The single way i know is to 'hack' the 'Option Explicit' with the 'On Error Resume Next' setting, as Tristan Havelick nicely does it here:
Is there any way to check to see if a VBScript function is defined? | unknown | |
d1535 | train | I'm afraid explode(' ', $body) is not enough because space is not the only white space character. Try preg_split instead.
$body = array_filter(preg_split('/\s+/', $body),
create_function('$str', 'return strlen($str) > 2;')); | unknown | |
d1536 | train | #include <iostream>
int &myFunction(int *arr, size_t pos) { return arr[pos]; }
int main() {
using std::cout;
int myArray[30];
size_t positionInsideMyArray = 5;
myFunction(myArray, positionInsideMyArray) = 17.;
cout << myArray[positionInsideMyArray] << "\n"; // Display muValue
}
or with error checking:
#include <stdexcept>
template<size_t N>
inline int &myFunction(int (&arr)[N], size_t pos)
{
if (pos >= N)
throw std::runtime_error("Index out of bounds");
return arr[pos];
}
A: myFunction(myArray, positionInsideMyArray) = myValue.
cout << myFunction[positionInsideMyArray] << endl;
With functions alone, the second line is not possible; you'll need a class.
However, that the second call remembers myArray from the
first makes the whole semantics a bit strange...
A rough idea (no complete class, only for int-arrays):
class TheFunc
{
int *arr;
int &operator() (int *arr, size_t pos)
{
this->arr = arr;
return arr[pos];
}
int &operator[] (size_t pos)
{
return arr[pos];
}
};
...
TheFunc myFunction;
myFunction(myArray, positionInsideMyArray) = myValue.
cout << myFunction[positionInsideMyArray] << endl;
A different, more robust version, where the array it set separately:
class TheFunc
{
int *arr;
TheFunc(int *arr)
{
this->arr = arr;
}
int &operator() (size_t pos)
{
return arr[pos];
}
int &operator[] (size_t pos)
{
return arr[pos];
}
};
...
TheFunc myFunction(myArray);
myFunction(positionInsideMyArray) = myValue.
cout << myFunction[positionInsideMyArray] << endl; | unknown | |
d1537 | train | If you want to get only the most recent message from each user that you are having a conversation with, create a new class called RecentMessage and update it each time using an afterSave cloud function on the Message class.
In the afterSave hook, maintain a pointer in the RecentMessage class to the latest Message in the conversation for each user. Then all you have to do is query for all of the current user's RecentMessage objects and use includeKey on the Message pointer.
This let's you abstract away more logic from the client side and streamline your queries where performance really counts :) | unknown | |
d1538 | train | Re: best ways to organize jQuery libraries, you should start by reading the Plugins Authoring article on jquery.com:
http://docs.jquery.com/Plugins/Authoring
A: Notes:
*
*Namespacing is a good practice because you have less chance of having conflicting names with other scripts. This way, only your name-space has to be unique, but multiple name-spaces can have the same functions in them.
*jQuery DOES use namespacing, and you do not need the plug-in. The jQuery object itself is a name-space. . . Any function inside jQuery is 'name-spaced' in the jQuery object. This is true for any JavaScript object.
In response to Amir's comment:
YUI achieves namespacing by adding a variable to the YUI object where the added variable is also an object. Their namespace function just builds it for you.
var lib = {
util:{},
widget:{},
tool:{}
};
//creates a function named reset in the lib.util namespace
lib.util.reset = function() {};
//creates a function named reset in the lib.widget namespace
lib.widget.reset = function() {};
In jQuery, you add it to the jQuery.fn (or $.fn if you use $ for jQuery() namespace.
A: require.js is a better practice because it doesn't require you to add objects onto the window object unnecessarily. It also doesn't mean you have to worry about the loading order of previous javascript files. | unknown | |
d1539 | train | Use -l option to list files that match then xargs command to apply grep on those files.
grep -l -rsI "some_string" *.c | xargs grep "second_string"
A: grep -rsIl "some_string" *.c | xargs grep -sI "second_string" | unknown | |
d1540 | train | Make sure you are changing the name/id on the checkbox or you are using an array, for example
Checkbox 1 is named checkbox[1]
Checkbox 2 is named checkbox[2]
If they have the same name, they will only come through as 1 item in the POST/GET! | unknown | |
d1541 | train | WebSharper can run as an ASP.NET module, so the easiest way to start your app is to run xsp4 (mono's self-hosted ASP.NET server) in the project folder. That's good as a quick server for testing; for production you should rather configure a server like Apache or nginx.
Another solution would be to use the websharpersuave template instead, which does generate a self-serving executable. | unknown | |
d1542 | train | Try something along these lines:
from bs4 import BeautifulSoup as bs
options = """[your html above]"""
for i in range(2,4):
targets = soup.select(f'tr td:nth-child({i})')
for target in targets:
target['style']="background-color:blue;text-align:center;"
soup
Output should be your expected html in the question. | unknown | |
d1543 | train | I used to @anastaciu 's solution.
As it was a fresh install without much customization, I resorted to the option of a complete re-install. Bizarre that that works a bit, as it was already a fresh install. I still had to copy stdlib.h and a few others (math.h etc.) to /usr/local/lib` to get to the point where it would at least compile. | unknown | |
d1544 | train | You may certainly have two Scanner objects read from the same File object simultaneously. Advancing one will not advance the other.
Example
Assume that the contents of myFile are 123 abc. The snippet below
File file = new File("myFile");
Scanner strFin = new Scanner(file);
Scanner numFin = new Scanner(file);
System.out.println(numFin.nextInt());
System.out.println(strFin.next());
... prints the following output...
123
123
However, I don't know why you would want to do that. It would be much simpler to use a single Scanner for your purposes. I called mine fin in the following snippet.
String next;
ArrayList<Integer> readIntegers = new ArrayList<>();
while (fin.hasNext()) {
next = fin.next();
while (next.equals("load") {
next = fin.next();
while (isInteger(next)) {
readIntegers.Add(Integer.parseInt(next));
next = fin.next();
}
}
} | unknown | |
d1545 | train | I did not fully understand your question but you can make request from your frontend React page and based on the result you can render whatever you want. | unknown | |
d1546 | train | You can use a css media query to target print:
@media print {
.hide-print {
display: none;
}
}
A: You can use CSS @media queries. For instance:
@media print {
#printPageButton {
display: none;
}
}
<button id="printPageButton" onClick="window.print();">Print</button>
The styles defined within the @media print block will only be applied when printing the page. You can test it by clicking the print button in the snippet; you'll get a blank page.
A: Assign an id to the other 2 buttons. For the POST NEWS button you can set id to postnews and RE-ENTER THE NEWS to reenterthenews; Then do this
function printpage() {
//Get the print button and put it into a variable
var printButton = document.getElementById("printpagebutton");
var postButton = document.getElementById("postnews");
var reenterButton = document.getElementById("reenterthenews");
//Set the button visibility to 'hidden'
printButton.style.visibility = 'hidden';
postButton.style.visibility = 'hidden';
reenterButton.style.visibility = 'hidden';
//Print the page content
window.print()
//Restore button visibility
printButton.style.visibility = 'visible';
postButton.style.visibility = 'visible';
reenterButton.style.visibility = 'visible';
}
HTML
<div id="options">
<input type="submit" id="postnews" value="post news" >
<input id="printpagebutton" type="button" value="print news" onclick="printpage()"/>
<input type="button" id="reenterthenews" value="re-enter the news">
</div> | unknown | |
d1547 | train | Your server is asking for a client-side certificate. You need to install a certificate (signed by a trusted authority) on your client machine, and let your program know about it.
Typically, your server has a certificate (with the key purpose set to "TLS server authentication") signed by either your organization's IT security or some globally trusted CA. You should get a certificate for "TLS client authentication" from the same source.
If you capture the TLS handshake in Wireshark, you'll see the ServerHello message followed by a "Client Certificate Request", to which you reply with a "Client Certificate" message with length 0. Your server chooses to reject this. | unknown | |
d1548 | train | Something like this?
library(shiny)
ui <- fluidPage (
numericInput("current", "Current Week",value = 40, min = 40, max = 80)
)
server <- function(input, output, session) {
observeEvent(input$current, {
updateNumericInput(session,"current", value = ({ if(!(is.numeric(input$current))){40}
else if(!(is.null(input$current) || is.na(input$current))){
if(input$current < 40){
40
}else if(input$current > 80){
80
} else{
return (isolate(input$current))
}
}
else{40}
})
)
})
}
shinyApp(ui=ui, server = server) | unknown | |
d1549 | train | Codesys v2.3 only has OPC-DA (Availability depends on PLC model and manufacturer. Even though OPC-UA may not always be available on a PLC with Codesys v3.5, check your vendor's documentation to check if is a optional).
There are Gateways (hardware and software) that allow "conversion" between OPC-DA and OPC-UA or between other protocols for OPC-UA, for example, if your PLC has Modbus-TCP/RTU. It is also possible to use another PLC, as Camile G. commented, but possibly the cost and development should be more complicated, depending on the case it may be worth migrating the entire system to a single PLC with Codesys v3.5 and OPC-UA. | unknown | |
d1550 | train | When you open your site (i.e. http://127.0.0.1:8090) it sends a GET request but doesn't send back to the browser any response. That is why it seems GET request wasn't made. Send a response in the app.get and it'll send a response.
app.get('/', async function(req, res){
console.log(req);
res.send('Hello World');
}
A: express.static('client') suggest from where your static files are to be loaded. Here 'client' is treated as your root path.
If your 'client' directory has some 'abcd.img' file then, http://127.0.0.1:8090/abcd.img will load 'abcd.img'. 'index.html' in your 'client' directory will be loaded by default when you point to root path. That means 'http://127.0.0.1:8090/' will load your index.html file.
Express has a very good documentation on this part. I am pasting it for your reference.
Express documentation for serving static files | unknown | |
d1551 | train | I suppose that exceljs hasn't implemented at least one feature used in input.xlsx.
Similar situation I had with images some times ago and fixed by PR: https://github.com/exceljs/exceljs/pull/702
Could I ask you to create an issue on GH?
If you want to find what exactly went wrong:
*
*unzip input.xlsx
*unzip output.xlsx
*check diff between.
You can also upload input.xlsx here, it should help to find a bug reason.
I think also, check any other version of exceljs may be helpful. | unknown | |
d1552 | train | You cannot parameterize the table name in SQL Server, so: that SQL is invalid, and the CREATE PROC did not in fact run. What the contents of the old proc are: only you can know, but: it isn't the code shown. It was probably a dummy version you had at some point in development. Try typing:
exec sp_helptext getLastFeatureUpdate;
Specifically, the server should have told you:
Msg 1087, Level 16, State 1, Procedure getLastFeatureUpdate, Line 12 [Batch Start Line 0]
Must declare the table variable "@tableName".
Msg 1087, Level 16, State 1, Procedure getLastFeatureUpdate, Line 19 [Batch Start Line 0]
Must declare the table variable "@tableName". | unknown | |
d1553 | train | When you create HTTP(S) Load Balancer, there should be a Certificate section in Frontend configuration if you set the protocol to HTTPS, also preserve a static IP. Then you can configure the DNS to point the domain to this IP. | unknown | |
d1554 | train | Spring will only handle injection dependencies to a class that is constructed by the container. When you call getInstance(), you are allocating the object itself... there is no opportunity there for Spring to inject the dependencies that you have @Autowired.
Your second solution works because Spring is aware of your LovHelper class; it handles constructing it and injecting it into your other class.
If you don't want to mark the class with@Component, you can declare the class as a bean directly in your XML configuration. If you don't want to have it be a singleton, you can set it with prototype scope.
If you really need to manage the class yourself, you could consider looking at @Configurable. I believe it is intended to solve this problem but it requires aspects and I have not played with it myself.
A: Your helper should be context aware, but you can make it static:
@Component
public class LovHelper {
private static LovHelper instance;
@PostConstruct
void init() {
instance = this;
}
// do stuff
In this case static instance will keep reference to Spring aware bean. | unknown | |
d1555 | train | You can use Server.MapPath()
as in
Server.MapPath("~/files/ ")
A: Assuming "web_app" in your example is always the root folder of your web application, you can reference the files like...
string path = Server.MapPath("/files/");
A: You can use var rootFolder = Server.MapPath("~") to retrieve the physical path.
The tilde character ~ is replaced with the root directory of your web application, e.g. c:\installation\path\web_app
A: Use Server.MapPath
http://msdn.microsoft.com/en-us/library/ms524632.aspx | unknown | |
d1556 | train | In header.html
logo
menu
In footer.html
social icon
copy rights
A: all of this needs to go in the header.html
<!DOCTYPE html>
<html>
<head>
<title>Responsive Design Website</title>
<link rel = "stylesheet" type = "text/css" href = "css/style.css" media="screen"/>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<link rel="stylesheet" href="http://cdn.jsdelivr.net/animatecss/2.1.0/animate.min.css">
<link href="http://www.jqueryscript.net/css/jquerysctipttop.css" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Open+Sans:400,700,800" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="engine1/style.css" />
<link href="video-js.css" rel="stylesheet" type="text/css">
<link rel="shortcut icon" href="img/favicon.ico">
</head>
</html>
And this goes in the footer.html
<!DOCTYPE html>
<html>
<footer>
<script src="video.js"></script>
<script type="text/javascript" src="engine1/jquery.js"></script>
<script>
videojs.options.flash.swf = "video-js.swf";
</script>
</footer>
</html> | unknown | |
d1557 | train | Users are stored in USER_ table:
select * from USER_;
Groups are stored in GROUP_ table:
select * from GROUP_;
Roles are stored in ROLE_ table:
select * from ROLE_;
Simple view of users and their groups:
select USER_.USERID, USER_.SCREENNAME, USER_.EMAILADDRESS, GROUP_.NAME
from USER_, USERS_GROUPS, GROUP_
where USER_.USERID = USERS_GROUPS.USERID and USERS_GROUPS.GROUPID = GROUP_.GROUPID
order by USER_.SCREENNAME;
Simple view of users and their roles:
select USER_.USERID, USER_.SCREENNAME, USER_.EMAILADDRESS, ROLE_.NAME
from USER_, USERS_ROLES, ROLE_
where USER_.USERID = USERS_ROLES.USERID and USERS_ROLES.ROLEID = ROLE_.ROLEID
order by USER_.SCREENNAME;
Custom fields can be added for uses, groups and roles alike. | unknown | |
d1558 | train | To "append" to numbers, you need to convert them to strings first with str(). Numbers are immutable objects in Python. Strings are not mutable either but they have an easy-to-use interface which makes it easy to create modified copies of them.
number = 345
new_number = int('2' + str(number))
Once you are done editing your string, you can easily convert it back to an int with int().
Note that strings don't have an append method like lists do. You can easily concatenate strings with the + operator however.
A: As @Fredrik comments, you can get from any integer to any other integer by a single addition - and this is how you should probably do it, if you deal with integers only.
>>> i = 345
>>> 2000 + i
2345
There are, however, many way to express "prepend a 2 to 345", one would be to use format:
>>> '2{}'.format(345)
'2345' | unknown | |
d1559 | train | Y can't you validate using .
$validemail = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($validemail) {
$headers .= "Reply-to: $validemail\r\n";
}else
{
//redirect.
}
considering your actual question .
<?php
$emails = explode(';',$emailList);
if(count ($emails)<3)
{
if(filter_var_array($emails, FILTER_VALIDATE_EMAIL))
{
mail();
}
else
{
//die
}
}
?>
A: You could check the number of email in the string like this:
if(count(explode(';',$emailList))<3)
{
// send email
}
else
{
// Oh no, jumbo!
}
This code will explode your email string based on the ; characters into an array while at the same time use a count function on the array and execute one of two scenarios based on the number.
A: This should work to only pick maximum two emails (the first two):
$emailString = "email@examplecom;[email protected];[email protected]";
$emails = explode(";", $emailString);
$emails = array_slice($emails, 0, 2);
$emailString = implode(";", $emails);
var_dump($emailString);
Outputs:
string(31) "email@examplecom;[email protected]" | unknown | |
d1560 | train | Many people don't realise that the DOM is not thread-safe (even if you are only doing reads). If you are caching a DOM object, make sure you synchronize all access to it.
Frankly, this makes DOM unsuited to this kind of application. I know I'm biased, but I would suggest switching to Saxon, whose native tree implementation is not only far faster than DOM, but also thread-safe. One user recently tweeted about getting a 100x performance improvement when they made this switch. | unknown | |
d1561 | train | Approach 1 :
4 different servers, mean four different URLs ok.
suppose ur application url is
http(s)://ipaddress:port/application
now it is possible that all four server instances are on same machine. in that case "ipaddress" would be same. but port would be different. if machines are different in that case both ipaddress and port would be different.
now inside your code you can get absoultepath. absolutepath would consist of the complete URL of the file absolutepath is requested on. like
http://ipaddress:port/application/abc/def/x.java.
Now from this you can extract the port/ipaddress and write your logic.
Approach2:
have a property file inside your application that contains the server its being deployed on. ( right now I cant think of something to set this automatically, but while deployment you can set the server name in this property file)
later on when you need. you can read the property file and you will know which version of application you are running on.
personally I`d prefer approach2 (and should be prefered in case we can think of initializing the properties file automatically)
Hope it helps :-) | unknown | |
d1562 | train | getElementbyName gets an element by its name.
The reference attribute:
*
*Is not a name attribute
*Is not valid HTML at all
So start by writing valid HTML:
<div id="123" data-reference="r045">
Then get a reference to that element:
const div = document.getElementById('123');
Then get the data from it using the dataset API:
console.log(div.dataset.reference);
Live demo
const div = document.getElementById('123');
console.log(div.dataset.reference);
<div id="123" data-reference="r045"></div>
A: You can use document.querySelectorAll('[reference]') if you have multiple div with same attribute.
var reference = document.querySelectorAll('[reference]');
console.log(reference);
<div id="123" reference="r045"></div>
But if you have only one div with reference attribute then use querySelector:
var reference = document.querySelector('[reference]');
console.log(reference);
<div id="123" reference="r045"></div>
A: var reference = document.getElementById("123").getAttribute("reference");
A:
var x = document.getElementById("123").getAttribute("reference");
console.log(x);
<div id="123" reference="r045"></div> | unknown | |
d1563 | train | Instead of / additional to naming your labels by specific names you can later match them on, I'd think a Map of JLabels with Strings or Integers as keys might be a better approach:
Map<String,JLabel> labelMap = new HashMap<String,JLabel>();
labelMap.put("1", OP_1);
labelMap.put("2", OP_2);
This will allow later access of "The label for key 2" as well as "list me all that labels and find the one with text 2" as well
A: Here I created an array of JLabels and a method, updateNextLabel(String), which will update the next JLabel with whatever you enter for str.
public class Example {
static int count = 0; //Create a count
static JLabel[] array = new JLabel[3]; //Create an array to hold all three JLabels
public static void main(String[] args) {
//Set the default text for each JLabel
array[0] = new JLabel("This is OP1");
array[1] = new JLabel("This is OP2");
array[2] = new JLabel("This is OP3");
//Here is an example if you wanted to use a for-loop to update the JLabels
for (int x = 0; x < array.length; x++) {
updateNextLabel("This is the new text for OP" + (count + 1));
System.out.println(array[x].getText());
}
}
public static void updateNextLabel(String str) {
array[count].setText(str);
count++;
}
} | unknown | |
d1564 | train | It's possible to set a windows hook to listen for text changes. This code currently picks up value changes from all fields, so you will need to figure out how to only detect the ComboBox filename field.
public class MyForm3 : Form {
public MyForm3() {
Button btn = new Button { Text = "Button" };
Controls.Add(btn);
btn.Click += btn_Click;
}
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr hmodWinEventProc, WinEventProc lpfnWinEventProc, uint idProcess, uint idThread, uint dwFlags);
[DllImport("user32.dll")]
private static extern bool UnhookWinEvent(IntPtr hWinEventHook);
[DllImport("user32.dll")]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
[DllImport("user32.dll", SetLastError = true)]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
private const int WINEVENT_OUTOFCONTEXT = 0;
private const uint EVENT_OBJECT_VALUECHANGE = 0x800E;
void btn_Click(object sender, EventArgs e) {
uint pid = 0;
uint tid = 0;
using (var p = Process.GetCurrentProcess())
GetWindowThreadProcessId(p.MainWindowHandle, out pid);
var hHook = SetWinEventHook(EVENT_OBJECT_VALUECHANGE, EVENT_OBJECT_VALUECHANGE, IntPtr.Zero, CallWinEventProc, pid, tid, WINEVENT_OUTOFCONTEXT);
OpenFileDialog d = new OpenFileDialog();
d.ShowDialog();
d.Dispose();
UnhookWinEvent(hHook);
MessageBox.Show("Original filename: " + OpenFilenameText);
}
private static String OpenFilenameText = "";
private static WinEventProc CallWinEventProc = new WinEventProc(EventCallback);
private delegate void WinEventProc(IntPtr hWinEventHook, int iEvent, IntPtr hWnd, int idObject, int idChild, int dwEventThread, int dwmsEventTime);
private static void EventCallback(IntPtr hWinEventHook, int iEvent, IntPtr hWnd, int idObject, int idChild, int dwEventThread, int dwmsEventTime) {
StringBuilder sb1 = new StringBuilder(256);
GetClassName(hWnd, sb1, sb1.Capacity);
if (sb1.ToString() == "Edit") {
StringBuilder sb = new StringBuilder(512);
GetWindowText(hWnd, sb, sb.Capacity);
OpenFilenameText = sb.ToString();
}
}
}
A: If you only want to get URL (not download file), set CheckFileExists flag to false.
Example code below
string urlName = null;
using (var dlg = new OpenFileDialog())
{
dlg.CheckFileExists = false;
dlg.ShowDialog();
urlName = dlg.FileName;
urlName = Path.GetFileName(urlName);
} | unknown | |
d1565 | train | If you only want to pass the Void object, but its constructor is private, you can use reflection.
Constructor<Void> c = Void.class.getDeclaredConstructor();
c.setAccessible(true);
Void v = c.newInstance();
then you can pass it.
Since the question was about how to do this from Kotlin, here is the Kotlin version
fun makeVoid(): Void {
val c: Constructor<Void> = Void::class.java.getDeclaredConstructor()
c.isAccessible = true
return c.newInstance()
}
and
val u = Uncallable()
u.myMethod(makeVoid()) | unknown | |
d1566 | train | Well, I don't think you following the guidelines when you're using images. The android documentation doesn't say anything about screen resolutions when dealing with images, it rather focuses on pixel density when referring image resources (usually drawables) which is explained here. Remember that you can have two types of images (as far as I know):
*
*Image resources (usually drawables)
*Image assets
When using drawables you have to focus on pixel density rather than screen resolution because as you have just found out a small (or regular) screen device can have exactly the same resolution as a large screen device, to top it off, sometimes a normal screen device (handset) can have a higher resolution than a large screen device (tablet) where obviously in this case the handset has a much higher pixel density. So, you need to follow their guidelines take a medium pixel density (mdpi) device as the baseline to design your image resources as follows...taking a 96px image as an example...
*
*for a medium density device (mdpi) provide an image with 96px in the drawable folder...this is your baseline
*then, target a high pixel density(hdpi) device by multiplying your baseline image by 1.5...that is, 96x1.5 = 144px...place this image inside the drawable-hdpi folder with exactly the same name
*a x-large pixel density device image would be the baseline image multiplied by 2 (96x2=192px). This goes inside the drawable-xhdpi folder
*for an xx-large picel density (xxhdpi) device multiply the baseline image by 3 (96x3=288) and place it inside the drawable-xxhdpi folder
Notice in the link provided that you don't need to provide an image for a device with a low pixel density since Android scales it down from mdpi without any problems...
Note: Android also supports low-density (LDPI) screens, but you normally don't need to create custom assets at this size because Android effectively down-scales your HDPI assets by 1/2 to match the expected size.
In your case, whats happening is that your Galaxy tablet has a lower pixel density and Android down-scales the image from a xxhdpi to whatever density the tablet has (hdpi or xhdpi)....so, it your image is a 512px image Android would down-scale it to 341px for xhdpi or 256px for an hdpi device.
If you follow these guidelines and focus on pixel density, you should be fine. However, for images in the assets folder there's no much you can do apart from using the ScaleType enum or using stretchable 9-patch images
Hope this helps
Update
Actually, according to this link, the Galaxy Tab 2 has mdpi screen, which means your image will be scale down three times from xxhdpi. You should provide the same images with different sizes inside the appropriate drawable-x folders
A: I know its a way too late but recently I faced the same issue about the way app launcher icons looks on a tablet and they are blurry. I'm sure that AOS honestly chooses mdpi drawables for tablets with mdpi display density and thats the problem. So I solved this by placing smartphones icons to a tablet resources dirs as following (left column - usual smartphone drawables-density and the right - tablet dirs):
drawable-xhdpi -> drawable-large-mdpi (these are 96x96px)
drawable-xxhdpi -> drawable-large-hdpi (these are 144x144px)
drawable-xxxhdpi -> drawable-large-xhdpi (these are 192x192px)
drawable-xxxhdpi -> drawable-xlarge (these are 192x192px)
I'm not sure if last two has to be 288x288 px but since I don't have such icons in the project I guess 192x192 should be enough. | unknown | |
d1567 | train | Your ThreadPoolTaskExecutor has too many threads. CPU spend lot of time to switch context between threds. On test you run just your controller so there are no other threads (calls) that exist on production. Core problem is waiting for DB, because it is blocking thread
Solutions
*
*set pool size smaller (make some experiment)
*remove executor and use actor system like Akka for save operation.
*Most important use batch to save objects in DB. There will be only one call per e.g. 1000 objects not 1k calls for 1k objects > JPA/Hibernate improve batch insert performance
A: It looks like you are turning the wrong knob.
In your first version you had up to N threads banging your database. With N being configured somewhere in your servlet container. And also doing the servlet thingy, accepting connections and stuff.
Now you created 200 additional threads, which do basically nothing but hitting the database. While the previous threads do their connection handling, request parsing thing. So you increased the load on the database and you added the load do to context switching (except when you have multiple hundred cores).
And for some weird reason, your database didn't get any faster.
In order to improve, reduce the number of threads in your thread pool which hits the database. Measure how many threads the database can handle before performance degrades.
Make the queueCapacity large enough to cover the request spikes you need to handle.
Implement something that gets a meaningfull answer to the user when this isn't sufficient. Something like "Sorry ..."
And then take care of the real issue: How to make your database handle the requests fast enough.
It might be that some db tuning is in place, or you need to switch to a different database system, or maybe the implementation of the save method needs some tuning ...
But all this is for a different question.
A: the bottle neck in your case are transactions (DB)
here's some proposals :
*
*if it's not necessary that data has to be instantly saved just use an asynchronous job to do it (JMS, In Memory Queue, etc)
*You may consider to load DB into RAM | unknown | |
d1568 | train | This should avoid loading the CSS with this conditional (maybe apply it somewhere else in your code):
function add_css_main($css){
if( !is_admin() ) {
add_action( 'wp_enqueue_scripts', array($this, 'main_css_setup'),10,1 );
do_action( 'wp_enqueue_scripts', $css );
}
} | unknown | |
d1569 | train | I‘m afraid that you will have no chance to fall back to just http. You are forced to use https. You need to configure insecure registries in your docker client.
This might help: https://docs.docker.com/registry/insecure/ | unknown | |
d1570 | train | A rigidbody will not move until some kind of force is applied to it, or you use it's MovePosition method. Here is a link ... https://docs.unity3d.com/ScriptReference/Rigidbody.MovePosition.html | unknown | |
d1571 | train | You can subclass your textField:
class TextField: UITextField {
private var leftLayer: CALayer!
override func awakeFromNib() {
super.awakeFromNib()
//create your layer here, and keep reference in leftLayer for further resize, color...
}
} | unknown | |
d1572 | train | The title is incorrectly phrased.
"utf8" is a "character set"
"utf8_bin" is a "collation" for the character set utf8.
You cannot change character_set... to collation. You may be able to set some of the collation_% entries to utf8_bin.
But none of that a valid solution for the problem you proceed to discuss.
Probably you can find more tips here: Trouble with UTF-8 characters; what I see is not what I stored
To help you further, we need to see the symptoms that got you started down this wrong path. | unknown | |
d1573 | train | Sifting through CSS for a few minutes and I found a solution, I have made a list of corrections.
Here is the CSS code on pastebin, it does all the fixes I have mentioned below.
Manual Fix
Find #middlewrapper #content .contentbox, disable float:left.
#middlewrapper #content .contentbox {
width: 650px;
padding: 15px;
/* float: left; */
background-color: white;
}
Find #middlewrapper #content .contentbox_shadow, disable float:left.
#middlewrapper #content .contentbox_shadow {
width: 690px;
height: 20px;
/* float: left; */
background-image: url('http://xn--nstvedhandel-6cb.dk/naestved/public/css/../images/content_skygge.png');
background-repeat: no-repeat;
}
Find #middlewrapper #content, disable float:left.
#middlewrapper #content {
width: 690px;
/* float: left; */
}
Finally, find #middlewrapper #content .contentbox, after it's definition, place #content.
#content {
width: 680px;
float: left;
}
Do not delete or alter the definition of #middlewrapper #content found a few lines later. | unknown | |
d1574 | train | The latest and most accurate update on timing of feature availability in Azure Government is always the Azure Government feedback forum.
As such, you should go by the date posted in the Azure Container Service (ACS/AKS) in Azure Government feedback entry which at this point in time is preview in CY18Q3. Vote for the feedback entry so that you get updates as they become available.
Side note: The Trends in Government Software Developers article dates back to January 2018 whereas the latest response to the dates back to February 2018. | unknown | |
d1575 | train | The position does not change! If you look closely at your linked images, you'll see that your fingerpainting does not move relative to the corner of the photo. In other words, you are saving the drawings' positions relative to the screen rather than relative to the current scroll position of the photo.
When you save, you have to take into account the fact that the background photo is cropped and/or scaled.
A: Maintain a paint/erase mode. When in paint/erase mode, disallow panning and zooming. When paint/erase is turned off, get the drawing cache and set it to imageview. Now the changes are permanently in the bitmap. So you can pan/zoom now and again enter the paint/erase mode to edit further. | unknown | |
d1576 | train | You're not showing us your connection string, but I'm assuming you're using some kind of AttachDbFileName=.... approach.
My recommendation for this would be: just don't do that. It's messy to fiddle around with .mdf files, specifying them directly by location, you're running into problems when Visual Studio wants to copy that file around - just forget about all that.
I would
*
*create the database on the SQL Server Express instance (CREATE DATABASE ..... in Mgmt Studio)
*talk to the database by its logical name - not a physical file name
So I would put my database onto the SQL Server Express server instance, and then use a connection string something like this:
Server=.\SQLEXPRESS;Database=MyShinyDatabase;Integrated Security=SSPI;
No messy file names, Visual Studio won't have to copy around files at runtime or anything, your data is on the server and can be used and administered there - seems like the much cleaner and much nicer approach to me. | unknown | |
d1577 | train | onRow seems expect a "factory" function which returns the actual event handlers.
(defn on-row-factory [record row-index]
#js {:onClick (fn [event] ...)
:onDoubleClick (fn [event] ...)})
;; reagent
[:> Table {:onRow on-row-factory} ...]
You don't need to use the defn and could just inline a fn instead. | unknown | |
d1578 | train | Create database connection in another file and assign to some variable.
After that import and use it wherever you need to get/modify data in database.
P.S. Don't do any app imports in that file to avoid circular dependency.
P.P.S. Link provided by @wwii should help with examples | unknown | |
d1579 | train | As @shmosel said, you can do it like this:
public static void sortedArrayByRowTot() {
int [][] array = {{4,5,6},{3,4,5},{2,3,4}};
Arrays.sort(array, Comparator.comparingInt(a -> IntStream.of(a).sum()));
}
A: I was able to solve my question. Thanks.
public void sortedArrayByRowTot() {
//Creates tempArray2 to copy salaryArray into
int [][] tempArray2 = new int [salaryArray.length][salaryArray[0].length];
//Copies salaryArray into tempArray2
for (int i = 0; i < salaryArray.length; i++) {
for (int j = 0; j < salaryArray[i].length; j++) {
tempArray2[i][j] = salaryArray[i][j];
}
}
//Creates rowSum array to store sum of each row
int [] rowSums = new int [tempArray2.length];
for (int i = 0; i < tempArray2.length; i++) {
for (int j = 0; j < tempArray2[0].length; j++) {
rowSums[i] += tempArray2[i][j];
}
}
//Modified Bubble Sort of rowSum array (highest to lowest values)
int temp;
int i = 0;
for(int j = rowSums.length; j > 0; j--){
boolean isSwap = false;
for (i = 1; i < j; i++) {
if(rowSums[i-1] < rowSums[i]) {
temp = rowSums[i-1];
rowSums[i-1] = rowSums[i];
rowSums[i] = temp;
isSwap = true;
//swaps rows in corresponding tempArray2
int [] temp2 = tempArray2[i-1];
tempArray2[i-1] = tempArray2[i];
tempArray2[i] = temp2;
}
}
if(!isSwap){
break;
}
}
//Prints sorted array
System.out.println("Sorted array: ");
for (i = 0; i < tempArray2.length; i++) {
for (int j = 0; j < tempArray2[i].length; j++) {
System.out.print("$"+ tempArray2[i][j] + " ");
}
System.out.println();
}
}
A: You may try this way. That I have solved.
public class Solution{
public static void sortedArrayByRowTot() {
int [][] salaryArray = { {4,5,6},{3,4,5},{2,3,4} };
int [][] tempArray2 = new int [salaryArray.length][salaryArray[0].length];
for (int i = 0; i < salaryArray.length; i++) {
for (int j = 0; j < salaryArray[i].length; j++) {
tempArray2[i][j] = salaryArray[i][j];
}
}
// Buble Sort to store rowSums
int [] rowSums = new int [tempArray2.length];
for (int i = 0; i < tempArray2.length; i++) {
for (int j = 0; j < tempArray2[0].length; j++) {
rowSums[i] += tempArray2[i][j];
}
}
//Buble Sort by Rows Sum (Lowest Value to Highest)
int temp;
int i = 0;
for(int j = rowSums.length; j > 0; j--){
boolean isSwap = false;
for (i = 1; i < j; i++) {
if(rowSums[i-1] > rowSums[i]) {
temp = rowSums[i-1];
rowSums[i-1] = rowSums[i];
rowSums[i] = temp;
isSwap = true;
//swaps rows in corresponding tempArray2
int [] temp2 = tempArray2[i-1];
tempArray2[i-1] = tempArray2[i];
tempArray2[i] = temp2;
}
}
if(!isSwap){
break;
}
}
/** No Need.
for (int k = 0; k < tempArray2.length; k++) {
temp = tempArray2[i-1][k];
tempArray2[i-1][k] = tempArray2[i][k];
tempArray2[i][k] = temp;
}
*/
for (int b = 0; b < tempArray2.length; b++) {
for (int c = 0; c < tempArray2[b].length; c++) {
System.out.print(tempArray2[b][c] + " ");
}
}
}
public static void main(String[] args) {
sortedArrayByRowTot();
}
} | unknown | |
d1580 | train | You should manually keep track of all "forms" in a list somewhere, then just iterate over that list and close them.
If for whatever reason this is not possible you could use JFrame.getWindows() which accesses all Windows in the application
for (Window each : JFrame.getWindows()) {
each.setVisible(false);
}
Note: This may not properly shutdown the forms, e.g. remove listeners/stop threads the forms may be using... | unknown | |
d1581 | train | You must first extract the number from the string. If the text part ("R") is always separated from the number part by a "|", you can easily separated the two with Split:
Dim Alltext_line = "R|1"
Dim parts = Alltext_line.Split("|"c)
parts is a string array. If this results in two parts, the string has the expected shape and we can try to convert the second part to a number, increase it and then re-create the string using the increased number
Dim n As Integer
If parts.Length = 2 AndAlso Integer.TryParse(parts(1), n) Then
Alltext_line = parts(0) & "|" & (n + 1)
End If
Note that the c in "|"c denotes a Char constant in VB.
A: An alternate solution that takes advantage of the String type defined as an Array of Chars.
I'm using string.Concat() to patch together the resulting IEnumerable(Of Char) and CInt() to convert the string to an Integer and sum 1 to its value.
Raw_data = "R|151"
Dim Result As String = Raw_data.Substring(0, 2) & (CInt(String.Concat(Raw_data.Skip(2))) + 1).ToString
This, of course, supposes that the source string is directly convertible to an Integer type.
If a value check is instead required, you can use Integer.TryParse() to perform the validation:
Dim ValuePart As String = Raw_data.Substring(2)
Dim Value As Integer = 0
If Integer.TryParse(ValuePart, Value) Then
Raw_data = Raw_data.Substring(0, 2) & (Value + 1).ToString
End If
If the left part can be variable (in size or content), the answer provided by Olivier Jacot-Descombes is covering this scenario already.
A: Sub IncrVal()
Dim s = "R|1"
For x% = 1 To 10
s = Regex.Replace(s, "[0-9]+", Function(m) Integer.Parse(m.Value) + 1)
Next
End Sub | unknown | |
d1582 | train | Just for reference here is the code I used.
$this->setWidget('logo_image', new sfWidgetFormInputFileEditable(array(
'file_src' => 'uploads/logos/'.$this->getObject()->getFilename(),
'edit_mode' => !$this->isNew()
)));
$validatorOptions = array(
'max_size' => 1024*1024*10,
'path' => sfConfig::get('sf_upload_dir').'/logos',
'mime_type_guessers' => array(),
'required' => false
);
if ($this->isNew())
{
$validatorOptions['required'] = true;
}
$this->setValidator('logo_image', new sfValidatorFile($validatorOptions));
$this->setValidator('logo_image_delete', new sfValidatorString(array('required' => false)));
A: I found a workaround. I had the page check to see if it was set to no-pic.png and then it displays a no-pic.png in another location. That way when it goes to upload a picture, it won't delete it. :) Thanks for your help though. | unknown | |
d1583 | train | What Animations are you using? I tried it with a TranslateAnimation and RotateAnimation, it is working. Also where are you calling the startAnimations from? | unknown | |
d1584 | train | You don't really need regexp for this.
select(.value | ascii_downcase == "[email protected]") .id
But if you insist on it, below is how you perform a case-insensitive match using test/2.
select(.value | test("[email protected]"; "i")) .id | unknown | |
d1585 | train | The problem is here:
"consumes": []
The consumes keyword specifies the Content-Type header in requests. Since you are POSTing form data, it should be:
"consumes": ["application/x-www-form-urlencoded"]
Tip: You can paste your spec into http://editor.swagger.io to check for syntax errors. | unknown | |
d1586 | train | You can use string_to_array along with unnest to break your data into first an array and then separate rows.
select * FROM (
select name, date, unnest(string_to_array(data, '|')) as data from stuff
) AS sub
WHERE sub.data != '';
The WHERE clause is required to remove the empty strings at the beginning and end of your data. | unknown | |
d1587 | train | I don't know what the QByteArray type is, but I'll wager that it is an array of signed characters. As a result, when the high bit of a byte is a one, that sign bit is extended when converted to an integer which all gets exclusive-or'ed into your CRC at crc ^= (quint16)buf[pos];. So when you got to the 0xdf, crc was exclusive-or'ed with 0xffdf instead of the intended 0xdf.
So the issue is not the length, but rather the likelihood of having a byte with the high bit set.
You need to provide unsigned bytes, or fix the conversion, or do an & 0xff to the resulting byte before exclusive-or'ing with the CRC. | unknown | |
d1588 | train | The upshot is I was trying to find a cell in a table that was about to be presented. I wanted to set the table's accessibilityIdentifier to make it easier to find. After Googling to confirm it needed to be done in code rather than IB, I found a post suggesting I also needed to set
tableView.isAccessibilityElement = true
I didn't realise it all stopped working the minute I did that, because I made other changes as well. Once this property was set, I could no longer find any cells/staticTexts within the table. When I commented the code out, it all started magically working again, including recording tests. | unknown | |
d1589 | train | To use AVG() or any sort of aggregate functions in SQL, you need to have a GROUP BY for the other columns you're displaying.
Think of it this way, when you SELECT a column, you display rows. When you show an average, you show a single output. You can't put rows and a single output together.
You'll need to try something along the lines of:
SELECT col1, col2, AVG(col3)
FROM table1
GROUP BY col1, col2
A: I created a fiddle with your example, and you can see that the query as it is works. It is probably an error in a wrapping query, store procedure or function. | unknown | |
d1590 | train | You can create a "custom wrapper" for JMockit's @Tested annotation (ie, use it as a meta-annotation), but not for any of the other annotations, @Mock included. So, the answer is no, it's not possible. | unknown | |
d1591 | train | now, I found myself a solution to my problem. There I, do not use CGI but PHP an Pyton. Certainly, this solution is not very elegant, but it does what I want. In addition, I must perform some MySQL queries. All in all I can by the way increase the performance of the whole page.
My Code now looks like this:
index.html
<html>
<head>
<title>TEST</title>
<script src="jquery.js"> </script>
</head>
<body>
<script>
function ButClick(){
var TestVar = "'Hallo! This is a test'";
$.post('test.php',{var:TestVar},function(response) $('#TestDiv').html(response)});
}
</script>
<form><input type='button' onclick="ButClick()" value="Click Me!" /></form>
<div id='TestDiv'></div> </body>
</body>
</html>
test.php
<?php
$param1=$_POST['var'];
$command="python test.py $param1 $param2";
$buffer='';
ob_start(); // prevent outputting till you are done
passthru($command);
$buffer=ob_get_contents();
ob_end_clean();
echo "PHP and".$buffer;
?>
test.py
#path to your python interpreter
#!/usr/bin/python
#sys module to get access to the passed in parameters
import sys
# the first parameters in sys.argv[0] is the path to the current executing python script
param1=sys.argv[1]
PyAnswer="python back: " +param1
# send the result back to php
print (PyAnswer)
I hope, that I can help with these post some other people! | unknown | |
d1592 | train | I just put the following in my parent activity in the onCreate ..., then used a public interface like Rarw mentioned above.
gesturedetector = new GestureDetector(new MyGestureListener());
myLayout.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
bTouch = true;
return false;
} else {
gesturedetector.onTouchEvent(event);
bTouch = false;
return true;
}
}
});
And added the following to my parent activity and a gesturedetector to catch the desired events.
public boolean dispatchTouchEvent(MotionEvent ev) {
super.dispatchTouchEvent(ev);
return gesturedetector.onTouchEvent(ev);
} | unknown | |
d1593 | train | Update your rowDrag definition in the name column definition to the following:
rowDrag: (params) => {
if (params.data.name == "John") {
return false;
}
return true;
}
Demo. | unknown | |
d1594 | train | You can always change that field to:
upload = models.DateTimeField(auto_now_add=True, null=True)
that should fix that problem.
PS you should not name classes with snake_case. It's bad habit. | unknown | |
d1595 | train | " + a + " b: " + b);
return myJsonString;
}
}
Here's the Javascript I'm trying to get working:
$(document).ready(function () {
$('#iframesubmit').click(function () {
//var obj = { username: $("#txtuser").val(), name: $("#txtname").val() };
var obj = '[{ username: $("#password_old").val(), name: $("#password_new").val() }]';
$.ajax({
type: "POST", //was POST
contentType: "application/json; charset=utf-8",
url: "http://localhost/PasswordResetter/Resetter.svc",
//data: "",
data: JSON.stringify(obj),
//data: "{ 'a': '" + $("#password_old").val() + "', 'b': '" + $("#password_new").val() + "'}",//JSON.stringify(obj),
dataType: "json",
success: function (data) {
alert("Successfully register");
document.getElementById("results").value = "Response: " + data; //service.responseText;
$("#iframesubmit").click();
},error: function (xhr)
{
window.alert('error: ' + xhr.statusText);
}
});
});
});
And finally my web.config:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="webHttpBindingWithJsonP" crossDomainScriptAccessEnabled="true">
<security mode="Transport">
<transport clientCredentialType="None"></transport>
</security>
</binding>
</webHttpBinding>
<customBinding>
<binding name="CRMPoint.CRM.Services.PasswordResetter.customBinding0">
<!-- <binaryMessageEncoding /> -->
<httpTransport />
</binding>
</customBinding>
</bindings>
<services>
<service name="PasswordResetter">
<endpoint address="http://localhost/PasswordResetter/Resetter.svc" behaviorConfiguration="PasswordResetter.Service1AspNetAjaxBehavior"
binding="webHttpBinding" bindingConfiguration="webHttpBindingWithJsonP"
contract="PasswordResetter.IResetter" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
<service name="Test">
<endpoint address="http://localhost/PasswordResetter/Resetter.svc" binding="customBinding"
bindingConfiguration="CRMPoint.CRM.Services.PasswordResetter.customBinding0"
contract="PasswordResetter" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
<service name="PasswordResetter.Service1">
<endpoint address="http://localhost/PasswordResetter/Resetter.svc" behaviorConfiguration="PasswordResetter.Service1AspNetAjaxBehavior"
binding="webHttpBinding" contract="PasswordResetter.Service1" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="webHttpBehavior">
<webHttp helpEnabled="true" />
</behavior>
<behavior name="PasswordResetter.Service1AspNetAjaxBehavior">
<enableWebScript />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
<standardEndpoints>
<webScriptEndpoint>
<standardEndpoint name="test" crossDomainScriptAccessEnabled="true" />
</webScriptEndpoint>
</standardEndpoints>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>
</httpProtocol>
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
A: there are some issues in the code...
*
*Firstly the method decoration with WebInvoke is usually done in the
interface not in main class
*Second is the method name (test) and the UriTemplate="/Test" should be
same. It should be like as follows
*UriTemplate="/Test"
public string Test(string a, string b)
{
string myJsonString = (new JavaScriptSerializer()).Serialize("Hello World! A: " + a + " b: " + b);
return myJsonString;
}
*There is an issue where you do an ajax call to this method
Replace the following line
url: "http://localhost/PasswordResetter/Resetter.svc"
with
url: "http://localhost/PasswordResetter/Resetter.svc/Test"
Hope this will help.... | unknown | |
d1596 | train | since you pass getLastImportTime function to when helper method, it should explicitly return a promise, (but in getLastImportTime() you are returning nothing and when() is expecting you to pass a promise) otherwise the helper could evaluate it as an immediate resolved (or rejected) promise.
This could explain why it seems that function in pipe is executed before getLastImportTime()
So try to change your function like so
var getLastImportTime = function () {
...
database.open();
database.query("SELECT ...");
return buildPromise.promise();
}; | unknown | |
d1597 | train | just update your vue-loader. in recent weeks, it updates fast! from v16 back to v15. | unknown | |
d1598 | train | You can do it this way, but it might require several complex string expressions.
E.g. create a ForEach loop over .xls files, inside the loop add an empty script task, then a data flow to load this file. Connect them with a precedence constraint and make it conditional: precedence constraint expression will the check if file name does not end with -loaded.xls. You may either do it in script task or purely using SSIS expression on precedence constraint. Finally, add File System Task to rename the file. You may need to build new file name with another expression.
It might be easier to create two folders: Incoming for new unprocessed files, and Loaded for the files you've processed, and just move the .xls to this folder after processing without renaming. This will avoid the first conditional expression (and dummy script task), and simplify the configuration of File System task.
A: You can get the SQL File watcher Task and add it to your SSIS. I think this is a cleaner way to do what you want.
SQL File Watcher | unknown | |
d1599 | train | On second thought, let me expand on my comment:
You can't set Dockerfile environment variables to the result of commands in a RUN statement. Variables set in a RUN statement are ephemeral; they exist only while the RUN statement is active
If you don't have access to the host environment (to pass arguments to the docker build command), you're not going to be able to do exactly what you want.
However, you can add an ENTRYPOINT script to your container that will set up dynamic environment variables before the main process runs. That is, if you have in your Dockerfile:
ENTRYPOINT ["/docker-entrypoint.sh"]
And in /docker-entrypoint.sh you have:
#!/bin/bash
branch=$(git branch | sed -n -e 's/^\* \(.*\)/\1/p' | awk -Frelease/ '/release/{print $2}') \
&& if [[ "$branch" != qa* ]]; then branch=$(git log -1 --pretty | grep release\/ | awk -Frelease/ '/release/{print $2}' | awk -F: '{print $1}'); fi)
export EXPORT_ENV="$branch"
exec "$@"
Then the EXPORT_ENV environment variable would be available in the environment of your CMD process. | unknown | |
d1600 | train | I'm the pathos author. When I try your code, I don't get an error. However, if you are seeing a CPickle.PicklingError, I'm guessing you have an issue with your install of multiprocess. You are on windows, so do you have a C compiler? You need one for multiprocess to get a full install of multiprocess. | unknown |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.