How to create empty constructor for data class in Kotlin Android
the modern answer for this should be using Kotlin's no-arg compiler plugin
which creates a non argument construct code for classic apies more about here
simply you have to add the plugin class path in build.gradle project level
dependencies {
....
classpath "org.jetbrains.kotlin:kotlin-noarg:1.4.10"
....
}
then configure your annotation to generate the no-arg
constructor
apply plugin: "kotlin-noarg"
noArg {
annotation("your.path.to.annotaion.NoArg")
invokeInitializers = true
}
then define your annotation file NoArg.kt
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.SOURCE)
annotation class NoArg
finally in any data class you can simply use your own annotation
@NoArg
data class SomeClass( val datafield:Type , ... )
I used to create my own no-arg
constructor as the accepted answer , which i got by search but then this plugin released or something and I found it way cleaner .
TypeError: a bytes-like object is required, not 'str'
A bit of encoding can solve this:
Client Side:
message = input("->")
clientSocket.sendto(message.encode('utf-8'), (address, port))
Server Side:
data = s.recv(1024)
modifiedMessage, serverAddress = clientSocket.recvfrom(message.decode('utf-8'))
How to catch exception output from Python subprocess.check_output()?
Based on the answer of @macetw I print the exception directly to stderr in a decorator.
Python 3
from functools import wraps
from sys import stderr
from traceback import format_exc
from typing import Callable, Collection, Any, Mapping
def force_error_output(func: Callable):
@wraps(func)
def forced_error_output(*args: Collection[Any], **kwargs: Mapping[str, Any]):
nonlocal func
try:
func(*args, **kwargs)
except Exception as exception:
stderr.write(format_exc())
stderr.write("\n")
stderr.flush()
raise exception
return forced_error_output
Python 2
from functools import wraps
from sys import stderr
from traceback import format_exc
def force_error_output(func):
@wraps(func)
def forced_error_output(*args, **kwargs):
try:
func(*args, **kwargs)
except Exception as exception:
stderr.write(format_exc())
stderr.write("\n")
stderr.flush()
raise exception
return forced_error_output
Then in your worker just use the decorator
@force_error_output
def da_worker(arg1: int, arg2: str):
pass
Python send UDP packet
With Python3x, you need to convert your string to raw bytes. You would have to encode the string as bytes. Over the network you need to send bytes and not characters. You are right that this would work for Python 2x since in Python 2x, socket.sendto on a socket takes a "plain" string and not bytes. Try this:
print("UDP target IP:", UDP_IP)
print("UDP target port:", UDP_PORT)
print("message:", MESSAGE)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
sock.sendto(bytes(MESSAGE, "utf-8"), (UDP_IP, UDP_PORT))
sending email via php mail function goes to spam
If you are sending this through your own mail server you might need to add a "Sender" header which will contain an email address of from your own domain. Gmail will probably be spamming the email because the FROM address is a gmail address but has not been sent from their own server.
Handling a timeout error in python sockets
from foo import *
adds all the names without leading underscores (or only the names defined in the modules __all__
attribute) in foo
into your current module.
In the above code with from socket import *
you just want to catch timeout
as you've pulled timeout
into your current namespace.
from socket import *
pulls in the definitions of everything inside of socket
but doesn't add socket
itself.
try:
# socketstuff
except timeout:
print 'caught a timeout'
Many people consider import *
problematic and try to avoid it. This is because common variable names in 2 or more modules that are imported in this way will clobber one another.
For example, consider the following three python files:
# a.py
def foo():
print "this is a's foo function"
# b.py
def foo():
print "this is b's foo function"
# yourcode.py
from a import *
from b import *
foo()
If you run yourcode.py
you'll see just the output "this is b's foo function".
For this reason I'd suggest either importing the module and using it or importing specific names from the module:
For example, your code would look like this with explicit imports:
import socket
from socket import AF_INET, SOCK_DGRAM
def main():
client_socket = socket.socket(AF_INET, SOCK_DGRAM)
client_socket.settimeout(1)
server_host = 'localhost'
server_port = 1234
while(True):
client_socket.sendto('Message', (server_host, server_port))
try:
reply, server_address_info = client_socket.recvfrom(1024)
print reply
except socket.timeout:
#more code
Just a tiny bit more typing but everything's explicit and it's pretty obvious to the reader where everything comes from.
Send a SMS via intent
I have developed this functionality from one Blog. There are 2 ways you can send SMS.
- Open native SMS composer
- write your message and send from your Android application
This is the code of 1st method.
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="@+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<Button
android:id="@+id/btnSendSMS"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Send SMS"
android:layout_centerInParent="true"
android:onClick="sendSMS">
</Button>
</RelativeLayout>
Activity
public class SendSMSActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void sendSMS(View v)
{
String number = "12346556"; // The number on which you want to send SMS
startActivity(new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", number, null)));
}
/* or
public void sendSMS(View v)
{
Uri uri = Uri.parse("smsto:12346556");
Intent it = new Intent(Intent.ACTION_SENDTO, uri);
it.putExtra("sms_body", "Here you can set the SMS text to be sent");
startActivity(it);
} */
}
NOTE:-
In this method, you don’t require SEND_SMS permission inside the AndroidManifest.xml file.
For 2nd method refer to this BLOG. You will find a good explanation from here.
Hope this will help you...
How can I send a file document to the printer and have it print?
public static void PrintFileToDefaultPrinter(string FilePath)
{
try
{
var file = File.ReadAllBytes(FilePath);
var printQueue = LocalPrintServer.GetDefaultPrintQueue();
using (var job = printQueue.AddJob())
using (var stream = job.JobStream)
{
stream.Write(file, 0, file.Length);
}
}
catch (Exception)
{
throw;
}
}
How to convert a structure to a byte array in C#?
This can be done very straightforwardly.
Define your struct explicitly with [StructLayout(LayoutKind.Explicit)]
int size = list.GetLength(0);
IntPtr addr = Marshal.AllocHGlobal(size * sizeof(DataStruct));
DataStruct *ptrBuffer = (DataStruct*)addr;
foreach (DataStruct ds in list)
{
*ptrBuffer = ds;
ptrBuffer += 1;
}
This code can only be written in an unsafe context. You have to free addr
when you're done with it.
Marshal.FreeHGlobal(addr);
java.lang.NoClassDefFoundError: javax/mail/Authenticator, whats wrong?
When I had this problem, I had included the mail-api.jar
in my maven pom file. That's the API specification only. The fix is to replace this:
<!-- DO NOT USE - it's just the API, not an implementation -->
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
with the reference implementation of that api:
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
I know it has sun in the package name, but that's the latest version. I learned this from https://stackoverflow.com/a/28935760/1128668
How do I best silence a warning about unused variables?
Using preprocessor directives is considered evil most of the time. Ideally you want to avoid them like the Pest. Remember that making the compiler understand your code is easy, allowing other programmers to understand your code is much harder. A few dozen cases like this here and there makes it very hard to read for yourself later or for others right now.
One way might be to put your parameters together into some sort of argument class. You could then use only a subset of the variables (equivalent to your assigning 0 really) or having different specializations of that argument class for each platform. This might however not be worth it, you need to analyze whether it would fit.
If you can read impossible templates, you might find advanced tips in the "Exceptional C++" book. If the people who would read your code could get their skillset to encompass the crazy stuff taught in that book, then you would have beautiful code which can also be easily read. The compiler would also be well aware of what you are doing (instead of hiding everything by preprocessing)
"CAUTION: provisional headers are shown" in Chrome debugger
I encountered this issue, and I managed to identify a specific cause, which isn't mentioned above either in answers or the question.
I am running a full js stack, angular front end and node back end on SSL, and the API is on a different domain running on port 8081, so I am doing CORS requests and withCredentials as I am dropping a session cookie from the API
So specifically my scenario was: POST request, withCredentials to port 8081 caused the "CAUTION: provisional headers are shown" message in the inspector and also of course blocked the request all together.
My solution was to set up apache to proxy pass the request from the usual SSL port of 443 to the node SSL port of 8081 (node has to be on a higher port as it cannot be ran as root in prod). So I guess Chrome doesn't like SSL requests to unconventional SSL ports, but perhaps their error message could be more specific.
facebook Uncaught OAuthException: An active access token must be used to query information about the current user
So I had the same issue, but it was because I was saving the access token but not using it. It could be because I'm super sleepy because of due dates, or maybe I just didn't think about it! But in case anyone else is in the same situation:
When I log in the user I save the access token:
$facebook = new Facebook(array(
'appId' => <insert the app id you get from facebook here>,
'secret' => <insert the app secret you get from facebook here>
));
$accessToken = $facebook->getAccessToken();
//save the access token for later
Now when I make requests to facebook I just do something like this:
$facebook = new Facebook(array(
'appId' => <insert the app id you get from facebook here>,
'secret' => <insert the app secret you get from facebook here>
));
$facebook->setAccessToken($accessToken);
$facebook->api(... insert own code here ...)
Angular get object from array by Id
// Used In TypeScript For Angular 4+
const viewArray = [
{id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
{id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
{id: 3, question: "Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
{id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
{id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
{id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
{id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
{id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
{id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
{id: 10, question: "Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
{id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
{id: 12, question: "Do you feel a sense of peace and contentment in your home? ", category: "Home Environment", subs: []},
{id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
{id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
{id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}
];
const arrayObj = any;
const objectData = any;
for (let index = 0; index < this.viewArray.length; index++) {
this.arrayObj = this.viewArray[index];
this.arrayObj.filter((x) => {
if (x.id === id) {
this.objectData = x;
}
});
console.log('Json Object Data by ID ==> ', this.objectData);
}
};
Define css class in django Forms
Use django-widget-tweaks, it is easy to use and works pretty well.
Otherwise this can be done using a custom template filter.
Considering you render your form this way :
<form action="/contact/" method="post">
{{ form.non_field_errors }}
<div class="fieldWrapper">
{{ form.subject.errors }}
<label for="id_subject">Email subject:</label>
{{ form.subject }}
</div>
</form>
form.subject is an instance of BoundField which has the as_widget method.
you can create a custom filter "addcss" in "my_app/templatetags/myfilters.py"
from django import template
register = template.Library()
@register.filter(name='addcss')
def addcss(value, arg):
css_classes = value.field.widget.attrs.get('class', '').split(' ')
if css_classes and arg not in css_classes:
css_classes = '%s %s' % (css_classes, arg)
return value.as_widget(attrs={'class': css_classes})
And then apply your filter:
{% load myfilters %}
<form action="/contact/" method="post">
{{ form.non_field_errors }}
<div class="fieldWrapper">
{{ form.subject.errors }}
<label for="id_subject">Email subject:</label>
{{ form.subject|addcss:'MyClass' }}
</div>
</form>
form.subjects will then be rendered with the "MyClass" css class.
Hope this help.
EDIT 1
EDIT 2
- Update filter according to Bhyd's comment
Recursive directory listing in DOS
You can use:
dir /s
If you need the list without all the header/footer information try this:
dir /s /b
(For sure this will work for DOS 6 and later; might have worked prior to that, but I can't recall.)
Calculating the angle between the line defined by two points
Had a need for similar functionality myself, so after much hair pulling I came up with the function below
/**
* Fetches angle relative to screen centre point
* where 3 O'Clock is 0 and 12 O'Clock is 270 degrees
*
* @param screenPoint
* @return angle in degress from 0-360.
*/
public double getAngle(Point screenPoint) {
double dx = screenPoint.getX() - mCentreX;
// Minus to correct for coord re-mapping
double dy = -(screenPoint.getY() - mCentreY);
double inRads = Math.atan2(dy, dx);
// We need to map to coord system when 0 degree is at 3 O'clock, 270 at 12 O'clock
if (inRads < 0)
inRads = Math.abs(inRads);
else
inRads = 2 * Math.PI - inRads;
return Math.toDegrees(inRads);
}
Best way to access web camera in Java
I think the project you are looking for is: https://github.com/sarxos/webcam-capture (I'm the author)
There is an example working exactly as you've described - after it's run, the window appear where, after you press "Start" button, you can see live image from webcam device and save it to file after you click on "Snapshot" (source code available, please note that FPS counter in the corner can be disabled):
The project is portable (WinXP, Win7, Win8, Linux, Mac, Raspberry Pi) and does not require any additional software to be installed on the PC.
API is really nice and easy to learn. Example how to capture single image and save it to PNG file:
Webcam webcam = Webcam.getDefault();
webcam.open();
ImageIO.write(webcam.getImage(), "PNG", new File("test.png"));
How do I get an animated gif to work in WPF?
Here is my version of animated image control. You can use standard property Source for specifying image source. I further improved it. I am a russian, project is russian so comments are also in Russian. But anyway you should be able understand everything without comments. :)
/// <summary>
/// Control the "Images", which supports animated GIF.
/// </summary>
public class AnimatedImage : Image
{
#region Public properties
/// <summary>
/// Gets / sets the number of the current frame.
/// </summary>
public int FrameIndex
{
get { return (int) GetValue(FrameIndexProperty); }
set { SetValue(FrameIndexProperty, value); }
}
/// <summary>
/// Gets / sets the image that will be drawn.
/// </summary>
public new ImageSource Source
{
get { return (ImageSource) GetValue(SourceProperty); }
set { SetValue(SourceProperty, value); }
}
#endregion
#region Protected interface
/// <summary>
/// Provides derived classes an opportunity to handle changes to the Source property.
/// </summary>
protected virtual void OnSourceChanged(DependencyPropertyChangedEventArgs aEventArgs)
{
ClearAnimation();
BitmapImage lBitmapImage = aEventArgs.NewValue as BitmapImage;
if (lBitmapImage == null)
{
ImageSource lImageSource = aEventArgs.NewValue as ImageSource;
base.Source = lImageSource;
return;
}
if (!IsAnimatedGifImage(lBitmapImage))
{
base.Source = lBitmapImage;
return;
}
PrepareAnimation(lBitmapImage);
}
#endregion
#region Private properties
private Int32Animation Animation { get; set; }
private GifBitmapDecoder Decoder { get; set; }
private bool IsAnimationWorking { get; set; }
#endregion
#region Private methods
private void ClearAnimation()
{
if (Animation != null)
{
BeginAnimation(FrameIndexProperty, null);
}
IsAnimationWorking = false;
Animation = null;
Decoder = null;
}
private void PrepareAnimation(BitmapImage aBitmapImage)
{
Debug.Assert(aBitmapImage != null);
if (aBitmapImage.UriSource != null)
{
Decoder = new GifBitmapDecoder(
aBitmapImage.UriSource,
BitmapCreateOptions.PreservePixelFormat,
BitmapCacheOption.Default);
}
else
{
aBitmapImage.StreamSource.Position = 0;
Decoder = new GifBitmapDecoder(
aBitmapImage.StreamSource,
BitmapCreateOptions.PreservePixelFormat,
BitmapCacheOption.Default);
}
Animation =
new Int32Animation(
0,
Decoder.Frames.Count - 1,
new Duration(
new TimeSpan(
0,
0,
0,
Decoder.Frames.Count / 10,
(int) ((Decoder.Frames.Count / 10.0 - Decoder.Frames.Count / 10) * 1000))))
{
RepeatBehavior = RepeatBehavior.Forever
};
base.Source = Decoder.Frames[0];
BeginAnimation(FrameIndexProperty, Animation);
IsAnimationWorking = true;
}
private bool IsAnimatedGifImage(BitmapImage aBitmapImage)
{
Debug.Assert(aBitmapImage != null);
bool lResult = false;
if (aBitmapImage.UriSource != null)
{
BitmapDecoder lBitmapDecoder = BitmapDecoder.Create(
aBitmapImage.UriSource,
BitmapCreateOptions.PreservePixelFormat,
BitmapCacheOption.Default);
lResult = lBitmapDecoder is GifBitmapDecoder;
}
else if (aBitmapImage.StreamSource != null)
{
try
{
long lStreamPosition = aBitmapImage.StreamSource.Position;
aBitmapImage.StreamSource.Position = 0;
GifBitmapDecoder lBitmapDecoder =
new GifBitmapDecoder(
aBitmapImage.StreamSource,
BitmapCreateOptions.PreservePixelFormat,
BitmapCacheOption.Default);
lResult = lBitmapDecoder.Frames.Count > 1;
aBitmapImage.StreamSource.Position = lStreamPosition;
}
catch
{
lResult = false;
}
}
return lResult;
}
private static void ChangingFrameIndex
(DependencyObject aObject, DependencyPropertyChangedEventArgs aEventArgs)
{
AnimatedImage lAnimatedImage = aObject as AnimatedImage;
if (lAnimatedImage == null || !lAnimatedImage.IsAnimationWorking)
{
return;
}
int lFrameIndex = (int) aEventArgs.NewValue;
((Image) lAnimatedImage).Source = lAnimatedImage.Decoder.Frames[lFrameIndex];
lAnimatedImage.InvalidateVisual();
}
/// <summary>
/// Handles changes to the Source property.
/// </summary>
private static void OnSourceChanged
(DependencyObject aObject, DependencyPropertyChangedEventArgs aEventArgs)
{
((AnimatedImage) aObject).OnSourceChanged(aEventArgs);
}
#endregion
#region Dependency Properties
/// <summary>
/// FrameIndex Dependency Property
/// </summary>
public static readonly DependencyProperty FrameIndexProperty =
DependencyProperty.Register(
"FrameIndex",
typeof (int),
typeof (AnimatedImage),
new UIPropertyMetadata(0, ChangingFrameIndex));
/// <summary>
/// Source Dependency Property
/// </summary>
public new static readonly DependencyProperty SourceProperty =
DependencyProperty.Register(
"Source",
typeof (ImageSource),
typeof (AnimatedImage),
new FrameworkPropertyMetadata(
null,
FrameworkPropertyMetadataOptions.AffectsRender |
FrameworkPropertyMetadataOptions.AffectsMeasure,
OnSourceChanged));
#endregion
}
How can I find where I will be redirected using cURL?
The answer above didn't work for me on one of my servers, something to to with basedir, so I re-hashed it a little. The code below works on all my servers.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$a = curl_exec($ch);
curl_close( $ch );
// the returned headers
$headers = explode("\n",$a);
// if there is no redirection this will be the final url
$redir = $url;
// loop through the headers and check for a Location: str
$j = count($headers);
for($i = 0; $i < $j; $i++){
// if we find the Location header strip it and fill the redir var
if(strpos($headers[$i],"Location:") !== false){
$redir = trim(str_replace("Location:","",$headers[$i]));
break;
}
}
// do whatever you want with the result
echo redir;
JavaScript moving element in the DOM
var swap = function () {
var divs = document.getElementsByTagName('div');
var div1 = divs[0];
var div2 = divs[1];
var div3 = divs[2];
div3.parentNode.insertBefore(div1, div3);
div1.parentNode.insertBefore(div3, div2);
};
This function may seem strange, but it heavily relies on standards in order to function properly. In fact, it may seem to function better than the jQuery version that tvanfosson posted which seems to do the swap only twice.
What standards peculiarities does it rely on?
insertBefore
Inserts the node newChild before the existing child node refChild. If
refChild is null, insert newChild at
the end of the list of children.
If newChild is a DocumentFragment object, all of its children are
inserted, in the same order, before
refChild. If the newChild is already
in the tree, it is first removed.
Java ByteBuffer to String
private String convertFrom(String lines, String from, String to) {
ByteBuffer bb = ByteBuffer.wrap(lines.getBytes());
CharBuffer cb = Charset.forName(to).decode(bb);
return new String(Charset.forName(from).encode(cb).array());
};
public Doit(){
String concatenatedLines = convertFrom(concatenatedLines, "CP1252", "UTF-8");
};
How to execute function in SQL Server 2008
I have come to this question and the one below several times.
how to call scalar function in sql server 2008
Each time, I try entering the Function using the syntax shown here in SQL Server Management Studio, or SSMS, to see the results, and each time I get the errors.
For me, that is because my result set is in tabular data format. Therefore, to see the results in SSMS, I have to call it like this:
SELECT * FROM dbo.Afisho_rankimin_TABLE(5);
I understand that the author's question involved a scalar function, so this answer is only to help others who come to StackOverflow often when they have a problem with a query (like me).
I hope this helps others.
The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path
For an Ant project:
Make sure, you have servlet-api.jar in the lib folder.
For a Maven project:
Make sure, you have the dependency added in POM.xml.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
Another way to do it is: Update the project facets to pick up the right server.
Check this box in this location:
Project ? Properties ? Target Runtimes ? Apache Tomcat (any server)
How to store Node.js deployment settings/configuration files?
My solution is fairly simple:
Load the environment config in ./config/index.js
var env = process.env.NODE_ENV || 'development'
, cfg = require('./config.'+env);
module.exports = cfg;
Define some defaults in ./config/config.global.js
var config = module.exports = {};
config.env = 'development';
config.hostname = 'dev.example.com';
//mongo database
config.mongo = {};
config.mongo.uri = process.env.MONGO_URI || 'localhost';
config.mongo.db = 'example_dev';
Override the defaults in ./config/config.test.js
var config = require('./config.global');
config.env = 'test';
config.hostname = 'test.example';
config.mongo.db = 'example_test';
module.exports = config;
Using it in ./models/user.js:
var mongoose = require('mongoose')
, cfg = require('../config')
, db = mongoose.createConnection(cfg.mongo.uri, cfg.mongo.db);
Running your app in test environment:
NODE_ENV=test node ./app.js
Turn off enclosing <p> tags in CKEditor 3.0
MAKE THIS YOUR config.js file code
CKEDITOR.editorConfig = function( config ) {
// config.enterMode = 2; //disabled <p> completely
config.enterMode = CKEDITOR.ENTER_BR // pressing the ENTER KEY input <br/>
config.shiftEnterMode = CKEDITOR.ENTER_P; //pressing the SHIFT + ENTER KEYS input <p>
config.autoParagraph = false; // stops automatic insertion of <p> on focus
};
Get current rowIndex of table in jQuery
Try this,
$('td').click(function(){
var row_index = $(this).parent().index();
var col_index = $(this).index();
});
If you need the index of table contain td then you can change it to
var row_index = $(this).parent('table').index();
Is it a good practice to use try-except-else in Python?
Python doesn't subscribe to the idea that exceptions should only be used for exceptional cases, in fact the idiom is 'ask for forgiveness, not permission'. This means that using exceptions as a routine part of your flow control is perfectly acceptable, and in fact, encouraged.
This is generally a good thing, as working this way helps avoid some issues (as an obvious example, race conditions are often avoided), and it tends to make code a little more readable.
Imagine you have a situation where you take some user input which needs to be processed, but have a default which is already processed. The try: ... except: ... else: ...
structure makes for very readable code:
try:
raw_value = int(input())
except ValueError:
value = some_processed_value
else: # no error occured
value = process_value(raw_value)
Compare to how it might work in other languages:
raw_value = input()
if valid_number(raw_value):
value = process_value(int(raw_value))
else:
value = some_processed_value
Note the advantages. There is no need to check the value is valid and parse it separately, they are done once. The code also follows a more logical progression, the main code path is first, followed by 'if it doesn't work, do this'.
The example is naturally a little contrived, but it shows there are cases for this structure.
Setting HttpContext.Current.Session in a unit test
In asp.net Core / MVC 6 rc2 you can set the HttpContext
var SomeController controller = new SomeController();
controller.ControllerContext = new ControllerContext();
controller.ControllerContext.HttpContext = new DefaultHttpContext();
controller.HttpContext.Session = new DummySession();
rc 1 was
var SomeController controller = new SomeController();
controller.ActionContext = new ActionContext();
controller.ActionContext.HttpContext = new DefaultHttpContext();
controller.HttpContext.Session = new DummySession();
https://stackoverflow.com/a/34022964/516748
Consider using Moq
new Mock<ISession>();
python pandas remove duplicate columns
It looks like you were on the right path. Here is the one-liner you were looking for:
df.reset_index().T.drop_duplicates().T
But since there is no example data frame that produces the referenced error message Reindexing only valid with uniquely valued index objects
, it is tough to say exactly what would solve the problem. if restoring the original index is important to you do this:
original_index = df.index.names
df.reset_index().T.drop_duplicates().reset_index(original_index).T
Java: Retrieving an element from a HashSet
You can HashMap<MyHashObject,MyHashObject>
instead of HashSet<MyHashObject>
.
Calling ContainsKey()
on your "reconstructed" MyHashObject
will first hashCode()
-check the collection, and if a duplicate hashcode is hit, finally equals()
-check your "reconstructed" against the original, at which you can retrieve the original using get()
This is O(1) but the downside is you will likely have to override both equals()
and hashCode()
methods.
Use SELECT inside an UPDATE query
Does this work? Untested but should get the point across.
UPDATE FUNCTIONS
SET Func_TaxRef =
(
SELECT Min(TAX.Tax_Code) AS MinOfTax_Code
FROM TAX, FUNCTIONS F1
WHERE F1.Func_Pure <= [Tax_ToPrice]
AND F1.Func_Year=[Tax_Year]
AND F1.Func_ID = FUNCTIONS.Func_ID
GROUP BY F1.Func_ID;
)
Basically for each row in FUNCTIONS, the subquery determines the minimum current tax code and sets FUNCTIONS.Func_TaxRef to that value. This is assuming that FUNCTIONS.Func_ID is a Primary or Unique key.
CSS How to set div height 100% minus nPx
If you need to support IE6, use JavaScript so manage the size of the wrapper div (set the position of the element in pixels after reading the window size). If you don't want to use JavaScript, then this can't be done. There are workarounds but expect a week or two to make it work in every case and in every browser.
For other modern browsers, use this css:
position: absolute;
top: 60px;
bottom: 0px;
Getting attribute of element in ng-click function in angularjs
Try passing it directly to the ng-click function:
<div class="col-lg-1 text-center">
<span class="glyphicon glyphicon-trash" data="{{event.id}}"
ng-click="deleteEvent(event.id)"></span>
</div>
Then it should be available in your handler:
$scope.deleteEvent=function(idPassedFromNgClick){
console.log(idPassedFromNgClick);
}
Here's an example
In SQL, is UPDATE always faster than DELETE+INSERT?
One command on the same row should always be faster than two on that same row. So the UPDATE only would be better.
EDIT
set up the table:
create table YourTable
(YourName varchar(50) primary key
,Tag int
)
insert into YourTable values ('first value',1)
run this, which takes 1 second on my system (sql server 2005):
SET NOCOUNT ON
declare @x int
declare @y int
select @x=0,@y=0
UPDATE YourTable set YourName='new name'
while @x<10000
begin
Set @x=@x+1
update YourTable set YourName='new name' where YourName='new name'
SET @y=@y+@@ROWCOUNT
end
print @y
run this, which took 2 seconds on my system:
SET NOCOUNT ON
declare @x int
declare @y int
select @x=0,@y=0
while @x<10000
begin
Set @x=@x+1
DELETE YourTable WHERE YourName='new name'
insert into YourTable values ('new name',1)
SET @y=@y+@@ROWCOUNT
end
print @y
File Not Found when running PHP with Nginx
in case it helps someone, my issue seems to be just because I was using a subfolder under my home directory, even though permissions seem correct and I don't have SELinux or anything like that.
changing it to be under /var/www/something/something made it work.
(if I ever found the real cause, and remember this answer, I'll update it)
Reset ID autoincrement ? phpmyadmin
I have just experienced this issue in one of my MySQL db's and I looked at the phpMyAdmin answer here. However the best way I fixed it in phpMyAdmin was in the affected table, drop the id column and make a fresh/new id column (adding A-I -autoincrement-). This restored my table id correctly-simples! Hope that helps (no MySQL code needed-I hope to learn to use that but later!) anyone else with this problem.
Windows error 2 occured while loading the Java VM
For me it works a deleting "C:\ProgramData\Oracle\Java\javapath" in my system enviroment PATH variable
Edit:
If you don't have that variable or it does not work you can directly delete or rename the directory "C:\ProgramData\Oracle\Java\javapath"
How to remove last n characters from a string in Bash?
This worked for me by calculating size of string.
It is easy you need to echo the value you need to return and then store it like below
removechars(){
var="some string.rtf"
size=${#var}
echo ${var:0:size-4}
}
removechars
var2=$?
some string
DB2 Date format
Current date is in yyyy-mm-dd
format. You can convert it into yyyymmdd
format using substring
function:
select substr(current date,1,4)||substr(current date,6,2)||substr(currentdate,9,2)
How do I get the full url of the page I am on in C#
Here is a list I normally refer to for this type of information:
Request.ApplicationPath : /virtual_dir
Request.CurrentExecutionFilePath : /virtual_dir/webapp/page.aspx
Request.FilePath : /virtual_dir/webapp/page.aspx
Request.Path : /virtual_dir/webapp/page.aspx
Request.PhysicalApplicationPath : d:\Inetpub\wwwroot\virtual_dir\
Request.QueryString : /virtual_dir/webapp/page.aspx?q=qvalue
Request.Url.AbsolutePath : /virtual_dir/webapp/page.aspx
Request.Url.AbsoluteUri : http://localhost:2000/virtual_dir/webapp/page.aspx?q=qvalue
Request.Url.Host : localhost
Request.Url.Authority : localhost:80
Request.Url.LocalPath : /virtual_dir/webapp/page.aspx
Request.Url.PathAndQuery : /virtual_dir/webapp/page.aspx?q=qvalue
Request.Url.Port : 80
Request.Url.Query : ?q=qvalue
Request.Url.Scheme : http
Request.Url.Segments : /
virtual_dir/
webapp/
page.aspx
Hopefully you will find this useful!
SyntaxError: "can't assign to function call"
You wrote the assignment backward: to assign a value (or an expression) to a variable you must have that variable at the left side of the assignment operator ( = in python )
subsequent_amount = invest(initial_amount,top_company(5,year,year+1))
How to convert Moment.js date to users local timezone?
var dateFormat = 'YYYY-DD-MM HH:mm:ss';
var testDateUtc = moment.utc('2015-01-30 10:00:00');
var localDate = testDateUtc.local();
console.log(localDate.format(dateFormat)); // 2015-30-01 02:00:00
- Define your date format.
- Create a moment object and set the UTC flag to true on the object.
- Create a localized moment object converted from the original moment
object.
- Return a formatted string from the localized moment object.
See: http://momentjs.com/docs/#/manipulating/local/
C# looping through an array
Here is a more general solution:
int increment = 3;
for(int i = 0; i < theData.Length; i += increment)
{
for(int j = 0; j < increment; j++)
{
if(i+j < theData.Length) {
//theData[i + j] for the current index
}
}
}
How do I create a folder in VB if it doesn't exist?
Try the System.IO.DirectoryInfo class.
The sample from MSDN:
Imports System
Imports System.IO
Public Class Test
Public Shared Sub Main()
' Specify the directories you want to manipulate.
Dim di As DirectoryInfo = New DirectoryInfo("c:\MyDir")
Try
' Determine whether the directory exists.
If di.Exists Then
' Indicate that it already exists.
Console.WriteLine("That path exists already.")
Return
End If
' Try to create the directory.
di.Create()
Console.WriteLine("The directory was created successfully.")
' Delete the directory.
di.Delete()
Console.WriteLine("The directory was deleted successfully.")
Catch e As Exception
Console.WriteLine("The process failed: {0}", e.ToString())
End Try
End Sub
End Class
Swift 3 - Comparing Date objects
As of the time of this writing, Swift natively supports comparing Dates with all comparison operators (i.e. <
, <=
, ==
, >=
, and >
). You can also compare optional Dates but are limited to <
, ==
, and >
. If you need to compare two optional dates using <=
or >=
, i.e.
let date1: Date? = ...
let date2: Date? = ...
if date1 >= date2 { ... }
You can overload the <=
and >=
operators to support optionals:
func <= <T: Comparable>(lhs: T?, rhs: T?) -> Bool {
return lhs == rhs || lhs < rhs
}
func >= <T: Comparable>(lhs: T?, rhs: T?) -> Bool {
return lhs == rhs || lhs > rhs
}
A connection was successfully established with the server, but then an error occurred during the pre-login handshake
I had a similar issue where I couldn't connect to a database and tried the recommendations here.
At the end of the day this is what worked for me:
Used the SQL Server Configuration Manager tool to enable the TCP/IP and/or the Named Pipes protocols on the SQL Server client computer.
- Click Start, point to All Programs, and click SQL Server Configuration Manager.
- Click to expand SQL Server Network Configuration and then click Client Protocols.
- Right-click the TCP/IP protocol and then click Enable.
- Right-click the Named Pipes protocol and then click Enable.
- Restart the SQL server service if prompted to do so.
I am still not sure why or when this was disabled.
Get an object attribute
Use getattr
if you have an attribute in string form:
>>> class User(object):
name = 'John'
>>> u = User()
>>> param = 'name'
>>> getattr(u, param)
'John'
Otherwise use the dot .
:
>>> class User(object):
name = 'John'
>>> u = User()
>>> u.name
'John'
TimeSpan to DateTime conversion
An easy method, use ticks:
new DateTime((DateTime.Now - DateTime.Now.AddHours(-1.55)).Ticks).ToString("HH:mm:ss:fff")
This function will give you a date (Without Day / Month / Year)
Convert a matrix to a 1 dimensional array
From ?matrix
: "A matrix is the special case of a two-dimensional 'array'." You can simply change the dimensions of the matrix/array.
Elts_int <- as.matrix(tmp_int) # read.table returns a data.frame as Brandon noted
dim(Elts_int) <- (maxrow_int*maxcol_int,1)
How change default SVN username and password to commit changes?
To use alternate credentials for a single operation, use the --username
and --password
switches for svn
.
To clear previously-saved credentials, delete ~/.subversion/auth
. You'll be prompted for credentials the next time they're needed.
These settings are saved in the user's home directory, so if you're using a shared account on "this laptop", be careful - if you allow the client to save your credentials, someone can impersonate you. The first option I provided is the better way to go in this case. At least until you stop using shared accounts on computers, which you shouldn't be doing.
To change credentials you need to do:
rm -rf ~/.subversion/auth
svn up
( it'll ask you for new username & password )
Get the second largest number in a list in linear time
This can be done in [N + log(N) - 2] time, which is slightly better than the loose upper bound of 2N (which can be thought of O(N) too).
The trick is to use binary recursive calls and "tennis tournament" algorithm. The winner (the largest number) will emerge after all the 'matches' (takes N-1 time), but if we record the 'players' of all the matches, and among them, group all the players that the winner has beaten, the second largest number will be the largest number in this group, i.e. the 'losers' group.
The size of this 'losers' group is log(N), and again, we can revoke the binary recursive calls to find the largest among the losers, which will take [log(N) - 1] time. Actually, we can just linearly scan the losers group to get the answer too, the time budget is the same.
Below is a sample python code:
def largest(L):
global paris
if len(L) == 1:
return L[0]
else:
left = largest(L[:len(L)//2])
right = largest(L[len(L)//2:])
pairs.append((left, right))
return max(left, right)
def second_largest(L):
global pairs
biggest = largest(L)
second_L = [min(item) for item in pairs if biggest in item]
return biggest, largest(second_L)
if __name__ == "__main__":
pairs = []
# test array
L = [2,-2,10,5,4,3,1,2,90,-98,53,45,23,56,432]
if len(L) == 0:
first, second = None, None
elif len(L) == 1:
first, second = L[0], None
else:
first, second = second_largest(L)
print('The largest number is: ' + str(first))
print('The 2nd largest number is: ' + str(second))
How to access the correct `this` inside a callback?
The question revolves around how this
keyword behaves in javascript. this
behaves differently as below,
- The value of
this
is usually determined by a function execution context.
- In the global scope,
this
refers to the global object (the window
object).
- If strict mode is enabled for any function then the value of
this
will be undefined
as in strict mode, global object refers to undefined
in place of the window
object.
- The object that is standing before the dot is what this keyword will be bound to.
- We can set the value of this explicitly with
call()
, bind()
, and apply()
- When the
new
keyword is used (a constructor), this is bound to the new object being created.
- Arrow Functions don’t bind
this
— instead, this
is bound lexically (i.e. based on the original context)
As most of the answers suggest, we can use Arrow function or bind()
Method or Self var. I would quote a point about lambdas (Arrow function) from Google JavaScript Style Guide
Prefer using arrow functions over f.bind(this), and especially over
goog.bind(f, this). Avoid writing const self = this. Arrow functions
are particularly useful for callbacks, which sometimes pass unexpectedly
additional arguments.
Google clearly recommends using lambdas rather than bind or const self = this
So the best solution would be to use lambdas as below,
function MyConstructor(data, transport) {
this.data = data;
transport.on('data', () => {
alert(this.data);
});
}
References:
- https://medium.com/tech-tajawal/javascript-this-4-rules-7354abdb274c
- arrow-functions-vs-bind
Fill remaining vertical space - only CSS
you need javascript and some client side calculations: http://jsfiddle.net/omegaiori/NERE8/2/
you will need jquery to effectively achieve what you want. this function is very simple but very effective:
(function () {
var heights = $("#wrapper").outerHeight(true);
var outerHeights = $("#first").outerHeight(true);
jQuery('#second').css('height', (heights - outerHeights) + "px");
})();
first it detects the wrapper height, as it is set to 100% it's different everytime (it depends on what screen you are landing).
in the second step it gives the #second
div the appropriate height subtracting from the wrapper height the #first
div height. the result is the available height left in the wrapper div
How to use a table type in a SELECT FROM statement?
Prior to Oracle 12C you cannot select from PL/SQL-defined tables, only from tables based on SQL types like this:
CREATE OR REPLACE TYPE exch_row AS OBJECT(
currency_cd VARCHAR2(9),
exch_rt_eur NUMBER,
exch_rt_usd NUMBER);
CREATE OR REPLACE TYPE exch_tbl AS TABLE OF exch_row;
In Oracle 12C it is now possible to select from PL/SQL tables that are defined in a package spec.
How to find cube root using Python?
You could use x ** (1. / 3)
to compute the (floating-point) cube root of x
.
The slight subtlety here is that this works differently for negative numbers in Python 2 and 3. The following code, however, handles that:
def is_perfect_cube(x):
x = abs(x)
return int(round(x ** (1. / 3))) ** 3 == x
print(is_perfect_cube(63))
print(is_perfect_cube(64))
print(is_perfect_cube(65))
print(is_perfect_cube(-63))
print(is_perfect_cube(-64))
print(is_perfect_cube(-65))
print(is_perfect_cube(2146689000)) # no other currently posted solution
# handles this correctly
This takes the cube root of x
, rounds it to the nearest integer, raises to the third power, and finally checks whether the result equals x
.
The reason to take the absolute value is to make the code work correctly for negative numbers across Python versions (Python 2 and 3 treat raising negative numbers to fractional powers differently).
Running .sh scripts in Git Bash
I was having two .sh scripts to start and stop the digital ocean servers that I wanted to run from the Windows 10. What I did is:
- downloaded "Git for Windows" (from https://git-scm.com/download/win).
- installed Git
- to execute the .sh script just double-clicked the script file it started the execution of the script.
Now to run the script each time I just double-click the script
Convert NSArray to NSString in Objective-C
The way I know is easy.
var NSArray_variable = NSArray_Object[n]
var stringVarible = NSArray_variable as String
n
is the inner position in the array
This in SWIFT Language.
It might work in Objective C
Selenium Error - The HTTP request to the remote WebDriver timed out after 60 seconds
In my case none of the answers above solved my problem completely.
I ended up using the (no-sandbox
) mode, the connection with extended timeout period (driver = new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub"), capability, TimeSpan.FromMinutes(3));
) and the page load timeout (driver.Manage().Timeouts().PageLoad.Add(System.TimeSpan.FromSeconds(30));
) so now my code looks like this:
public IWebDriver GetRemoteChromeDriver(string downloadPath)
{
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.AddArguments(
"start-maximized",
"enable-automation",
"--headless",
"--no-sandbox", //this is the relevant other arguments came from solving other issues
"--disable-infobars",
"--disable-dev-shm-usage",
"--disable-browser-side-navigation",
"--disable-gpu",
"--ignore-certificate-errors");
capability = chromeOptions.ToCapabilities();
SetRemoteWebDriver();
SetImplicitlyWait();
Thread.Sleep(TimeSpan.FromSeconds(2));
return driver;
}
private void SetImplicitlyWait()
{
driver.Manage().Timeouts().PageLoad.Add(TimeSpan.FromSeconds(30));
}
private void SetRemoteWebDriver()
{
driver = new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub"), capability, TimeSpan.FromMinutes(3));
}
But as I mentioned none of the above method solved my problem, I was continuously get the error, and multiple chromedriver.exe and chrome.exe processses were active (~10 of the chromedriver and ~50 of chrome).
So somewhere I read that after disposing the driver I should wait a few seconds before starting the next test, so I added the following line to dispose method:
driver?.Quit();
driver?.Dispose();
Thread.Sleep(3000);
With this sleep modification I have no longer get the timeout error and there is no unnecessarily opened chromedriver.exe and chrome.exe processses.
I hope I helped someone who struggles with this issue for that long as I did.
Install Chrome extension form outside the Chrome Web Store
For Windows, you can also whitelist your extension through Windows policies. The full steps are details in this answer, but there are quicker steps:
- Create the registry key
HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\ExtensionInstallWhitelist
.
- For each extension you want to whitelist, add a string value whose name should be a sequence number (starting at 1) and value is the extension ID.
For instance, in order to whitelist 2 extensions with ID aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
and bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
, create a string value with name 1
and value aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
, and a second value with name 2
and value bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
. This can be sum up by this registry file:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome]
[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\ExtensionInstallWhitelist]
"1"="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"2"="bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
EDIT: actually, Chromium docs also indicate how to do it for other OS.
How to match letters only using java regex, matches method?
matches
method performs matching of full line, i.e. it is equivalent to find()
with '^abc$'. So, just use Pattern.compile("[a-zA-Z]").matcher(str).find()
instead. Then fix your regex. As @user unknown mentioned your regex actually matches only one character. You probably should say [a-zA-Z]+
how to read xml file from url using php
Your code seems right, check if you have fopen wrappers enabled (allow_url_fopen = On
on php.ini)
Also, as mentioned by other answers, you should provide a properly encoded URI or encode it using urlencode() function. You should also check if there is any error fetching the XML string and if there is any parsing error, which you can output using libxml_get_errors() as follows:
<?php
if (($response_xml_data = file_get_contents($map_url))===false){
echo "Error fetching XML\n";
} else {
libxml_use_internal_errors(true);
$data = simplexml_load_string($response_xml_data);
if (!$data) {
echo "Error loading XML\n";
foreach(libxml_get_errors() as $error) {
echo "\t", $error->message;
}
} else {
print_r($data);
}
}
?>
If the problem is you can't fetch the XML code maybe it's because you need to include some custom headers in your request, check how to use stream_context_create() to create a custom stream context for use when calling file_get_contents()
on example 4 at http://php.net/manual/en/function.file-get-contents.php
Difference between F5, Ctrl + F5 and click on refresh button?
F5 reloads the page from server, but it uses the browser's cache for page elements like scripts, image, CSS stylesheets, etc, etc. But Ctrl + F5, reloads the page from the server and also reloads its contents from server and doesn't use local cache at all.
So by pressing F5 on, say, the Yahoo homepage, it just reloads the main HTML frame and then loads all other elements like images from its cache. If a new element was added or changed then it gets it from the server. But Ctrl + F5 reloads everything from the server.
How to use boost bind with a member function
Use the following instead:
boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );
This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.
Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.
Spring profiles and testing
Can I recommend doing it this way, define your test like this:
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
TestPreperationExecutionListener.class
})
@Transactional
@ActiveProfiles(profiles = "localtest")
@ContextConfiguration
public class TestContext {
@Test
public void testContext(){
}
@Configuration
@PropertySource("classpath:/myprops.properties")
@ImportResource({"classpath:context.xml" })
public static class MyContextConfiguration{
}
}
with the following content in myprops.properties file:
spring.profiles.active=localtest
With this your second properties file should get resolved:
META-INF/spring/config_${spring.profiles.active}.properties
How to add a new line in textarea element?
To get a new line inside text-area, put an actual line-break there:
_x000D_
_x000D_
<textarea cols='60' rows='8'>This is my statement one._x000D_
This is my statement2</textarea>
_x000D_
_x000D_
_x000D_
typesafe select onChange event using reactjs and typescript
The easiest way is to add a type to the variable that is receiving the value, like this:
var value: string = (event.target as any).value;
Or you could cast the value
property as well as event.target
like this:
var value = ((event.target as any).value as string);
Edit:
Lastly, you can define what EventTarget.value
is in a separate .d.ts
file. However, the type will have to be compatible where it's used elsewhere, and you'll just end up using any
again anyway.
globals.d.ts
interface EventTarget {
value: any;
}
How to make promises work in IE11
If you want this type of code to run in IE11 (which does not support much of ES6 at all), then you need to get a 3rd party promise library (like Bluebird), include that library and change your coding to use ES5 coding structures (no arrow functions, no let
, etc...) so you can live within the limits of what older browsers support.
Or, you can use a transpiler (like Babel) to convert your ES6 code to ES5 code that will work in older browsers.
Here's a version of your code written in ES5 syntax with the Bluebird promise library:
<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.4/bluebird.min.js"></script>
<script>
'use strict';
var promise = new Promise(function(resolve) {
setTimeout(function() {
resolve("result");
}, 1000);
});
promise.then(function(result) {
alert("Fulfilled: " + result);
}, function(error) {
alert("Rejected: " + error);
});
</script>
Writing BMP image in pure c/c++ without other libraries
The best bitmap encoder is the one you do not write yourself. The file format is a lot more involved, than one might expect. This is evidenced by the fact, that all proposed answers do not create a monochrome (1bpp) bitmap, but rather write out 24bpp files, that happen to only use 2 colors.
The following is a Windows-only solution, using the Windows Imaging Component. It doesn't rely on any external/3rd party libraries, other than what ships with Windows.
Like every C++ program, we need to include several header files. And link to Windowscodecs.lib while we're at it:
#include <Windows.h>
#include <comdef.h>
#include <comip.h>
#include <comutil.h>
#include <wincodec.h>
#include <vector>
#pragma comment(lib, "Windowscodecs.lib")
Next up, we declare our container (a vector, of vectors! Of bool
!), and a few smart pointers for convenience:
using _com_util::CheckError;
using container = std::vector<std::vector<bool>>;
_COM_SMARTPTR_TYPEDEF(IWICImagingFactory, __uuidof(IWICImagingFactory));
_COM_SMARTPTR_TYPEDEF(IWICBitmapEncoder, __uuidof(IWICBitmapEncoder));
_COM_SMARTPTR_TYPEDEF(IWICBitmapFrameEncode, __uuidof(IWICBitmapFrameEncode));
_COM_SMARTPTR_TYPEDEF(IWICStream, __uuidof(IWICStream));
_COM_SMARTPTR_TYPEDEF(IWICPalette, __uuidof(IWICPalette));
With that all settled, we can jump right into the implementation. There's a bit of setup required to get a factory, an encoder, a frame, and get everything prepared:
void write_bitmap(wchar_t const* pathname, container const& data)
{
// Create factory
IWICImagingFactoryPtr sp_factory { nullptr };
CheckError(sp_factory.CreateInstance(CLSID_WICImagingFactory, nullptr,
CLSCTX_INPROC_SERVER));
// Create encoder
IWICBitmapEncoderPtr sp_encoder { nullptr };
CheckError(sp_factory->CreateEncoder(GUID_ContainerFormatBmp, nullptr, &sp_encoder));
// Create stream
IWICStreamPtr sp_stream { nullptr };
CheckError(sp_factory->CreateStream(&sp_stream));
CheckError(sp_stream->InitializeFromFilename(pathname, GENERIC_WRITE));
// Initialize encoder with stream
CheckError(sp_encoder->Initialize(sp_stream, WICBitmapEncoderNoCache));
// Create new frame
IWICBitmapFrameEncodePtr sp_frame { nullptr };
IPropertyBag2Ptr sp_properties { nullptr };
CheckError(sp_encoder->CreateNewFrame(&sp_frame, &sp_properties));
// Initialize frame with default properties
CheckError(sp_frame->Initialize(sp_properties));
// Set pixel format
// SetPixelFormat() requires a pointer to non-const
auto pf { GUID_WICPixelFormat1bppIndexed };
CheckError(sp_frame->SetPixelFormat(&pf));
if (!::IsEqualGUID(pf, GUID_WICPixelFormat1bppIndexed))
{
// Report unsupported pixel format
CheckError(WINCODEC_ERR_UNSUPPORTEDPIXELFORMAT);
}
// Set size derived from data argument
auto const width { static_cast<UINT>(data.size()) };
auto const height { static_cast<UINT>(data[0].size()) };
CheckError(sp_frame->SetSize(width, height));
// Set palette on frame. This is required since we use an indexed pixel format.
// Only GIF files support global palettes, so make sure to set it on the frame
// rather than the encoder.
IWICPalettePtr sp_palette { nullptr };
CheckError(sp_factory->CreatePalette(&sp_palette));
CheckError(sp_palette->InitializePredefined(WICBitmapPaletteTypeFixedBW, FALSE));
CheckError(sp_frame->SetPalette(sp_palette));
At that point everything is set up, and we have a frame to dump our data into. For 1bpp files, every byte stores the information of 8 pixels. The left-most pixel is stored in the MSB, with pixels following all the way down to the right-most pixel stored in the LSB.
The code isn't entirely important; you'll be replacing that with whatever suits your needs, when you replace the data layout of your input anyway:
// Write data to frame
auto const stride { (width * 1 + 7) / 8 };
auto const size { height * stride };
std::vector<unsigned char> buffer(size, 127u);
// Convert data to match required layout. Each byte stores 8 pixels, with the
// MSB being the leftmost, the LSB the right-most.
for (size_t x { 0 }; x < data.size(); ++x)
{
for (size_t y { 0 }; y < data[x].size(); ++y)
{
auto shift { x % 8 };
auto mask { 0x80 >> shift };
auto bit { mask * data[x][y] };
auto& value { buffer[y * stride + x / 8] };
value &= ~mask;
value |= bit;
}
}
CheckError(sp_frame->WritePixels(height, stride,
static_cast<UINT>(buffer.size()), buffer.data()));
What's left is to commit the changes to the frame and the encoder, which will ultimately write the image file to disk:
// Commit frame
CheckError(sp_frame->Commit());
// Commit image
CheckError(sp_encoder->Commit());
}
This is a test program, writing out an image to a file passed as the first command-line argument:
#include <iostream>
int wmain(int argc, wchar_t* argv[])
try
{
if (argc != 2)
{
return -1;
}
CheckError(::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED));
// Create 64x64 matrix
container data(64, std::vector<bool>(64, false));
// Fill with arrow pointing towards the upper left
for (size_t i { 0 }; i < data.size(); ++i)
{
data[0][i] = true;
data[i][0] = true;
data[i][i] = true;
}
::write_bitmap(argv[1], data);
::CoUninitialize();
}
catch (_com_error const& e)
{
std::wcout << L"Error!\n" << L" Message: " << e.ErrorMessage() << std::endl;
}
It produces the following image (true 1bpp, 574 bytes in size):
ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response
Follow the below steps:
Add to sending request header Content-Type
field:
axios.post(`/Order/`, orderId,
{
headers: {'Content-Type': 'application/json'}
})
Every data (simple or complex type) sent with axios should be placed without any extra brackets (axios.post('/Order/', orderId, ...)
).
WARNING! There is one exception for string
type - stringify it before send (axios.post('/Order/', JSON.stringify(address), ...)
).
Add method to controller:
[HttpPost]
public async Task<IActionResult> Post([FromBody]int orderId)
{
return Ok();
}
Implement specialization in ER diagram
So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]
How to disable Google Chrome auto update?
For latest versions, use following steps:
- Go to "msconfig" from Win+R
- Go to Service tab
- Uncheck both "Google Update Service" boxes.
- Click OK and Restart computer to save changes.
How to split one text file into multiple *.txt files?
You can use the linux bash core utility split
split -b 1M -d file.txt file
Note that M
or MB
both are OK but size is different. MB is 1000 * 1000, M is 1024^2
If you want to separate by lines you can use -l
parameter.
UPDATE
a=(`wc -l yourfile`) ; lines=`echo $(($a/12)) | bc -l` ; split -l $lines -d file.txt file
Another solution as suggested by Kirill, you can do something like the following
split -n l/12 file.txt
Note that is l
not one
, split -n
has a few options, like N
, k/N
, l/k/N
, r/N
, r/k/N
.
Reading e-mails from Outlook with Python through MAPI
I have created my own iterator to iterate over Outlook objects via python. The issue is that python tries to iterates starting with Index[0], but outlook expects for first item Index[1]... To make it more Ruby simple, there is below a helper class Oli with following
methods:
.items() - yields a tuple(index, Item)...
.prop() - helping to introspect outlook object exposing available properties (methods and attributes)
from win32com.client import constants
from win32com.client.gencache import EnsureDispatch as Dispatch
outlook = Dispatch("Outlook.Application")
mapi = outlook.GetNamespace("MAPI")
class Oli():
def __init__(self, outlook_object):
self._obj = outlook_object
def items(self):
array_size = self._obj.Count
for item_index in xrange(1,array_size+1):
yield (item_index, self._obj[item_index])
def prop(self):
return sorted( self._obj._prop_map_get_.keys() )
for inx, folder in Oli(mapi.Folders).items():
# iterate all Outlook folders (top level)
print "-"*70
print folder.Name
for inx,subfolder in Oli(folder.Folders).items():
print "(%i)" % inx, subfolder.Name,"=> ", subfolder
file_get_contents("php://input") or $HTTP_RAW_POST_DATA, which one is better to get the body of JSON request?
The usual rules should apply for how you send the request. If the request is to retrieve information (e.g. a partial search 'hint' result, or a new page to be displayed, etc...) you can use GET. If the data being sent is part of a request to change something (update a database, delete a record, etc..) then use POST.
Server-side, there's no reason to use the raw input, unless you want to grab the entire post/get data block in a single go. You can retrieve the specific information you want via the _GET/_POST arrays as usual. AJAX libraries such as MooTools/jQuery will handle the hard part of doing the actual AJAX calls and encoding form data into appropriate formats for you.
Sending SOAP request using Python Requests
It is indeed possible.
Here is an example calling the Weather SOAP Service using plain requests lib:
import requests
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
#headers = {'content-type': 'application/soap+xml'}
headers = {'content-type': 'text/xml'}
body = """<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:ns0="http://ws.cdyne.com/WeatherWS/" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<ns1:Body><ns0:GetWeatherInformation/></ns1:Body>
</SOAP-ENV:Envelope>"""
response = requests.post(url,data=body,headers=headers)
print response.content
Some notes:
- The headers are important. Most SOAP requests will not work without the correct headers.
application/soap+xml
is probably the more correct header to use (but the weatherservice prefers text/xml
- This will return the response as a string of xml - you would then need to parse that xml.
- For simplicity I have included the request as plain text. But best practise would be to store this as a template, then you can load it using jinja2 (for example) - and also pass in variables.
For example:
from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('myapp', 'templates'))
template = env.get_template('soaprequests/WeatherSericeRequest.xml')
body = template.render()
Some people have mentioned the suds library. Suds is probably the more correct way to be interacting with SOAP, but I often find that it panics a little when you have WDSLs that are badly formed (which, TBH, is more likely than not when you're dealing with an institution that still uses SOAP ;) ).
You can do the above with suds like so:
from suds.client import Client
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
client = Client(url)
print client ## shows the details of this service
result = client.service.GetWeatherInformation()
print result
Note: when using suds, you will almost always end up needing to use the doctor!
Finally, a little bonus for debugging SOAP; TCPdump is your friend. On Mac, you can run TCPdump like so:
sudo tcpdump -As 0
This can be helpful for inspecting the requests that actually go over the wire.
The above two code snippets are also available as gists:
Histogram using gnuplot?
yes, and its quick and simple though very hidden:
binwidth=5
bin(x,width)=width*floor(x/width)
plot 'datafile' using (bin($1,binwidth)):(1.0) smooth freq with boxes
check out help smooth freq
to see why the above makes a histogram
to deal with ranges just set the xrange variable.
CSS vertical-align: text-bottom;
Vertical align only works in some select cases. The easiest way to make it function is to set display: table
in the parent element's CSS and display: table-cell;
to the child element and then apply your vertical align attribute.
Getting data posted in between two dates
if your date filed is timestamp into database then this is the easy way to get record
$this->db->where('DATE(RecordDate) >=', date('Y-m-d',strtotime($startDate)));
$this->db->where('DATE(RecordDate) <=', date('Y-m-d',strtotime($endDate)));
PHP save image file
No need to create a GD resource, as someone else suggested.
$input = 'http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com';
$output = 'google.com.jpg';
file_put_contents($output, file_get_contents($input));
Note: this solution only works if you're setup to allow fopen access to URLs. If the solution above doesn't work, you'll have to use cURL.
Please initialize the log4j system properly warning
Add the code
BasicConfigurator.configure();
in your static main class as below..
Note:
add " \hadoop-2.7.1\share\hadoop\common\lib\commons-logging-1.1.3.jar &
\hadoop-2.7.1\share\hadoop\common\lib\log4j-1.2.17.jar "
as the external references
import org.apache.log4j.BasicConfigurator;
public class ViewCountDriver extends Configured implements Tool{
public static void main(String[]args) throws Exception{
BasicConfigurator.configure();
int exitcode = ToolRunner.run(new ViewCountDriver(), args);
System.exit(exitcode);
}
}
How to check if two arrays are equal with JavaScript?
Based on Tim James answer and Fox32's comment, the following should check for nulls, with the assumption that two nulls are not equal.
function arrays_equal(a,b) { return !!a && !!b && !(a<b || b<a); }
> arrays_equal([1,2,3], [1,3,4])
false
> arrays_equal([1,2,3], [1,2,3])
true
> arrays_equal([1,3,4], [1,2,3])
false
> arrays_equal(null, [1,2,3])
false
> arrays_equal(null, null)
false
mysql said: Cannot connect: invalid settings. xampp
The above code fixed problem for most of the ppl but I still could not login. Finally I found this (line#9 in the above code needs to be changed)
$cfg['Servers'][$i]['AllowNoPassword'] = true; <--- change this
$cfg['Servers'][$i]['AllowNoPassword'] = false; <--- to this fixed the problem.
Note: there are other areas in localhost where you have to change the password manually. For example in "CD Collection" example. The password is hard coded there rather than picking it up from config.inc.php.
SQL Server : fetching records between two dates?
You need to be more explicit and add the start and end times as well, down to the milliseconds:
select *
from xxx
where dates between '2012-10-26 00:00:00.000' and '2012-10-27 23:59:59.997'
The database can very well interpret '2012-10-27'
as '2012-10-27 00:00:00.000'
.
What are all the user accounts for IIS/ASP.NET and how do they differ?
This is a very good question and sadly many developers don't ask enough questions about IIS/ASP.NET security in the context of being a web developer and setting up IIS. So here goes....
To cover the identities listed:
IIS_IUSRS:
This is analogous to the old IIS6 IIS_WPG
group. It's a built-in group with it's security configured such that any member of this group can act as an application pool identity.
IUSR:
This account is analogous to the old IUSR_<MACHINE_NAME>
local account that was the default anonymous user for IIS5 and IIS6 websites (i.e. the one configured via the Directory Security tab of a site's properties).
For more information about IIS_IUSRS
and IUSR
see:
Understanding Built-In User and Group Accounts in IIS 7
DefaultAppPool:
If an application pool is configured to run using the Application Pool Identity feature then a "synthesised" account called IIS AppPool\<pool name>
will be created on the fly to used as the pool identity. In this case there will be a synthesised account called IIS AppPool\DefaultAppPool
created for the life time of the pool. If you delete the pool then this account will no longer exist. When applying permissions to files and folders these must be added using IIS AppPool\<pool name>
. You also won't see these pool accounts in your computers User Manager. See the following for more information:
Application Pool Identities
ASP.NET v4.0:
-
This will be the Application Pool Identity for the ASP.NET v4.0 Application Pool. See DefaultAppPool
above.
NETWORK SERVICE:
-
The NETWORK SERVICE
account is a built-in identity introduced on Windows 2003. NETWORK SERVICE
is a low privileged account under which you can run your application pools and websites. A website running in a Windows 2003 pool can still impersonate the site's anonymous account (IUSR_ or whatever you configured as the anonymous identity).
In ASP.NET prior to Windows 2008 you could have ASP.NET execute requests under the Application Pool account (usually NETWORK SERVICE
). Alternatively you could configure ASP.NET to impersonate the site's anonymous account via the <identity impersonate="true" />
setting in web.config
file locally (if that setting is locked then it would need to be done by an admin in the machine.config
file).
Setting <identity impersonate="true">
is common in shared hosting environments where shared application pools are used (in conjunction with partial trust settings to prevent unwinding of the impersonated account).
In IIS7.x/ASP.NET impersonation control is now configured via the Authentication configuration feature of a site. So you can configure to run as the pool identity, IUSR
or a specific custom anonymous account.
LOCAL SERVICE:
The LOCAL SERVICE
account is a built-in account used by the service control manager. It has a minimum set of privileges on the local computer. It has a fairly limited scope of use:
LocalService Account
LOCAL SYSTEM:
You didn't ask about this one but I'm adding for completeness. This is a local built-in account. It has fairly extensive privileges and trust. You should never configure a website or application pool to run under this identity.
LocalSystem Account
In Practice:
In practice the preferred approach to securing a website (if the site gets its own application pool - which is the default for a new site in IIS7's MMC) is to run under Application Pool Identity
. This means setting the site's Identity in its Application Pool's Advanced Settings to Application Pool Identity
:
In the website you should then configure the Authentication feature:
Right click and edit the Anonymous Authentication entry:
Ensure that "Application pool identity" is selected:
When you come to apply file and folder permissions you grant the Application Pool identity whatever rights are required. For example if you are granting the application pool identity for the ASP.NET v4.0
pool permissions then you can either do this via Explorer:
Click the "Check Names" button:
Or you can do this using the ICACLS.EXE
utility:
icacls c:\wwwroot\mysite /grant "IIS AppPool\ASP.NET v4.0":(CI)(OI)(M)
...or...if you site's application pool is called BobsCatPicBlog
then:
icacls c:\wwwroot\mysite /grant "IIS AppPool\BobsCatPicBlog":(CI)(OI)(M)
I hope this helps clear things up.
Update:
I just bumped into this excellent answer from 2009 which contains a bunch of useful information, well worth a read:
The difference between the 'Local System' account and the 'Network Service' account?
Inline elements shifting when made bold on hover
A compromised solution is to fake bold with text-shadow, e.g:
text-shadow: 0 0 0.01px black;
For better comparison I created these examples:
_x000D_
_x000D_
a, li {_x000D_
color: black;_x000D_
text-decoration: none;_x000D_
font: 18px sans-serif;_x000D_
letter-spacing: 0.03em;_x000D_
}_x000D_
li {_x000D_
display: inline-block;_x000D_
margin-right: 20px;_x000D_
color: gray;_x000D_
font-size: 0.7em;_x000D_
}_x000D_
.bold-x1 a.hover:hover,_x000D_
.bold-x1 a:not(.hover) {_x000D_
text-shadow: 0 0 .01px black;_x000D_
}_x000D_
.bold-x2 a.hover:hover,_x000D_
.bold-x2 a:not(.hover){_x000D_
text-shadow: 0 0 .01px black, 0 0 .01px black;_x000D_
}_x000D_
.bold-x3 a.hover:hover,_x000D_
.bold-x3 a:not(.hover){_x000D_
text-shadow: 0 0 .01px black, 0 0 .01px black, 0 0 .01px black;_x000D_
}_x000D_
.bold-native a.hover:hover,_x000D_
.bold-native a:not(.hover){_x000D_
font-weight: bold;_x000D_
}_x000D_
_x000D_
.bold-native li:nth-child(4),_x000D_
.bold-native li:nth-child(5){_x000D_
margin-left: -6px;_x000D_
letter-spacing: 0.01em;_x000D_
}
_x000D_
<ul class="bold-x1">_x000D_
<li><a class="hover" href="#">Home</a></li>_x000D_
<li><a class="hover" href="#">Products</a></li>_x000D_
<li><a href="#">Contact</a></li>_x000D_
<li><a href="#">About</a></li>_x000D_
<li>Bold (text-shadow x1)</li>_x000D_
</ul>_x000D_
<ul class="bold-x2">_x000D_
<li><a class="hover" href="#">Home</a></li>_x000D_
<li><a class="hover" href="#">Products</a></li>_x000D_
<li><a href="#">Contact</a></li>_x000D_
<li><a href="#">About</a></li>_x000D_
<li>Extra Bold (text-shadow x2)</li>_x000D_
</ul>_x000D_
<ul class="bold-native">_x000D_
<li><a class="hover" href="#">Home</a></li>_x000D_
<li><a class="hover" href="#">Products</a></li>_x000D_
<li><a href="#">Contact</a></li>_x000D_
<li><a href="#">About</a></li>_x000D_
<li>Bold (native)</li>_x000D_
</ul>_x000D_
<ul class="bold-x3">_x000D_
<li><a class="hover" href="#">Home</a></li>_x000D_
<li><a class="hover" href="#">Products</a></li>_x000D_
<li><a href="#">Contact</a></li>_x000D_
<li><a href="#">About</a></li>_x000D_
<li>Black (text-shadow x3)</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_
Passing to text-shadow
really low value for blur-radius
will make the blurring effect not so apparent.
In general the more your repeat text-shadow
the bolder your text will get but in the same time loosing original shape of the letters.
I should warn you that setting the blur-radius
to fractions is not going to render the same in all browsers! Safari for example need bigger values to render it the same way Chrome will do.
Putting text in top left corner of matplotlib plot
import matplotlib.pyplot as plt
plt.figure(figsize=(6, 6))
plt.text(0.1, 0.9, 'text', size=15, color='purple')
# or
fig, axe = plt.subplots(figsize=(6, 6))
axe.text(0.1, 0.9, 'text', size=15, color='purple')
Output of Both
import matplotlib.pyplot as plt
# Build a rectangle in axes coords
left, width = .25, .5
bottom, height = .25, .5
right = left + width
top = bottom + height
ax = plt.gca()
p = plt.Rectangle((left, bottom), width, height, fill=False)
p.set_transform(ax.transAxes)
p.set_clip_on(False)
ax.add_patch(p)
ax.text(left, bottom, 'left top',
horizontalalignment='left',
verticalalignment='top',
transform=ax.transAxes)
ax.text(left, bottom, 'left bottom',
horizontalalignment='left',
verticalalignment='bottom',
transform=ax.transAxes)
ax.text(right, top, 'right bottom',
horizontalalignment='right',
verticalalignment='bottom',
transform=ax.transAxes)
ax.text(right, top, 'right top',
horizontalalignment='right',
verticalalignment='top',
transform=ax.transAxes)
ax.text(right, bottom, 'center top',
horizontalalignment='center',
verticalalignment='top',
transform=ax.transAxes)
ax.text(left, 0.5 * (bottom + top), 'right center',
horizontalalignment='right',
verticalalignment='center',
rotation='vertical',
transform=ax.transAxes)
ax.text(left, 0.5 * (bottom + top), 'left center',
horizontalalignment='left',
verticalalignment='center',
rotation='vertical',
transform=ax.transAxes)
ax.text(0.5 * (left + right), 0.5 * (bottom + top), 'middle',
horizontalalignment='center',
verticalalignment='center',
transform=ax.transAxes)
ax.text(right, 0.5 * (bottom + top), 'centered',
horizontalalignment='center',
verticalalignment='center',
rotation='vertical',
transform=ax.transAxes)
ax.text(left, top, 'rotated\nwith newlines',
horizontalalignment='center',
verticalalignment='center',
rotation=45,
transform=ax.transAxes)
plt.axis('off')
plt.show()
Create Map in Java
I use such kind of a Map population thanks to Java 9. In my honest opinion, this approach provides more readability to the code.
public static void main(String[] args) {
Map<Integer, Point2D.Double> map = Map.of(
1, new Point2D.Double(1, 1),
2, new Point2D.Double(2, 2),
3, new Point2D.Double(3, 3),
4, new Point2D.Double(4, 4));
map.entrySet().forEach(System.out::println);
}
Put byte array to JSON and vice versa
Amazingly now org.json now lets you put a byte[] object directly into a json and it remains readable. you can even send the resulting object over a websocket and it will be readable on the other side. but i am not sure yet if the size of the resulting object is bigger or smaller than if you were converting your byte array to base64, it would certainly be neat if it was smaller.
It seems to be incredibly hard to measure how much space such a json object takes up in java. if your json consists merely of strings it is easily achievable by simply stringifying it but with a bytearray inside it i fear it is not as straightforward.
stringifying our json in java replaces my bytearray for a 10 character string that looks like an id. doing the same in node.js replaces our byte[]
for an unquoted value reading <Buffered Array: f0 ff ff ...>
the length of the latter indicates a size increase of ~300% as would be expected
Fast way of finding lines in one file that are not in another?
Like konsolebox suggested, the posters grep solution
grep -v -f file2 file1
actually works great (fast) if you simply add the -F
option, to treat the patterns as fixed strings instead of regular expressions. I verified this on a pair of ~1000 line file lists I had to compare. With -F
it took 0.031 s (real), while without it took 2.278 s (real), when redirecting grep output to wc -l
.
These tests also included the -x
switch, which are necessary part of the solution in order to ensure totally accuracy in cases where file2 contains lines which match part of, but not all of, one or more lines in file1.
So a solution that does not require the inputs to be sorted, is fast, flexible (case sensitivity, etc) is:
grep -F -x -v -f file2 file1
This doesn't work with all versions of grep, for example it fails in macOS, where a line in file 1 will be shown as not present in file 2, even though it is, if it matches another line that is a substring of it. Alternatively you can install GNU grep on macOS in order to use this solution.
onChange and onSelect in DropDownList
To make a robust form, have it load in a useful state and use script to enhance its behaviour. In the following, the select has been replaced by radio buttons (makes life much easier for the user).
The "yes" option is checked by default and the select is enabled. If the user checks either radio button, the select is enabled or disabled accordingly.
<form onclick="this.mySelect1.disabled = this.becomeMember[1].checked;" ... >
<input type="radio" name="becomeMember" checked>Yes<br>
<input type="radio" name="becomeMember">No<br>
<select id="mySelect1">
<option>Dep1
<option>Dep2
<option>Dep3
<option>Dep4
</select>
...
</form>
.NET NewtonSoft JSON deserialize map to a different property name
If you'd like to use dynamic mapping, and don't want to clutter up your model with attributes, this approach worked for me
Usage:
var settings = new JsonSerializerSettings();
settings.DateFormatString = "YYYY-MM-DD";
settings.ContractResolver = new CustomContractResolver();
this.DataContext = JsonConvert.DeserializeObject<CountResponse>(jsonString, settings);
Logic:
public class CustomContractResolver : DefaultContractResolver
{
private Dictionary<string, string> PropertyMappings { get; set; }
public CustomContractResolver()
{
this.PropertyMappings = new Dictionary<string, string>
{
{"Meta", "meta"},
{"LastUpdated", "last_updated"},
{"Disclaimer", "disclaimer"},
{"License", "license"},
{"CountResults", "results"},
{"Term", "term"},
{"Count", "count"},
};
}
protected override string ResolvePropertyName(string propertyName)
{
string resolvedName = null;
var resolved = this.PropertyMappings.TryGetValue(propertyName, out resolvedName);
return (resolved) ? resolvedName : base.ResolvePropertyName(propertyName);
}
}
How does strcmp() work?
This code is equivalent, shorter, and more readable:
int8_t strcmp (const uint8_t* s1, const uint8_t* s2)
{
while( (*s1!='\0') && (*s1==*s2) ){
s1++;
s2++;
}
return (int8_t)*s1 - (int8_t)*s2;
}
We only need to test for end of s1, because if we reach the end of s2 before end of s1, the loop will terminate (since *s2 != *s1).
The return expression calculates the correct value in every case, provided we are only using 7-bit (pure ASCII) characters. Careful thought is needed to produce correct code for 8-bit characters, because of the risk of integer overflow.
Converting string to title case
I needed a way to deal with all caps words, and I liked Ricky AH's solution, but I took it a step further to implement it as an extension method. This avoids the step of having to create your array of chars then call ToArray on it explicitly every time - so you can just call it on the string, like so:
usage:
string newString = oldString.ToProper();
code:
public static class StringExtensions
{
public static string ToProper(this string s)
{
return new string(s.CharsToTitleCase().ToArray());
}
public static IEnumerable<char> CharsToTitleCase(this string s)
{
bool newWord = true;
foreach (char c in s)
{
if (newWord) { yield return Char.ToUpper(c); newWord = false; }
else yield return Char.ToLower(c);
if (c == ' ') newWord = true;
}
}
}
Using Python String Formatting with Lists
Since I just learned about this cool thing(indexing into lists from within a format string) I'm adding to this old question.
s = '{x[0]} BLAH {x[1]} FOO {x[2]} BAR'
x = ['1', '2', '3']
print (s.format (x=x))
Output:
1 BLAH 2 FOO 3 BAR
However, I still haven't figured out how to do slicing(inside of the format string '"{x[2:4]}".format...
,) and would love to figure it out if anyone has an idea, however I suspect that you simply cannot do that.
How to do a GitHub pull request
To learn how to make a pull request I just followed two separate help pages on Github (linked below as bullet points). The following command line commands are for Part 1. Part 2, the actual pull request, is done entirely on Github's website.
$ git clone https://github.com/tim-peterson/dwolla-php.git
$ cd dwolla-php
$ git remote add upstream https://github.com/Dwolla/dwolla-php.git
$ git fetch upstream
// make your changes to this newly cloned, local repo
$ git add .
$ git commit -m '1st commit to dwolla'
$ git push origin master
How do I fix a "Expected Primary-expression before ')' token" error?
showInventory(player); // I get the error here.
void showInventory(player& obj) { // By Johnny :D
this means that player is an datatype and showInventory expect an referance to an variable of type player.
so the correct code will be
void showInventory(player& obj) { // By Johnny :D
for(int i = 0; i < 20; i++) {
std::cout << "\nINVENTORY:\n" + obj.getItem(i);
i++;
std::cout << "\t\t\t" + obj.getItem(i) + "\n";
i++;
}
}
players myPlayers[10];
std::string toDo() //BY KEATON
{
std::string commands[5] = // This is the valid list of commands.
{"help", "inv"};
std::string ans;
std::cout << "\nWhat do you wish to do?\n>> ";
std::cin >> ans;
if(ans == commands[0]) {
helpMenu();
return NULL;
}
else if(ans == commands[1]) {
showInventory(myPlayers[0]); // or any other index,also is not necessary to have an array
return NULL;
}
}
Nested jQuery.each() - continue/break
Labeled Break
outerloop:
$(sentences).each(function()
{
$(words).each(function(i)
{
break; /* breaks inner loop */
}
$(words).each(function(i)
{
break outerloop; /* breaks outer loop */
}
}
How to pass parameters to a partial view in ASP.NET MVC?
Here is another way to do it if you want to use ViewData:
@Html.Partial("~/PathToYourView.cshtml", null, new ViewDataDictionary { { "VariableName", "some value" } })
And to retrieve the passed in values:
@{
string valuePassedIn = this.ViewData.ContainsKey("VariableName") ? this.ViewData["VariableName"].ToString() : string.Empty;
}
Calculating distance between two geographic locations
Try This Code. here we have two longitude and latitude values and selected_location.distanceTo(near_locations) function returns the distance between those places in meters.
Location selected_location = new Location("locationA");
selected_location.setLatitude(17.372102);
selected_location.setLongitude(78.484196);
Location near_locations = new Location("locationB");
near_locations.setLatitude(17.375775);
near_locations.setLongitude(78.469218);
double distance = selected_location.distanceTo(near_locations);
here "distance" is distance between locationA & locationB (in Meters
)
How to install Hibernate Tools in Eclipse?
Instructions for Eclipse Indigo:
Once installed click on Window -> Show View -> Others. A new window pops up. Click on folder Hibernate and select Hibernate Configurations to setup a DB connection. It is possible to setup a new connection using an existing Hiberbate properties file or creating a JDBC connection.
Once setup your DB connection click on Ping to test everything is correct.
Lastly, click on the Open HQL Editor button (third button on the top Hibernate Configurations menu) to run a HQL query.
sub and gsub function?
That won't work if the string contains more than one match... try this:
echo "/x/y/z/x" | awk '{ gsub("/", "_") ; system( "echo " $0) }'
or better (if the echo
isn't a placeholder for something else):
echo "/x/y/z/x" | awk '{ gsub("/", "_") ; print $0 }'
In your case you want to make a copy of the value before changing it:
echo "/x/y/z/x" | awk '{ c=$0; gsub("/", "_", c) ; system( "echo " $0 " " c )}'
Simple prime number generator in Python
Here is a numpy version of Sieve of Eratosthenes having both okay complexity (lower than sorting an array of length n) and vectorization.
import numpy as np
def generate_primes(n):
is_prime = np.ones(n+1,dtype=bool)
is_prime[0:2] = False
for i in range(int(n**0.5)+1):
if is_prime[i]:
is_prime[i*2::i]=False
return np.where(is_prime)[0]
Timings:
import time
for i in range(2,10):
timer =time.time()
generate_primes(10**i)
print('n = 10^',i,' time =', round(time.time()-timer,6))
>> n = 10^ 2 time = 5.6e-05
>> n = 10^ 3 time = 6.4e-05
>> n = 10^ 4 time = 0.000114
>> n = 10^ 5 time = 0.000593
>> n = 10^ 6 time = 0.00467
>> n = 10^ 7 time = 0.177758
>> n = 10^ 8 time = 1.701312
>> n = 10^ 9 time = 19.322478
How to get the path of running java program
Try this code:
final File f = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
replace 'MyClass
' with your class containing the main method.
Alternatively you can also use
System.getProperty("java.class.path")
Above mentioned System property provides
Path used to find directories and JAR archives containing class files.
Elements of the class path are separated by a platform-specific
character specified in the path.separator property.
LINQ select in C# dictionary
If you are searching by the fieldname1
value, try this:
var r = exitDictionary
.Select(i => i.Value).Cast<Dictionary<string, object>>()
.Where(d => d.ContainsKey("fieldname1"))
.Select(d => d["fieldname1"]).Cast<List<Dictionary<string, string>>>()
.SelectMany(d1 =>
d1
.Where(d => d.ContainsKey("valueTitle"))
.Select(d => d["valueTitle"])
.Where(v => v != null)).ToList();
If you are looking by the type of the value in the subDictionary
(Dictionary<string, object>
explicitly), you may do this:
var r = exitDictionary
.Select(i => i.Value).Cast<Dictionary<string, object>>()
.SelectMany(d=>d.Values)
.OfType<List<Dictionary<string, string>>>()
.SelectMany(d1 =>
d1
.Where(d => d.ContainsKey("valueTitle"))
.Select(d => d["valueTitle"])
.Where(v => v != null)).ToList();
Both alternatives will return:
title1
title2
title3
title1
title2
title3
Build the full path filename in Python
This works fine:
os.path.join(dir_name, base_filename + "." + filename_suffix)
Keep in mind that os.path.join()
exists only because different operating systems use different path separator characters. It smooths over that difference so cross-platform code doesn't have to be cluttered with special cases for each OS. There is no need to do this for file name "extensions" (see footnote) because they are always connected to the rest of the name with a dot character, on every OS.
If using a function anyway makes you feel better (and you like needlessly complicating your code), you can do this:
os.path.join(dir_name, '.'.join((base_filename, filename_suffix)))
If you prefer to keep your code clean, simply include the dot in the suffix:
suffix = '.pdf'
os.path.join(dir_name, base_filename + suffix)
That approach also happens to be compatible with the suffix conventions in pathlib, which was introduced in python 3.4 after this question was asked. New code that doesn't require backward compatibility can do this:
suffix = '.pdf'
pathlib.PurePath(dir_name, base_filename + suffix)
You might prefer the shorter Path
instead of PurePath
if you're only handling paths for the local OS.
Warning: Do not use pathlib's with_suffix()
for this purpose. That method will corrupt base_filename
if it ever contains a dot.
Footnote: Outside of Micorsoft operating systems, there is no such thing as a file name "extension". Its presence on Windows comes from MS-DOS and FAT, which borrowed it from CP/M, which has been dead for decades. That dot-plus-three-letters that many of us are accustomed to seeing is just part of the file name on every other modern OS, where it has no built-in meaning.
How to delete session cookie in Postman?
I think the response of aaron can be enhanced for URL that contains variables:
var sdk = require('postman-collection');
const testURL=pm.environment.values.substitute(pm.request.url, null, false);
const objURL=new sdk.Url(testURL);
console.log("clearing cookies for: "+testURL);
const jar = pm.cookies.jar();
jar.clear(objURL, function (error) {
// error - <Error>
if(error)
console.log("Error clearing cookies: "+error);
});
What is the difference between a Shared Project and a Class Library in Visual Studio 2015?
The difference between a shared project and a class library is that the latter is compiled and the unit of reuse is the assembly.
Whereas with the former, the unit of reuse is the source code, and the shared code is incorporated into each assembly that references the shared project.
This can be useful when you want to create separate assemblies that target specific platforms but still have code that should be shared.
See also here:
The shared project reference shows up under the References node in the Solution Explorer, but the code and assets in the shared project are treated as if they were files linked into the main project.
In previous versions of Visual Studio1, you could share source code between projects by Add -> Existing Item and then choosing to Link. But this was kind of clunky and each separate source file had to be selected individually. With the move to supporting multiple disparate platforms (iOS, Android, etc), they decided to make it easier to share source between projects by adding the concept of Shared Projects.
1 This question and my answer (up until now) suggest that Shared Projects was a new feature in Visual Studio 2015. In fact, they made their debut in Visual Studio 2013 Update 2
How do I change the formatting of numbers on an axis with ggplot?
Another option is to format your axis tick labels with commas is by using the package scales
, and add
scale_y_continuous(name="Fluorescent intensity/arbitrary units", labels = comma)
to your ggplot statement.
If you don't want to load the package, use:
scale_y_continuous(name="Fluorescent intensity/arbitrary units", labels = scales::comma)
How to split long commands over multiple lines in PowerShell
In PowerShell 5 and PowerShell 5 ISE, it is also possible to use just Shift + Enter for multiline editing (instead of standard backticks `
at the end of each line):
PS> &"C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe" # Shift+Enter
>>> -verb:sync # Shift+Enter
>>> -source:contentPath="c:\workspace\xxx\master\Build\_PublishedWebsites\xxx.Web" # Shift+Enter
>>> -dest:contentPath="c:\websites\xxx\wwwroot,computerName=192.168.1.1,username=administrator,password=xxx"
How to delete an element from an array in C#
You can also convert your array to a list and call remove on the list. You can then convert back to your array.
int[] numbers = {1, 3, 4, 9, 2};
var numbersList = numbers.ToList();
numbersList.Remove(4);
Checking if a SQL Server login already exists
As a minor addition to this thread, in general you want to avoid using the views that begin with sys.sys* as Microsoft is only including them for backwards compatibility. For your code, you should probably use sys.server_principals. This is assuming you are using SQL 2005 or greater.
INSERT statement conflicted with the FOREIGN KEY constraint - SQL Server
I ran into this problem when my insert value fields contained tabs and spaces that were not obvious to the naked eye. I had created my value list in Excel, copied, and pasted it to SQL, and run queries to find non-matches on my FK fields.
The match queries did not detect there were tabs and spaces in my FK field, but the INSERT did recognize them and it continued to generate the error.
I tested again by copying the content of the FK field in one record and pasting it into the insert query. When that record also failed, I looked closer at the data and finally detected the tabs/spaces.
Once I cleaned removed tabs/spaces, my issue was resolved. Hope this helps someone!
How to pass arguments within docker-compose?
This can now be done as of docker-compose v2+ as part of the build
object;
docker-compose.yml
version: '2'
services:
my_image_name:
build:
context: . #current dir as build context
args:
var1: 1
var2: c
See the docker compose docs.
In the above example "var1" and "var2" will be sent to the build environment.
Note: any env variables (specified by using the environment
block) which have the same name as args
variable(s) will override that variable.
Load arrayList data into JTable
You probably need to use a TableModel
(Oracle's tutorial here)
How implements your own TableModel
public class FootballClubTableModel extends AbstractTableModel {
private List<FootballClub> clubs ;
private String[] columns ;
public FootBallClubTableModel(List<FootballClub> aClubList){
super();
clubs = aClubList ;
columns = new String[]{"Pos","Team","P", "W", "L", "D", "MP", "GF", "GA", "GD"};
}
// Number of column of your table
public int getColumnCount() {
return columns.length ;
}
// Number of row of your table
public int getRowsCount() {
return clubs.size();
}
// The object to render in a cell
public Object getValueAt(int row, int col) {
FootballClub club = clubs.get(row);
switch(col) {
case 0: return club.getPosition();
// to complete here...
default: return null;
}
}
// Optional, the name of your column
public String getColumnName(int col) {
return columns[col] ;
}
}
You maybe need to override anothers methods of TableModel
, depends on what you want to do, but here is the essential methods to understand and implements :)
Use it like this
List<FootballClub> clubs = getFootballClub();
TableModel model = new FootballClubTableModel(clubs);
JTable table = new JTable(model);
Hope it help !
How to get arguments with flags in Bash
This example uses Bash's built-in getopts
command and is from the Google Shell Style Guide:
a_flag=''
b_flag=''
files=''
verbose='false'
print_usage() {
printf "Usage: ..."
}
while getopts 'abf:v' flag; do
case "${flag}" in
a) a_flag='true' ;;
b) b_flag='true' ;;
f) files="${OPTARG}" ;;
v) verbose='true' ;;
*) print_usage
exit 1 ;;
esac
done
Note: If a character is followed by a colon (e.g. f:
), that option is expected to have an argument.
Example usage: ./script -v -a -b -f filename
Using getopts has several advantages over the accepted answer:
- the while condition is a lot more readable and shows what the accepted options are
- cleaner code; no counting the number of parameters and shifting
- you can join options (e.g.
-a -b -c
? -abc
)
However, a big disadvantage is that it doesn't support long options, only single-character options.
Check if input is number or letter javascript
Use Regular Expression to match for only letters. It's also good to have knowledge about, if you ever need to do something more complicated, like make sure it's a certain count of numbers.
function checkInp()
{
var x=document.forms["myForm"]["age"].value;
var regex=/^[a-zA-Z]+$/;
if (!x.match(regex))
{
alert("Must input string");
return false;
}
}
Even better would be to deny anything but numbers:
function checkInp()
{
var x=document.forms["myForm"]["age"].value;
var regex=/^[0-9]+$/;
if (x.match(regex))
{
alert("Must input numbers");
return false;
}
}
CSS text-align not working
You have to make the UL
inside the div
behave like a block. Try adding
.navigation ul {
display: inline-block;
}
Can I have multiple :before pseudo-elements for the same element?
In CSS2.1, an element can only have at most one of any kind of pseudo-element at any time. (This means an element can have both a :before
and an :after
pseudo-element — it just cannot have more than one of each kind.)
As a result, when you have multiple :before
rules matching the same element, they will all cascade and apply to a single :before
pseudo-element, as with a normal element. In your example, the end result looks like this:
.circle.now:before {
content: "Now";
font-size: 19px;
color: black;
}
As you can see, only the content
declaration that has highest precedence (as mentioned, the one that comes last) will take effect — the rest of the declarations are discarded, as is the case with any other CSS property.
This behavior is described in the Selectors section of CSS2.1:
Pseudo-elements behave just like real elements in CSS with the exceptions described below and elsewhere.
This implies that selectors with pseudo-elements work just like selectors for normal elements. It also means the cascade should work the same way. Strangely, CSS2.1 appears to be the only reference; neither css3-selectors nor css3-cascade mention this at all, and it remains to be seen whether it will be clarified in a future specification.
If an element can match more than one selector with the same pseudo-element, and you want all of them to apply somehow, you will need to create additional CSS rules with combined selectors so that you can specify exactly what the browser should do in those cases. I can't provide a complete example including the content
property here, since it's not clear for instance whether the symbol or the text should come first. But the selector you need for this combined rule is either .circle.now:before
or .now.circle:before
— whichever selector you choose is personal preference as both selectors are equivalent, it's only the value of the content
property that you will need to define yourself.
If you still need a concrete example, see my answer to this similar question.
The legacy css3-content specification contains a section on inserting multiple ::before
and ::after
pseudo-elements using a notation that's compatible with the CSS2.1 cascade, but note that that particular document is obsolete — it hasn't been updated since 2003, and no one has implemented that feature in the past decade. The good news is that the abandoned document is actively undergoing a rewrite in the guise of css-content-3 and css-pseudo-4. The bad news is that the multiple pseudo-elements feature is nowhere to be found in either specification, presumably owing, again, to lack of implementer interest.
How do I get the current date in JavaScript?
If by "current date" you are thinking about "today", then this trick may work for you:
> new Date(3600000*Math.floor(Date.now()/3600000))
2020-05-07T07:00:00.000Z
This way you are getting today Date instance with time 0:00:00.
The principle of operation is very simple: we take the current timestamp and divide it for 1 day expressed in milliseconds. We will get a fraction. By using Math.floor, we get rid of the fraction, so we get an integer. Now if we multiply it back by one day (again - in milliseconds), we get a date timestamp with the time exactly at the beginning of the day.
> now = Date.now()
1588837459929
> daysInMs = now/3600000
441343.73886916664
> justDays = Math.floor(daysInMs)
441343
> today = justDays*3600000
1588834800000
> new Date(today)
2020-05-07T07:00:00.000Z
Clean and simple.
How do I update a GitHub forked repository?
Android Studio now has learned to work with GitHub fork repositories (you don't even have to add "upstream" remote repository by console command).
Open menu VCS ? Git
And pay attention to the two last popup menu items:
Rebase my GitHub fork
Create Pull Request
Try them. I use the first one to synchronize my local repository. Anyway the branches from the parent remote repository ("upstream") will be accessible in Android Studio after you click "Rebase my GitHub fork", and you will be able to operate with them easily.
(I use Android Studio 3.0 with "Git integration" and "GitHub" plugins.)
What do Push and Pop mean for Stacks?
A Stack is a LIFO (Last In First Out) data structure. The push and pop operations are simple. Push puts something on the stack, pop takes something off. You put onto the top, and take off the top, to preserve the LIFO order.
edit -- corrected from FIFO, to LIFO. Facepalm!
to illustrate, you start with a blank stack
|
then you push 'x'
| 'x'
then you push 'y'
| 'x' 'y'
then you pop
| 'x'
How to decrypt a password from SQL server?
The SQL Server password hashing algorithm:
hashBytes = 0x0100 | fourByteSalt | SHA1(utf16EncodedPassword+fourByteSalt)
For example, to hash the password "correct horse battery staple". First we generate some random salt:
fourByteSalt = 0x9A664D79;
And then hash the password (encoded in UTF-16) along with the salt:
SHA1("correct horse battery staple" + 0x9A66D79);
=SHA1(0x63006F007200720065006300740020006200610074007400650072007900200068006F00720073006500200073007400610070006C006500 0x9A66D79)
=0x6EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3
The value stored in the syslogins
table is the concatenation of:
[header] + [salt] + [hash]
0x0100
9A664D79
6EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3
Which you can see in SQL Server:
SELECT
name, CAST(password AS varbinary(max)) AS PasswordHash
FROM sys.syslogins
WHERE name = 'sa'
name PasswordHash
==== ======================================================
sa 0x01009A664D796EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3
- Version header:
0100
- Salt (four bytes):
9A664D79
- Hash:
6EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3
(SHA-1 is 20 bytes; 160 bits)
Validation
You validate a password by performing the same hash:
- grab the salt from the saved
PasswordHash
: 0x9A664D79
and perform the hash again:
SHA1("correct horse battery staple" + 0x9A66D79);
which will come out to the same hash, and you know the password is correct.
What once was good, but now is weak
The hashing algorithm introduced with SQL Server 7, in 1999, was good for 1999.
- It is good that the password hash salted.
- It is good to append the salt to the password, rather than prepend it.
But today it is out-dated. It only runs the hash once, where it should run it a few thousand times, in order to thwart brute-force attacks.
In fact, Microsoft's Baseline Security Analyzer will, as part of it's checks, attempt to bruteforce passwords. If it guesses any, it reports the passwords as weak. And it does get some.
Brute Forcing
To help you test some passwords:
DECLARE @hash varbinary(max)
SET @hash = 0x01009A664D796EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3
--Header: 0x0100
--Salt: 0x9A664D79
--Hash: 0x6EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3
DECLARE @password nvarchar(max)
SET @password = 'password'
SELECT
@password AS CandidatePassword,
@hash AS PasswordHash,
--Header
0x0100
+
--Salt
CONVERT(VARBINARY(4), SUBSTRING(CONVERT(NVARCHAR(MAX), @hash), 2, 2))
+
--SHA1 of Password + Salt
HASHBYTES('SHA1', @password + SUBSTRING(CONVERT(NVARCHAR(MAX), @hash), 2, 2))
SQL Server 2012 and SHA-512
Starting with SQL Server 2012, Microsoft switched to using SHA-2 512-bit:
hashBytes = 0x0200 | fourByteSalt | SHA512(utf16EncodedPassword+fourByteSalt)
Changing the version prefix to 0x0200
:
SELECT
name, CAST(password AS varbinary(max)) AS PasswordHash
FROM sys.syslogins
name PasswordHash
---- --------------------------------
xkcd 0x02006A80BA229556EB280AA7818FAF63A0DA8D6B7B120C6760F0EB0CB5BB320A961B04BD0836 0C0E8CC4C326220501147D6A9ABD2A006B33DEC99FCF1A822393FC66226B7D38
- Version:
0200
(SHA-2 256-bit)
- Salt:
6A80BA22
- Hash (64 bytes):
9556EB280AA7818FAF63A0DA8D6B7B120C6760F0EB0CB5BB320A961B04BD0836 0C0E8CC4C326220501147D6A9ABD2A006B33DEC99FCF1A822393FC66226B7D38
This means we hash the UTF-16 encoded password, with the salt suffix:
- SHA512("correct horse battery staple"+
6A80BA22
)
- SHA512(
63006f0072007200650063007400200068006f0072007300650020006200610074007400650072007900200073007400610070006c006500
+ 6A80BA22
)
9556EB280AA7818FAF63A0DA8D6B7B120C6760F0EB0CB5BB320A961B04BD0836 0C0E8CC4C326220501147D6A9ABD2A006B33DEC99FCF1A822393FC66226B7D38
Get parent of current directory from Python script
import os def parent_directory(): # Create a relative path to the
parent # of the current working directory
path = os.getcwd()
parent = os.path.dirname(path)
relative_parent = os.path.join(path, parent)
# Return the absolute path of the parent directory
return relative_parent
print(parent_directory())
Is there an easy way to add a border to the top and bottom of an Android View?
In android 2.2 you could do the following.
Create an xml drawable such as /res/drawable/textlines.xml and assign this as a TextView's background property.
<TextView
android:text="My text with lines above and below"
android:background="@drawable/textlines"
/>
/res/drawable/textlines.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape
android:shape="rectangle">
<stroke android:width="1dp" android:color="#FF000000" />
<solid android:color="#FFDDDDDD" />
</shape>
</item>
<item android:top="1dp" android:bottom="1dp">
<shape
android:shape="rectangle">
<stroke android:width="1dp" android:color="#FFDDDDDD" />
<solid android:color="#00000000" />
</shape>
</item>
</layer-list>
The down side to this is that you have to specify an opaque background colour, as transparencies won't work. (At least i thought they did but i was mistaken). In the above example you can see that the solid colour of the first shape #FFdddddd is copied in the 2nd shapes stroke colour.
How do I enter a multi-line comment in Perl?
POD is the official way to do multi line comments in Perl,
From faq.perl.org[perlfaq7]
The quick-and-dirty way to comment out more than one line of Perl is
to surround those lines with Pod directives. You have to put these
directives at the beginning of the line and somewhere where Perl
expects a new statement (so not in the middle of statements like the #
comments). You end the comment with =cut
, ending the Pod section:
=pod
my $object = NotGonnaHappen->new();
ignored_sub();
$wont_be_assigned = 37;
=cut
The quick-and-dirty method only works well when you don't plan to
leave the commented code in the source. If a Pod parser comes along,
your multiline comment is going to show up in the Pod translation. A
better way hides it from Pod parsers as well.
The =begin
directive can mark a section for a particular purpose. If
the Pod parser doesn't want to handle it, it just ignores it. Label
the comments with comment
. End the comment using =end
with the
same label. You still need the =cut
to go back to Perl code from the
Pod comment:
=begin comment
my $object = NotGonnaHappen->new();
ignored_sub();
$wont_be_assigned = 37;
=end comment
=cut
Pandas aggregate count distinct
Just adding to the answers already given, the solution using the string "nunique"
seems much faster, tested here on ~21M rows dataframe, then grouped to ~2M
%time _=g.agg({"id": lambda x: x.nunique()})
CPU times: user 3min 3s, sys: 2.94 s, total: 3min 6s
Wall time: 3min 20s
%time _=g.agg({"id": pd.Series.nunique})
CPU times: user 3min 2s, sys: 2.44 s, total: 3min 4s
Wall time: 3min 18s
%time _=g.agg({"id": "nunique"})
CPU times: user 14 s, sys: 4.76 s, total: 18.8 s
Wall time: 24.4 s
How to escape indicator characters (i.e. : or - ) in YAML
If you're using @ConfigurationProperties
with Spring Boot 2 to inject maps with keys that contain colons then you need an additional level of escaping using square brackets inside the quotes because spring only allows alphanumeric and '-' characters, stripping out the rest. Your new key would look like this:
"[8.11.32.120:8000]": GoogleMapsKeyforThisDomain
See this github issue for reference.
Tesseract running error
I'm using windows OS, I tried all solutions above and none of them work.
Finally, I install Tesseract-OCR on D drive(Where I run my python script from) instead of C drive and it works.
So, if you are using windows, run your python script in the same drive as your Tesseract-OCR.
TypeScript: casting HTMLElement
TypeScript uses '<>' to surround casts, so the above becomes:
var script = <HTMLScriptElement>document.getElementsByName("script")[0];
However, unfortunately you cannot do:
var script = (<HTMLScriptElement[]>document.getElementsByName(id))[0];
You get the error
Cannot convert 'NodeList' to 'HTMLScriptElement[]'
But you can do :
(<HTMLScriptElement[]><any>document.getElementsByName(id))[0];
Read HttpContent in WebApi controller
By design the body content in ASP.NET Web API is treated as forward-only stream that can be read only once.
The first read in your case is being done when Web API is binding your model, after that the Request.Content
will not return anything.
You can remove the contact
from your action parameters, get the content and deserialize it manually into object (for example with Json.NET):
[HttpPut]
public HttpResponseMessage Put(int accountId)
{
HttpContent requestContent = Request.Content;
string jsonContent = requestContent.ReadAsStringAsync().Result;
CONTACT contact = JsonConvert.DeserializeObject<CONTACT>(jsonContent);
...
}
That should do the trick (assuming that accountId
is URL parameter so it will not be treated as content read).
LD_LIBRARY_PATH vs LIBRARY_PATH
LIBRARY_PATH
is used by gcc before compilation to search directories containing static and shared libraries that need to be linked to your program.
LD_LIBRARY_PATH
is used by your program to search directories containing shared libraries after it has been successfully compiled and linked.
EDIT:
As pointed below, your libraries can be static or shared. If it is static then the code is copied over into your program and you don't need to search for the library after your program is compiled and linked. If your library is shared then it needs to be dynamically linked to your program and that's when LD_LIBRARY_PATH
comes into play.
Swift - How to convert String to Double
You can use StringEx. It extends String
with string-to-number conversions including toDouble()
.
extension String {
func toDouble() -> Double?
}
It verifies the string and fails if it can't be converted to double.
Example:
import StringEx
let str = "123.45678"
if let num = str.toDouble() {
println("Number: \(num)")
} else {
println("Invalid string")
}
How do I download a file with Angular2 or greater
I got a solution for downloading from angular 2 without getting corrupt,
using spring mvc and angular 2
1st- my return type is :-ResponseEntity from java end. Here I am sending byte[] array has return type from the controller.
2nd- to include the filesaver in your workspace-in the index page as:
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2014-11-29/FileSaver.min.js"></script>
3rd- at component ts write this code:
import {ResponseContentType} from '@angular.core';
let headers = new Headers({ 'Content-Type': 'application/json', 'MyApp-Application' : 'AppName', 'Accept': 'application/pdf' });
let options = new RequestOptions({ headers: headers, responseType: ResponseContentType.Blob });
this.http
.post('/project/test/export',
somevalue,options)
.subscribe(data => {
var mediaType = 'application/vnd.ms-excel';
let blob: Blob = data.blob();
window['saveAs'](blob, 'sample.xls');
});
This will give you xls file format. If you want other formats change the mediatype and file name with right extension.
How to clear an EditText on click?
For me the easiest way...
Create an public EditText, for Example "myEditText1"
public EditText myEditText1;
Then, connect it with the EditText which should get cleared
myEditText1 = (EditText) findViewById(R.id.numberfield);
After that, create an void which reacts to an click to the EditText an let it clear the Text inside it when its Focused, for Example
@OnClick(R.id.numberfield)
void textGone(){
if (myEditText1.isFocused()){
myEditText1.setText("");
}
}
Hope i could help you, Have a nice Day everyone
Unbound classpath container in Eclipse
Click on the error message displaying "Unbound classpath container: 'JRE System Library[jdk1.5.0_08]", left click anyd choose quick fix. Under quick, list of possible options will get displated. Choose replace library. Choose the library you installed. Your good to go.
Defining array with multiple types in TypeScript
Defining array with multiple types in TypeScript
Use a union type (string|number)[]
demo:
const foo: (string|number)[] = [ 1, "message" ];
I have an array of the form: [ 1, "message" ].
If you are sure that there are always only two elements [number, string]
then you can declare it as a tuple:
const foo: [number, string] = [ 1, "message" ];
How do I run a docker instance from a DockerFile?
Straightforward and easy solution is:
docker build .
=> ....
=> Successfully built a3e628814c67
docker run -p 3000:3000 a3e628814c67
3000
- can be any port
a3e628814c68
- hash result given by success build command
NOTE: you should be within directory that contains Dockerfile.
How can I get a Bootstrap column to span multiple rows?
<div class="row">
<div class="col-4 alert alert-primary">
1
</div>
<div class="col-8">
<div class="row">
<div class="col-6 alert alert-primary">
2
</div>
<div class="col-6 alert alert-primary">
3
</div>
<div class="col-6 alert alert-primary">
4
</div>
<div class="col-6 alert alert-primary">
5
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-4 alert alert-primary">
6
</div>
<div class="col-4 alert alert-primary">
7
</div>
<div class="col-4 alert alert-primary">
8
</div>
</div>
Publish to IIS, setting Environment Variable
What you need to know in one place:
- For environment variables to override any config settings, they must be prefixed with
ASPNETCORE_
.
- If you want to match child nodes in your JSON config, use
:
as a separater. If the platform doesn't allow colons in environment variable keys, use __
instead.
- You want your settings to end up in
ApplicationHost.config
. Using the IIS Configuration Editor will cause your inputs to be written to the application's Web.config
-- and will be overwritten with the next deployment!
For modifying ApplicationHost.config
, you want to use appcmd.exe
to make sure your modifications are consistent. Example: %systemroot%\system32\inetsrv\appcmd.exe set config "Default Web Site/MyVirtualDir" -section:system.webServer/aspNetCore /+"environmentVariables.[name='ASPNETCORE_AWS:Region',value='eu-central-1']" /commit:site
Characters that are not URL-safe can be escaped as Unicode, like %u007b
for left curly bracket.
- To list your current settings (combined with values from Web.config):
%systemroot%\system32\inetsrv\appcmd.exe list config "Default Web Site/MyVirtualDir" -section:system.webServer/aspNetCore
- If you run the command to set a configuration key multiple times for the same key, it will be added multiple times! To remove an existing value, use something like
%systemroot%\system32\inetsrv\appcmd.exe set config "Default Web Site/MyVirtualDir" -section:system.webServer/aspNetCore /-"environmentVariables.[name='ASPNETCORE_MyKey',value='value-to-be-removed']" /commit:site
.
How to name Dockerfiles
Dockerfile
is good if you only have one docker file (per-directory). You can use whatever standard you want if you need multiple docker files in the same directory -
if you have a good reason. In a recent project there were AWS docker files and local dev environment files because the environments differed enough:
Dockerfile
Dockerfile.aws
How do I fetch multiple columns for use in a cursor loop?
Here is slightly modified version. Changes are noted as code commentary.
BEGIN TRANSACTION
declare @cnt int
declare @test nvarchar(128)
-- variable to hold table name
declare @tableName nvarchar(255)
declare @cmd nvarchar(500)
-- local means the cursor name is private to this code
-- fast_forward enables some speed optimizations
declare Tests cursor local fast_forward for
SELECT COLUMN_NAME, TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE 'pct%'
AND TABLE_NAME LIKE 'TestData%'
open Tests
-- Instead of fetching twice, I rather set up no-exit loop
while 1 = 1
BEGIN
-- And then fetch
fetch next from Tests into @test, @tableName
-- And then, if no row is fetched, exit the loop
if @@fetch_status <> 0
begin
break
end
-- Quotename is needed if you ever use special characters
-- in table/column names. Spaces, reserved words etc.
-- Other changes add apostrophes at right places.
set @cmd = N'exec sp_rename '''
+ quotename(@tableName)
+ '.'
+ quotename(@test)
+ N''','''
+ RIGHT(@test,LEN(@test)-3)
+ '_Pct'''
+ N', ''column'''
print @cmd
EXEC sp_executeSQL @cmd
END
close Tests
deallocate Tests
ROLLBACK TRANSACTION
--COMMIT TRANSACTION
Trim characters in Java
This does what you want:
public static void main (String[] args) {
String a = "\\joe\\jill\\";
String b = a.replaceAll("\\\\$", "").replaceAll("^\\\\", "");
System.out.println(b);
}
The $
is used to remove the sequence in the end of string. The ^
is used to remove in the beggining.
As an alternative, you can use the syntax:
String b = a.replaceAll("\\\\$|^\\\\", "");
The |
means "or".
In case you want to trim other chars, just adapt the regex:
String b = a.replaceAll("y$|^x", ""); // will remove all the y from the end and x from the beggining
How unique is UUID?
Very safe:
the annual risk of a given person being hit by a meteorite is
estimated to be one chance in 17 billion, which means the
probability is about 0.00000000006 (6 × 10-11), equivalent to the odds
of creating a few tens of trillions of UUIDs in a year and having one
duplicate. In other words, only after generating 1 billion UUIDs every
second for the next 100 years, the probability of creating just one
duplicate would be about 50%.
Caveat:
However, these probabilities only hold when the UUIDs are generated
using sufficient entropy. Otherwise, the probability of duplicates
could be significantly higher, since the statistical dispersion might
be lower. Where unique identifiers are required for distributed
applications, so that UUIDs do not clash even when data from many
devices is merged, the randomness of the seeds and generators used on
every device must be reliable for the life of the application. Where
this is not feasible, RFC4122 recommends using a namespace variant
instead.
Source: The Random UUID probability of duplicates section of the Wikipedia article on Universally unique identifiers (link leads to a revision from December 2016 before editing reworked the section).
Also see the current section on the same subject on the same Universally unique identifier article, Collisions.
How to display databases in Oracle 11g using SQL*Plus
I am not clearly about it but typically one server has one database (with many users), if you create many databases mean that you create many instances, listeners, ... as well. So you can check your LISTENER
to identify it.
In my testing I created 2 databases (dbtest
and dbtest_1
) so when I check my LISTENER status it appeared like this:
lsnrctl status
....
STATUS of the LISTENER
.....
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=10.10.20.20)(PORT=1521)))
Services Summary...
Service "dbtest" has 1 instance(s).
Instance "dbtest", status READY, has 1 handler(s) for this service...
Service "dbtest1XDB" has 1 instance(s).
Instance "dbtest1", status READY, has 1 handler(s) for this service...
Service "dbtest_1" has 1 instance(s).
Instance "dbtest1", status READY, has 1 handler(s) for this service... The command completed successfully
How to iterate over a string in C?
One common idiom is:
char* c = source;
while (*c) putchar(*c++);
A few notes:
- In C, strings are null-terminated. You iterate while the read character is not the null character.
*c++
increments c
and returns the dereferenced old value of c
.
printf("%s")
prints a null-terminated string, not a char. This is the cause of your access violation.
Google Maps JS API v3 - Simple Multiple Marker Example
var arr = new Array();
function initialize() {
var i;
var Locations = [
{
lat:48.856614,
lon:2.3522219000000177,
address:'Paris',
gval:'25.5',
aType:'Non-Commodity',
title:'Paris',
descr:'Paris'
},
{
lat: 55.7512419,
lon: 37.6184217,
address:'Moscow',
gval:'11.5',
aType:'Non-Commodity',
title:'Moscow',
descr:'Moscow Airport'
},
{
lat:-9.481553000000002,
lon:147.190242,
address:'Port Moresby',
gval:'1',
aType:'Oil',
title:'Papua New Guinea',
descr:'Papua New Guinea 123123123'
},
{
lat:20.5200,
lon:77.7500,
address:'Indore',
gval:'1',
aType:'Oil',
title:'Indore, India',
descr:'Airport India'
}
];
var myOptions = {
zoom: 2,
center: new google.maps.LatLng(51.9000,8.4731),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), myOptions);
var infowindow = new google.maps.InfoWindow({
content: ''
});
for (i = 0; i < Locations.length; i++) {
size=15;
var img=new google.maps.MarkerImage('marker.png',
new google.maps.Size(size, size),
new google.maps.Point(0,0),
new google.maps.Point(size/2, size/2)
);
var marker = new google.maps.Marker({
map: map,
title: Locations[i].title,
position: new google.maps.LatLng(Locations[i].lat, Locations[i].lon),
icon: img
});
bindInfoWindow(marker, map, infowindow, "<p>" + Locations[i].descr + "</p>",Locations[i].title);
}
}
function bindInfoWindow(marker, map, infowindow, html, Ltitle) {
google.maps.event.addListener(marker, 'mouseover', function() {
infowindow.setContent(html);
infowindow.open(map, marker);
});
google.maps.event.addListener(marker, 'mouseout', function() {
infowindow.close();
});
}
Full working example. You can just copy, paste and use.
The I/O operation has been aborted because of either a thread exit or an application request
995 is an error reported by the IO Completion Port. The error comes since you try to continue read from the socket when it has most likely been closed.
Receiving 0 bytes from EndRecieve
means that the socket has been closed, as does most exceptions that EndRecieve
will throw.
You need to start dealing with those situations.
Never ever ignore exceptions, they are thrown for a reason.
Update
There is nothing that says that the server does anything wrong. A connection can be lost for a lot of reasons such as idle connection being closed by a switch/router/firewall, shaky network, bad cables etc.
What I'm saying is that you MUST handle disconnections. The proper way of doing so is to dispose the socket and try to connect a new one at certain intervals.
As for the receive callback a more proper way of handling it is something like this (semi pseudo code):
public void OnDataReceived(IAsyncResult asyn)
{
BLCommonFunctions.WriteLogger(0, "In :- OnDataReceived", ref swReceivedLogWriter, strLogPath, 0);
try
{
SocketPacket client = (SocketPacket)asyn.AsyncState;
int bytesReceived = client.thisSocket.EndReceive(asyn); //Here error is coming
if (bytesReceived == 0)
{
HandleDisconnect(client);
return;
}
}
catch (Exception err)
{
HandleDisconnect(client);
}
try
{
string strHEX = BLCommonFunctions.ByteArrToHex(theSockId.dataBuffer);
//do your handling here
}
catch (Exception err)
{
// Your logic threw an exception. handle it accordinhly
}
try
{
client.thisSocket.BeginRecieve(.. all parameters ..);
}
catch (Exception err)
{
HandleDisconnect(client);
}
}
the reason to why I'm using three catch blocks is simply because the logic for the middle one is different from the other two. Exceptions from BeginReceive/EndReceive usually indicates socket disconnection while exceptions from your logic should not stop the socket receiving.
Split by comma and strip whitespace in Python
re
(as in regular expressions) allows splitting on multiple characters at once:
$ string = "blah, lots , of , spaces, here "
$ re.split(', ',string)
['blah', 'lots ', ' of ', ' spaces', 'here ']
This doesn't work well for your example string, but works nicely for a comma-space separated list. For your example string, you can combine the re.split power to split on regex patterns to get a "split-on-this-or-that" effect.
$ re.split('[, ]',string)
['blah',
'',
'lots',
'',
'',
'',
'',
'of',
'',
'',
'',
'spaces',
'',
'here',
'']
Unfortunately, that's ugly, but a filter
will do the trick:
$ filter(None, re.split('[, ]',string))
['blah', 'lots', 'of', 'spaces', 'here']
Voila!
Delete column from pandas DataFrame
As you've guessed, the right syntax is
del df['column_name']
It's difficult to make del df.column_name
work simply as the result of syntactic limitations in Python. del df[name]
gets translated to df.__delitem__(name)
under the covers by Python.
Change input value onclick button - pure javascript or jQuery
My Attempt ( JsFiddle)
Javascript
$(document).ready(function () {
$('#buttons input[type=button]').on('click', function () {
var qty = $(this).data('quantity');
var price = $('#totalPrice').text();
$('#count').val(price * qty);
});
});
Html
Product price:$500
<br>Total price: $<span id='totalPrice'>500</span>
<br>
<div id='buttons'>
<input id='qty2' type="button" data-quantity='2' value="2
Qty">
<input id='qty2' type="button" class="mnozstvi_sleva" data-quantity='4' value="4
Qty">
</div>
<br>Total
<input type="text" id="count" value="1">
C# - How to get Program Files (x86) on Windows 64 bit
C# Code:
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)
Output:
C:\Program Files (x86)
Note:
We need to tell the compiler to not prefer a particular build platform.
Go to Visual Studio > Project Properties > Build > Uncheck "Prefer 32 bit"
Reason:
By default for most .NET Projects is "Any CPU 32-bit preferred"
When you uncheck 32 bit assembly will:
JIT to 32-bit code on 32 bit process
JIT to 32-bit code on 64 bit process
How to check whether a pandas DataFrame is empty?
To see if a dataframe is empty, I argue that one should test for the length of a dataframe's columns index:
if len(df.columns) == 0: 1
Reason:
According to the Pandas Reference API, there is a distinction between:
- an empty dataframe with 0 rows and 0 columns
- an empty dataframe with rows containing
NaN
hence at least 1 column
Arguably, they are not the same. The other answers are imprecise in that df.empty
, len(df)
, or len(df.index)
make no distinction and return index is 0 and empty is True in both cases.
Examples
Example 1: An empty dataframe with 0 rows and 0 columns
In [1]: import pandas as pd
df1 = pd.DataFrame()
df1
Out[1]: Empty DataFrame
Columns: []
Index: []
In [2]: len(df1.index) # or len(df1)
Out[2]: 0
In [3]: df1.empty
Out[3]: True
Example 2: A dataframe which is emptied to 0 rows but still retains n
columns
In [4]: df2 = pd.DataFrame({'AA' : [1, 2, 3], 'BB' : [11, 22, 33]})
df2
Out[4]: AA BB
0 1 11
1 2 22
2 3 33
In [5]: df2 = df2[df2['AA'] == 5]
df2
Out[5]: Empty DataFrame
Columns: [AA, BB]
Index: []
In [6]: len(df2.index) # or len(df2)
Out[6]: 0
In [7]: df2.empty
Out[7]: True
Now, building on the previous examples, in which the index is 0 and empty is True. When reading the length of the columns index for the first loaded dataframe df1, it returns 0 columns to prove that it is indeed empty.
In [8]: len(df1.columns)
Out[8]: 0
In [9]: len(df2.columns)
Out[9]: 2
Critically, while the second dataframe df2 contains no data, it is not completely empty because it returns the amount of empty columns that persist.
Why it matters
Let's add a new column to these dataframes to understand the implications:
# As expected, the empty column displays 1 series
In [10]: df1['CC'] = [111, 222, 333]
df1
Out[10]: CC
0 111
1 222
2 333
In [11]: len(df1.columns)
Out[11]: 1
# Note the persisting series with rows containing `NaN` values in df2
In [12]: df2['CC'] = [111, 222, 333]
df2
Out[12]: AA BB CC
0 NaN NaN 111
1 NaN NaN 222
2 NaN NaN 333
In [13]: len(df2.columns)
Out[13]: 3
It is evident that the original columns in df2 have re-surfaced. Therefore, it is prudent to instead read the length of the columns index with len(pandas.core.frame.DataFrame.columns)
to see if a dataframe is empty.
Practical solution
# New dataframe df
In [1]: df = pd.DataFrame({'AA' : [1, 2, 3], 'BB' : [11, 22, 33]})
df
Out[1]: AA BB
0 1 11
1 2 22
2 3 33
# This data manipulation approach results in an empty df
# because of a subset of values that are not available (`NaN`)
In [2]: df = df[df['AA'] == 5]
df
Out[2]: Empty DataFrame
Columns: [AA, BB]
Index: []
# NOTE: the df is empty, BUT the columns are persistent
In [3]: len(df.columns)
Out[3]: 2
# And accordingly, the other answers on this page
In [4]: len(df.index) # or len(df)
Out[4]: 0
In [5]: df.empty
Out[5]: True
# SOLUTION: conditionally check for empty columns
In [6]: if len(df.columns) != 0: # <--- here
# Do something, e.g.
# drop any columns containing rows with `NaN`
# to make the df really empty
df = df.dropna(how='all', axis=1)
df
Out[6]: Empty DataFrame
Columns: []
Index: []
# Testing shows it is indeed empty now
In [7]: len(df.columns)
Out[7]: 0
Adding a new data series works as expected without the re-surfacing of empty columns (factually, without any series that were containing rows with only NaN
):
In [8]: df['CC'] = [111, 222, 333]
df
Out[8]: CC
0 111
1 222
2 333
In [9]: len(df.columns)
Out[9]: 1
Print raw string from variable? (not getting the answers)
Get rid of the escape characters before storing or manipulating the raw string:
You could change any backslashes of the path '\' to forward slashes '/' before storing them in a variable. The forward slashes don't need to be escaped:
>>> mypath = os.getcwd().replace('\\','/')
>>> os.path.exists(mypath)
True
>>>
adb devices command not working
HTC One m7 running fresh Cyanogenmod 11.
Phone is connected USB and tethering my data connection.
Then I get this surprise:
cinder@ultrabook:~/temp/htc_m7/2015-11-11$ adb shell
error: insufficient permissions for device
cinder@ultrabook:~/temp/htc_m7/2015-11-11$ adb devices
List of devices attached
???????????? no permissions
SOLUTION: Turn tethering OFF on phone.
cinder@ultrabook:~/temp/htc_m7/2015-11-11$ adb devices
List of devices attached
HT36AW908858 device
Using .Select and .Where in a single LINQ statement
Did you add the Select()
after the Where()
or before?
You should add it after, because of the concurrency logic:
1 Take the entire table
2 Filter it accordingly
3 Select only the ID's
4 Make them distinct.
If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.
Update: For clarity, this order of operators should work:
db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();
Probably want to add a .toList()
at the end but that's optional :)
Jquery array.push() not working
another workaround:
var myarray = [];
$("#test").click(function() {
myarray[index]=$("#drop").val();
alert(myarray);
});
i wanted to add all checked checkbox to array. so example, if .each is used:
var vpp = [];
var incr=0;
$('.prsn').each(function(idx) {
if (this.checked) {
var p=$('.pp').eq(idx).val();
vpp[incr]=(p);
incr++;
}
});
//do what ever with vpp array;
Maven: How do I activate a profile from command line?
Just remove activation section, I don't know why -Pdev1 doesn't override default false activation. But if you omit this:
<activation>
<activeByDefault>false</activeByDefault>
</activation>
then your profile will be activated only after explicit declaration as -Pdev1
Tools to search for strings inside files without indexing
If you don't want to install Non-Microsoft tools, please download STRINGS.EXE from Microsoft Sysinternals and make a procedure like this one:
@echo off
if '%1' == '' goto NOPARAM
if '%2' == '' goto NOPARAM
if not exist %1 goto NOFOLDER
echo ------------------------------------------
echo - %1 : folder
echo - %2 : string to be searched in the folder
echo - PLEASE WAIT FOR THE RESULTS ...
strings -s %1\* | findstr /i %2 > grep.txt
notepad.exe grep.txt
goto END
:NOPARAM rem - input command not correct
echo ====================================
echo Usage of GREP.CMD:
echo Grep "SearchFolder" SearchString
echo Please specify all parameters
echo ====================================
goto END
:NOFOLDER
echo Folder %1 does not exist
goto END
:END rem - exit