text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: How to set the background of a custom shaped ImageButton in a RecyclerView? In a recyclerView I have list of imageButtons with a custom shape applied as the background of all ImageButtons. Each ImageButton currently has a solid color from a colorlist: colors[]
This is how it looks right now:
I want to put a icon.png in the place of index 0 (brown colored button) instead of the solid color. So far I have used many days of trying to find a solution myself but without any succses.
Here is all relevant code:
This is the code in the recyclerView adapter that sets the colors:
Resources resources = App.getAppContext().getResources();
String colors[] = resources.getStringArray(R.array.backgroundcolors);
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Drawable drawable = holder.colorButton.getBackground();
//This is here where each ImageButton gets a color from the colorlist colors[]
if (drawable instanceof GradientDrawable) {
GradientDrawable gd = (GradientDrawable) drawable.getCurrent();
gd.setColor(Color.parseColor(colors[position]));
//This does nothing
} else if (drawable instanceof RippleDrawable) {
RippleDrawable rd = (RippleDrawable) drawable;
int color = Color.parseColor(colors[position]);
rd.setColor(newColorStateList(color));
}
}
The colorStatList code for each imageButton:
private static ColorStateList newColorStateList(int color) {
int[][] states = new int[][]{
new int[]{android.R.attr.state_enabled}, // enabled
new int[]{-android.R.attr.state_enabled}, // disabled
};
int[] colors = new int[]{
color, color
};
return new ColorStateList(states, colors);
}
My Custom button for the recyclerView Adapter:
public class ColorButton{
private ImageButton button;
private String color;
public static List<ColorButton> colorButtonList;
public ColorButton(ImageButton button, String color) {
this.button = button;
this.color = color;
}
static ColorButton colorButton = new ColorButton(new ImageButton(App.getAppContext()), null);
public static List<ColorButton> initColorButtons(){
colorButtonList = new ArrayList<>();
Resources resources = App.getAppContext().getResources();
String colors[] = resources.getStringArray(R.array.backgroundcolors);
for(int i=0; i<colors.length; i++){
colorButtonList.add(new ColorButton(new ImageButton(App.getAppContext()), colors[i]));
}
return colorButtonList;
}
You may wonder why I have String color;
This is for setting the background color of my app when the user clicks on a colorbutton:mEditText.setBackgroundColor(Color.parseColor((mColorButtons.get(position).getColor())));
A: Try this:
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
if(position ==0){
holder.colorButton.setBackgroundResource(R.drawable.colorpicker2);
}
else
{
GradientDrawable gd = context.getResources().getDrawable(R.drawable.bbshape);
gd.setColor(Color.parseColor(colors[position]));
holder.colorButton.setBackGroundDrawable(gd);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36387448",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to clean JVM heap memory in spark scala or pyspark How to clean my JVM occupied memory in spark scala streaming application. I am running streaming job which is in 60 sec interval of time. For my first six hours no issue after that, I am facing JVM heap memory issue. Is there any way programmatically I can clean my GC or JVM memory in spark scala.
In my application, I am using Dataframe, registertemptable also end of my program I am writing the result into HDFS. Presently in my application spark SQL context level, I am uncaching, like this any other way we can release the memory?
Error msg: Exception in thread "dag-scheduler-event-loop" java.lang.outofmemoryError: Java heap space
Thanks
Venkat
A: I would suggest you to see if there is any thread leak in the application.
You can look at the thread dump in the application master near the executor logs.
Try to set this parameter. --conf spark.cleaner.ttl=10000.
If you are using cache I would suggest you to use persist() it in both memory and disc
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46245554",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Wolfram alpha and floating point arithmetic (loss of significance) I'm studying floating point aritmetic. Suppose we are in double precision. We know that when we subtract two numbers which has "almost" the same magnitude, the relative error is large.
In MatLab command window, for instance, if I compute
2.0000001-2.0
I obtain 9.99999998363421e-08
and with a relative error errRel = 1.63657882716964e-09 which is not negligible.
But If I do that in Wolfram alpha (or with the calculator of my laptop), I actually obtain the right result, which is 1e-7.
So, my question is: why is that? I thought that both MatLab and the calculator of my laptop used the floating point arithmetic in the same way
A: There are two possible causes of seeing exactly 1e-7 on subtracting 2.0000001-2.0.
One is that many systems round to a reasonable number of digits on output. The exact conversion to decimal of IEEE 64-bit binary 2.0000001-2.0 is 9.9999999836342112757847644388675689697265625E-8. Some systems round to a limited number of significant digits, and might print that as 1e-7. On the other hand, Java, for example, delivers by default enough digits to distinguish the original value from any other double, and prints 9.999999983634211E-8
The other possible cause is if the arithmetic is being done in decimal, in which case the real numbers 2.0000001, 2, and their difference are all exactly representable because they are all decimal fractions. You would need to calculate something like 1/3 to see rounding error.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60533661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: ChildrenRect always returns 0 I have a Flickable item in where I want to put a customized flow component, so I created the Flickable like this:
import QtQuick 2.0
import UICore.Layouts 1.0 as Layouts
Flickable{
anchors.fill: parent;
contentWidth: parent.width;
contentHeight: flow.childrenRect.height;
Component.onCompleted: {
console.log("The content height is: " + contentHeight);
}
}
Then in my main.qml I have this (The file above is MyFlickable, and the MyFlow is a flow with specific properties):
MyFlickable{
....
MyFlow{
id: flow
...
}
}
This works great but the problem is that I want to be able to reuse this item with as little overhead as possible. Setting the id inside of my MyFlow doesn't work, and I tried this
contentHeight: contentItem.childrenRect.height
as suggested in here under contentWidth section: http://doc.qt.io/qt-5/qml-qtquick-flickable.html#contentItem-prop
but that always returns 0. I've tried a couple of other ways to receive onCompleted signals but I get the same luck. This doesn't work for example:
contentHeight: children[0].childrenRect.height
Which in my mind should be the same as accessing the item through the id, bu apparently not.
So my question is: how do I get to height of my flow after all the components have been added?
Thanks in advance!
A: This wlil achieve what you want:
contentHeight: contentItem.children[0].childrenRect.height
From Qt docs
Items declared as children of a Flickable are automatically parented to the Flickable's contentItem. This should be taken into account when operating on the children of the Flickable; it is usually the children of contentItem that are relevant.
But I must say it is bad practice for a component to make assumptions about things outside its own QML file, as it makes the component difficult to reuse. Specifically in this case the Flickable is making the assumption that its first child is of a Component type that makes use of the childrenRect property. Your MyFlow component does, but many other components do not, for example an Image.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45088883",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Python 3 Multiprocessing and openCV problem with dictionary sharing between processor I would like to use multiprocessing to compute the SIFT extraction and SIFT matching for object detection.
For now, I have a problem with the return value of the function that does not insert data in the dictionary.
I'm using Manager class and image that are open inside the function. But does not work.
Finally, my idea is:
Computer the keypoint for every reference image, use this keypoint as a parameter of a second function that compares and match with the keypoint and descriptors of the test image.
My code is:
# %% Import Section
import cv2
import numpy as np
from matplotlib import pyplot as plt
import os
from datetime import datetime
from multiprocessing import Process, cpu_count, Manager, Lock
import argparse
# %% path section
tests_path = 'TestImages/'
references_path = 'ReferenceImages2/'
result_path = 'ResultParametrizer/'
#%% Number of processor
cpus = cpu_count()
# %% parameter section
eps = 1e-7
useTwo = False # using the m and n keypoint better with False
# good point parameters
distanca_coefficient = 0.75
# gms parameter
gms_thresholdFactor = 3
gms_withRotation = True
gms_withScale = True
# flann parameter
flann_trees = 5
flann_checks = 50
#%% Locker
lock = Lock()
# %% function definition
def keypointToDictionaries(keypoint):
x, y = keypoint.pt
pt = float(x), float(y)
angle = float(keypoint.angle) if keypoint.angle is not None else None
size = float(keypoint.size) if keypoint.size is not None else None
response = float(keypoint.response) if keypoint.response is not None else None
class_id = int(keypoint.class_id) if keypoint.class_id is not None else None
octave = int(keypoint.octave) if keypoint.octave is not None else None
return {
'point': pt,
'angle': angle,
'size': size,
'response': response,
'class_id': class_id,
'octave': octave
}
def dictionariesToKeypoint(dictionary):
kp = cv2.KeyPoint()
kp.pt = dictionary['pt']
kp.angle = dictionary['angle']
kp.size = dictionary['size']
kp.response = dictionary['response']
kp.octave = dictionary['octave']
kp.class_id = dictionary['class_id']
return kp
def rootSIFT(dictionary, image_name, image_path,eps=eps):
# SIFT init
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
sift = cv2.xfeatures2d.SIFT_create()
keypoints, descriptors = sift.detectAndCompute(image, None)
descriptors /= (descriptors.sum(axis=1, keepdims=True) + eps)
descriptors = np.sqrt(descriptors)
print('Finito di calcolare, PID: ', os.getpid())
lock.acquire()
dictionary[image_name]['keypoints'] = keypoints
dictionary[image_name]['descriptors'] = descriptors
lock.release()
def featureMatching(reference_image, reference_descriptors, reference_keypoints, test_image, test_descriptors,
test_keypoints, flann_trees=flann_trees, flann_checks=flann_checks):
# FLANN parameter
FLANN_INDEX_KDTREE = 1
index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=flann_trees)
search_params = dict(checks=flann_checks) # or pass empty dictionary
flann = cv2.FlannBasedMatcher(index_params, search_params)
flann_matches = flann.knnMatch(reference_descriptors, test_descriptors, k=2)
matches_copy = []
for i, (m, n) in enumerate(flann_matches):
if m.distance < distanca_coefficient * n.distance:
matches_copy.append(m)
gsm_matches = cv2.xfeatures2d.matchGMS(reference_image.shape, test_image.shape, keypoints1=reference_keypoints,
keypoints2=test_keypoints, matches1to2=matches_copy,
withRotation=gms_withRotation, withScale=gms_withScale,
thresholdFactor=gms_thresholdFactor)
#%% Starting reference list file creation
reference_init = datetime.now()
print('Start reference file list creation')
reference_image_process_list = []
manager = Manager()
reference_image_dictionary = manager.dict()
reference_image_list = manager.list()
for root, directories, files in os.walk(references_path):
for file in files:
if file.endswith('.DS_Store'):
continue
reference_image_path = os.path.join(root, file)
reference_name = file.split('.')[0]
image = cv2.imread(reference_image_path, cv2.IMREAD_GRAYSCALE)
reference_image_dictionary[reference_name] = {
'image': image,
'keypoints': None,
'descriptors': None
}
proc = Process(target=rootSIFT, args=(reference_image_list, reference_name, reference_image_path))
reference_image_process_list.append(proc)
proc.start()
for proc in reference_image_process_list:
proc.join()
reference_end = datetime.now()
reference_time = reference_end - reference_init
print('End reference file list creation, time required: ', reference_time)
A: I faced pretty much the same error. It seems that the code hangs at detectAndCompute in my case, not when creating the dictionary. For some reason, sift feature extraction is not multi-processing safe (to my understanding, it is the case in Macs but I am not totally sure.)
I found this in a github thread. Many people say it works but I couldn't get it worked. (Edit: I tried this later which works fine)
Instead I used multithreading which is pretty much the same code and works perfectly. Of course you need to take multithreading vs multiprocessing into account
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58869053",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Ionic android app works fine on mobile data but failed to send http request on wifi I am developing app on ionic and angularjs.
Webservices deployed on cloud based server.
My android app is working fine on mobile data but not in wifi.
App Permissions
<uses-sdk android:minSdkVersion="16" android:targetSdkVersion="23" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission android:name="${applicationId}.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="${applicationId}.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.INTERNET" />
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38890488",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to sort a collected based on descending order in laravel? I am very new to the laravel , i have one collection i want to sort the collection based on the id by using sortBy() method but it's not working,please help me to achieve this thing ..
$new=collect($transformed['data']);
$v= $new->sortByDesc(function($prod,$key){
return count($prod['id']);
});
dd($v->all());
error:- count(): Parameter must be an array or an object that implements Countable
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70797549",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why does this `while` loop not process all records when it changes the data? I have a PHP while loop in a WordPress script that only seems to process half of the records it's supposed to when it modifies the data, and I'm struggling to see why this is happening.
I'm writing a WP-CLI script that will set a meta with key reviewed and value 1 on all comments that don't already have it. My script looks like this:
class Mark_Comments_Reviewed {
public function __invoke() {
$limit = 100;
$offset = 0;
while ( $comment_ids = $this->get_unreviewed_comments( $limit, $offset ) ) {
array_walk(
$comment_ids,
function ( $comment_id ) {
$comment_id = (int) $comment_id;
$this->process_comment( $comment_id );
}
);
$offset += $limit;
}
}
protected function get_unreviewed_comments( int $limit, int $offset ): array {
global $wpdb;
return $wpdb->get_col(
$wpdb->prepare(
"SELECT DISTINCT comments.comment_ID
FROM wp_comments AS comments
AND comments.comment_ID NOT IN (
SELECT meta.comment_id
FROM wp_commentmeta AS meta
WHERE meta.meta_key = 'reviewed'
)
LIMIT %d
OFFSET %d",
$limit,
$offset
)
);
}
protected function process_comment( int $comment_id ): bool {
return ! ! update_comment_meta( $comment_id, 'reviewed', (int) true );
}
}
(The wp_commentmeta table has fields meta_id, meta_key,meta_valueandcomment_id, and the last field relates to the ID of a comment record in thewp_comments` table.)
I have 810 comments without the meta. When I run the script like this, it finishes having processed 410. When I replace the $this->process_comment( $comment_id ); line with return true, the script "processes" all 810.
With the process_comment call restored, I have to run the script four times to process all 810 records.
*
*The first time, the script loops 6 times and processes 410 records. The database confirms 400 remain. Apart from the fact the loop finishes early, this is weird because 6 batches of 100 should be 600.
*The second time, it loops 3 times and processes 200 records, leaving 200. So it's done 200 instead of 300.
*The third time, it loops 2 times and processes 100 records, leaving 100.
*The fourth time it loops once and leaves no unchanged records.
Clearly something in the updating of the comment metas is causing the loop to finish before it should. Am I missing something obvious?
EDIT
I've found the script is only processing every other batch of 100 records.
A: Aaaargh! It was the offset! When I remove it, the script processes all the records as intended.
The first iteration of the loop processed the first 100 records, removing them from the set of records that didn't have the meta value. This left 710. But the next iteration started from offset 100, which meant the first 100 of those 710 weren't processed. I didn't need an offset – I just needed to select the first batch of remaining records each time.
The corrected script is
class Mark_Comments_Reviewed {
public function __invoke() {
$limit = 100;
while ( $comment_ids = $this->get_unreviewed_comments( $limit ) ) {
array_walk(
$comment_ids,
function ( $comment_id ) {
$comment_id = (int) $comment_id;
$this->process_comment( $comment_id );
}
);
}
}
protected function get_unreviewed_comments( int $limit ): array {
global $wpdb;
return $wpdb->get_col(
$wpdb->prepare(
"SELECT DISTINCT comments.comment_ID
FROM wp_comments AS comments
AND comments.comment_ID NOT IN (
SELECT meta.comment_id
FROM wp_commentmeta AS meta
WHERE meta.meta_key = 'reviewed'
)
LIMIT %d"
$limit
)
);
}
protected function process_comment( int $comment_id ): bool {
return ! ! update_comment_meta( $comment_id, 'reviewed', (int) true );
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61588877",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Instantiating class with parameterized constructor from COM Is it possible to call the parameterized constructor with COM?
I am going to create an instance of C# class which has parameterized constructor with COM.
Now it raises the Memory Excpetion. so I am not sure about instantiation of C# class carrying the parameterized constructor with COM. So Please let me know about the same.
My C# constructor is
public GetNumberFromClass(NumberClass number)
{
}
C++ Constructor:
NumberFromC#::NumberFromC#
{
getNumberFromClassPtr.CreateInstance(__uuidof(GetNumberFromClass));
}
and the pointer getNumberFromClassPtr throws memory exception as it comes NULL .
A: That's not possible, COM doesn't have a mechanism to pass arguments to a constructor. This is most visible in your C++ snippet, you specified the GUID of the class with the __uuidof keyword as required but you didn't pass a NumberClass argument. You can't.
What goes wrong next is that you didn't check for an error, CreateInstance() returns an HRESULT. Which would have told you that the method failed. The embedded interface pointer is still NULL and that's going to blow your program with an access violation when you just keep motoring on.
Start fixing this by first getting rid of that constructor in your C# class, it must have a default constructor to be usable by COM. Add a property of type NumberClass so you can set that value after the object is created. And of course improve the error handling in your C++ code, these kind of failures just become completely undiagnosable if you don't have any. You must check the return value of CreateInstance() and you must add try/catch blocks in the code that uses the object so you can catch the _com_error exceptions that will be thrown when a method call fails.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19289427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How can I use Google Chrome as a node.js server? I copy/pasted a node js hello world example into an html file
<html>
<head>
<script>
var http = require("http");
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
</script>
</head>
</html>
I'm using a Chrome app called OK 200! Server to make this page available at http://127.0.0.1:8887/
The ideal solution would work on a Google Chromebook.
When I run this it gives error:
Uncaught ReferenceError: require is not defined(…)
So that implies several features unique to node won't be embedded in Chrome. Is there an extension, chrome app, or native client app that would make those features available and still leverage the v8 engine already embedded in Chrome?
A: I'm not really sure about your goal ? Are you trying to run a server from a client web browser ? I'm not sure this is possible for many reason (as security for example)... I think you need to read this !
If you're just trying to run a node server on your localhost (127.0.0.1), you need to install nodejs on your computer Node.js, then you need to save your nodejs example in javascript file (named "myServer.js" for example) and run node in CLI using:
node path/to/myServer.js
And about:
Uncaught ReferenceError: require is not defined
you should see #19059580
Best regards,
Tristan
A: You could use something like electron.
It basically gives you node.js and chromium and enables you to build cross-platform desktop apps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40567572",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Efficient way to store SKLearn Birch model in Snowflake (and bypass 8MB binary limit) my code is exactly that on the answer by @SimonD in this post Store and retrieve pickled python objects to/from snowflake. However I am now running into an error
Programming Error: 100145 (22000): Binary value '800.....' is too long and would be truncated.
The object I am trying to persist is a clustering model (Birch) from skLearn. I am wondering if there is a better method for storing sklearn models in snowflake.
Thanks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64056846",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I enter data in array from a text file in JavaScript? I would like to populate an array using the data in text file in JavaScript. The data in text file is in the following format:
0.1 0.5
0.2 0.8
0.3 0.7
0.4 0.9
0.5 0.2
and so on..
A: Some browsers support opening files in JavaScript through the FileAPI. If you want a more cross-browser solution, you'll have to use a java/swf applet, or you'll need to pass the file to a PHP server and get back its content through AJAX.
Yes, it's that complex to do something as simple as opening a file in JS. It wasn't made for this purpose, and it would be a security issue if JS could easily access any file in your PC.
As for how to parse the data, look at String.split like Blazemonger suggested, or learn how to do regular expressions.
Finally, you could store the file in this format:
[0.1, 0.5, 0.2, 0.8]
And call JSON.parse(filecontent) and it would return an array with the values. JSON is the standard way to store JS objects in files.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29833642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Calling powershell script in VBA with return value Let's say I have a powershell script sorta like this:
'Hey'
Which I want to call in VBA sorta like this:
Sub CallPowerShell()
Call Shell("powershell.exe -ExecutionPolicy Bypass C:\Users\chm\Documents\5.ps1")
End Sub
I know this works as a console window briefly pops up with the word 'Hey' in it. What I really want however, is to use this string in my VBA code.
Is there a simple way how to get a return value from a powershell script through VBA?
Ideally it would be something like this:
Dim x As String
Sub CallPowerShell()
x = Shell("powershell.exe -ExecutionPolicy Bypass C:\Users\chm\Documents\5.ps1")
End Sub
But that just sets x to seemingly random numbers like 70640 or 30960.
I could have the powershell script write the value I want to a file and then read the file in VBA but it'd be really nice if I could skip that so I figured I'd ask here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52034757",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Change File Permission in Python File System I want to change permission of file inside python file system (pyfilesystem).
Here's the code I have:
fslocal = fs.osfs.OSFS(localdir, create=True, thread_synchronize=True)
fslocal.setcontents('/file1', b'This is file 1')
Now I want to change file permission of file 1. I am using os.chmod for this
os.chmod(localdir + '/file1', stat.S_IWOTH)
However, I get this error:
Traceback (most recent call last):
File "/Users/user/.conda/envs/scram/lib/python3.4/site-packages/fs/errors.py", line 257, in wrapper
return func(self,*args,**kwds)
File "/Users/user/.conda/envs/scram/lib/python3.4/site-packages/fs/osfs/__init__.py", line 251, in listdir
listing = os.listdir(sys_path)
PermissionError: [Errno 13] Permission denied: '/Users/user/Documents/tests/function/arwan/localfs/file1
Can you please tell me if it is possible to do it and how?
Thanks.
A: One problem is that it appears you're calling chmod with the intent of adding a single permission bit. In fact, you are setting all of the permission bits, so the call is trying to clear all of them except the one you want set. Assuming you're on a Unix system, you will presumably want to set the user and group bits as well, including the read and execute bits.
You can do the following:
st = os.stat(path)
old_mode = st.st_mode
new_mode = old_mode | stat.S_IWOTH
os.chmod(path, new_mode)
Hopefully that will help you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33261630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Access store in ember.view How we can access this.store in Ember.view ?
I tried inject method , but it doesn't work for me . Is there any way to do this ?
A: This is an antipattern you want to send an action to the controller and do you work with the store in the controller.
However if you have to inject the store into the view you would do this.
Ember.onLoad('Ember.Application', function(Application) {
Application.initializer({
name: "store",
initialize: function(container, application) {
application.register('store:main', application.Store);
...
}
container.lookup('store:main');
}
});
Application.initializer({
name: "injectingTheStore",
initialize: function(container, application) {
application.inject('view', 'store', 'store:main');
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21465390",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to sort MongoDB results by element in array that matches a condition? I have a collection of places which is like this :
{
"_id" : ObjectId("575014da6b028f07bef51d10"),
"name" : "MooD",
.
.
.
"categories" : [
{
"categoryList" : [Nightlife, Bar],
"weight" : 8
},
{
"categoryList" : [Restaurant, Italian Restaurant],
"weight" : 4
}
]
}
I want to search in places by a category, for example "Bar".
So, I look into categories' categoryList if there is "Bar".
After that, I want to sort by the weight of the matched category's weight,
so that the above place (where Bar weight is 8) appears before another place where Bar weight is 5.
A: You have to use aggregation framework.
Check this:
db.mongo.aggregate(
{ $unwind: '$scores' },
{ $match: {
'scores.categoryList': 'Bar'
}},
{ $sort: {
'scores.weight': -1
}}
)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38351460",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Some special characters are not appearing in Text Field of Android In my app user is asked to input text. But some special characters are not appearing
User input : test{ "@","\" }
Actual result : test{"",""}
How can I fix this ? is there anything special required with text.setText() code ?
A: use text watcher and Input Filter interface implemetation
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15608104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: NVD3 tooltip change event I have a nvd3 chart and a html table. I need to update table values as the user moves the mouse over the chart. Is there an event I can use to catch a nvd3 tooltip change and get the date value at the current mouse position?
My first idea was to get the nv.tooltip values on mousemove over the chart element. Not of much help.
$('#chart').mousemove(function(e) {
console.log(nv.tooltip);
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64063043",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Angular CLI 7 installed angular material 9 My pc has installed angular cli version 7.3.10 & ts 3.2.4
then i have hit below command for installing angular material>
npm install --save @angular/material @angular/cdk @angular/animations hammerjs
Now i can see angular material version 9 has installed
"@angular/animations": "^7.2.16",
"@angular/cdk": "^9.2.3",
"@angular/common": "~7.2.0",
"@angular/compiler": "~7.2.0",
"@angular/core": "~7.2.0",
"@angular/forms": "~7.2.0",
"@angular/material": "^9.2.3",
My problem is when i add material like progress bar then application could not compile and showing below errors:
*ERROR in node_modules/@angular/cdk/coercion/array.d.ts(10,60): error TS1005: ',' expected.
*node_modules/@angular/cdk/coercion/array.d.ts(10,61): error TS1005: ',' expected.
*node_modules/@angular/cdk/coercion/array.d.ts(10,75): error TS1144: '{' or ';' expected.
*node_modules/@angular/cdk/coercion/array.d.ts(10,77): error TS1011: An element access expression should take an argument.
Can anyone please help. why angular cli 7 has installed 9 material , i could not understand.
A: It appears the @angular/core is version ~7.2.0 but the @angular/material is ^9.2.3. You either need to upgrade the Angular or downgrade the Angular Material library. I'd rather downgrade the Material library. Try the following commands in order
npm uninstall @angular/material
npm uninstall @angular/cdk
npm install @angular/[email protected]
npm install @angular/[email protected]
A: I'm not sure why this happened (normally the dependencies of material 9 are set to angular 9), but you can delete it and resintall the correct version again
npm un -S @angular/material @angular/cdk
npm add -S @angular/material@7 @angular/cdk@7
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61833340",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Any way to make Project References work without loading them in the solution in Expression Blend? We have a Solution with 25 projects in it referencing each other and it builds successfully in Visual Studio 2012.
But when it comes to Expression Blend (Blend for Visual Studio 2012), I am having the following issues :
1) The solution fails to build. Gives me missing references, missing resource dictionary errors.
2) Takes long time to load or perform any operation.
I am wondering if there is any way to just load my main project in to a solution and still make the project references work.
Does the order in which the individual projects are compiled in a solution matter in Expression Blend? I am not sure why the blend is unable to find the resource dictionaries when it is seen clearly in Visual Studio 2012.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19385894",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: operator << in c# i couldn't understand this code in c#
int i=4
int[] s =new int [1<<i];
Console.WriteLine(s.length);
the ouput is 16
i don't know why the output like that?
A: bit shift operator
A: From documentation
If first operand is an int or uint
(32-bit quantity), the shift count is
given by the low-order five bits of
second operand.
If first operand is a long or ulong
(64-bit quantity), the shift count is
given by the low-order six bits of
second operand.
Note that i<<1 and i<<33 give the same
result, because 1 and 33 have the same
low-order five bits.
This will be the same as 2^( the actual value of the lower 5 bits ).
So in your case it would be 2^4=16.
A: I'm assuming you mean i in place of r...
<<n means "shift left by n* bits". Since you start with 1=binary 00...00001, if you shift left 4 times you get binary 00...10000 = 16 (it helps if you are familiar with binary arithmetic - otherwise "calc.exe" has a binary converter).
Each bit moves left n places, filling (on the right) with 0s. *=note that n is actually "mod 32" for int, so (as a corner case) 1 << 33 = 2, not 0 which you might expect.
There is also >> (right shift), which moves for the right, filling with 0 for uints and +ve ints, and 1 for -ve ints.
A: << is the left shift operator
x << y
means shift x to the left by y bits.
3 is 0011, 3<<1 is 0110 which 6.
It's usually used to multiply by 2 (shifting to the left is multiplying by 2)
A: As already mentioned, << is the left shift operator. In your particular example, the array size is being defined as a power of 2. The value 1 shifted left by some number is going to be 1, 2, 4, 8, 16, ...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1961816",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Upload to YouTube directly from stdin via Data API? As the title says, I want to pipe the output of a commandline encoder (that's recording a livestream) directly to YouTube via stdin.
Does the YouTube Data API have this functionality or is there some other little trick in order to accomplish this?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35118109",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can we give a color with specific color code in the styles.xml in Android Studio? I want to change the status bar color to a specific color with a color code. Only the default colors can be specified in the code as given below, is there any way to give a specific color code to get that color?
<item name="android:statusBarColor">@color/dark_blue_Shade1</item>
A: create a color.xml into values folder
code for color.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="dark_blue_Shade1">#000080</color>
</resources>
if the color.xml already exists there then just put the
<color name="dark_blue_Shade1">#000080</color>
inside <resources> </resources> tag
A: create color.xml file inside values folder
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ColorPrimary">#8E67E0</color>
<color name="ColorPrimaryDark">#59419B</color>
<color name="LightPrimaryColor">@android:color/holo_blue_bright</color>
<color name="AccentColor">#ff4081</color>
<color name="PrimaryText">#212121</color>
<color name="SecondarText">#727272</color>
</resources>
and then in style.xml file change like this
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">@color/ColorPrimaryDark</item>
<item name="colorPrimaryDark">@color/ColorPrimaryDark</item>
<item name="colorAccent">@color/AccentColor</item>
</style>
</resources>
From this your entire project will take this colors.
ColorPrimaryDark
is your status bar color you dont want to apply it manually system will get colorPrimaryDark as your status bar color
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32836999",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Calculating minimumZoomScale of a UIScrollView I have an image that I want to load into an image view and set the minimumZoomScale, as well as the zoomScale to an aspectFill like scale that I calculate as follows:
// configure the map image scroll view
iImageSize = CGSizeMake(iImageView.bounds.size.width, iImageView.bounds.size.height);
iScrollView.minimumZoomScale = iScrollView.bounds.size.height / iImageSize.height;
iScrollView.maximumZoomScale = 2;
iScrollView.zoomScale = iScrollView.minimumZoomScale;
iScrollView.contentOffset = CGPointMake(0, 0);
iScrollView.clipsToBounds = YES;
The iScrollView size is 450 x 320px and the iImageSize is 1600 x 1960px.
Doing the minimumZoomScale math by hand: 450 / 1960 = 0.22959184.
The system determines 0.234693885 instead (???).
But to get the window fit into the 450px space, both figures don't work (!!!).
I manually tried and found 0.207 is the right number (that would translate to a image height of 2174 xp or alternatively a UIScrollView height of 406px).
For information: the UIScrollview screen is 450px, namely 480px minus status bar height (10), minus UITabBar height (20)
Any clues on this misbehaviour?
A: Not sure if you still have this problem, but for me, the scale is exactly the opposite. minimumZoomScale = 1 for me and I have to calculate the maximumZoomScale.
Here's the code:
[self.imageView setImage:image];
// Makes the content size the same size as the imageView size.
// Since the image size and the scroll view size should be the same, the scroll view shouldn't scroll, only bounce.
self.scrollView.contentSize = self.imageView.frame.size;
// despite what tutorials say, the scale actually goes from one (image sized to fit screen) to max (image at actual resolution)
CGRect scrollViewFrame = self.scrollView.frame;
CGFloat minScale = 1;
// max is calculated by finding the max ratio factor of the image size to the scroll view size (which will change based on the device)
CGFloat scaleWidth = image.size.width / scrollViewFrame.size.width;
CGFloat scaleHeight = image.size.height / scrollViewFrame.size.height;
self.scrollView.maximumZoomScale = MAX(scaleWidth, scaleHeight);
self.scrollView.minimumZoomScale = minScale;
// ensure we are zoomed out fully
self.scrollView.zoomScale = minScale;
A: For simple zoom in/out i generally use below code. minimumZoomScale= 1 sets initial zoom to current image size. I have given maximumZoomScale = 10 which can be calculated from actual ratio of image size and container frame size.
[scrollView addSubview: iImageView];
scrollView.contentSize = iImageView.frame.size;
scrollView.minimumZoomScale = 1.0;
scrollView.maximumZoomScale = 10;
[iImageView setFrame:CGRectMake(0, 0, 450, 320)];
[scrollView scrollRectToVisible:iImageView.frame animated:YES];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3869779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Double-decoding unicode in python I am working against an application that seems keen on returning, what I believe to be, double UTF-8 encoded strings.
I send the string u'XüYß' encoded using UTF-8, thus becoming X\u00fcY\u00df (equal to X\xc3\xbcY\xc3\x9f).
The server should simply echo what I sent it, yet returns the following: X\xc3\x83\xc2\xbcY\xc3\x83\xc2\x9f (should be X\xc3\xbcY\xc3\x9f). If I decode it using str.decode('utf-8') becomes u'X\xc3\xbcY\xc3\x9f', which looks like a ... unicode-string, containing the original string encoded using UTF-8.
But Python won't let me decode a unicode string without re-encoding it first - which fails for some reason, that escapes me:
>>> ret = 'X\xc3\x83\xc2\xbcY\xc3\x83\xc2\x9f'.decode('utf-8')
>>> ret
u'X\xc3\xbcY\xc3\x9f'
>>> ret.decode('utf-8')
# Throws UnicodeEncodeError: 'ascii' codec can't encode ...
How do I persuade Python to re-decode the string? - and/or is there any (practical) way of debugging what's actually in the strings, without passing it though all the implicit conversion print uses?
(And yes, I have reported this behaviour with the developers of the server-side.)
A: What you want is the encoding where Unicode code point X is encoded to the same byte value X. For code points inside 0-255 you have this in the latin-1 encoding:
def double_decode(bstr):
return bstr.decode("utf-8").encode("latin-1").decode("utf-8")
A: ret.decode() tries implicitly to encode ret with the system encoding - in your case ascii.
If you explicitly encode the unicode string, you should be fine. There is a builtin encoding that does what you need:
>>> 'X\xc3\xbcY\xc3\x9f'.encode('raw_unicode_escape').decode('utf-8')
'XüYß'
Really, .encode('latin1') (or cp1252) would be OK, because that's what the server is almost cerainly using. The raw_unicode_escape codec will just give you something recognizable at the end instead of raising an exception:
>>> '€\xe2\x82\xac'.encode('raw_unicode_escape').decode('utf8')
'\\u20ac€'
>>> '€\xe2\x82\xac'.encode('latin1').decode('utf8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'latin-1' codec can't encode character '\u20ac' in position 0: ordinal not in range(256)
In case you run into this sort of mixed data, you can use the codec again, to normalize everything:
>>> '€\xe2\x82\xac'.encode('raw_unicode_escape').decode('utf8')
'\\u20ac€'
>>> '\\u20ac€'.encode('raw_unicode_escape')
b'\\u20ac\\u20ac'
>>> '\\u20ac€'.encode('raw_unicode_escape').decode('raw_unicode_escape')
'€€'
A: Don't use this! Use @hop's solution.
My nasty hack: (cringe! but quietly. It's not my fault, it's the server developers' fault)
def double_decode_unicode(s, encoding='utf-8'):
return ''.join(chr(ord(c)) for c in s.decode(encoding)).decode(encoding)
Then,
>>> double_decode_unicode('X\xc3\x83\xc2\xbcY\xc3\x83\xc2\x9f')
u'X\xfcY\xdf'
>>> print _
XüYß
A: Here's a little script that might help you, doubledecode.py --
https://gist.github.com/1282752
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4267019",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: Error: UnregisteredEnv with OpenAI Universe on Python 3.5 Linux Mint. Cannot load any environments I am running Python3.5 on Linux Mint.
I can import OpenAI Universe and Gym modules with no error, but when I try to run an example codes I get an error.
More specifically
raise error.UnregisteredEnv('No registered env with id: {}'.format(id))
gym.error.UnregisteredEnv: No registered env with id: flashgames.DuskDrive-v0
I get similar errors for any environment.
I have installed Docker and retried it, but still doesn't work.
And I am having issues with Anaconda, will appreciate a non-Conda solution.
Thank you!
Code:
import gym
import universe
env = gym.make('flashgames.DuskDrive-v0')
env.configure(remotes=1) # automatically creates a local docker container
observation_n = env.reset()
while True:
action_n = [[('KeyEvent', 'ArrowUp', True)] for ob in observation_n] # your agent here
observation_n, reward_n, done_n, info = env.step(action_n)
env.render()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42104722",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: SQL to find runs of matching values I have the following table called [Store_Sales] -
Store Date Sales
1 23/04 10000
2 23/04 11000
1 22/04 10000
2 22/04 10500
1 21/04 10000
2 21/04 10550
I want a SQL that will return a "run" of similar values in the Sales column for a particular store. For example, from the above table it would return store 1 for the 23rd, 22nd and 21st, as they all have the same value (10,000).
I am using SQL Server 2008.
A: Have a look at something like this (full example)
DECLARE @Store_Sales TABLE(
Store INT,
Date DATETIME,
Sales FLOAT
)
INSERT INTO @Store_Sales SELECT 1,'23 Apr 2010',10000
INSERT INTO @Store_Sales SELECT 2,'23 Apr 2010',11000
INSERT INTO @Store_Sales SELECT 1,'22 Apr 2010',10000
INSERT INTO @Store_Sales SELECT 2,'22 Apr 2010',10500
INSERT INTO @Store_Sales SELECT 1,'21 Apr 2010',10000
INSERT INTO @Store_Sales SELECT 2,'21 Apr 2010',10550
SELECT ss.Store,
MIN(ss.Date) StartDate,
MAX(ssNext.Date) EndDate,
ss.Sales
FROM @Store_Sales ss INNER JOIN
@Store_Sales ssNext ON ss.Store = ssNext.Store
AND ss.Date + 1 = ssNext.Date
AND ss.Sales = ssNext.Sales
GROUP BY ss.Store,
ss.Sales
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3723960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Number of READS in firestore and the basis of its calculation I still fail to understand the calculation of no. of reads on Firestore. Just as an experiment, I just sat a the Firestore console without doing anything, no devices connected, no mobile, no emulator nothing, and the no. of reads registered in under the usage TAB was about 600 reads in about 10 minutes. So my guess is, if it's a real app out there, 50000 reads will be breached in no time at all! Can someone please explain FIRESTORE READS and its fundamentals?
A: The number of reads in Firestore is always equal to the number of documents that are returned from the server by a query. Let's say you have a collection of 1 million documents, but your query only returns 10 documents, then you'll have to pay only 10 document reads.
If your query yields no results, according to the official documentation regarding Firestore pricing, it said that:
Minimum charge for queries
There is a minimum charge of one document read for each query that you perform, even if the query returns no results.
Those unexpected reads most likely come from the fact that you are using the Firebase console. All operations that you perform in the console are counted towards the total quota. So please remember to not keeping your Firebase console open, as it is considered another Firestore client that reads data. So you'll be also billed for the reads that are coming from the console.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69594590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Get first record per identifier group in SQL Code Description Whatever
---------------------------------
1 stuff blah
1 something meh
2 yah bong
2 never hammer time
How do I get a results set from this with each Code only present once? (I don't overly care which record for that code it is).
So I want....
1 stuff blah
2 yah bong
A: SELECT *
FROM (
SELECT * , row_number() over(partition by code order by Description) as id
from yourTable
) temp
WHERE id = 1
I think this is sql server only
A: You first need to pick a column which determines what counts as 'the first result'. In my example I chose Description:
SELECT * FROM YourTable first
WHERE
(SELECT COUNT(*) FROM YourTable previous
WHERE previous.Code=first.Code AND previous.Description < first.Description) = 0
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4884736",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Socket request fails on second call when using the same connection Im opening up a connection to a server that accepts XML requests. I am required to send two requests one after the other.
If I run the first request on its own I get data back
If I run the second request on its own I get data back
If I run both within a loop using the same connection, only the first request works, the second returns no data.
Is there something I need to send to the socket between each request to indecate the end of each request, otherwise what am I doing wrong?
// Open socket connection
$socket = pfsockopen($this->config['ip'], $this->config['port'], $errno, $errstr, 30);
// Try and open a connection
if ( ! $socket) {
throw new \Exception($errstr . '('.$errno.')');
}
// If connection was successfull start sending requests
else{
// Loop each request within the container
foreach($this->container as $key => $object){
print "Request" . ($key+1) . PHP_EOL;
// Reset data and post string
$data = array();
$xml_post_string = null;
// Create XML string
$xml = \LSS\Array2XML::createXML('request', $object->request);
$xml_post_string = $xml->saveXML();
// Add ending lines
$xml_post_string = $xml_post_string . PHP_EOL . PHP_EOL;
// Loop
fwrite($socket, $xml_post_string);
while ( ! feof($socket)) {
$data[] = fgets($socket, 1024);
}
// Tried adding, but fails
ftruncate($socket, 2);
if(count($data)){
print implode($data);
}
else{
print "No response from server - you broke it" . PHP_EOL;
}
}
}
fclose($socket);
A second attempt. The results are the same for any random server out there.
// Create a TCP/IP socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
// Connect the socket
socket_connect($socket, 'xxx.xxx.xxx.xxx', '80');
$xml_post_string_one = '<request><message>Hello first world</message></request>';
$xml_post_string_two = '<request><message>Hello second world</message></request>';
// FIRST ROUND //
// Send data to it
socket_write($socket, $xml_post_string_one, strlen($xml_post_string_one));
// Get data from it
socket_recv($socket, $bufA, 2048, MSG_WAITALL);
// Done
print strlen($bufA) . PHP_EOL; // Got info back
// SECOND ROUND //
// Send data to it
socket_write($socket, $xml_post_string_two, strlen($xml_post_string_two));
// Get data from it
socket_recv($socket, $bufB, 2048, MSG_WAITALL);
// Done
print strlen($bufB). PHP_EOL; // Returns 0, Why?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32744164",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Show images and play videos without allowing copying, or downloading Is there any way to display images and / or videos on a website and not allow visitors to download or copy them?
I once saw a website where I tried to download an image, but then it was impossible to open it on my computer because the file type was not recognized on my computer!
Is there any way to encode the files, maybe?
Thank you all.
A: If you can show the images and videos in a browser, they will always find a way to copy these. You can't have the cake and eat it.
The only thing you can do is to make it harder for the newbie.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47528903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to add prefix to all columns values in pandas I have following data frame in Pandas
Date stockA stockB stockC stockD stockE
2020-01-01 1 1 2 1 3
2020-01-01 1 2 2 1 2
2020-01-01 1 1 3 2 1
2020-01-01 3 1 2 1 2
I want to add prefix for each column e.g. for stockA:01, stockB:02 so on and so forth.
My desired data frame would be
Date stockA stockB stockC stockD stockE
2020-01-01 011 021 032 041 053
2020-01-01 011 022 032 041 052
2020-01-01 011 021 033 042 051
2020-01-01 013 021 032 041 052
I have 25 columns likewise. How can I do it in pandas?
A: Try with df.radd:
m = df.set_index('Date')
#add prefix 0X if less than 10 else add prefix X
m = m.astype(str).radd([f"0{i}" if i<10 else f"{i}"
for i in range(1,m.shape[1]+1)]).reset_index()
print(m)
Date stockA stockB stockC stockD stockE
0 2020-01-01 011 021 032 041 053
1 2020-01-01 011 022 032 041 052
2 2020-01-01 011 021 033 042 051
3 2020-01-01 013 021 032 041 052
A: A somewhat more cumbersome but perhaps more readable solution:
v = [1,23,33]
cols = {'A': v, 'B': v, 'C': v, 'D': v, 'E': v,
'F': v, 'G': v, 'H': v, 'I': v, 'J': v}
df = pd.DataFrame(data = cols,
index = ['2020-01-01']*3,
columns = cols)
for n, col in enumerate(df.columns, 1):
df[col] = str(n).zfill(2) + df[col].astype(str)
>>
A B C D E F G H I J
2020-01-01 011 021 031 041 051 061 071 081 091 101
2020-01-01 0123 0223 0323 0423 0523 0623 0723 0823 0923 1023
2020-01-01 0133 0233 0333 0433 0533 0633 0733 0833 0933 1033
A: Use:
m = df.columns.str.contains('stock')
cols_change = df.columns[m]
num = ('0'+pd.Index(range(1,len(cols_change)+1)).astype(str)).str[-2:]
df.columns = df.columns[~m].tolist()+[f'{name}:{n}' for n,name in zip(num,cols_change)]
print(df)
Date stockA:01 stockB:02 stockC:03 stockD:04 stockE:05
0 2020-01-01 1 1 2 1 3
1 2020-01-01 1 2 2 1 2
2 2020-01-01 1 1 3 2 1
3 2020-01-01 3 1 2 1 2
or with pd.Index.difference
cols_change = df.columns.difference(['Date'])
num = ('0'+pd.Index(range(1,len(cols_change)+1)).astype(str)).str[-2:]
df.columns = ['Date']+[f'{name}:{n}' for n,name in zip(num,cols_change)]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59909763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: route print command show almost all On-link gateway Trying to learn about routing tables, when preforming route print on cmd window I get this result on the IPv4 table:
===========================================================================
Active Routes:
Network Destination Netmask Gateway Interface Metric
0.0.0.0 0.0.0.0 10.0.0.138 10.0.0.9 50
10.0.0.0 255.255.255.0 On-link 10.0.0.9 306
10.0.0.9 255.255.255.255 On-link 10.0.0.9 306
10.0.0.255 255.255.255.255 On-link 10.0.0.9 306
127.0.0.0 255.0.0.0 On-link 127.0.0.1 331
127.0.0.1 255.255.255.255 On-link 127.0.0.1 331
127.255.255.255 255.255.255.255 On-link 127.0.0.1 331
224.0.0.0 240.0.0.0 On-link 127.0.0.1 331
224.0.0.0 240.0.0.0 On-link 10.0.0.9 306
255.255.255.255 255.255.255.255 On-link 127.0.0.1 331
255.255.255.255 255.255.255.255 On-link 10.0.0.9 306
===========================================================================
From my understanding, the Network Destination and Netmask combine show the Network ID, and Gateway is the "next hop" meaning it is the address where addresses from Network ID can get to the internet, via the Interface on the right.
This table is different from other I seen on line, and almost all the gateways are On-link. From a simple google search, I found those On-link mean addresses reachable locally (my router's address?) so On-link=10.0.0.138 in this example? And since network ID is all 0.0.0.0 that means the only routing available on my system is going to 10.0.0.138 through 10.0.0.9? If so why I need the other rows? If I'm wrong I would love to know better.
Thanks.
A: "on-link" doesn't equal 10.0.0.138. It means that the destination network is directly attached to the interface - meaning traffic that matches this route entry will trigger an ARP request that should be sent from this link to resolve the destination IP directly (not the gateway 10.0.0.138).
This is also called "glean adjacency".
The 10.0.0.9 route instructs packets with destination IP 10.0.0.9 to be sent to the CPU (AKA punt adjacency).
127.0.0.0/24 network is for internal communication within the machine.
224.0.0.0/4 is for multicast traffic.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62219754",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: how can I declare that the seat is already taken in if else statement I have taken all of your comments, and I am still unsure about it but am I doing it properly? And do I need to use for loop to replace if/else-if statements?
if(p.seatrow > ROWS || p.seatcol > COLS)
{
printf("Invalid option!");
chooseseat();
} else if (seat[p.seatrow-1][p.seatcol-'A'] != 'X')
{ printf("\n\t\t Seat is already reserved. Choose another seat? (Y/N)");
scanf("%c", answer);
if(answer == 'Y')
{
chooseseat();
}
else{
printf("Your data will be not saved and will be returned to main menu:");
main();
}
}else if if (seat[p.seatrow-1][p.seatcol-'A'] != 'X'){
printf("Congratulations. Your seat number is %d%c",p.seatrow,p.seatcol);
}
I am still working with the same program and still facing issues. I want to have an else-if statement where I can say that the input of the user is already taken. I want to say that the seat that they entered is already taken, but the problem is I don't know what variable or condition should I use for it.
#define ROWS 11
#define COLS 8
#define PASSENGERSIZE sizeof(passenger)
typedef struct{
char city[20], name[50], seatcol;
int age, seatrow, id;
}passenger;
char seat[ROWS][COLS];
int selection;
int seatavailable=60;
int i,j,x,k;
char answer, Y ;
int status=0;
void chooseseat(){
passenger p;
printf("\n\t\t\tEnter your seat number: (EX: 1A)");
scanf(" %d%c",&p.seatrow, &p.seatcol);
if(p.seatrow == 1 && p.seatcol == 'A'){
seat[0][0]= 'X';}
else if(p.seatrow == 1 && p.seatcol == 'B'){
seat[0][1]= 'X';}
else if(p.seatrow == 1 && p.seatcol == 'C'){
seat[0][2]= 'X';}
else if(p.seatrow == 1 && p.seatcol == 'D'){
seat[0][3]= 'X';}
else if(p.seatrow == 1 && p.seatcol == 'E'){
seat[0][4]= 'X';}
else if(p.seatrow == 1 && p.seatcol == 'F'){
seat[0][5]= 'X';}
.....
//10
else if(p.seatrow == 10 && p.seatcol == 'A'){
seat[9][0]= 'X';}
else if(p.seatrow == 10 && p.seatcol == 'B'){
seat[9][1]= 'X';}
else if(p.seatrow == 10 && p.seatcol == 'C'){
seat[9][2]= 'X';}
else if(p.seatrow == 10 && p.seatcol == 'D'){
seat[9][3]= 'X';}
else if(p.seatrow == 10 && p.seatcol == 'E'){
seat[9][4]= 'X';}
else if(p.seatrow == 10 && p.seatcol == 'F'){
seat[9][5]= 'X';}
/* In this part, I want to declare that the seat entered is already taken. */
else if(seat[p.seatrow][p.seatcol] != 'X'){
printf("\n\t\t Seat is already reserved. Choose another seat? (Y/N)");
scanf(" %c", &answer);
if(answer == 'Y'){
chooseseat();
}
else{
printf("Your data will be not saved and will be returned to main menu:");
main();
}
}
else{
printf("Invalid option!");
}
printf("Congratulations. Your seat number is %d%c",p.seatrow,p.seatcol);
A: I think your code needs restructuring. You need to check if the seat is empty before doing anything else. Also "main" is entry point of program in C, it is better not to use it for other purposes.
As described in the comments, instead of using if-else statement for assignment it is better to use the following:
seat[p.seatrow - 1][p.seatcol - 'A'] = ...
Considering all of these, the following code will do the job you want.
First, it asks about user input, then it checks if it is in valid range of inputs. After that, it checks if the seat is already taken or not.
If the seat was empty it reserves it and quits the function. If any of the above steps fails, it asks for user input again.
The code:
#include <stdio.h>
#include <stdbool.h>
#define ROWS 11
#define COLS 8
#define PASSENGERSIZE sizeof(passenger)
typedef struct{
char city[20], name[50], seatcol;
int age, seatrow, id;
}passenger;
char seat[ROWS][COLS]={0};
int selection;
int seatavailable=60;
int i,j,x,k;
char answer, Y ;
int status=0;
void chooseseat(){
passenger p;
// Read the user input until it reserves a seat or request quitting.
while (true){
// Read user input.
printf("\nEnter your seat number: (EX: 1A)");
scanf(" %d%c",&p.seatrow, &p.seatcol);
// Check if the seat requested is valid entry.
if (p.seatrow > 0 && p.seatrow <= ROWS &&
p.seatcol >= 'A' && p.seatcol <= 'A' + COLS){
// Input range is valid, check if seat is already taken.
if (seat[p.seatrow - 1][p.seatcol - 'A'] != 'X'){
// Seat is available, reserve it and break the loop.
seat[p.seatrow - 1][p.seatcol - 'A'] = 'X';
printf("Congratulations. Your seat number is %d%c\n",p.seatrow,p.seatcol);
break;
}
else{
// Seat is already taken.
printf("Seat is already taken\n.");
}
}
else{
// Input range is invalid.
printf("Invalid seat row/col,\n");
}
// Ask user if he wants to continue.
printf("\nChoose another seat? (Y/N)");
scanf(" %c", &answer);
if (answer != 'Y'){
printf("Your data will be not saved and will be returned to main menu.\n");
break;
}
}
}
int main() {
chooseseat();
return 0;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73028723",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Equivalent of OracleParameter [C#/.NET/SQL Server] I working on a database migration (from Oracle to SQL Server) and in this context, I need to change the DAL layer of an ASP.NET project. Part of this is finding the SQL Server equivalent of the class OracleParameter (From Oracle.DataAccess.dll).
So I would like to know which class I have to use, is it DbParameter or another one?
A: Best to use:
SqlParameter
Eg:
var parameter = new SqlParameter();
parameter.ParameterName = "@paramName";
parameter.Direction = ParameterDirection.Input;
parameter.SqlDbType = SqlDbType.Int;
//parameter.IsNullable = true;
parameter.Value = DaysInStock;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43611669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: When User Click on submit Mail goes to my email I recently followed:
link here
but in my app little difference that in above question only user name and password is available but i need to add name,emailid and message
what change i do in my application
when i click on submit mail goes to my email id : *********@gmail.com
and my code is :
MailActivity.java
package com.amcct.amcostapp;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MailActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mail);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.mail, menu);
return true;
}
final Button submit_button= (Button) this.findViewById(R.id.button1);
View.OnClickListener Button1_Listener=new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try
{
GmailSender sender=new GmailSender("editText1","editText2","editText3");
sender.sendMail("This is Subject","This is Body"
,"[email protected]");
}
catch(Exception e)
{
Log.e("sendMail",e.getMessage(),e);
}
}
};
}
GmailSender.java
package com.amcct.amcostapp;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Security;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import android.os.Message;
//simple mail transfer protocol
public class GmailSender extends javax.mail.Authenticator
{
private String mailhost="smtp.gmail.com";
private String name;
private String emailid;
private String message;
private Session session;
static
{
Security.addProvider(new com.amcct.JSSEProvider());
}
public GmailSender(String name,String emailid,String message)
{
this.name=name;
this.emailid=emailid;
this.message=message;
Properties prop=new Properties();
prop.setProperty("mail.transport.protocol","smtp");
prop.setProperty("mail.host",mailhost);
prop.put("mail.smtp.auth","true");
prop.put("mail.smtp.port", "465");
prop.put("mail.smtp.socketFactory.port", "465");
prop.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
prop.put("mail.smtp.socketFactory.fallback", "false");
session=Session.getDefaultInstance(prop,this);
}
public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception {
try{
MimeMessage message = new MimeMessage(session);
DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setDataHandler(handler);
if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
Transport.send(message);
}catch(Exception e){
}
}
public class ByteArrayDataSource implements DataSource {
private byte[] data;
private String type;
public ByteArrayDataSource(byte[] data, String type) {
super();
this.data = data;
this.type = type;
}
public ByteArrayDataSource(byte[] data) {
super();
this.data = data;
}
public void setType(String type) {
this.type = type;
}
public String getContentType() {
if (type == null)
return "application/octet-stream";
else
return type;
}
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
}
public String getName() {
return "ByteArrayDataSource";
}
public OutputStream getOutputStream() throws IOException {
throw new IOException("Not Supported");
}
}
}
JSSEProvider.java
package com.amcct;
import java.security.AccessController;
import java.security.Provider;
public class JSSEProvider extends Provider
{
/**
*
*/
private static final long serialVersionUID = -4241732100545779346L;
public JSSEProvider()
{
super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
AccessController.doPrivileged(new java.security.PrivilegedAction<Void>()
{
public Void run()
{
put("SSLContext.TLS",
"org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
put("Alg.Alias.SSLContext.TLSv1", "TLS");
put("KeyManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
put("TrustManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
return null;
}
});
}
}
Now I am confused that where I add name,emailid and message.
A: In Gmail Sender there is one method
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
which set account from which mail will be sent
I am using the same this is my GmailSender
public class GMailSender extends javax.mail.Authenticator {
private String mailhost = "smtp.gmail.com";
private String user;
private String password;
private Session session;
static {
Security.addProvider(new JSSEProvider());
}
public GMailSender(String user, String password) {
this.user = user;
this.password = password;
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", mailhost);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.quitwait", "false");
session = Session.getDefaultInstance(props, this);
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
public synchronized void sendMail(String subject, String body,
String sender, String recipients) throws Exception {
Log.d("EmailSender", "Sending Mail initiallized");
try {
MimeMessage message = new MimeMessage(session);
DataHandler handler = new DataHandler(new ByteArrayDataSource(
body.getBytes(), "text/plain"));
message.setFrom(new InternetAddress(sender));
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setDataHandler(handler);
if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
Transport.send(message);
} catch (Exception e) {
}
}
public class ByteArrayDataSource implements DataSource {
private byte[] data;
private String type;
public ByteArrayDataSource(byte[] data, String type) {
super();
this.data = data;
this.type = type;
}
public ByteArrayDataSource(byte[] data) {
super();
this.data = data;
}
public void setType(String type) {
this.type = type;
}
public String getContentType() {
if (type == null)
return "application/octet-stream";
else
return type;
}
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
}
public String getName() {
return "ByteArrayDataSource";
}
public OutputStream getOutputStream() throws IOException {
throw new IOException("Not Supported");
}
}
}
Edit 1:
GmailSender sender=new GmailSender("YourUserName","YourPassword");
sender.sendMail("This is Subject","This is Body","[email protected]","[email protected]");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18814253",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: How are transactions partitioned/isolated in SQLite? I have been reading the SQLite documentation and also referencing code I have written previously but I don't seem to be able to find a definitive answer to what I imagine to be a rather simple question.
I would like to execute many (separate) compiled statements within a transaction, but child threads may also be creating transactions or just executing statements at the same time and I would not want them included in this particular transaction. Currently, I have a single database handle that I share between all threads.
So, my question is,
1) .. is it generally better to have some kind of semaphore around transactions to ensure they will not clash/collect with other statements being executed against a database handle. I already marshal writes to prevent problems with multithreaded issues with SQLite (although with WAL now it's very hard to unsettle it at all).
2) .. or are you expected to open multiple database connections and start/commit the transactions one per database connection if they will be concurrent?
A: Changes made in one database connection are invisible to all other database connections prior to commit.
So it seems a hybrid approach of having several connections open to the database provides adequate concurrency guarantees, trading off the expense of opening a new connection with the benefit of allowing multi-threaded write transactions.
A query sees all changes that are completed on the same database connection prior to the start of the query, regardless of whether or not those changes have been committed.
If changes occur on the same database connection after a query starts running but before the query completes, then it is undefined whether or not the query will see those changes.
If changes occur on the same database connection after a query starts running but before the query completes, then the query might return a changed row more than once, or it might return a row that was previously deleted.
For the purposes of the previous four items, two database connections that use the same shared cache and which enable PRAGMA read_uncommitted are considered to be the same database connection, not separate database connections.
Here is the SQLite information on isolation. Which is exceptionally useful to read and understand for this problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41146228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why is $timeout needed when dynamically nesting ng-form in Angular to ensure child form links with parent form? I cannot seem to avoid the need to generate dynamic sub forms in the application I am working on. The sub form is working as expected and the sub form shows $invalid=true when one or more of it's inputs are invalid. The parent form however has $invalid=false.
I have seen people achieve nested forms where invalid sub forms invalidate the parent form, but I can't seem to do it dynamically without wrapping the dynamic compiling of the sub form in a $timeout.
See Plunker HERE
In the above link I have recreated the scenario. I have three forms. The parent form, a sub form created at the same time as the parent form, and a dynamically created sub form.
If you clear the bottom existing sub form's input, it will invalidate the parent form (parent form turns red).
If you clear the top dynamic form's input, it will not invalidate the parent form (parent form remains green).
It will begin to work if you stick the addForm method in a $timeout:
// WORKS! : When you delete the dynamic added sub form input
// the parent form also becomes invalid
//timeout(addForm,0);
// FAILS! : When you delete the dynamic added sub form input text
// the parent form does NOT become invalid
addForm();
It's great that I have a workaround, but I would like to understand why I need the $timeout and if there is a solution that avoids the use of a $timeout.
A: DOM manipulations should be done in the link phase and not in the controller.
See $compile
The link function is responsible for registering DOM listeners as well
as updating the DOM. It is executed after the template has been
cloned. This is where most of the directive logic will be put.
Detailed explanation:
The problem lies in the the angular FormController. At intialization it will look for a parent form controller instance. As the sub form was created in the controller phase - the parent form initialization has not been finished. The sub form won't find it's parent controller and can't register itself as a sub control element.
FromController.js
//asks for $scope to fool the BC controller module
FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
function FormController(element, attrs, $scope, $animate, $interpolate) {
var form = this,
controls = [];
var parentForm = form.$$parentForm = element.parent().controller('form') || nullFormCtrl;
Plunker
A: As Michael said, the correct place to do any DOM manipulations is the link function and not the controller function of the directive. Some extra information on why what you already have does / does not work depending on the use of $timeout:
According to the Angular documentation of the $compile service for directive definitions the controller
is instantiated before the pre-linking phase
while the link function
is executed after the template has been cloned
You can observe this yourself if you include a link function in your directive and write two console.log statements, one in the controller function and one in the link function. The link function is always executed after the controller. Now, when you include addForm(); in your controller this will be executed at the time the controller is instantiated, ie. before the linking phase, at which time, as it is mentioned in the documentation it is
not safe to do DOM transformation since the compiler linking function
will fail to locate the correct elements for linking.
On the other hand, if you call the addForm() function in the $timeout, this will actually be executed after the linking phase, since a $timeout call with a zero timeout value causes the code in the timeout to be called in the next digest cycle, at which point the linking has been performed and the DOM transformation is performed correctly (once again you can see the timing of all these calls by adding console.logs in appropriate places).
A: Usually altering dom elements inside of a controller is typically not ideal. You should be able achieve what you are looking for without the need for '$compile' and make things a bit easier to handle if you introduce a second directive an array of items to use 'ng-repeat'. My guess is that $timeout() is working to signal angular about the new elements and causes a digest cycle to handle the correct validation.
var app = angular.module('app',[]);
app.directive('childForm', function(){
return{
restrict: 'E"',
scope:{
name:"="
},
template:[
'<div ng-form name="form2">',
'<div>Dynamically added sub form</div>',
'<input type="text" name="input1" required ng-model="name"/>',
'<button ng-click="name=\'\'">CLEAR</button>',
'</div>'
].join('')
}
});
app.directive('myTest', function() {
return {
restrict: 'E',
scope: {},
controller: function ($scope, $element, $compile, $timeout) {
$scope.items = [];
$scope.items.push({
name:'myname'
});
$scope.name = 'test';
$scope.onClick = function () {
console.log("SCOPE:", $scope, $childScope);
};
$scope.addItem = function(){
$scope.items.push({name:''});
}
},
template: [
'<div>',
'<div>Parent Form</div>',
'<div ng-form name="form1">',
'<div class="form-container">',
'<div ng-repeat="item in items">',
'<child-form/ name="item.name">',
'</div>',
'</div>',
'<div>Existing sub form on parent scope</div>',
'<div ng-form name="form3">',
'<input type="text" name="input2" required ng-model="name"/>',
'<button ng-click="name=\'\'">CLEAR</button>',
'</div>',
'</div>',
'<button ng-click="addItem()">Add Form</button>',
'<button ng-click="onClick()">Console Out Scopes</button>',
'</div>'
].join('')
};
});
Updated plunkr
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30948066",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Making a jquery carousel from scratch I know there are a ton of questions on here about jquery image carousel, but they all refer to a plugin. I would like to make one from scratch. It's a pretty simple one, there are 2 buttons, one left and one right. when you click the left button, the position of the overall container that has all the images shifts to the left, and the right makes it go right.
This is what I have so far... Right now the problem is only the left button works. (the right button works only once you slide the image to the left once) And I also want it to animate across all the images, and go to the last image when you get to the end of the set of images
JS:
total_entries = $("image-entry").length;
var current_index = 0;
var slider_entries = $('#slider-entries');
$('#home-slider #left').click(function(){
go_to_index(current_index-1);
return false;
});
$('#home-slider #right').click(function(){
go_to_index(current_index+1);
return false;
});
var go_to_index = function(index){
if(index < 0)
index = total_entries - 1;
if(index > total_entries - 1)
index = 0;
if(current_index == index)
return;
var left_offset = -1 * index * 720;
slider_entries.stop().animate({"left": left_offset}, 250);
//description_container.stop().animate({"left":left_offset}, 250);
current_index = index;
};
HTML:
<div id="slider">
<div id="slider-entries">
<div class="image-entry">
<img src="http://placekitten.com/720/230" />
</div>
<div class="image-entry">
<img src="http://placedog.com/720/230" />
</div>
<div class="image-entry">
<img src="http://placedog.com/720/230" />
</div>
</div>
</div>
total width of each image is 720px
total with of slider-entries is
Thanks
A: You have a problem with the total_entries variable.
First of all you need a "var" in front, to define that it's a new variable.
Second, you forgot a "." (dot) to search for the class in your HTML code..
your first line should be:
var total_entries = $(".image-entry").length;
Hope it works ;-)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5764892",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: php+MYSQL+Get n rows once I have a database that looks like this: (dates are formated with strtotime)
ID Date
1 1338366170000
2 1337761370000
3 1337761370000
4 1337761370000
5 1337156570000
6 1331713370000
7 1331713370000
As you can see some entries are from the same date. I would now like to grab each date and the count how often it occurs.
So the end result would look like:
Date: 1338366170000
Count: 1
Date: 1337761370000
Count: 3
Date: 1337156570000
Count: 1
Date: 1331713370000
Count: 2
I am currently doing this to get all dates and count each date:
First I grab all rows:
$stats = $sql->query("SELECT * FROM stats_clicks");
Now, I think the problems begin when I try to count the entries with same date: I loop through all results and search for each date and count it.
foreach($sql->get() as $result){
//Sum clicks for each date
$date = $result["date"];
$stats = $sql->query("SELECT * FROM stats_clicks WHERE date = '$date'");
$count = count($sql->get());
echo "Date: $date<br>Count: $count<br><br>";
}
The output is:
Date: 1338366170000
Count: 1
Date: 1337761370000
Count: 3
Date: 1337761370000
Count: 3
Date: 1337761370000
Count: 3
Date: 1337156570000
Count: 1
Date: 1331713370000
Count: 2
Date: 1331713370000
Count: 2
How can I avoid outputing each date multiple times, but instead each date only once with the correct count?
A: SELECT `Date`, COUNT(`Date`) as `Count`
FROM stats_clicks
GROUP BY `Date`
Result
Date Count
1331713370000 2
1337156570000 1
1337761370000 3
1338366170000 1
A: Go with this query. You will get corect count with no repetition.
SELECT date,count(*) FROM stats_clicks GROUP BY date;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10813108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: CSS and jQuery universal tree menu I want to create universal tree menu, with ul li ul. And I've made something like this using just CSS:
CSS
.category-list {
}
.category-list li ul {
display: none;
}
.category-list li:hover > ul {
display: block;
}
HTML
<ul class="category-list">
<li>
<a href="" title="">Category 1</a>
<ul>
<li><a href="" title="">Sub-category 1</a></li>
<li><a href="" title="">Sub-cateagory 1</a></li>
<li><a href="" title="">Sub-category 1</a></li>
</ul>
</li>
<li>
<a href="" title="">Category 2</a>
<ul>
<li><a href="" title="">Sub-category 2</a></li>
<li><a href="" title="">Sub-category 2</a></li>
<li><a href="" title="">Sub-category 2</a></li>
</ul>
</li>
</ul>
https://jsfiddle.net/usz9ycmj/1/
--
And I want to make similar effect, but on click, so just current clicked tab displays its parent content.
Even more important for me is the ability to add and remove class on specific action:
.category-list li.current -- while is currently clicked (active)
.category-list li -- removed while different li is clicked (active)
Just, the trigger li has two different states for active and inactive. It changes the colors and arrow from closed to opened to give it a look of a tree menu - I bet You get the point.
I want the simple jquery code, if someone has time to help. feel welcome.
A: Here is a working code.
Please read the comments and let me know if something not clear.
// listen to the click event
var all_items = $('.category-list>li').click(function(event) {
// stop the propagation - this will abort the function when you click on the child li
event.stopPropagation();
var elm = $(this);
// remove the class from all the items
all_items.not(elm).removeClass('current');
// add class if it's not the current item
elm.toggleClass('current', !elm.is('.current'));
});
.category-list {
}
.category-list li ul {
display: none;
}
.category-list li.current > ul {
display: block;
}
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<ul class="category-list">
<li>
<a href="#" title="">Category 1</a>
<ul>
<li><a href="#" title="">Sub-category 1</a></li>
<li><a href="#" title="">Sub-category 1</a></li>
<li><a href="#" title="">Sub-category 1</a></li>
</ul>
</li>
<li>
<a href="#" title="">Category 2</a>
<ul>
<li><a href="#" title="">Sub-category 2</a></li>
<li><a href="#" title="">Sub-category 2</a></li>
<li><a href="#" title="">Sub-category 2</a></li>
</ul>
</li>
</ul>
http://jsbin.com/tocewe/edit?html,css,js
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36113996",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Getting data from JSON in node-red with http request Disclaimer: this is my first time attempting to write in Javascript; I don't know what I am doing.
I tried looking for example of this, but everything I found has the JSON object included in Javascript. Trying to return just the price_usd from this JSON
https://api.coinmarketcap.com/v1/ticker/bitcoin/
[
{
"id": "bitcoin",
"name": "Bitcoin",
"symbol": "BTC",
"rank": "1",
"price_usd": "972.935",
"price_btc": "1.0",
"24h_volume_usd": "501202000.0",
"market_cap_usd": "15650425175.0",
"available_supply": "16085787.0",
"total_supply": "16085787.0",
"percent_change_1h": "-2.35",
"percent_change_24h": "-17.36",
"percent_change_7d": "2.55",
"last_updated": "1483690766"
}
]
My current code in the linked function box is :
return {payload:msg.payload.price_usd};
msg.payload returns undefined. Tried with both http request set to return as parsed JSON object and as UTF-8 string.
A: The response is surrounded by [ ]. This indicates it's an array. So you need to reference into that array to get to the data.
msg.payload[0].price_usd
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41501850",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Moving subproject files and updating links in master project I am working in MS Project and frequently move schedules from a share drive to my computer, manipulate and run macros on them, then copy them back up to the share drive.
Generally if I copy all of the subprojects with the Master project at one time the links to the subprojects will update to the destination folder (the one on my computer.) Occasionally I do this and the links do not update, so the Master Schedule is still pointing to the files on the share drive. This causes problems with the macro I then run on it. I have not been able to find anything in forums about this problem.
Has anyone come across this problem? Is there a setting somewhere that is getting changed? Any help would be appreciated.
A: Yes, I've come across this problem.
The most reliable way of copying a master schedule and all it's sub projects without creating the duplicate links is to:
*
*Select all the files on the share drive
*Right click and send them to a zip file
*Move this zip file to your local drive
*Right click on the zip file and extract all
Then do the same in reverse once you've run your macros. This should reliably copy the master/sub project files with the correct links, without creating the erroneous links you've seen.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21732547",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Find next object without specific word in style I have these divs in my html:
<div class="slide" style=""></div>
<div class="slide" style="background: url(/img/2.jpg)"></div>
<div class="slide" style="background: url(/img/3.jpg)"></div>
<div class="slide" style="background: url(/img/4.jpg)"></div>
<div class="slide" style=""></div>
<div class="slide" style=""></div>
<div class="slide" style=""></div>
I have a var which is an index of one of the divs above,
lets say it equals 2, so it's the one with 3.jpg as a background.
Now, I'm trying to get the index of the next div with class "slide", which index is greater than my var and which has no "background" in "style".
If there are no divs like that with index greater than my var, I'd like to start searching the divs from the beginning of the list.
Similarly I'm trying to find the last div before my var, with no word "background" in "styles" and similarly, if there is no divs like that, I'd like to start searching from the end of the list.
So basically I'm trying to get a value of 4 for the nextDiv and 0 for the lastDiv, for the example above.
I know that $.nextAll() with :first can help to achieve what I need and I also know, that selecting '.slide' with no "background" in in-line "styles" can be done with $(".slide [style*='background']"), but I can't find a way to put the syntax together adding required conditions.
Please help.
Thank you.
A:
I have a var which is an index of one of the divs above, lets say it equals 2, so it's the one with 3.jpg as a background.
...
Now, I'm trying to get the index of the next div with class "slide", which index is greater than my var and which has no "background" in "style".
What you need for that literal requirement is a combination of eq, nextAll, filter, and (if you really want the index) index.
var index = $(".slide").eq(startingIndex).nextAll(".slide").filter(function() {
return $(this).attr("style").indexOf("background") === -1;
}).index();
That will give you the element's index relative to its siblings (all of them).
But if you just want the element, use first instead:
var nextSlideWithoutBackground = $(".slide").eq(startingIndex).nextAll(".slide").filter(function() {
return $(this).attr("style").indexOf("background") === -1;
}).first();
Actually, you could use :gt but it's a pseudo-selector so it may not be any better than using nextAll. Here's what it would look like, though:
var index = $(".slide:gt(" + startingIndex + ")").filter/*...and so on...*/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23548507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: htaccess exclusions don't work the second exclusion ( !/example-folder ) in the htaccess file doesn't work. What am I missing here?
CMS: Magento
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} !/admin/
RewriteCond %{REQUEST_URI} !/example-subfolder/
RewriteCond %{HTTP_HOST} ^www.domain.com
RewriteRule ^index.php/.*/(.*)$ http://www.domain.com/$1 [L,R=301]
RewriteRule ^index.php/(.*)$ http://www.domain.com/$1 [L,R=301]
A: What is your server? Is it apache or Ngnix?
Rewrite engine won't work with ngnix, you may have to update the ngnix conf files for this to work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30171703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: conversion error while grouping the data and returning as JSON With the help of another developer from stackoverflow, I managed to use his query to create a code which returns me data back based upon grouping by groupid and return as json
Try using the following concept:
Insert data:
CREATE TABLE some_table (some_data VARCHAR(20), some_other_data VARCHAR(20), groupId VARCHAR(20));
INSERT INTO some_table (some_data, some_other_data, groupId) values ('a', '1', 'id1');
INSERT INTO some_table (some_data, some_other_data, groupId) values ('b', '2', 'id1');
INSERT INTO some_table (some_data, some_other_data, groupId) values ('c', '3', 'id2');
Execute the query:
SELECT '{"' + t.groupId + '": [{' + STUFF(
(
SELECT '{ "some_data":"' + td.some_data + '"', ', "some_other_data":' + td.some_other_data + '},'
FROM some_table td
WHERE t.groupId = td.groupId
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 1, '') + ']}'
FROM some_table t
GROUP BY t.groupId
Results:
{"id1": [{ "some_data":"a", "some_other_data":1},{ "some_data":"b","some_other_data":2},]}
{"id2": [{ "some_data":"c","some_other_data":3},]}
Fiddle:
http://sqlfiddle.com/#!6/66b19/35
But i run this i see an error
Error SQL Server Database Error: Conversion failed when converting the varchar value '{"' to data type int. 4 0
A: Jason array format can be found here
Looking at the example in the link you can see that you have an extra brace and an extra coma.
Solution:
Move , (coma) from + '},' to ',{ "some_data":"
Remove extra curly brace: '": [{' + STUFF( -> '": [' + STUFF(
Update:
Non-varchar columns will need to be converted to (N)VARCHAR: CONVERT( NVARCHAR, [field] )
Final Query:
SELECT '{"' + t.groupId + '": [' + STUFF(
(
SELECT ',{ "some_data":"' + td.some_data + '"', ', "some_other_data":' + CONVERT( NVARCHAR, td.some_other_data ) + '}'
FROM some_table td
WHERE t.groupId = td.groupId
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 1, '') + ']}'
FROM some_table t
GROUP BY t.groupId
P.S. looks like https://stackoverflow.com/a/45427001/6305294 simply has made a typo with the brace
A: If you are on MSSQL 2016:
SELECT t.groupId,
(
SELECT td.some_data, td.some_other_data
FROM some_table td
WHERE t.groupId = td.groupId
FOR JSON PATH
) As json_data
FROM some_table t
GROUP BY t.groupId
You can find the docs https://learn.microsoft.com/en-us/sql/relational-databases/json/json-data-sql-server
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45451261",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to create delay before ajax call? I am using jQuery 1.8.
I have a series of checkboxes that a user can check to get information on particular product. When the box is check, a function is called and loads the product info into a div. CURRENTLY, the function fires immediately after each click. So, if the visitor checks all five boxes, the ajax call will be made five times.
What I want is for the function to fire after a certain period of time once the visitor stops clicking. The function should fire only once. The purpose of the delay is to limit the number of calls and create a smoother user experience.
Here is my HTML:
<input type='checkbox' class='SomeClass' data=prodid='1'> 1
<input type='checkbox' class='SomeClass' data=prodid='2'> 2
<input type='checkbox' class='SomeClass' data=prodid='3'> 3
<input type='checkbox' class='SomeClass' data=prodid='4'> 4
<input type='checkbox' class='SomeClass' data=prodid='5'> 5
<div id='ProductInfoDiv'></div>
Here is my pseudo JavaScript:
// set vars
$Checkbox = $('input.SomeClass');
$ProductInfoDiv = $('div#ProductInfoDiv');
// listen for click
$Checkbox.click(getProductInfo);
// check which boxes are checked and load product info div
getProductInfo = function() {
// create list of product id from boxes that are checked
var QString = $Checkbox.filter(":checked");
// LOAD THE PRODUCT DIV
$ProductInfoDiv.load('SomePage.cfm?'+QString);
}
So, where do I put the delay? How do ensure that the function only fires ONCE?
A: setTimeout with clearTimeout will accomplish this. Each click would do
var timeout = null;
$(element).click(function(){
if(timeout)
{
clearTimeout(timeout);
}
timeout = setTimeout([some code to call AJAX], 500);
})
On each click, if there is a timeout it is cleared and restarted at 500 milliseconds. That way, the ajax can never fire until the user has stopped clicking for 500 milliseconds.
A: // set vars
$Checkbox = $('input.SomeClass');
$ProductInfoDiv = $('div#ProductInfoDiv');
// listen for click
$Checkbox.click(getProductInfo);
var timeout;
var timeoutDone = function () {
$ProductInfoDiv.load('SomePage.cfm?'+QString);
}
// check which boxes are checked and load product info div
getProductInfo = function() {
// create list of product id from boxes that are checked
var QString = $Checkbox.filter(":checked");
// LOAD THE PRODUCT DIV
clearTimeout(timeout);
timeout = setTimeout(timeoutDone, 4000);
}
A: var clickTimer = false;
// listen for click
$Checkbox.click(function(){
if(clickTimer) {
// abort previous request if 800ms have not passed
clearTimeout(clickTimer);
}
clickTimer = setTimeout(function() {
getProductInfo();
},800); // wait 800ms
});
Working example here:
http://jsfiddle.net/Th9sb/
A: Would it be possible to disable the checkboxes until the ajax request has been completed?
$('.SomeClass').on('click', function(e) {
$('.SomeClass').attr('disabled', true);
//-- ajax request that enables checkboxes on success/error
$.ajax({
url: "http://www.yoururl.com/",
success: function (data) {
$('.SomeClass').removeAttr('disabled');
},
error: function(jqXHR, textStatus, errorThrown) {
$('.SomeClass').removeAttr('disabled');
}
});
});
A: i think you have to put it here
$Checkbox.click(getProductInfo);
it should be like this : working example is here--> http://jsbin.com/umojib/1/edit
$Checkbox.one("click", function() {
setTimeout(function() {
getProductInfo();
},200);
});
A: If you are allowed to add another library.
Underscore has a debounce function which fits perfect on what you want.
function callback(){
// some code to call AJAX
}
$(element).click(_.debounce(callback, 500))
```
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13480706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to add multiple value for a relationship properties in neo4j? I want to add multiple value for a single relationship properties.
just like below..
I have a relation is "CALLED" which is bidirectional.I want to have two value for "DURATION" like DURATION (100-200->500,200-100->600)
Can I put two values for a single proeprties??
A: You can use a property having an array of Strings as value:
MERGE (a:Person{number:'123'})
MERGE (b:Person{number:'456'})
MERGE (a)-[r:CALLED]->(b)
ON CREATE SET r.duration = ["100-200->500"]
ON MATCH SET r.duration = ["100-200->500"]
Later on when adding the second duration value, use
MERGE (a:Person{number:'123'})
MERGE (b:Person{number:'456'})
MERGE (a)-[r:CALLED]->(b)
ON MATCH SET r.duration = n.duration + "200-100->600"
N.B. the "+" operator on an array amends a new element to the array.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29869872",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Is it possible to eliminate data loss with Redis? I understand Redis AOF and RDB persistence options and have read the doc (maybe not thoroughly). What I want to ask is this: is it possible to eliminate the possibility of data loss with Redis?
Setting appendfsync to always seems to be the closest solution. However, there is stil the possibility that Redis crashes just after responding to the client with "OK" and before persisting the data to disk. There would be no way for the client to know that the data is lost, which will result in inconsistency.
As far as I'm concerned, an option to make Redis respond after fsync should resolve the issue (or maybe an additional WAITFSYNC command). Is that possible?
A: i think for now the safest option is to add appendonly yes in your redis config.
if you are using version 1.1 or greater one.
appendfsync always is slowest among them. if you are okay with that then sure you can use it. but if you care about your DB's performance use appendfsync everysec.
The append-only file is a fully-durable strategy for Redis. every time Redis receives a command that changes the dataset (e.g. SET) it will append it to the AOF. When you restart Redis it will re-play the AOF to rebuild the state.
details
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65732779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Error in node module while installing the package in dev ERROR in /node_modules/react-file-viewer/src/app.js Module build failed (from /node_modules/babel-loader/lib/index.js):
SyntaxError: /home/myfiles/myfiles-code/myfiles/frontend/node_modules/react-file-viewer/src/app.js. Support
for the experimental syntax 'jsx' isn't currently enabled (6:3):
ReactDOM.render (Fileviewer/,
document.getElementByld('app')
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74128063",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to start text from bottom to Top? How to start the text from bottom to Top?
I Need:
I tried:
.rotated {
writing-mode: tb-rl;
transform: rotateZ(-270deg);
}
<div class="rotated">
<span>5000</span><br>
<span>3000</span><br>
<span>2000</span><br>
<span>1000</span>
</div>
Using <br /> it can be solved easily, but it will be of no used when the screen is small and <div> is position: fixed;.
A: Just change the order of adding items and use flex like this:
.rotated {
display: flex;
height: 300px;
flex-direction: column-reverse;
}
<div class="rotated">
<span>1000</span>
<span>2000</span>
<span>3000</span>
<span>5000</span>
</div>
A: You can use flexbox (display: flex) with align-items: flex-start and justify-content: flex-end.
.rotated {
display: flex;
align-items: flex-start;
justify-content: flex-end;
flex-direction: column;
/* For demo */
border: 1px solid black;
height: 200px;
width: 200px;
}
<div class="rotated">
<span>5000</span><br>
<span>3000</span><br>
<span>2000</span><br>
<span>1000</span>
</div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51101412",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to extract date from text string I need to extract the date (08-01-2021) from the below string that has no whitespace
select 'Date-08-01-2021-Trans-1000008-PH.0000-BA-CR-9999.21' from dual
I tried to apply the REGEXP_SUBSTR function as shown below, but using this query I just removed 'Date-'
with x as
(select 'Date-08-01-2021-Trans-1000008-PH.0000-BA-CR-9999.21' as str
from dual)
SELECT REGEXP_SUBSTR(STR, 'Date-([^ ]+)',1,1,'i',1)
FROM x;
Please advise
A: Just use a more precise regular expression:
SELECT REGEXP_SUBSTR(STR, 'Date-([0-9]{2}-[0-9]{2}-[0-9]{4})', 1, 1, 'i', 1)
FROM x;
Or for less accuracy but more conciseness:
SELECT REGEXP_SUBSTR(STR, 'Date-([-0-9]{10})', 1, 1, 'i', 1)
A: You are zero-padding the date values so each term has a fixed length and have a fixed prefix so you do not need to use (slow) regular expressions and can just use simple string functions:
SELECT TO_DATE(SUBSTR(value, 6, 10), 'DD-MM-YYYY')
FROM table_name;
(Note: if you still want it as a string, rather than as a date, then just use SUBSTR without wrapping it in TO_DATE.)
For example:
WITH table_name ( value ) AS (
SELECT 'Date-08-01-2021-Trans-1000008-PH.0000-BA-CR-9999.21' FROM DUAL
)
SELECT TO_DATE(SUBSTR(value, 6, 10), 'DD-MM-YYYY') AS date_value
FROM table_name;
Outputs:
DATE_VALUE
08-JAN-21
db<>fiddle here
If the Date- prefix is not going to always be at the start then use INSTR to find it:
WITH table_name ( value ) AS (
SELECT 'Date-08-01-2021-Trans-1000008-PH.0000-BA-CR-9999.21' FROM DUAL UNION ALL
SELECT 'Trans-1000008-Date-08-02-2021-PH.0000-BA-CR-9999.21' FROM DUAL
)
SELECT TO_DATE(SUBSTR(value, INSTR(value, 'Date-') + 5, 10), 'DD-MM-YYYY') AS date_value
FROM table_name;
Which outputs:
DATE_VALUE
08-JAN-21
08-FEB-21
If you can have multiple Date- substrings and you want to find the one that is either at the start of the string or has a - prefix then you may need regular expressions:
WITH table_name ( value ) AS (
SELECT 'Date-08-01-2021-Trans-1000008-PH.0000-BA-CR-9999.21' FROM DUAL UNION ALL
SELECT 'TransDate-1000008-Date-08-02-2021-PH.0000-BA-CR-9999.21' FROM DUAL
)
SELECT TO_DATE(
REGEXP_SUBSTR(value, '(^|-)Date-(\d\d-\d\d-\d{4})([-.]|$)', 1, 1, 'i', 2),
'DD-MM-YYYY'
) AS date_value
FROM table_name;
db<>fiddle here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68408215",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Run file in conda inside docker I have a python code that I attempt to wrap in a docker:
FROM continuumio/miniconda3
# Python 3.9.7 , Debian (use apt-get)
ENV TARGET=dev
RUN apt-get update
RUN apt-get install -y gcc
RUN apt-get install dos2unix
RUN apt-get install -y awscli
RUN conda install -y -c anaconda python=3.7
WORKDIR /app
COPY . .
RUN conda env create -f conda_env.yml
RUN echo "conda activate tensorflow_p36" >> ~/.bashrc
RUN pip install -r prod_requirements.txt
RUN pip install -r ./architectures/mask_rcnn/requirements.txt
RUN chmod +x aws_pipeline/set_env_vars.sh
RUN chmod +x aws_pipeline/start_gpu_aws.sh
RUN dos2unix aws_pipeline/set_env_vars.sh
RUN dos2unix aws_pipeline/start_gpu_aws.sh
RUN aws_pipeline/set_env_vars.sh $TARGET
Building the image works fine, running the image using the following commands works fine:
docker run --rm --name d4 -dit pd_v2 sh
My OS in windows11, when I use the docker desktop "CLI" button to enter the container, all I need to do is type "bash" and the conda environment "tensorflow_p36" is activated and I can run my code.
When I try docker exec in the following manner:
docker exec d4 bash && <path_to_sh_file>
I get an error that the file doesn't exists.
What is missing here? Thanks
A: Won't bash && <path_to_sh_file> enter a bash shell, successfully exit it, then try to run your sh file in a new shell? I think it would be better to put #! /usr/bin/bash as the top line of your sh file, and be sure the sh file has executable permissions chmod a+x <path_to_sh_file>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72172927",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: LabView: Icon identification I'm entirely new to LabView, and as a pet project, I'm trying to recreate a pulse detector. Thing is, the version of the .VI is LabView2010, and I can't open the.VI in LabView2009, so were trying to remake it by looking at the module. I do however, have the image, but since I'm pretty new, I can't identify some of the components used. Below is an image of the .VI, as well as, the parts I don't know encircled with red and enumerated. What exactly are these? Thanks!
A: To make a shift register, right click on the edge of the while loop and place a shift register. The Wait (ms) node is found in the timing functions pallet. #1 and #3 are found in the waveform generation pallet. And #2 is a waveform graph that is bound to the output of the filter. Just right click on the output of the filter and create an Indicator
A: I only have limited experience with the specific features in this code, so I don't have exact names, but it should point you in the right direction:
2 is a dynamic data indicator.
1 converts it to a waveform (it probably appears automatically if you hook up a DDT wire to a WF function.
3 unbundles the data from the waveform. It should be in the waveform palette.
4 is a shift register.
5 is a wait function.
In general, I would recommend that you get to learning, as you will need to understand these things to at least that level before you can be proficient.
Also, the NI forums are much more suitable for this type of question and they have many more users. I would suggest if you have such questions which you can't answer yourself, then post them there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15017921",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is it possible to override nant targets from included buildfile? I have a generic common.xml file that holds a number of generic nant targets that are re-used among multiple builds. What I want to do is 'override' some of these nant targets and include additional steps either before or after the existing target is executed.
Are nant targets used from the current file first? ie. If i create a nant target in the current buildfile with the same name as a target in an included file does that one get called and the included one ignored? If that's the case I can just do and call the included target but it would seem like then that would be a recursive call rather then to an included task.
Thoughts?
A: I had the same question (and found the same results), but I also found a workaround. Allow me to illustrate with an example.
You have a ProjectFile.build and a CommonFile.build. Let's say you want to overwrite a target called "Clean".
You would need to create a new file (call it CommonFile_Clean.build) which contains:
<?xml version="1.0"?>
<project>
<target name="Clean">
<echo message="Do clean stuff here" />
</target>
</project>
In CommonFile.build, you conditionally include CommonFile_Clean.build:
<?xml version="1.0"?>
<project>
<echo message="checking Clean definition..." />
<if test="${not target::exists('Clean')}">
<echo message="Clean target not defined." />
<include buildfile="CommonFile_Clean.build" />
</if>
</project>
In ProjectFile.build, you can either define the Clean target (in which case CommonFile_Clean.build will not be used) or use the default implementation as defined in CommonFile_Clean.build.
Of course, if you have a large number of targets, this will be quite a bit of work.
Hope that helps.
A: No, I've just tried it for you, as I have a similar set-up, in that I have all of the build targets we use in a commonFile.build and then use the following code to bring it in...
<include buildfile="../commonFile.build"/>
In my newFile.build (that includes the commonFile.build at the top of the file), I added a new target called 'build', as it exists in the commonFile, and here's the error message you get in response...
BUILD FAILED
Duplicate target named 'build'!
Nice idea, probably bourne of OO principles, but sadly it doesn't work.
Any good?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1158882",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: IBM Mobile Application Platform Pattern Type 6.1 deployment error I get the following error when I deploy an instance of a pattern created using the "Out of the Box" IBM Mobile Application Platform Pattern Type 6.1 Template on IBM PureApplication System. The template uses the artifacts/WorklightStarter.ear file as the enterprise application for the WL Server part.
Error 500: javax.servlet.ServletException: Worklight Console
initialization failed.Logged Exception: java.lang.RuntimeException:
FWLSE0206E: The project /WorklightStarter failed to initialize,
because the project database schema for data source
jdbc:db2://10.14.15.184:50000/WLRTIME is from version N/A, which is
not supported by the server from version 6.1.0.00.20131123-2150. Use
the Worklight ant tasks to upgrade the project database schema.
[project WorklightStarter].
I have seen posts that explain the WL Runtime DB migration I need go through to fix this error. But that migration should be required for WL Applications that were built on an earlier version of WL (for e.g 5.0.6). I am getting this error from an Out of the Box WorkliteStarter.ear application that is shipped with the IBM Mobile Application Platform Pattern Type 6.1 Template. How do I fix this error?
A: The error you saw is usually caused by not upgrading the database workload standard to match the version of your worklight pattern.
Can you please check following things?
a) Have you installed the database workload standard shipped with 6.1?
http://pic.dhe.ibm.com/infocenter/wrklight/v6r1m0/topic/com.ibm.worklight.deploy.doc/pureapp/t_pureapp_installing_DB_workload_standards.html
b) Did you explicitly re-selected the workload standard in virtual application builder after importing the sample pattern? There is an issue with DB2 component that database workload standard is not selected correctly when importing the pattern zip. So to workaround this, you need to make sure the imported pattern has selected correct database workload standard
http://pic.dhe.ibm.com/infocenter/wrklight/v6r1m0/topic/com.ibm.worklight.deploy.doc/pureapp/t_pureapp_importing_sample_wl_application_pattern.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22645681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Encrypting data for storage in database We have a site, where a user will be saving extremely personal and sensitive data in our database.
We of course will need to be encrypting this data before it is stored in the database, and using SSL. It is an MVC application that will use form authentication. what is the best way to ensure that this data is encrypted from the time we save it until the time it is decrypted for display on their personal page.
We need to also ensure that it will be secure from even our developers and dba's working on the app.
What is the best way to handle this situation?
A: SQL Server has some built-in encryption capabilities (dead link) encryption capabilities you might take a look at.
A: There is no way to keep a DBA out of the data unless you used a public key encryption and the end user would have to control this. If the end user lost their key, they would lose all their data.
You could have a separate database where you store the keys and your DBA wouldn't have access to this DB.
You would have to have two DBAs, one for the data and one for the keys.
This is assuming you don't trust your DBAs, but then you shouldn't have hired them.
If you trust your DBAs, then you let them have access to both DBs, but require that they have separate accounts so if one account gets compromised, they(hackers) wouldn't have access to everything.
Typically, in a well designed system, the DBA/Admins have separate accounts for their personal work and an elevated account for doing work.
I'm assuming the programmers only have access to a test environment. If they have access to the production environment, then they will have access to both the keys and the data.
A: Every Encryption has a key and the key is ( to get / not to get ) that key :)
The best way is to set the key on web.config which you can do without any programming background
And I have seen a beautiful AES Encryption Algorithm implementation at StackOverflow. I would suggest you use that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4924799",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Can not modify inside prototype array Well the problem is with the Game's instance of rects: [], which should be array of objects Rect. When i access the rects property inside Game gives undefined.
http://jsbin.com/ibilec/34/edit
(function(window, document, console) {
'use strict';
function Rect() {
this.x = 0;
this.y = 0;
this.width = 20;
this.height = 20;
}
Rect.prototype.draw = function(ctx) {
ctx.fillRect(this.x, this.y, this.width, this.height);
};
var Game = Object.create({
rects: [], /// PROBLEM IS WITH this
draw: function() {
console.log('Draw called', this.rects);
if (this.rects) {
this.rects.forEach(function(rect, index) {
console.log(rect);
rect.draw(this.ctx);
});
}
//window.setInterval(function() { this.ctx.clearRect(0, 0, 200, 200); }, 1000);
},
genRect: function() {
var newRect = new Rect();
newRect.x = parseInt(Math.random() * 200, 10);
newRect.y = parseInt(Math.random() * 200, 10);
this.rects.push(newRect);
},
loop: function() {
//Game.draw();
// Frame rate about 30 FPS
window.setInterval(this.draw, 1000 / 30);
},
init: function() {
this.canvas = document.getElementById('game');
this.height = this.canvas.height;
this.width = this.canvas.width;
window.ctx = this.canvas.getContext('2d');
this.genRect();
this.loop(); //start loop
}
});
var game = Object.create(Game);
game.init();
})(window, document, console);
A: The draw method is not called as a method of the object, it's called as a function in the global scope, so this will be a reference to window, not to the Game object.
Copy this to a variable, and use it to call the method from a function:
var t = this;
window.setInterval(function() { t.draw(); }, 1000 / 30);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14303595",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to keep a sprite drawn even after the the condition that drew it is no longer valid? The question I have has to do with a specific portion of my code in Pygame where I m trying to draw a new sprite onto the screen every couple of seconds.
def spawn(self):
self.count += 2
alien1_sprite = Alien1((rand.randrange(38,462),50))
rem = self.count % 33
if rem == 0:
self.alien1 = pygame.sprite.Group()
self.alien1.add(alien1_sprite)
self.alien1.draw(screen)
Whenever I call the spawn function no sprites exist at the same time, how can I resolve this issue?
A: The problem is, you create a new Group for each alien. You only have to create the Group once and add the Alien Sprites to this one Group:
*
*Create the alien1 Group in the constructor (init) of the class.
*Add the aliens in spawn method.
*Draw all the aliens in the Group using your "draw" method. (The name of your method may be different - I don't know)
class ...
def __init__(self):
# [...]
self.alien1 = pygame.sprite.Group() # creat the group in the constructor
def spawn(self):
self.count += 2
rem = self.count % 33
if rem == 0:
alien1_sprite = Alien1((rand.randrange(38,462),50))
self.alien1.add(alien1_sprite)
def draw(self): # your draw or render method
# [...]
self.alien1.draw(screen) # draw all the aliens
Read the documentation of pygame.sprite.Group. The Group manages the Sprites it contains. The Group is the "list" that stores the Sprites.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70630237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Temporarily caching HTTP responses from parametrised requests using RxJS (and Angular) I would like to cache and expire the HTTP responses from e.g. a GET request with certain params.
An example of a use case:
Suppose I build a service like this:
@Injectable()
export class ProductService {
constructor(private http: HttpClient) {}
getProduct$(id: string): Observable<Product> {
return this.http.get<Product>(`${API_URL}/${id}`);
}
getProductA$(id: string): Observable<ProductA> {
return this.getProduct$(id).pipe(
// bunch of complicated operations here
};
}
getProductB$(id: string): Observable<ProductB> {
return this.getProduct$(id).pipe(
// bunch of other complicated operations here
};
}
}
Now for whatever reason, function A is called in component A and function B is called in component B. I know this could be done in another way (such as a top-level smart component getting the HTTP data and passing it through input params), but for whatever reason, the two components are "smart" and they each call a service function.
Both components are loaded on the same page, so two subscriptions happen = two HTTP requests to the same endpoint - even though we know that the result will most likely be the same.
I want to simply cache the response of getProduct$, BUT I also want this cache to expire pretty quickly, because in 2 minutes Margareth from product management is going to change the product price.
What I tried but doesn't work:
Basically, I tried keeping a dictionary of hot observables using shareReplay with a window time of 5s. My assumption was that if the (source) observable completes or the number of subscriptions is 0, then the next subscriber would simply refire the observable, but this does not seem to be the case.
private product$: { [productId: string]: Observable<Product> } = {};
getProduct$(id: string): Observable<Product> {
if (this.product$[id]) {
return this.product$[id];
}
this.product$[id] = this.http.get<Product>(`${API_URL}/${id}`)
.pipe(
shareReplay(1, 5000), // expire after 5s
)
);
return this.product$[id];
}
I thought, I can try to remove the observable from my dictionary on completion using finalize or finally, but unfortunately those are also called on every unsubscribe.
So the solution must be perhaps more complicated.
Any suggestions?
A: EDIT July 2022: Since the original solution worked only on older RxJS versions and was basically based on a bug in RxJS here's the same functionality for RxJS 7.0+:
import { of, defer, share, delay, tap, timestamp, map, Observable } from 'rxjs';
let counter = 1;
const mockHttpRequest = () =>
defer(() => {
console.log('Making request...');
return of(`Response ${counter++}`).pipe(delay(100));
});
const createCachedSource = (
makeRequest: () => Observable<any>,
windowTime: number
) => {
let cache;
return new Observable((obs) => {
const isFresh = cache?.timestamp + windowTime > new Date().getTime();
// console.log(isFresh, cache);
if (isFresh) {
obs.next(cache.value);
obs.complete();
} else {
return makeRequest()
.pipe(
timestamp(),
tap((current) => (cache = current)),
map(({ value }) => value)
)
.subscribe(obs);
}
}).pipe(share());
};
const cached$ = createCachedSource(() => mockHttpRequest(), 1000);
// Triggers the 1st request.
cached$.subscribe(console.log);
cached$.subscribe(console.log);
setTimeout(() => cached$.subscribe(console.log), 50);
setTimeout(() => cached$.subscribe(console.log), 200);
// Triggers the 2nd request.
setTimeout(() => cached$.subscribe(console.log), 1500);
setTimeout(() => cached$.subscribe(console.log), 1900);
setTimeout(() => cached$.subscribe(console.log), 2400);
// Triggers the 3nd request.
setTimeout(() => cached$.subscribe(console.log), 3000);
Live demo: https://stackblitz.com/edit/rxjs-rudgkn?devtoolsheight=60&file=index.ts
ORIGINAL ANSWER: If I understand you correctly you want to cache responses based on their id parameter so when I make two getProduct() with different ids I'll get two different uncached results.
I think the last variant is almost correct. You want it to unsubscribe from its parent so it can re-subscribe and refresh the cached value later.
The shareReplay operator worked differently until RxJS 5.5 if I recall this correctly where shareReplay has changed and it didn't re-subscribe to its source. It was later reimplemented in RxJS 6.4 where you can modify its behavior based on a config object passed to shareReplay. Since you're using shareReplay(1, 5000) it seems like you're using RxJS <6.4 so it's better to use publishReplay() and refCount() operators instead.
private cache: Observable<Product>[] = {}
getProduct$(id: string): Observable<Product> {
if (!this.cache[id]) {
this.cache[id] = this.http.get<Product>(`${API_URL}/${id}`).pipe(
publishReplay(1, 5000),
refCount(),
take(1),
);
}
return this.cache[id];
}
Notice that I also included take(1). That's because I want the chain to complete immediately after publishReplay emits its buffer and before it subscribes to its source Observable. It's not necessary to subscribe to its source because we just want to use the cached value. After 5s the cached value is discarded and publishReplay will subscribe to its source again.
I hope this all makes sense :).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54947878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Compiling/Using MySQL Connector/C++ with MinGW Well, I guess the title sums it up pretty well. The connector comes with Visual Studio libraries and dlls. There is also a source tar available which doesn't compile.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3419876",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Filter an excel range based on multiple dynamic filter conditions (with column values delimited) I posted a similar question: Filter an excel range based on multiple dynamic filter conditions. Now I am considering a more general case, i.e. for one of the filter column (Releases, column E) it may have several values delimited by comma. The expected result should filter by rows that have as release values: A or B, but the releases column can come with more than one value and for team filter by specific one or all of them (ALL wildcard).
Here is the sample (when we have a maximum of two values for releases column):
I was able to obtain the desired result based on filter conditions, but it requires helper columns (columns: J,K,L), via the formula in N3:
=FILTER(D3:H15, (IF(B3="ALL", D3:D15<>"*",D3:D15=B3)) * (L3:L15))
and column L does the magic to identify the rows with the wanted release values:
=LET(result, ISNUMBER(MATCH(J3:K15,TEXTSPLIT(B4,", "),0)), IF((FILTER(result, {1,0})
+ FILTER(result, {0,1}))>0, TRUE, FALSE))
I am looking for a solution that wouldn't require helper columns and also for the general case where Release column can have more than two values, for example: A, C, G, F... if that is possible.
Here a link to my sample file:
https://1drv.ms/x/s!AlZxw2GG3C7Ihyyx8_AM5ylbZWaI?e=F3WUep
Note:
*
*I cannot use TEXTSPLITin a single invocation to obtain columns J,K, because when the text input argument is an array (range) there is no way to delimit by empty string, so TEXTSPLIT(E3:E15,",") doesn't return two columns (it works for a single cell, but not for a range), so I have to use TEXTAFTER(E3:E15,",") to obtain the information after the comma in column K
A: Lets try-
=FILTER(D3:H15,BYROW(E3:E15,
LAMBDA(x,MAX(--ISNUMBER(XMATCH(TOCOL(TEXTSPLIT(x,",")),
TOCOL(TEXTSPLIT(B4,", ")),0)))))
* IF(B3="ALL",D3:D15<>"",D3:D15=B3))
Explanation of the solution to identify if release value is present:
It uses BYROW function which processes each row by a LAMBDA function you define.
The formula: TOCOL(TEXTSPLIT(B4,", ")
Generates a column array with the values of B4, i.e.: {A;B}(semicolon represents a column array) in our case a 2x1 array. TEXTSPLIT spits a string by delimiter (", ").
The formula: TOCOL(TEXTSPLIT(x,", "))
Generates an array column for a value represented by x split by the delimiter (", ") . For example if x is: A it will generate: {A} and for A,C the output will be: {A;C}, i.e 2x1 array.
The XMATCH function with signature: XMATCH(lookup_value, lookup_array, 0)
will return the index position of lookup_array when an exact match is found for look_value, otherwise N/A. If lookup_value is a column array, the XMATCH function is evaluated for each element of the array and return the result in a column array.
For lookup_array: {A;B} it will produce the following output, based on the following input values:
Lookup_value
Result
{A}
{1}
{A;C}
{1;N/A}
{C;D}
{N/A;N/A}
{A;B}
{1;2}
{B;A}
{2;1}
{B;A;C}
{2;1;N/A}
{C}
{N/A}
In our case:
XMATCH(TOCOL(TEXTSPLIT(x,", ")),TOCOL(TEXTSPLIT(B4,", ")),0)
will return for each releases value (x) ({A}, {A;B}, {A;C}, etc.) a column array of size of the number or elements of x, indicating the row position of {A, B} (if matches) or N/A (not found) for each element of x.
ISNUMBER converts the result to TRUE (if matches) or FALSE (for N/A). --ISNUMBER(cell) converts the result to 1 (match) or 0 (for N/A). Finally MAX function returns 1 if there is at least one match, otherwise 0.
Because BYROW processes the LAMBDA function for each row, it returns 1 (at least one match) or 0 (no match) for each row of E3:E15.
=BYROW(E3:E15,LAMBDA(x,
MAX(--ISNUMBER(XMATCH(TOCOL(TEXTSPLIT(x,", ")),
TOCOL(TEXTSPLIT(B4,", ")),0)))))
which is what we need as a filter condition
Note: You can use MATCH function instead of XMATCH, but keep in mind that for the third input argument the default behavior is different. The default value for MATCH is 1 (largest value that is less than or equal to lookup_value) and for XMATCH is 0 (exact match).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73725751",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Excel how get number of hours in a time interval? I have 2 columns with:
Night shift start: 19:00
Night end: 04:00
And I have some date columns with for each day..
Work started: 07:30
Worked ended: 22:00
I want to get the number of hours as a decimal that is between the night shift start and night end. I need to calculate the number of "night shift hours" for worked hours.
From comment: I do not want to get the total number of hours. I want to calculate the number of "night shift hours" and that is hours between 19:00-04:00
A: =IF(B1-A1 < 0, 1-(A1-B1),( B1-A1))
Assuming that cell A1 contains start, B1 contains end time.
Let me know, if it helps OR errors.
Time without date is not enough to do the subtraction considering the start can be the night before today.
Are you OK to try VBA?
EDIT: The formula is meaningful within 12 hour limit. I will see if it can be made simpler.
A: Given start time in B5 and end time in C5 this formula will give you the decimal number of hours that fall in the range 19:00 to 04:00
=MOD(C5-B5,1)*24-(C5<B5)*(19-4)-MEDIAN(C5*24,4,19)+MEDIAN(B5*24,4,19)
format result cell as number
A: just substract the two dates to get the difference in days, and multiply by 24 to get the difference in hours
=(B1-A1)*24
this is correct when both B1 and A1 contain a datetime value, but in case your cells contain just a time value, with no day value, and given that the calculation spans the night (there is a day change in between) you need to add one day to the difference:
=IF(B1<A1,1+B1-A1,B1-A1)*24
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17654303",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Function javascript I want to show a dialog box containing a random code I make. This is my function:
function randomString() {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var string_length = 8;
var randomstring = '';
for (var i = 0; i < string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum, rnum + 1);
}
alert(randomstring);
window.location = "Insert-Transac.jsp";
}
I want to show the variable randomstring for a time and hide it. Can any one help me?
A: Would this work?
function randomString() {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var string_length = 8;
var randomstring = '';
for (var i = 0; i < string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum, rnum + 1);
}
return randomstring;
}
document.getElementById("randstring").innerHTML = randomString();
window.setTimeout(function(){document.getElementById("randstring").innerHTML = ""}, 2000);
This assumes you have an element with the ID of randstring.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16245322",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Compare two lists of class objects and keep the difference and the equals in Python I'm currently stuck and i hope someone here can help me out. What I am trying to achieve is following: I have two APIs, those deliver me each a list of learning courses represented as python class instance. At one side there is the MS Learn API and the workflow is that I get them, map the data and insert them in my database. But before I do this I want to check for 1.) duplicated courses and 2.) if there is a duplicate - is it maybe newer then my saved course in my database? And 3.) Do I have courses in my database that are not existing in the MS Learn Course List?
The attributes I need to check are the "referenceID" for dupes / non existing courses on external side and the "created_at" if something is newer / older. Instead of wild looping and saving values in different list I would like to use something more clean and pythonic like a custom eq function and then comparing the whole two lists of class objects and keeping 1. all new courses, removing the dupes from the list and 2. the difference that is not existing in the list for external courses so I can delete them
Sorry for the long text here’s some code:
@dataclass
class Courses:
id: str
title: str
description: str
courseUrl: str
referenceId: str
providerId: int
publishingState: str
createdAt: str
updatedAt: str
First try of an custom eq func - never used that before idk if this would work:
def __eq__(self, other):
if isinstance(other, Courses):
return self.title == other.title \
and self.description == other.description \
and self.courseUrl == other.courseUrl \
and self.referenceId == other.referenceId \
and self.providerId == other.providerId \
and self.publishingState == other.publishingState \
and self.createdAt == other.createdAt \
and self.updatedAt == other.updatedAt
return False
First start of my looping chaos:
internal_courses = get_courses(request)
internal_reference_ids = []
duplicated_courses = []
for int_course in internal_courses:
internal_reference_ids.append(int_course.referenceId)
for ext_course in external_courses:
if ext_course.referenceId in internal_reference_ids:
duplicated_courses.append(ext_course)
external_courses.remove(ext_course)
Thank you very much in advance, I am exited to learn something new :)
A: Your defined __eq__ method enables you to compare class instances like this:
if course_a == course_b:
# Do something
When comparing two lists, you call list.__eq__ method instead. If this list contains your Courses objects (btw, you should use singular form, as it is single Course), they will be compared using your defined __eq__ method.
This means, that you can just compare [course_a, course_b] == [course_a, course_c] and it should work as you intented.
class Example:
def __init__(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2
def __eq__(self, other):
return self.arg1 == other.arg1 and self.arg2 == other.arg2
# Initialize two instances with identical arguments.
one = Example('x', 'y')
two = Example('x', 'y')
print(one == two) # True
a = [one]
b = [two]
print(a == b) # Also True
P.S.
Check out @dataclass(eq=True) as it does pretty much the same thing
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69135843",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Coverting old js project to webpack npm getting error like Cannot read property 'className' of null I am converting old codekit project into webpack. I almost there but getting strange error when using scrollReveal which I never got before.
There is error seems purely javascript related tho...
Uncaught TypeError: Cannot read property 'className' of null
This is the usage which is currently worked on the old site.
// scroll reveal
const ScrollReveal = require('scrollreveal');
// jQuery
(function ($) {
// scroll reveal profile listings
if (!/(?:^|\s)ie\-[6-9](?:$|\s)/.test(document.body.className)) {
window.sr = new ScrollReveal({reset: false});
sr.reveal('[data-reveal="true"]', {duration: 1000});
}
})(jQuery);
What I am doing is testing the body class with some regex to make sure scrollReveal does not fire in IE 6-9.
Everything compiles fine, it's just i'm getting error in the console log and no scrollReveal.
Any ideas would be great thanks.
A: Add a wrapper around your code:
document.addEventListener("DOMContentLoaded", function(event) {
// scroll reveal
const ScrollReveal = require('scrollreveal');
// scroll reveal profile listings
if (!/(?:^|\s)ie\-[6-9](?:$|\s)/.test(document.body.className)) {
window.sr = new ScrollReveal({reset: false});
sr.reveal('[data-reveal="true"]', {duration: 1000});
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62497677",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: list comprehension using multiple columns I have a pandas data frame with a column for actuals, and predicted. I would like to make a new column using list comprehension that = 1 when actuals = predicted, 0 otherwise. I know how to do this using np.where, but I was curious to know how to do it using list comprehension.
This works using np.where:
combined['correct'] = np.where(combined.actual==combined.predicted, 1, 0)
Thanks!
A: You don't need np.where nor list comprehension:
You can use this:
combined['correct'] = (combined.actual == combined.predict).mul(1)
or
combined['correct'] = (combined.actual == combined.predict).astype(int)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47758808",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: DIV's reorder by themselves upon expand - how do I keep the same order? I've got a grid of items that upon click expand to show a table below it. It works fine, but it reorders the DIV's positions as per my illustration below.
I need them to keep their respective position in their "columns".
Here's the illustration to make it clear:
And here is my HTML code:
<div
class="item-component"
ng-controller="CollapseCtrl"
ng-repeat="component in components.components | filter : components.filterByFilter | filter : searchText"
>
<div class="component-wrapper" ng-click="isCollapsed = !isCollapsed">
Item - click to expand
</div>
<div class="codes-wrapper" collapse="isCollapsed">
<table class="table table-striped table-condensed">
Expanded content here
</table>
</div>
</div>
And here is the .item-component class:
.item-component {
width: 33.33333333333333%;
float: left;
padding-left: 15px;
}
How would I achieve the "expected result" in my illustration?
A: Use display:inline-block instead of float:left on your .item-component
Living Demo
.item-component {
width: 33.33333333333333%;
display: inline-block;
padding-left: 15px;
}
Or, you can take a look at BootStrap and do it by using the :before element maintaning the float:left as you had it before.
You would also need to wrap each row:
.col{
float:left;
width: 32.33%;
min-height: 50px;
background: #ccc;
padding: 20px;
box-sizing: border-box;
}
.row{
display:block;
}
/* This do the trick */
.row:before{
content: " ";
display: table;
box-sizing: border-box;
clear: both;
}
Living example
Update
If you don't want the gap you will have to look for another HTML markup. You will have to print first each column with each rows.
This is the needed html markup:
<div class="col">
<div class="row" id="demo">1</div>
<div class="row">4</div>
<div class="row">7</div>
</div>
<div class="col">
<div class="row">2</div>
<div class="row">5</div>
<div class="row">8</div>
</div>
<div class="col">
<div class="row">3</div>
<div class="row">6</div>
<div class="row">9</div>
</div>
And the needed css:
.col{
float:left;
width: 32.33%;
}
.row{
display:block;
padding: 20px;
box-sizing: border-box;
background: #ccc;
min-height: 50px;
}
#demo{
height: 150px;
background: red;
}
Living demo
A: You can do it in the following way.
HTML:
<div class="container">
<div class="col">1</div>
<div class="col">2</div>
<div class="col">3</div>
<br class="clear" />
<div class="col">4</div>
<div class="col">5</div>
<div class="col">6</div>
<br class="clear" />
<div class="col">7</div>
<div class="col">8</div>
<div class="col">9</div>
<div>
CSS:
.col {
float: left;
width: 100px;
min-height: 100px;
background: #ccc;
padding: 20px;
margin: 10px;
cursor: pointer;
}
.col:hover {
background: yellow;
}
JS:
$('.col').click(function() {
if ($(this).is('.clicked')) {
$(this).removeClass('clicked');
} else {
$(this).addClass('clicked')
}
});
Live demo: http://jsfiddle.net/S7r3D/1/
ETA: the problem with this solution is that it moves entire row down. I don't really see how to nicely achieve what you want...You could try to overflow the other divs, but it depends on your needs. Is such solution acceptable?
ETA2: actually I made it perfect I think! Have a look here: http://jsfiddle.net/S7r3D/3/
The crucial change was rearranging divs and putting them in columns instead.
HTML:
<div class="container">
<div class="fleft">
<div class="col">1</div>
<div class="col">4</div>
<div class="col">7</div>
</div>
<div class="fleft">
<div class="col">2</div>
<div class="col">5</div>
<div class="col">8</div>
</div>
<div class="fleft">
<div class="col">3</div>
<div class="col">6</div>
<div class="col">9</div>
</div>
<div>
CSS:
.col {
clear: both;
width: 100px;
min-height: 100px;
background: #ccc;
padding: 20px;
margin: 10px;
cursor: pointer;
}
.col:hover {
background: yellow;
}
.col.clicked {
height: 300px;
background-color: red;
}
.fleft
{
float: left;
}
JS: /* same as above */
A: Create three container divs, and afterwards, put {1, 4, 7} into div1, {2, 5, 8} into div2, and {3, 6, 9} into div3.
Otherwise you will have it very difficult to control their positioning.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21779673",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Incorrect File Download using mechanize response in Perl I created a script which access a URL with basic authentication. Once I've passed the credentials, it will download the file in my local folder. The problem is I got an incorrect filename. Here's my sample code:
#!/usr/bin/env perl
use strict;
use warnings;
use WWW::Mechanize;
use HTTP::Cookies;
my $url = "http://sampleurl.com";
my $dir = 'C:\\pl';
my $mech = WWW::Mechanize->new();
$mech->cookie_jar(HTTP::Cookies->new());
$mech ->credentials("sampleurl.com:80", "sampleurl.com", "username", "password");
$mech->get($url);
my $res = $mech->res();
if($res->is_success){
my $filename = $res->filename();
print $filename;
$mech->save_content( $dir.'\\'.$filename, binmode => ':raw', decoded_by_headers => 1 );
print $mech->status;
}else{
print "Error";
}
exit 0;
Instead of downloading sample_url.DOC, it only downloaded sample with no file extension. can you help with my problem? I want to download the whole file.
A: There's no guarantee that $res->filename(); will produce a file extension or anything at all for that matter. The page you're currently reading doesn't have a filename extension for example.
You will have to guess a filename extension from the media type.
use MIME::Types qw(by_mediatype);
...
my $filename = $r->filename();
if(!$filename) { $filename = 'untitled'; }
if($filename !~ /\.[a-zA-Z0-9]{1,4}$/) {
my $type = $res->header('Content-Type');
my $ext = 'txt';
if($type) {
my @types = by_mediatype($type);
if($#types > -1) {
$ext = $types[0][0];
}
}
$filename .= '.' . $ext;
}
print $filename;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20067040",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Dividing a bit string into three parts in C I currently have a integer value that was read from an input file as a hexadecimal. I need to divide the 32 bit bitstream into three separate parts in order to manipulate it. The desired output is below:
desired output:
In this, V is my input value, left is the first X1 digits, next is the digits between X1 and X2, and last is the digits from X2 to the end. There is a constraint that each subsection must be greater than 0 in length.
What makes this difficult is that the location where I am splitting x varies (X1 and X2 can change)
Is there a good way to split these up?
A: If i understand your question, you want to allocate data. Look alloca malloc fucntions.
A: The splitter() function here does the job you ask for. It takes quite a lot of arguments, unfortunately. There's the value to be split (value), the size of the chunk at the least significant end of the value (p1), the size of the middle chunk (p2), and then pointers to the high, medium and low values (hi_val, md_val, lo_val).
#include <assert.h>
#include <inttypes.h>
#include <stdio.h>
static void splitter(uint32_t value, unsigned p1, unsigned p2, uint32_t *hi_val, uint32_t *md_val, uint32_t *lo_val)
{
assert(p1 + p2 < 32);
*lo_val = value & ((1U << p1) - 1);
value >>= p1;
*md_val = value & ((1U << p2) - 1);
value >>= p2;
*hi_val = value;
}
static void test_splitter(uint32_t value, int p1, int p2)
{
uint32_t hi_val;
uint32_t md_val;
uint32_t lo_val;
splitter(value, p1, p2, &hi_val, &md_val, &lo_val);
printf("0x%.8" PRIX32 " (%2u,%2u,%2u) = 0x%.4" PRIX32 " : 0x%.4" PRIX32 " : 0x%.4" PRIX32 "\n",
value, (32 - p1 - p2), p2, p1, hi_val, md_val, lo_val);
}
int main(void)
{
uint32_t value;
value = 0xFFFFFFFF;
test_splitter(value, 9, 11);
value = 0xFFF001FF;
test_splitter(value, 9, 11);
value = 0x000FFE00;
test_splitter(value, 9, 11);
value = 0xABCDEF01;
test_splitter(value, 10, 6);
test_splitter(value, 8, 8);
test_splitter(value, 13, 9);
test_splitter(value, 10, 8);
return 0;
}
The test_splitter() function allows for simple testing of a single value plus the sections it is to be split in, and main() calls the test function a number of times.
The output is:
0xFFFFFFFF (12,11, 9) = 0x0FFF : 0x07FF : 0x01FF
0xFFF001FF (12,11, 9) = 0x0FFF : 0x0000 : 0x01FF
0x000FFE00 (12,11, 9) = 0x0000 : 0x07FF : 0x0000
0xABCDEF01 (16, 6,10) = 0xABCD : 0x003B : 0x0301
0xABCDEF01 (16, 8, 8) = 0xABCD : 0x00EF : 0x0001
0xABCDEF01 (10, 9,13) = 0x02AF : 0x006F : 0x0F01
0xABCDEF01 (14, 8,10) = 0x2AF3 : 0x007B : 0x0301
If any of the sections is larger than 16, the display gets spoiled — but the code still works.
In theory, the 1U values could be a 16-bit quantity, but I'm assuming that the CPU is working with 32-bit int. There are ways (UINT32_C(1)) to ensure that it is a 32-bit value, but that's probably OTT. The code explicitly forces 32-bit unsigned integer values, and prints them as such.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42311028",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-5"
}
|
Q: Check If List of Objects Contains Empty or Null Item Value I have List of object returned from a native query. This list has String, Integer and Date. The variable looks like this:
Object[] result = (Object[])query.getSingleResult();
I need to check whether the list contains null or empty value. ObjectUtils from org.apache.commons.lang3.ObjectUtils worked effortlessly but if I were to do this without the library, how to achieve same result?
A: There is no canonical definition of 'empty value' for either Integer or Date.
You just program what you mean, and 'empty' is not a valid answer to the question 'what do you mean'.
For example: "Empty strings, the 0 integer, and sentinel instant value with epochmillis 0 (Date is a lie. It does not represent dates; it represents instants, and badly at that; use java.time.Instant instead normally)".
Then, you just.. program that:
for (Object obj : result) {
if (obj == null) return false;
if (obj instanceof Date) {
if (((Date) obj).getTime() == 0) return false;
} else if (obj instanceof String) {
if (((String) obj).isEmpty()) return false;
} else if (obj instanceof Integer) {
if (((Integer) obj).intValue() == 0) return false;
} else throw new IllegalStateException("Unexpected type: " + obj.getClass());
return true;
}
It's an if for every type because there is no such thing as CouldBeEmpty as an interface that all these types implement. Said differently, "an empty Date" isn't a thing.
A: This should work. I tried it with a mock array, but I don't know if it is exactly the same as yours:
public static void main(String[] args) {
Object result[] = new Object[5];
result[0] = 1;
result[1] = "";
result[3] = 5;
result[4] = LocalDate.now();
result[5] = "string";
boolean listcontainsnullorempty = false;
for(var obj: result){
if(obj == null || obj.equals("")){
listcontainsnullorempty = true;
}
}
System.out.println(listcontainsnullorempty);
}
depending on your list, you might need to add || obj.isEmpty() in the if-clause.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74110675",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Anylogic Error Source Arrival Table in DB based Variable (Not Unique Database Value!) I have combo box in experiment screen with options : Lala, Poo, and Twinky. They will be input in variable as initial value. Lala, Poo, and Twinky. Also their database for arrival table :
I am trying to make source based on variable as below :
but I get this problem :
My objective is if I choose Lala, then Lala database arrival date will be used.
Hope you can help me, thanks
A: In your dbase query wizard, select the "Single value" option. This will adjust the SQL code to use the firstResult query, which take the first entry it finds for your query, in your case the first time it finds "Lala".
Kudos on the data adjustments for the question :D
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71837260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Implementing static shared counter in microservice architecture I have a use case where i want to record data in rows and display to the user.
Multiple users can add these records and they have to be displayed in order of insertion AND - MOST IMPORTANTLY - with a sequence number starting from 1.
I have a Spring boot microservice architecture at the backend, which obviously means i cannot hold state in my boot application as i'm gonna have multiple running instances.
Another method was to fetch all existing records in the db,count them,increment the count by 1 and use that as my sequence. I need to do this every time i am doing an insert.
But the problem with the second approach is with parallel requests, which could result in same sequence number being given to 2 records.
Third approach is to configure the counter in a db , but since i am using cosmos DB, apparently that is also not an option.
Any suggestions as to how i can implement a static, shared counter ?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62369875",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Cannot run tflearn with sklearn's GridSearchCV I intend to perform a grid search over hyperparams of a tflearn model. It seems that the model produced by tflearn.DNN is not compatible with sklearn's GridSearchCV expectations:
from sklearn.grid_search import GridSearchCV
import tflearn
import tflearn.datasets.mnist as mnist
import numpy as np
X, Y, testX, testY = mnist.load_data(one_hot=True)
encoder = tflearn.input_data(shape=[None, 784])
encoder = tflearn.fully_connected(encoder, 256)
encoder = tflearn.fully_connected(encoder, 64)
# Building the decoder
decoder = tflearn.fully_connected(encoder, 256)
decoder = tflearn.fully_connected(decoder, 784)
# Regression, with mean square error
net = tflearn.regression(decoder, optimizer='adam', learning_rate=0.01,
loss='mean_square', metric=None)
model = tflearn.DNN(net, tensorboard_verbose=0)
grid_hyperparams = {'optimizer': ['adam', 'sgd', 'rmsprop'], 'learning_rate': np.logspace(-4, -1, 4)}
grid = GridSearchCV(model, param_grid=grid_hyperparams, scoring='mean_squared_error', cv=2)
grid.fit(X, X)
I get the error:
TypeError Traceback (most recent call last)
<ipython-input-3-fd63245cd0a3> in <module>()
22 grid_hyperparams = {'optimizer': ['adam', 'sgd', 'rmsprop'], 'learning_rate': np.logspace(-4, -1, 4)}
23 grid = GridSearchCV(model, param_grid=grid_hyperparams, scoring='mean_squared_error', cv=2)
---> 24 grid.fit(X, X)
25
26
/home/deeplearning/anaconda3/lib/python3.5/site-packages/sklearn/grid_search.py in fit(self, X, y)
802
803 """
--> 804 return self._fit(X, y, ParameterGrid(self.param_grid))
805
806
/home/deeplearning/anaconda3/lib/python3.5/site-packages/sklearn/grid_search.py in _fit(self, X, y, parameter_iterable)
539 n_candidates * len(cv)))
540
--> 541 base_estimator = clone(self.estimator)
542
543 pre_dispatch = self.pre_dispatch
/home/deeplearning/anaconda3/lib/python3.5/site-packages/sklearn/base.py in clone(estimator, safe)
45 "it does not seem to be a scikit-learn estimator "
46 "as it does not implement a 'get_params' methods."
---> 47 % (repr(estimator), type(estimator)))
48 klass = estimator.__class__
49 new_object_params = estimator.get_params(deep=False)
TypeError: Cannot clone object '<tflearn.models.dnn.DNN object at 0x7fead09948d0>' (type <class 'tflearn.models.dnn.DNN'>): it does not seem to be a scikit-learn estimator as it does not implement a 'get_params' methods.
Any idea how I could get an object suitable for GridSearchCV?
A: I have no experience with tflearn, but I do have some basic background in Python and sklearn. Judging from the error in your StackOverflow screenshot, tflearn **models **do not have the same methods or attributes as scikit-learn estimators. This is understandable as they are not, well, scikit-learn estimators.
Sklearn’s grid search CV only works on objects that have the same methods and attributes as scikit-learn estimators (e.g. has fit() and predict() methods). If you are intent on using sklearn’s grid search, you will have to write your own wrapper around the tflearn model to make it work as a drop in replacement for an sklearn estimator, meaning you’ll have to write your own class that has the same methods as any other scikit-learn estimator, but uses the tflearn library to actually implement these methods.
To do that, understand the code for a basic scikit-learn estimator (preferably one you know well) and see what the methods fit(), predict(), get_params(), etc. actually do to the object and its internals. Then write your own class using the tflearn library.
To get started, a quick Google search reveals that this repository is “a thin scikit-learn style wrapper for tensorflow framework”: DSLituiev/tflearn (https://github.com/DSLituiev/tflearn). I have no idea if this will work as a drop in replacement for Grid Search, but it’s worth a look.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38968249",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: how do u make a program that checks many txt files how do you make a program that checks many txt files to see if the input goes with any of the text in the files and prints where it was found.
A: I'm not sure if this is what you are asking, but I interpreted this as list the files in a given directory, and then check if the input is in the file.
import os
string = input("Please type the input ")
directory = "c://files//python"
for file in os.listdir(directory):
if file.endswith(".txt"):
filecontent = open(file, "r")
if string in filecontent.read():
print("The file that matches the input was found at" + file)
Line 2: Set the string to whatever the input is
Line 3: Use double slashes to avoid escape characters http://learnpythonthehardway.org/book/ex10.html
Line 4: Goes through every file in the directory. listdir returns a list with all the file names
Line 5: Can change this to .jpg, .png, etc
Line 6: Opens the file contents
Line 7: Reads the file's contents into a string, then check if the input is in said string
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35027907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-6"
}
|
Q: how to inject $attrs into a controller through $routeProvider I have a mini app with a controller that looks like that:
app.controller("MyController", [ '$scope', '$attrs', 'ServiceA', 'ServiceB', function($scope, $attrs, svc1, svc2) {
...
}])
When I tried to add angular-routing to my app, I added the following route.js file:
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/main.html',
controller: 'MyController',
controllerAs: 'appCtrl',
resolve: {
attrs: $attrs
}
})
}
]);
It seems that I can't inject $attrs like before. I've tried playing with resolve inside when() but it didn't seem to help.
I must say it looks a bit weird to inject $attrs into the controller anyway, and since that's my first app I think I'm doing something wrong here.. I need $attrs to read a data attribute from the div and initialize some array according to it. Any ideas to how I should do it or why I couldn't do it with my approach? (which worked without the routes)
Thanks!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29730240",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Adding states and using them inside react component functions I have some rect componets whihc are just functions, I have posted a part of one of my components below
.....
const useStyles = makeStyles(presentationStyle);
export default function PresentationPage() {
React.useEffect(() => {
window.scrollTo(0, 0);
document.body.scrollTop = 0;
});
const classes = useStyles();
return (
<div>
<Header
brand="...."
links={<HeaderLinks dropdownHoverColor="info" />}
fixed
color="transparent"
changeColorOnScroll={{
height: 400,
color: "info"
}}
/>
.....
Now, I need to use states and functions inside such function components, can someone give me a hint how to write them there?
A: You can use useState hook from react. check the docs here: https://reactjs.org/docs/hooks-state.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63504908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: NuGet package adds incorrect hint path During an automated build, my nuget package needs to be non framework dependent, however I keep finding that the nuget package getting added is incorrectly adding a HintPath.
Within my nuspec I've defined the files that are part of the package:
<files>
<file src="lib\xyz.dll" target="lib\xyz.dll" />
<file src="lib\xyz.xml" target="lib\xyz.xml" />
</files>
However whenever I add the package to my project/solution, it incorrectly adds a hint path specifying:
<Reference Include="xyz, Version=11.0.0.0, Culture=neutral, PublicKeyToken=4a3c0a4c668b48b4">
<HintPath>..\packages\xyz.11.0.0.0\xyz.dll</HintPath>
<Private>True</Private>
</Reference>
This is causing the automated build server to not find the assembly and fail to build. I can manually fix the hint path, but would rather not.
I took a look at this post (Failed to add NuGet package) but I don't find it relevant. This post (NuGet package install uses specific assembly version in csproj files) seemed to be referring to the same problem but with no answer. Anybody have any thoughts?
A: You can work around this by using a custom MSBuild task.
Instead of adding the assembly to the lib directory create an MSBuild .targets file named after the package id and put your xyz assembly next to it.
\build
\Net45
\MyPackage.targets
\xyz.dll
\xyz.xml
Then in the MSBuild .targets file add the reference exactly how you want it to be. Something like:
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Reference Include="xyz">
<HintPath>$(MSBuildThisFileDirectory)\xyz.dll</HintPath>
</Reference>
</ItemGroup>
</Project>
The above shows how to specify a hint path relative to the MSBuild .targets file. You said that you do want to use a hint path so you could remove that if xyz.dll can be resolved by MSBuild somehow, such as it being in the GAC.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38729190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: iOS In-App Purchases: Sandbox Invalid Product ID Background on the slightly odd setup before I get to the problem: Working on an app for a client and we're using an different iTunes developer account than the one this will eventually be published on for development and Ad-Hoc builds of an app that has Game Center and IAP integration. Obviously, we'll eventually have to duplicate our setup on the final release account, but the issue seems to be unrelated.
The issue is trying to test In-App Purchases in the sandbox. We do not have any Tax/Banking info in the interim account, it was not set up in my name so I can't just add mine. Right now, every time we send an SKProductsRequest with the Product Identifier for the product I've added in the iTunes Connect portion of the account for the interim app, it is returned in the response as an invalid product identifier.
This request where identifiers is an array with the string product identifier I'm trying to get:
_productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithArray:identifiers]];
_productsRequest.delegate = self;
And this delegate method:
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
/*Other code for handling valid responses*/
for (NSString *invalidProductId in response.invalidProductIdentifiers) {
DLog(@"Invalid product id: %@" , invalidProductId);
}
}
Returns this log for the identifer:
-[InAppPurchaseManager productsRequest:didReceiveResponse:] Invalid product id: [Product ID That matches the one in ITC exactly]
I know ITC is working in the interim account because all our GameCenter sandbox integration is working fine through that.
Other things to note:
*
*Same results on Simulator and multiple devices.
*Logged out of normal iTunes/App store accounts on sim and all devices.
*Tried waiting 24 hours and trying again.
*Tried adding a different Product and trying its identifier (though I didn't wait 24 hours on this one).
*Took a look at this: Resolving invalid product id issue with in-app purchases? and didn't see anything terribly helpful, unfortunately.
At this point, I'm stumped. Other than getting the person who set up this interim account to add their tax/banking info, is there anything I can do to actually get a valid product back from the SKProductsRequest?
Any help would be greatly appreciated. Thank you!
A: Just wanted to confirm what DesignatedNerd said, about having to have a paid app agreement with Apple before testing can work. I had that yesterday, where we were using our account to test in app products on an app we're doing for a client. After a lot of web searching and other attempts, I happened to notice the text that said that we didn't have an agreement in place. We entered all our bank details in itunesconnect, and a little while later the message was gone, and my in app testing started to work.
A: Wound up having to get everything moved over to the final account, which did have banking and tax info. Exact same code that returned invalid product IDs was totally fine once I set the IAP up with the same name in the other account's app.
So yeah, you need the banking and tax info to even test in the sandbox. Boo-urns.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12736712",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: get table rows only when table checkbox is "checked" I am using below code to retrieve the values of selected row using checkbox class = btnSelect.
I want to get the rows only when the checkbox is marked as checked.
Current code get the values, both when checkbox is checked and unchecked.
Why does the code below get the values when the checkbox is either checked or unchecked?
$("#itemtable").on('click', '.btnSelect', function() {
// get the current row
alert("i am inside dddd");
var currentRow = $(this).closest("tr");
var col1 = currentRow.find("td:eq(0)").text(); // get SI no from checkbox
var col2 = currentRow.find("td:eq(1)").text(); // get item name
var col3 = currentRow.find("td:eq(2)").text(); // get item code
var col4 = currentRow.find("td:eq(3)").text(); // get supplier
var col5 = currentRow.find("td:eq(4)").text(); // get received qty
var col6 = $(currentRow).find("td:eq(5) input[type='text']").val(); // get accepted qty
var col7 = $(currentRow).find("td:eq(6) input[type='text']").val(); // get rejected qty
var col8 = $(currentRow).find("td:eq(7) input[type='text']").val(); // get remarks
var data = col1 + "\n" + col2 + "\n" + col3 + "\n" + col4 + "\n" + col5 + "\n" + col6 + "\n" + col7 + "\n" + col8;
alert(data);
});
[![enter image description here][1]][1]
A: You can use checked property from the DOM object.
For exmaple
$("#itemtable").on('click', '.btnSelect', function() {
if(this.checked){
// get the current row
alert("i am inside dddd");
var currentRow = $(this).closest("tr");
var col1 = currentRow.find("td:eq(0)").text(); // get SI no from checkbox
var col2 = currentRow.find("td:eq(1)").text(); // get item name
var col3 = currentRow.find("td:eq(2)").text(); // get item code
var col4 = currentRow.find("td:eq(3)").text(); // get supplier
var col5 = currentRow.find("td:eq(4)").text(); // get received qty
var col6 = $(currentRow).find("td:eq(5) input[type='text']").val(); // get accepted qty
var col7 = $(currentRow).find("td:eq(6) input[type='text']").val(); // get rejected qty
var col8 = $(currentRow).find("td:eq(7) input[type='text']").val(); // get remarks
var data = col1 + "\n" + col2 + "\n" + col3 + "\n" + col4 + "\n" + col5 + "\n" + col6 + "\n" + col7 + "\n" + col8;
alert(data);
}
});
I have made an exmaple on jsfiddle:
https://jsfiddle.net/fcaj5g52/1/
A:
$(document).ready(function() {
$("#saverecord").click(function(event) {
//$("#itemtable").on('click', '.btnSelect', function() {
// get the current row
var currentRow = $(".btnSelect:checked").closest("tr");
console.log(currentRow.index())
var col1 = currentRow.find("td:eq(0)").text(); // get SI no from checkbox
var col2 = currentRow.find("td:eq(1)").text(); // get item name
var col3 = currentRow.find("td:eq(2)").text(); // get item code
var col4 = currentRow.find("td:eq(3)").text(); // get supplier
var col5 = currentRow.find("td:eq(4)").text(); // get received qty
var col6 = currentRow.find("td:eq(5)").text()
var col7 = currentRow.find("td:eq(6)").text()
var col8 = currentRow.find("td:eq(7)").text()
var data = col1 + "\n" + col2 + "\n" + col3 + "\n" + col4 + "\n" + col5 + "\n" + col6 + "\n" + col7 + "\n" + col8;
console.log(data);
});
//});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tablediv">
<table cellspacing="0" id="itemtable" align="center">
<tr>
<td><input type="checkbox" class="btnSelect" id="chk" name="chk" /></td>
<th scope="col"> SIno</th>
<th scope="col">Item name</th>
<th scope="col">Item code</th>
<th scope="col">Supplier</th>
<th scope="col">Received qty</th>
<th scope="col">Accepted qty</th>
<th scope="col">Rejected qty</th>
<th scope="col">Remarks</th>
</tr>
<tr>
<td><input type="checkbox" class="btnSelect" id="chk" name="chk" /></td>
<td> 1 </td>
<td> biscuit </td>
<td>e123</td>
<td>abc company</td>
<td>23</td>
<td>20</td>
<td>3</td>
<td>waste</td>
</tr>
<tr>
<td><input type="checkbox" class="btnSelect" id="chk" name="chk" /></td>
<td> 2 </td>
<td> chocolate </td>
<td>e526</td>
<td>xyz company</td>
<td>25</td>
<td>20</td>
<td>5</td>
<td>waste</td>
</tr>
</table>
<input type="button" value="Save the record" id="saverecord" class="button0">
</div>
DOnt use this context because your click event is the save button
A: Reason of this - you need to use change event when you work with checkboxes, because they have state, like this:
$(document).on('change', '.btnSelect', function() {
I use $(document) in my test because you did not post rest of you code.
A: just check a condition that the check box is checked or not
var isChecked= document.getElementById("btnSelect").checked;
if(isChecked){
// write your code here
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42499860",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to create a view which contain image and text as like newspaper has? I want to create a view which contains image and text, like a newspaper has.
For example, in 320 pixel width, a 200 x 100 image. The image is on the left side of the view, and the remaining space on the right side and bottom will contain text.
A: Well you can 3 options:
*
*Create a layout with UIIImageViews and UITextView
*Use HTML and UIWebView
*NSAttributedString and draw it on a view with CoreText
A: That's almost certainly laid out in an UIWebView, with the styling on the image set to "float: left" with margin settings that hold the text off from the edge of it but let it wrap around it.
Here's a little tutorial about it: http://www.tizag.com/cssT/float.php
Note that this is about the HTML and CSS content to feed the UIWebView, not anything iOS-ish.
A: You arrange UIImageViews and UITextViews in the way you want them by setting their frames. Then assign images to the imageViews and text to the textViews.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7888749",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Why does redux form return string instead of the object? I am trying to access the touched property on my redux form, but for some reason when I print the field props I only the value instead of the object. What am I missing?
import { reduxForm, Field } from 'redux-form';
render() {
const { fields: { email, phone }, handleSubmit } = this.props;
console.log(email) //prints just the value "email" instead of the field object with the touched method, etc. When I do console.log(email.touched) I get undefined error.
return (
<form onSubmit={handleSubmit(this.onSubmit)}>
<Field name="email" component="input" type="email" { ...email } />
<Field name="phone" component="input" type="number" { ...phone } />
</form>
);
}
export default ReduxFormTest = reduxForm({
form: 'uniqueForm',
fields: ['email', 'phone']
})(TestClass);
A: There were breaking changes in redux-forms from v5 to v6. Previously you could do something similar to what you have to access the touched field. If you want to do something similar to see if there are errors on a field, you need to create your own component to pass to redux-form's Field component.
Your custom component
const CustomComponent = function(field) {
return (
<div>
<input
type={field.type}
{...field.input}
/>
{field.meta.touched && field.meta.error && <div className='error'>{field.meta.error}</div>}
</div>
)
}
Then using it with the Field component
<Field name="my-prop" component={CustomComponent} />
Also take a look at the migration guide, hope this helps!
A: You are confusing v5 syntax with v6 syntax. In v6, your decorated form component is no longer passed this.props.fields. Re-read the migration guide, like @tyler-iguchi said.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42355560",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: node.js with child processes in docker I have a node.js web application that runs on my amazon aws server using nginx and pm2. The application processes files for the user, which is done using a job system and child processes. In short, when the application starts via pm2, i create a child process for each cpu core of the server. Each child process (worker) then completes jobs from the job queue.
My question is, could i replicate this in docker or would i need to modify it somehow. One assumption i had was that i would need to create a container for the database, one container for the application, and then multiple worker containers to do the processing, so that if one crashes i just spin up another worker.
I have been doing research online, including a udemy course to get my head around this stuff, but i haven't come across an example or something i can relate to my problem/question.
Any help, reading material or suggestions would be greatly appreciated.
A: Containers run at the same performance level as the host OS. There is no process performance hit. I created a whitepaper with Docker and HPE on this.
You wouldn't use pm2 or nodemon, which are meant to start multiple processes of your node app and restart them if they fail. That's the job of Docker now.
If in Swarm, you'd just increase the replica count of your service to be similar to the number of CPU/threads you'd want to run at the same time in the swarm.
I don't mention the nodemon/pm2 thing for Swarm in my node-docker-good-defaults so I'll at that as an issue to update it for.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50571285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Form with tinymce textarea failing to submit more than once using ajax I'm trying to submit a form using ajax while using tinymce as my textarea editor but the form is only submitting on the first instance and not working in subsequent submissions.
This is my form
<form action="{{action('QuizController@postQuiz', [$quiz_id])}}" method="POST" id="quiz_form">
<textarea class=" tinymce" placeholder="Enter the question" name="m_c_question" required></textarea>
</form>
This is my tinymce initializer
<script>
$(function () {
tinymce.init({
selector: "tinymce",
statusbar: false,
setup: function (editor) {
editor.on('change', function () {
editor.save();
});
}
});
});
</script>
And this is my ajax code to submit the form to the database
$('#quiz_form').submit(function(event) {
tinyMCE.triggerSave();
// get the form data
var formData = {
'm_c_question' : $('textarea[name=m_c_question]').val(),
};
// process the form
$.ajax({
type : 'POST',
url : 'quiz',
data : formData,
dataType : 'json',
encode : true
})
I can't seem to find the problem. Any help will be greatly appreciated. Thanks.
A: By default, ajax is cached
cache (default: true, false for dataType 'script' and 'jsonp')
So add cache to the list of params
$.ajax({
cache : false,
type : 'POST',
url : 'quiz',
data : formData,
dataType : 'json',
encode : true
})
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45470547",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Bootstrap xs should be "less than 768" so how come it breaks already at 826? I tried to test this way, and I measured with photoshop.
My ultimate goal is to make the xs be smaller (for small devices)
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<div class="container-fluid visible-xs" style="border: 1px solid black;">
<div>HOW COME THIS IS SHOWN AT WIDTH 826px AND NOT AT 768px</div>
<div>AND HOW CAN I CHANGE THAT TO 480px</div>
</div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38428029",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Gson TypeAdapterFactory using gson.getDelegateAdapter issues I'm having issues with how my TypeAdapterFactory falls back on default serialization (custom Deserialization is working fine.) For background reference this is for deserializing GraphQL responses which feature a obj.getTypeName so I have to look up type names and deserialize properly.
Expected behavior: Serializes object the same as a new Gson().fromJson would.
Actual Behavior: Serializes objects as empty/null
public static class GsonGenericsFactory implements TypeAdapterFactory {
private final Map<Class, Set<Class>> classes;
public GsonGenericsFactory(Map<Class, Set<Class>> classes) {
this.classes = classes;
}
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
//returns types that implement an interface for getting typename
Set<Class> subTypes = classes.get(type.getRawType());
if (subTypes != null) {
List<Class> val = new ArrayList<>(subTypes);
final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
return new TypeAdapter<T>() {
Class<T> previousClass;
@Override
public void write(JsonWriter out, T value) throws IOException {
delegate.write(out, value);
}
@Override
public T read(JsonReader in) throws IOException {
JsonElement tree = elementAdapter.read(in);
if (tree.isJsonNull()) {
return null;
}
for (int i = 0; i < val.size(); i++) {
if (isAssignable(tree, val.get(i))) {
previousClass = (Class<T>) val.get(i);
return gson.fromJson(tree, previousClass);
}
}
Timber.e("ERROR %S", tree.toString());
throw new IllegalStateException("Invalid type:" + type.toString());
}
};
}
return null;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40008436",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Session is not being set in ASP.NET MVC 5 I am working on a project which is using
HttpContext.Current.Session["XYZSession"]="abcValue";
in a get request which gets a parameter from the link being opened.
The problem is, when I open the link by right-clicking on it and selecting the option open in new tab or by pressing the Ctrl-Key+Mouse left click, it doesn't save session, but when I paste a link in search box of browser and hit enter and then the session is being saved now.
I am using
*
*C#, .NET Framework 4.7.x
*Visual Studio 2017
*Hosted on IIS Server
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73194332",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I create a function similar to current_user? In Flask, I would like to understand how to create a function that behaves similar to current_user in the sense that it is available everywhere (controllers and views) but I'm struggling to actually know what to search for to find the answer.
The closest post on SO that I've been able to find is this one, but it's for Ruby rather than Python, could someone point me in the right direction? Thanks!
What I have so far:
In my __main__.py I have this:
@app.context_processor
def foo_processor():
def foo():
return 'Hello World'
The result of this is that I can access {{ foo }} in my Jinja templates without having to send it through from my controller. Unfortunately, I can't access foo within my controllers, and this is what I would like to also be able to do. Do I need to import it somehow, and if I do, how?
A: If I understand this correctly, you want a variable you can use in your templates and the controllers without having to pass it into the templates each time. To do this, first, create a function to get the variable. This could be something like getting a user's setting. Then in the context processor, you pass the result of this function through. To access it in your controllers as well, create an additional variable that holds the value of the getter. Note that if the function returns different values, you may need to call the function instead of using a variable.
# create a getter function, this returns the property's value.
def get_property():
return "Test Text"
property = get_property() # this is only to make code pretty later on.
# the context processor passes the property to the templates.
@app.context_processor
def property_processor():
return dict(property=get_property())
In your controllers, you can access the variable created earlier.
def view():
if property == true:
return redirect(url_for('index'))
else:
return redirect(url_for('access_denied'))
Note that if your value will change, you may need to use the function instead and recall the getter each time you render a view. This would make the first if statement into if get_property() == true: instead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65047812",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to update srore after fetching data with RTK i am learning react js by doing a project wher i am using RTK to manipulate the state of my app . The problem is after fetching data i want my store to change automatically . this is my server
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
export const openSeaApi = createApi({
reducerPath: "collectionsApi",
baseQuery: fetchBaseQuery({
baseUrl: `https://testnets-api.opensea.io/api/v1`,
}),
endpoints: (builder) => ({
retreiveCollections: builder.query({
query: ({ asset_owner, offset, limit }) =>
`collections?asset_owner=${asset_owner}&offset=${offset}&limit=${limit}`,
}),
}),
});
export const { useRetreiveCollectionsQuery } = openSeaApi;
This is my slice file:
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
allCollections: [],
isError: false,
isSuccess: false,
isLoading: false,
message: "",
};
export const collectionsSlice = createSlice({
name: "collection",
initialState,
reducers: {
appendCollections: (state, action) => {
state.allCollections = { ...state.allCollections, ...action.payload };
},
},
});
export const { appendCollections } = collectionsSlice.actions;
export default collectionsSlice.reducer;
this my store.js
import { configureStore } from "@reduxjs/toolkit";
import { setupListeners } from "@reduxjs/toolkit/dist/query";
import collectionReducer from "../features/collections/collectionSlice";
import { openSeaApi } from "../services/openseaService";
export const store = configureStore({
reducer: {
collection: collectionReducer,
[openSeaApi.reducerPath]: openSeaApi.reducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(openSeaApi.middleware),
});
setupListeners(store.dispatch);
and my component
const user = JSON.parse(localStorage.getItem("user"));
const { data, isError, isLoading } = useRetreiveCollectionsQuery({
asset_owner: user?.account,
offset: 0,
limit: 300,
});
So when i look in my store i fiend the collection reducer but it doesn't get the data even after the action is fulfilled . how can i put the data into the collections array in the store . thank you .
A: That data is already in the store. The point is that RTK Query manages the data for you - you don't have to write a slice by hand any more. Just use the hook in your component and you're done.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73067300",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: $.ajax({ }) Post request to a PHP file is returning a null value I have been looking at this problem for quite a while now and cannot seem to figure out why I keep receiving null after my $.ajax function is called.I input an associative array that contains my method name and then call my method in PHP to return a j son string back to the front end. I receive null when I call alert in my java script. Here is my code
Java script:
$(document).ready(function()
{
var data = {};
data["Method"] = "test";
$.ajax({
url:"test.php/test",
data: data,
type:"POST",
contentType:"application/json",
dataType:"json",
success: function(data){
alert(data);
},
error:function(data, textStatus, error)
{
}
});
});
PHP:
<?
//require_once("database.php");
class methods
{
function __contructor()
{
if(isset($_POST["Method"]))
{
$function = $_POST["Method"];
call_user_func($function);
}
else
{
echo "{\"status\":\"false\"}";
}
}
function test()
{
$json = array(
"kyle" => "broflowksi",
"eric" => "cartman",
"stan" => "marsh"
);
echo json_encode($json);
}
}
$method = new methods();
?>
A: What you are trying to call is an instance method. Call it this way:
if(isset($_POST["Method"]))
{
$function = $_POST["Method"];
$method = new ReflectionMethod('methods', $function);
$method->invoke($this);
}
A: Try forcing a content-type header before sending the output,
header("Content-type: application/json");
A: There's simply a typo in your class constructor method, it should be
function __construct()
One other thing to keep in mind is that I'm not sure you should be setting the contentType to json, as that variable is for what you're sending... not what you're receiving.
So if you end up having a situation where the post variables are being stripped, try and remove the contentType form your ajax call.
A: Try removing the echo in test method. You are calling
call_user_func($function);
and your $function is not returning but echoing, .i.e
function test() {
$json = array(
"kyle" => "broflowksi",
"eric" => "cartman",
"stan" => "marsh"
);
echo json_encode($json); // This line should be returning
}
I had dealt with similar issue earlier with a php function call (not in ajax particular).to catch.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13438975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How do I incorporate await sleep(milliseconds) between two set of messages in MS Bot Framework? I am developing a Bot using NodeJs which should ask the user a set of questions and then after a break, ask the same another of questions again.
I am using await sleep(milliseconds) in between.
While testing using the Emulator, I noticed that the questions from the first set are sent one by one, saving the user's response. The second set is sent all at once without allowing the user to respond to each question of the second set individually.
await turnContext.sendActivity(askFirstSetOfQuestions(question));
await sleep(60000);
await turnContext.sendActivity(askSecondSetOfQuestions(question));
await next();
image - screen capture from emulator
Quite lost here..
any help would be appreciated.
A: There are two things to consider here. First, if you truly need a delay, it is better to await a promise than use sleep. You can do this via await new Promise (resolve => setTimeout(resolve, DELAY_LENGTH);. I use this frequently in conjunction with typing indicator to give the bot a more natural feeling conversation flow when it sends two or more discrete messages without waiting for user input.
However, as Eric mentioned, it seems like you might want a waterfall dialog instead for your use case. This sample from botbuilder-samples is a good example. Each step would be a prompt, and it will wait for user input before proceeding. I won't try to write an entire bot here, but a single question-answer step would look something like:
async firstQuestion(stepContext) {
return await stepContext.prompt(TEXT_PROMPT, 'Question 1');
}
async secondQuestion(stepContext) {
stepContext.values.firstAnswer = stepContext.result;
return await stepContext.prompt(TEXT_PROMPT, 'Question 2');
}
and so forth. Not sure what you are doing with the responses, but in the example above I'm saving it to stepContext.values so that the answers are all available in later steps as part of the context object.
If you can detail more of what your use case/expected behavior and share what askFirstSetOfQuestions is, we could provide further assistance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60592317",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: What is the meaning of mode(x).mode[0]? I am trying to find mode along a column(named Outlet_Size) of a dataset using pandas library of python which contains values in the form of {small, medium,large} corresponding to 10 different outlet stores with total of 1000+ rows.enter image description here.
For Finding the mode along that column for each store type the following code was used:
Determing the mode for each type of outlet(10 different types)
outlet_size_mode = data.pivot_table(values='Outlet_Size', columns='Outlet_Type',aggfunc=(lambda x:mode(x).mode[0]) ) .
However I am unable to understand the format of using the lambda function mode(x).mode[0]. What is the meaning of that?
A: For a column having several rows mode(x) can be an array as there can be multiple values with high frequency. We will take the first one by default always using: mode[0] at the end.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47950227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Creating a COM port out of a ttyUSB port in Ubuntu The Question
I'm having to work with a rather awkward API at the moment which insists on me giving the address of a device, linked via USB port, in the form COM*. However, on the Ubuntu machine on which I'm working, and have to use, if I plug in this device it will automatically be assigned an address in the form /dev/ttyUSB*.
Given that I can't modify the source code of the API - which I would dearly like to do! - what is the least painful way getting the API to talk to said device?
Extra Detail
An example of how to use the API from the manual:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using com.caen.RFIDLibrary;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
CAENRFIDReader MyReader = new CAENRFIDReader();
MyReader.Connect(CAENRFIDPort.CAENRFID_RS232, "COM3");
CAENRFIDLogicalSource MySource = MyReader.GetSource("Source_0");
CAENRFIDTag[] MyTags = MySource.InventoryTag();
if (MyTags.Length > 0)
{
for (int i = 0; i < MyTags.Length; i++)
{
String s = BitConverter.ToString(MyTags[i].GetId());
Console.WriteLine(s);
}
}
Console.WriteLine("Press a key to end the program.");
Console.ReadKey();
MyReader.Disconnect();
}
}
}
The line MyReader.Connect(CAENRFIDPort.CAENRFID_RS232, "COM3"); is where I'm running into problems.
A little later in the manual, it states that the Connect method is to have two parameters:
ConType: The communication link to use for the connection.
Address: Depending on ConType parameter: IP address for TCP/IP communications ("xxx.xxx.xxx.xxx"), COM port for RS232 communications ("COMx"), an index for USB communications (not yet supported).
Bonus Question
The API in question seems to have been written on the assumption that it would be run on a Windows machine. (It's in C#.) The COM* format seems to be favoured - I'm happy to be corrected on this point - by Windows architectures, whereas Ubuntu seems to favour the ttyUSB* format. Assuming that I can funnel the data from my device from a ttyUSB* port to a COM* port, will the API actually be able to find said data? Or will it incorrectly follow the default Windows path?
A: Given the new information i suspect you can just give the ttyUSB as the parameter, mono will handle the connection correctly. However the same caution for the line endings below still applies. You might also consider making the parameter a command-line parameter thus making your code run on any platform by being able to supply the COM/USB through the command line parameters. I see no other issues using this code. Did you try it yet?
PS: i think your confusion is actually the statement usb id's are not supported yet, i suspect that is because the library relies on a (text-based) serial connection wich are fundamentally different from direct USB connections (wich drivers normally handle) that handle the connection in a more direct way. The ttyUSB ports on linux however DO represent the (UART) serial connections the same way as windows COM-ports, these are not direct USB connections.
Some handy info about the differences: https://rfc1149.net/blog/2013/03/05/what-is-the-difference-between-devttyusbx-and-devttyacmx/
Old answer
I am assuming you run this program on Mono?
Mono expects the path to the port, so COM* will not do. You could try creating a symlink named COM* to the ttyUSB*. Preferrably located in the environment directory. Once you get them linked the program should see no difference. However line endings in the data/program might be different than on windows. If the device expects CRLF and the program uses Environment.NewLine you might get unexpected behaviour too. It might just be easier if you have the permission/rights to edit the assembly with recompilation tools.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59267486",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Python Socket Programming: Upload files from Client to Server I'm looking to find some assistance in my python socket programming.
Objective: upload a file from the Client to the Server. My current setup involves two virtual machines, a Server and a Client, where the respective .py files will reside; server.py and client.py . The issues I'm experiencing is, that when I go to choose the upload option, the output reads "File uploading.... File successfully uploaded" But when I look on the server side, the file doesn't exist - nor do I receive an error. The server shows that it received a connection when I send the file to upload. What I have currently is below... Any assistance would be greatly appreciated.
Server.py
import config, protocol
import os
from socket import *
import threading
import time
import sys
class server():
# Constructor: load the server information from config file
def __init__(self):
self.port, self.path, self.path2 = config.config().readServerConfig()
# function to receive file data from client
def receiveFile(self, serverSocket, fileName):
serverSocket.connect()
serverSocket.send(protocol.prepareMsg(protocol.HEAD_UPLOAD, fileName))
with open(fileName, 'wb') as f:
print('file incoming...')
while True:
print('receiving data...')
data = serverSocket.recv(1024)
if not data:
break
f.write(data)
print(fileName + " has been Received!")
serverSocket.close()
# Main function of server, start the file sharing service
def start(self):
serverPort=self.port
serverSocket=socket(AF_INET,SOCK_STREAM)
serverSocket.bind(('',serverPort))
serverSocket.listen(20)
print('The server is ready to receive')
while True:
connectionSocket, addr = serverSocket.accept()
print("**Conn. to ", addr)
dataRec = connectionSocket.recv(1024)
header,msg= protocol.decodeMsg(dataRec.decode()) # get client's info, parse it to header and content
# Main logic of the program, send different content to client according to client's requests
if(header== protocol.HEAD_REQUEST):
self.listFile(connectionSocket)
elif(header == protocol.HEAD_DOWNLOAD):
self.sendFile(connectionSocket, self.path+"/"+msg)
elif(header == protocol.HEAD_UPLOAD):
self.receiveFile(connectionSocket, self.path2+"/"+msg)
else:
connectionSocket.send(protocol.prepareMsg(protocol.HEAD_ERROR, "Invalid Message"))
connectionSocket.close()
def main():
s=server()
s.start()
main()
Client.py
import config, protocol
from socket import *
import threading
import time
import os
import sys
class client:
fileList=[] # list to store the file information
uploadFileList = []
#Constructor: load client configuration from config file
def __init__(self):
self.serverName, self.serverPort, self.clientPort, self.downloadPath, self.uploadPath = config.config().readClientConfig()
# Function to produce user menu
def printMenu(self):
print("Welcome to simple file sharing system!")
print("Please select operations from menu")
print("--------------------------------------")
print("3. Upload File")
print("5. Quit")
# Function to get user selection from the menu
def getUserSelection(self):
ans=0
# only accept option 1-4
while ans>5 or ans<1:
self.printMenu()
try:
ans=int(input())
except:
ans=0
if (ans<=5) and (ans>=1):
return ans
print("Invalid Option")
# Build connection to server
def connect(self):
serverName = self.serverName
serverPort = self.serverPort
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName,serverPort))
return clientSocket
def getUploadFileList(self):
self.uploadFileList = os.listdir(self.uploadPath)
def printUploadFileList(self):
count = 0
for f in self.uploadFileList:
count += 1
print('{:<3d}{}'.format(count, f))
def selectUploadFile(self):
if (len(self.uploadFileList)==0):
self.getUploadFileList()
ans=-1
while ans<0 or ans>len(self.uploadFileList)+1:
self.printUploadFileList()
print("Please select the file you want to upload from the list (enter the number of files):")
try:
ans=int(input())
except:
ans=-1
if (ans>0) and (ans<len(self.uploadFileList)+1):
return self.uploadFileList[ans-1]
print("Invalid number")
def uploadFile(self, fileName):
mySocket=self.connect()
mySocket.send(protocol.prepareMsg(protocol.HEAD_UPLOAD, fileName))
f = open(fileName, 'rb')
l = f.read(1024) # each time we only send 1024 bytes of data
while (l):
print('File uploading...')
mySocket.sendall(l)
l = f.read(1024)
f.close()
print("File Uploaded Successfully!")
# Main logic of the client, start the client application
def start(self):
opt=0
while opt!=5:
opt=self.getUserSelection()
if opt==3:
self.uploadFile(self.selectUploadFile())
else:
pass
def main():
c=client()
c.start()
main()
I've defined modules in the protocol file that I have...
Protocol.py
HEAD_LIST='LST'
HEAD_REQUEST='REQ'
HEAD_DOWNLOAD='DLD'
HEAD_UPLOAD='ULD'
HEAD_FILE='FIL'
HEAD_ERROR='ERR'
# we prepare the message that are sent between server and client as the header + content
def prepareMsg(header, msg):
return (header+msg).encode()
def prepareFileList(header,fList):
'''
function to prepare file list to msg
'''
msg=header
for i in range(len(fList)):
if (i==len(fList)-1):
msg+=fList[i]
else:
msg+=fList[i]+','
return msg.encode()
# Decode the received message, the first three letters are used as protocol header
def decodeMsg(msg):
if (len(msg)<=3):
return HEAD_ERROR, 'EMPTY MESSAGE'
else:
return msg[0:3],msg[3:len(msg)]
I've also defined my config file as follows...
Config.py
class config:
#define header
server_port='SERVER_PORT'
path="PATH"
path2="PATH2"
server="SERVER"
client_port="CLIENT_PORT"
download="DOWNLOAD"
upload="UPLOAD"
serverConfig="server.config"
clientConfig="client.config"
def __init__(self):
pass
def readServerConfig(self):
try:
with open(self.serverConfig,'r') as f:
serPort=0
sharePath=""
sharePath2=""
for l in f:
sub=l.strip().split("=")
if(sub[0]==self.server_port):
serPort=int(sub[1])
elif(sub[0]==self.path):
sharePath=sub[1]
elif (sub[0] == self.path2):
sharePath2 = sub[1]
else:
pass
return serPort, sharePath, sharePath2
except:
print(Exception.message())
def readClientConfig(self):
'''
This function read client configuration file, return four values
@return: serverName
@return: serverPort
@return: clientPort
@return: downloadPath
'''
try:
with open(self.clientConfig,'r') as f:
serPort=0
serName=""
clientPort=0
downPath=""
upPath=""
for l in f:
sub=l.strip().split("=")
if(sub[0]==self.server_port):
serPort=int(sub[1])
elif(sub[0]==self.server):
serName=sub[1]
elif(sub[0]==self.client_port):
clientPort=sub[1]
elif(sub[0]==self.download):
downPath=sub[1]
elif(sub[0]==self.upload):
upPath=sub[1]
else:
pass
return serName, serPort, clientPort, downPath, upPath
except:
print(Exception.message())
# The function to test the configuration class
def test():
conf=config()
client=conf.readClientConfig()
server=conf.readServerConfig()
print(client)
print(server)
The above code will return a file list, I can choose which file I'd like to upload, and the code will state its complete but I cannot find the files on the server. I have test files set up in directories paths on both machines. in addition, my server.config and client.config files are set up as:
server.config
SERVER_PORT=12007
PATH=/root/serverFiles
PATH2=/root/files
client.config
SERVER=192.168.10.1
SERVER_PORT=12007
CLIENT_PORT=12006
DOWNLOAD=/root/Downloads
UPLOAD=/root/Upload
A: Your uploadFile() method will connect() to the server and then sendall() the file content (in 1024 byte chunks).
Your server, on the other hand, will receive the first 1024 bytes (i.e. the first 1024 bytes of file content), and interpret it according to the protocol, looking at the first three bytes of the file content. The client, however, never sends protocol.HEAD_UPLOAD as the server expects.
(BTW, I would really recommend you PEP8 the code, and refrain from * imports. It makes the code much easier to read, and thus to help.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53353987",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Jquery ui Selectable() cant properly unselect outside the method I have a table with selectable objects as follow :
/* ESPACE OU LES TATOUAGES SONT SELECTABLE */
$(".tatooInk > tbody").bind("mousedown", function(e) {
e.metaKey = true;
}).selectable();
$( ".tatooInk > tbody" ).selectable({
filter: ":not(td, img ,b,span,div)",
/* Quand on select un tatoo */
selected: function( e, ui ) {
if(tatoos.length < 28){
// JSON.stringify(ui.selected);
console.log($( ui.selected ).html());
$( ui.selected ).addClass( "ui-state-highlight" );
getAllTats( $(ui.selected) );
updateCode();
}
else{
alert('trop de tatouages');
$(ui.selecting).removeClass("ui-selecting");
}
},
unselected: function( e, ui ) {
$( ui.unselected ).removeClass( "ui-state-highlight" );
removeTat( $(ui.unselected) );
updateCode();
}
});
This code works great, when i select an item in my list it looks like this :
At another place in my code, i do some modification depending what has been selected
At another, another, place in my code, if the conditions are meeted i unselect manually using this code
function TabletatooDel(url){
$('.tatooInk tr').each(function(){
var lien = $(this).children(':nth-child(1)').children().attr('src');
if(lien == url){
$(this).removeClass('ui-selected ui-state-highlight');
$(this).trigger('unselecting');
$(this).trigger('unselected');
}
});
}
When passing through that, this is what i think happens :
Even if i removed every Class, when i click on the previously unselected element, even if it goes like this again
The modifications depending on my select DOESNT run.
I have to unselect it again, by clicking on it, and reselect it again in order to have the modifications running.
Any idea how to properly unselect out of the method ?
A: ... It's ok ! I found my problem. I forgot to erase the tatoo out of a json list containing them all.
It looks like this now :
for(var i=0; i< tatoos.length; i++){
if(tatoos[i].url === url ){
tatoos.splice(i, 1);
}
}
$(this).removeClass('ui-state-highlight');
$(this).removeClass('ui-selected');
$(this).children(':nth-child(4)').removeClass( "tatooSelect" );
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34247897",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: GLSL compute world coordinate from eye depth and screen position I'm trying to recover WORLD position of a point knowing it's depth in EYE space, computed as follow (in a vertex shader) :
float depth = - uModelView * vec4( inPos , 1.0 ) ;
where inPos is a point in world space (Obviously, I don't want to recover this particular point, but a point where depth is expressed in that format).
And it's normalized screen position (between 0 and 1), computed as follow (in a fragment shader ) :
vec2 screen_pos = ( vec2( gl_FragCoord.xy ) - vec2( 0.5 ) ) / uScreenSize.xy ;
I can access to the following info :
*
*uScreenSize : as it's name suggest, it's screen width and height
*uCameraPos : camera position in WORLD space
and standard matrices :
*
*uModelView : model view camera matrix
*uModelViewProj : model view projection matrix
*uProjMatrix : projection matrix
How can I compute position (X,Y,Z) of a point in WORLD space ? (not in EYE space)
I can't have access to other (I can't use near, far, left, right, ...) because projection matrix is not restricted to perspective or orthogonal.
Thanks in advance.
A: I get your question right, you have x and y as window space (and already converted to normalized device space [-1,1]), but z in eye space, and want to recosntruct the world space position.
I can't have access to other (I can't use near, far, left, right, ...)
because projection matrix is not restricted to perspective or
orthogonal.
Well, actually, there is not much besides an orthogonal or projective mapping which can be achieved by matrix multiplication in homogenous space. However, the projection matrix is sufficient, as long as it is invertible (In theory, a projection matrix could transform all points to a plane, line or a single point. In that case, some information is lost and it will never be able to reconstruct the original data. But that would be a very untypical case).
So what you can get from the projection matrix and your 2D position is actually a ray in eye space. And you can intersect this with the z=depth plane to get the point back.
So what you have to do is calculate the two points
vec4 p = inverse(uProjMatrix) * vec4 (ndc_x, ndc_y, -1, 1);
vec4 q = inverse(uProjMatrix) * vec4 (ndc_x, ndc_y, 1, 1);
which will mark two points on the ray in eye space. Do not forget to divide p and q by the respective w component to get the 3D coordinates. Now, you simply need to intersect this with your z=depth plane and get the eye space x and y. Finally, you can use the inverse of the uModelView matrix to project that point back to object space.
However, you said that you want world space. But that is impossible. You would need the view matrix to do that, but you have not listed that as a given. All you have is the compisition of the model and view matrix, and you need to know at least one of these to reconstruct the world space position. The cameraPosition is not enoguh. You also need the orientation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26691029",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Accessing 32 bit hive in .Net Core Application What is the correct way to access 32 bit registry hive on a 64 bit machine? I tried the following code to set some value in HKCU\Software 32 bit hive but it still gets the 64 bit hive. I couldnt find any alternate api to pass RegistryView enum, In C++ the Wow64 flag can be specified when opening/creating a key but I dont find similar usage in Microsoft.Win32 library.
[SupportedOSPlatform("Windows")]
void SetValue()
{
using var key = GetOrCreateKey(RegistryHive.CurrentUser,
RegistryView.Registry32,
@"SOFTWARE\MyApp\Key"
);
key?.SetValue("Value", 1);
}
[SupportedOSPlatform("Windows")]
static RegistryKey? GetOrCreateKey(RegistryHive hive, RegistryView view, string keyPath)
{
using var baseKey = RegistryKey.OpenBaseKey(hive, view);
var subKey = baseKey?.OpenSubKey(keyPath);
if (subKey != null)
{
return subKey;
}
return baseKey?.CreateSubKey(keyPath);
}
On 64 bit machine, I want the value to be set on key on HKEY_CURRENT_USER\Software\Wow6432Node\MyApp\Key but its getting written on HKEY_CURRENT_USER\Software\MyApp\Key
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71329249",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: visibility map: all visible pages The relallvisible field in pg_class view display the Number of pages that are marked all-visible in the table's visibility map.
When I try this example:
INSERT INTO foo (x) SELECT n FROM generate_series(1, 10000000) as n;
analyze table foo;
select nspname, relpages, reltuples, relallvisible, relfrozenxid, relminmxidfrom pg_class as c
join pg_namespace as ns on c.relnamespace = ns.oid
where relname = 'foo';
nspname | relpages | reltuples | relallvisible | relfrozenxid | relminmxid
---------+----------+-------------+---------------+--------------+------------
public | 44248 | 9.99998e+06 | 0 | 60995 | 1
(1 row)
Why is relallvisible field equal to 0 and not equal to the total number of pages that is 44248?
A: Because VACUUM has never run on the table. That command builds and maintains the visibility map.
You are probably on PostgreSQL v12 or lower, and the table not received enough updates or deletes to trigger autovacuum. If your use case involves insert-only tables, upgrade – from v13 on, autovacuum will also run on insert-only tables.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69808988",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: When an iOS application goes to the background, are lengthy tasks paused? Yes, I know if I wish my app to be responsive to users' multitasking actions, such as switch to another app, I should deal with
- (void)applicationWillResignActive:(UIApplication *)application
- (void)applicationDidBecomeActive:(UIApplication *)application
What if my app is doing a quite-long time consuming operation (like downloading a big file) and the user causes my app to enter the background? Will that operation automatically be suspended and resumed when the user comes back to my app?
What exactly will happen behind the scene when my app enters the background or resumes in the foreground?
What if when users let my app go to the background my app's execution is just in the middle of a method?
For e.g., my app is doing
for (int i = 1 to 10000K) {
do some calculation;
}
When i== 500K, user switches to another app. What happens to the for-loop in my app?
A: From the documentation:
Return from applicationDidEnterBackground(_:) as quickly as possible. Your implementation of this method has approximately five seconds to perform any tasks and return. If the method doesn’t return before time runs out, your app is terminated and purged from memory.
If you need additional time to perform any final tasks, request additional execution time from the system by calling beginBackgroundTask(expirationHandler:). Call beginBackgroundTask(expirationHandler:) as early as possible. Because the system needs time to process your request, there’s a chance that the system might suspend your app before that task assertion is granted. For example, don’t call beginBackgroundTask(expirationHandler:) at the very end of your applicationDidEnterBackground(_:) method and expect your app to continue running.
If the long-running operation you describe above is on the main thread and it takes longer than 5 seconds to finish after your application heads to the background, your application will be killed. The main thread will be blocked and you won't have a chance to return from -applicationDidEnterBackground: in time.
If your task is running on a background thread (and it really should be, if it's taking long to execute), that thread appears to be paused if the application returns from -applicationDidEnterBackground: (according to the discussion in this answer). It will be resumed when the application is brought back to the foreground.
However, in the latter case you should still be prepared for your application to be terminated at any time while it's in the background by cleaning things up on your way to the background.
A: If you are doing some operation which might consume time and you don't want to kill it then you can extend the time for your operation by executing in UIBackground Task i
{
UIBackgroundTaskIdentifier taskId = 0;
taskId = [application beginBackgroundTaskWithExpirationHandler:^{
taskId = UIBackgroundTaskInvalid;
}];
// Execute long process. This process will have 10 mins even if your app goes in background mode.
}
The block argument called "handler" is what will happen when the background task expire (10min).
Here is a link to the documentation
A: Like mentioned above, there are a few cases where your app runs in the background and apple can allow or deny depending on what you are doing.
https://developer.apple.com/library/ios/documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html
More importantly if you do fit into one of these categories your app refresh rate is determined by an apple algorithm that takes into consideration your app usage on that device vs other apps. If your app is used more often then it gets more background time allotted. This is just one variable but you get the idea that background time allocation varies app to app and not under your control.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6650717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "74"
}
|
Q: Clear log files on OpenShift - RedHat Debugging my apps on OpenShift is becoming difficult due to excessive log data.
I'm using the terminal command rhc tail -a appname to view logs
Is there a way to clear the log files via a rhc command? (or any other method)
Any other recommendations for viewing / handling log data on OpenShift?
A: You can use rhc app-tidy <yorApp> to delete the logs and contents of the /tmp directory on the gears (this is used primarily in order to free up some disk space).
You can also ssh into your app rhc ssh <yourApp> and check individual logs in ~/app-root/logs/, which may bring some clarity if you are reading only the log that interests you.
A: Configure logs
To set
*
*maximum file size
*maximum number of files
The maximum file size and maximum number of files can be configured
with the LOGSHIFTER__MAX_FILESIZE and
LOGSHIFTER__MAX_FILES environment variables.
$ rhc env set LOGSHIFTER_PHP_MAX_FILESIZE=5M LOGSHIFTER_PHP_MAX_FILES=5 -a myapp
Setting environment variable(s) ... done
$ rhc app stop
RESULT:
myapp stopped
$ rhc app start
RESULT:
myapp started
The exact variable names depend on the type of cartridge; the value of
is DIY, JBOSSAS, JBOSSEAP, JBOSSEWS, JENKINS, MONGODB,
MYSQL, NODEJS, PERL, PHP, POSTGRESQL, PYTHON, or RUBY as appropriate.
copied from:
https://developers.openshift.com/managing-your-applications/log-files.html
https://developers.openshift.com/managing-your-applications/environment-variables.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34191560",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.