An unhandled exception of type 'System.TypeInitializationException' occurred in EntityFramework.dll
Check which version of Entity Framework reference you have in your References and make sure that it matches with your configSections
node in Web.config
file. In my case it was pointing to version 5.0.0.0 in my configSections and my reference was 6.0.0.0. I just changed it and it worked...
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
Best way to deploy Visual Studio application that can run without installing
It is possible and is deceptively easy:
- "Publish" the application (to, say, some folder on drive C), either from menu Build or from the project's properties ? Publish. This will create an installer for a ClickOnce application.
- But instead of using the produced installer, find the produced files (the EXE file and the .config, .manifest, and .application files, along with any DLL files, etc.) - they are all in the same folder and typically in the
bin\Debug
folder below the project file (.csproj).
- Zip that folder (leave out any *.vhost.* files and the
app.publish
folder (they are not needed), and the .pdb files unless you foresee debugging directly on your user's system (for example, by remote control)), and provide it to the users.
An added advantage is that, as a ClickOnce application, it does not require administrative privileges to run (if your application follows the normal guidelines for which folders to use for application data, etc.).
As for .NET, you can check for the minimum required version of .NET being installed (or at all) in the application (most users will already have it installed) and present a dialog with a link to the download page on the Microsoft website (or point to one of your pages that could redirect to the Microsoft page - this makes it more robust if the Microsoft URL change). As it is a small utility, you could target .NET 2.0 to reduce the probability of a user to have to install .NET.
It works. We use this method during development and test to avoid having to constantly uninstall and install the application and still being quite close to how the final application will run.
How do I make calls to a REST API using C#?
My suggestion would be to use RestSharp. You can make calls to REST services and have them cast into POCO objects with very little boilerplate code to actually have to parse through the response. This will not solve your particular error, but it answers your overall question of how to make calls to REST services. Having to change your code to use it should pay off in the ease of use and robustness moving forward. That is just my two cents though.
Example:
namespace RestSharpThingy
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using RestSharp;
public static class Program
{
public static void Main()
{
Uri baseUrl = new Uri("https://httpbin.org/");
IRestClient client = new RestClient(baseUrl);
IRestRequest request = new RestRequest("get", Method.GET) { Credentials = new NetworkCredential("testUser", "P455w0rd") };
request.AddHeader("Authorization", "Bearer qaPmk9Vw8o7r7UOiX-3b-8Z_6r3w0Iu2pecwJ3x7CngjPp2fN3c61Q_5VU3y0rc-vPpkTKuaOI2eRs3bMyA5ucKKzY1thMFoM0wjnReEYeMGyq3JfZ-OIko1if3NmIj79ZSpNotLL2734ts2jGBjw8-uUgKet7jQAaq-qf5aIDwzUo0bnGosEj_UkFxiJKXPPlF2L4iNJSlBqRYrhw08RK1SzB4tf18Airb80WVy1Kewx2NGq5zCC-SCzvJW-mlOtjIDBAQ5intqaRkwRaSyjJ_MagxJF_CLc4BNUYC3hC2ejQDoTE6HYMWMcg0mbyWghMFpOw3gqyfAGjr6LPJcIly__aJ5__iyt-BTkOnMpDAZLTjzx4qDHMPWeND-TlzKWXjVb5yMv5Q6Jg6UmETWbuxyTdvGTJFzanUg1HWzPr7gSs6GLEv9VDTMiC8a5sNcGyLcHBIJo8mErrZrIssHvbT8ZUPWtyJaujKvdgazqsrad9CO3iRsZWQJ3lpvdQwucCsyjoRVoj_mXYhz3JK3wfOjLff16Gy1NLbj4gmOhBBRb8rJnUXnP7rBHs00FAk59BIpKLIPIyMgYBApDCut8V55AgXtGs4MgFFiJKbuaKxq8cdMYEVBTzDJ-S1IR5d6eiTGusD5aFlUkAs9NV_nFw");
request.AddParameter("clientId", 123);
IRestResponse<RootObject> response = client.Execute<RootObject>(request);
if (response.IsSuccessful)
{
response.Data.Write();
}
else
{
Console.WriteLine(response.ErrorMessage);
}
Console.WriteLine();
string path = Assembly.GetExecutingAssembly().Location;
string name = Path.GetFileName(path);
request = new RestRequest("post", Method.POST);
request.AddFile(name, File.ReadAllBytes(path), name, "application/octet-stream");
response = client.Execute<RootObject>(request);
if (response.IsSuccessful)
{
response.Data.Write();
}
else
{
Console.WriteLine(response.ErrorMessage);
}
Console.ReadLine();
}
private static void Write(this RootObject rootObject)
{
Console.WriteLine("clientId: " + rootObject.args.clientId);
Console.WriteLine("Accept: " + rootObject.headers.Accept);
Console.WriteLine("AcceptEncoding: " + rootObject.headers.AcceptEncoding);
Console.WriteLine("AcceptLanguage: " + rootObject.headers.AcceptLanguage);
Console.WriteLine("Authorization: " + rootObject.headers.Authorization);
Console.WriteLine("Connection: " + rootObject.headers.Connection);
Console.WriteLine("Dnt: " + rootObject.headers.Dnt);
Console.WriteLine("Host: " + rootObject.headers.Host);
Console.WriteLine("Origin: " + rootObject.headers.Origin);
Console.WriteLine("Referer: " + rootObject.headers.Referer);
Console.WriteLine("UserAgent: " + rootObject.headers.UserAgent);
Console.WriteLine("origin: " + rootObject.origin);
Console.WriteLine("url: " + rootObject.url);
Console.WriteLine("data: " + rootObject.data);
Console.WriteLine("files: ");
foreach (KeyValuePair<string, string> kvp in rootObject.files ?? Enumerable.Empty<KeyValuePair<string, string>>())
{
Console.WriteLine("\t" + kvp.Key + ": " + kvp.Value);
}
}
}
public class Args
{
public string clientId { get; set; }
}
public class Headers
{
public string Accept { get; set; }
public string AcceptEncoding { get; set; }
public string AcceptLanguage { get; set; }
public string Authorization { get; set; }
public string Connection { get; set; }
public string Dnt { get; set; }
public string Host { get; set; }
public string Origin { get; set; }
public string Referer { get; set; }
public string UserAgent { get; set; }
}
public class RootObject
{
public Args args { get; set; }
public Headers headers { get; set; }
public string origin { get; set; }
public string url { get; set; }
public string data { get; set; }
public Dictionary<string, string> files { get; set; }
}
}
Troubleshooting BadImageFormatException
For anyone who may arrive here at a later time...
For Desktop solution I got BadImageFormatException
exception.
All project's build options was fine (all x86
). But StartUp project of solution was changed to some other project(class library project).
Changing StartUp project to the original(.exe application project) was a solution in my case
C# : "A first chance exception of type 'System.InvalidOperationException'"
Consider using System.Windows.Forms.Timer
instead of System.Threading.Timer
for a GUI application, for timers that are based on the Windows message queue instead of on dedicated threads or the thread pool.
In your scenario, for the purpose of periodic updates of UI, it seems particularly appropriate since you don't really have a background work or long calculation to perform. You just want to do periodic small tasks that have to happen on the UI thread anyway.
What is the purpose of the vshost.exe file?
The vshost.exe feature was introduced with Visual Studio 2005 (to answer your comment).
The purpose of it is mostly to make debugging launch quicker - basically there's already a process with the framework running, just ready to load your application as soon as you want it to.
See this MSDN article and this blog post for more information.
Set up adb on Mac OS X
After trying all the solutions, none of them where working for me.
In my case I had the Android Studio and the adb was correctly working but the Android Studio was not capable to detect the adb. These was because I installed it with homebrew in another directory, not the /Users/$USER/Library/Android/sdk but Usr/Library blabla
Apparently AS needed to have it in his route /Users/$USER/Library/Android/sdk (same place as in preferences SDK installation route)
So I deleted all the adb from my computer (I installed several) and executed these terminal commands:
echo 'export ANDROID_HOME=/Users/$USER/Library/Android/sdk' >> ~/.bash_profile
echo 'export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools' >> ~/.bash_profile
source ~/.bash_profile
adb devices
Well, after that, still wasn't working, because for some reason the route for the adb was /Users/$USER/Library/Android/sdk/platform-tools/platform-tools (yes, repeated) so I just copied the last platform-tools into the first directory with all the license files and started working.
Weird but true
How do I make a transparent border with CSS?
Many of you must be landing here to find a solution for opaque border instead of a transparent one. In that case you can use rgba
, where a
stands for alpha
.
.your_class {
height: 100px;
width: 100px;
margin: 100px;
border: 10px solid rgba(255,255,255,.5);
}
Demo
Here, you can change the opacity
of the border
from 0-1
If you simply want a complete transparent border, the best thing to use is transparent
, like border: 1px solid transparent;
How to check if an email address exists without sending an email?
Although this question is a bit old, this service tip might help users searching for a similar solution checking email addresses beyond syntax validation prior to sending.
I have been using this open sourced service for a more in depth validating of emails (checking for mx records on the e-mail address domain etc.) for a few projects with good results. It also checks for common typos witch is quite useful. Demo here.
Getter and Setter?
Why use getters and setters?
- Scalability: It's easier refactor a getter than search all the var assignments in a project code.
- Debugging: You can put breakpoints at setters and getters.
- Cleaner: Magic functions are not good solution for writting less, your IDE will not suggest the code. Better use templates for fast-writting getters.
Determine project root from a running node.js application
__dirname
isn't a global; it's local to the current module so each file has its own local, different value.
If you want the root directory of the running process, you probably do want to use process.cwd()
.
If you want predictability and reliability, then you probably need to make it a requirement of your application that a certain environment variable is set. Your app looks for MY_APP_HOME
(Or whatever) and if it's there, and the application exists in that directory then all is well. If it is undefined or the directory doesn't contain your application then it should exit with an error prompting the user to create the variable. It could be set as a part of an install process.
You can read environment variables in node with something like process.env.MY_ENV_VARIABLE
.
Checking character length in ruby
Ruby provides a built-in function for checking the length of a string. Say it's called s
:
if s.length <= 25
# We're OK
else
# Too long
end
Prevent cell numbers from incrementing in a formula in Excel
In Excel 2013 and resent versions, you can use F2 and F4 to speed things up when you want to toggle the lock.
About the keys:
How To:
Notes:
- These notes are based on my observations while I was looking into this for one of my own projects.
- It only works on one cell formula at a time.
- Hitting F4 without selecting anything will update the locking on the last cell reference in the formula.
- Hitting F4 when you have mixed locking in the formula will convert everything to the same thing. Example two different cell references like '$A4' and 'A$4' will both become 'A4'. This is nice because it can prevent a lot of second guessing and cleanup.
- Ctrl+A does not work in the formula editor but you can hit the End key and then Ctrl + Shift + Home to highlight the entire formula. Hitting
Home and then Ctrl + Shift + End.
- OS and Hardware manufactures have many different keyboard bindings for the Function (F Lock) keys so F2 and F4 may do different things. As an example, some users may have to hold down you 'F Lock' key on some laptops.
- 'DrStrangepork' commented about F4 actually closes Excel which can be true but it depends on what you last selected. Excel changes the behavior of F4 depending
on the current state of Excel. If you have the cell selected and are
in formula edit mode (F2), F4 will toggle cell reference locking as Alexandre had originally suggested. While playing with this, I've had F4 do at least 5 different things. I view F4 in Excel as an all purpose function key that behaves something like this; "As an Excel user, given my last action, automate or repeat logical next step for me".
Partial Dependency (Databases)
I hope this explaination gives a more intuitive appeal to dependency than the answers previously given.
Functional Dependency
An analysis of dependency operates on the attribute level, i.e. one or more attribute is determined by another attribute, it comes before the concept of keys. 'The role of a key is based on the concept of determination. 'Determination is the state
in which knowing the value of one attribute makes it possible to determine the value
of another.' Database Systems 12ed
Functional dependency is when one or more attributes determine one or more attributes. For instance:
Social Security Number -> First Name, Last Name.
However, by definition of functional dependency:
(SSN, First Name) -> Last Name
This is also a valid functional dependency. The determinants (The attribute that which determines another attribution) are called super key.
Full Functional Dependency
Thus, as a subset of functional dependency, there is the concept of full functional dependency, where the bare minimal determinant is considered. We refer those bare minimal determinants collectively as one candidate key (weird linguistic quirk in my opinion, like the concept of vector).
Partial Functional Dependency
However, sometimes one of the attributes in the candidate key is sufficient to determine another attribute(s), BUT not all, in a relation (a table with no rows). That, is when you have a partial functional dependency within a relation.
C# find highest array value and index
This is not the most glamorous way but works.
(must have using System.Linq;
)
int maxValue = anArray.Max();
int maxIndex = anArray.ToList().IndexOf(maxValue);
How to set a timeout on a http.request() in Node?
Elaborating on the answer @douwe here is where you would put a timeout on a http request.
// TYPICAL REQUEST
var req = https.get(http_options, function (res) {
var data = '';
res.on('data', function (chunk) { data += chunk; });
res.on('end', function () {
if (res.statusCode === 200) { /* do stuff with your data */}
else { /* Do other codes */}
});
});
req.on('error', function (err) { /* More serious connection problems. */ });
// TIMEOUT PART
req.setTimeout(1000, function() {
console.log("Server connection timeout (after 1 second)");
req.abort();
});
this.abort() is also fine.
SyntaxError: non-default argument follows default argument
Let me clarify two points here :
- Firstly non-default argument should not follow the default argument, it means you can't define
(a = 'b',c)
in function.
The correct order of defining parameter in function are :
- positional parameter or non-default parameter i.e
(a,b,c)
- keyword parameter or default parameter i.e
(a = 'b',r= 'j')
- keyword-only parameter i.e
(*args)
- var-keyword parameter i.e
(**kwargs)
def example(a, b, c=None, r="w" , d=[], *ae, **ab):
(a,b)
are positional parameter
(c=none)
is optional parameter
(r="w")
is keyword parameter
(d=[])
is list parameter
(*ae)
is keyword-only
(*ab)
is var-keyword parameter
so first re-arrange your parameters
- now the second thing is you have to define len1 when you are doing hgt=len1
the len1 argument is not defined when default values are saved, Python computes and saves default values when you define the function
len1 is not defined, does not exist when this happens (it exists only when the function is executed)
so second remove this "len1 = hgt"
it's not allowed in python.
keep in mind the difference between argument and parameters.
java collections - keyset() vs entrySet() in map
An Iterator
moves forward only, if it read it once, it's done. Your
m.get(itr2.next());
is reading the next value of itr2.next();
, that is why you are missing a few (actually not a few, every other) keys.
Bootstrap 3 scrollable div for table
Well one way to do it is set the height of your body to the height
that you want your page
to be. In this example I did 600px
.
Then set your wrapper
height to a percentage of the body here I did 70%
This will adjust your table so that it does not fill up the whole screen but in stead just takes up a percentage of the specified page height.
body {
padding-top: 70px;
border:1px solid black;
height:600px;
}
.mygrid-wrapper-div {
border: solid red 5px;
overflow: scroll;
height: 70%;
}
http://jsfiddle.net/4NB2N/7/
Update How about a jQuery approach.
$(function() {
var window_height = $(window).height(),
content_height = window_height - 200;
$('.mygrid-wrapper-div').height(content_height);
});
$( window ).resize(function() {
var window_height = $(window).height(),
content_height = window_height - 200;
$('.mygrid-wrapper-div').height(content_height);
});
http://jsfiddle.net/4NB2N/11/
How to change the default GCC compiler in Ubuntu?
I used just the lines below and it worked. I just wanted to compile VirtualBox
and VMWare WorkStation
using kernel 4.8.10
on Ubuntu 14.04
. Initially, most things were not working for example graphics and networking. I was lucky that VMWare workstation
requested for gcc 6.2.0
. I couldn't start my Genymotion Android emulators
because virtualbox was down. Will post results later if necessary.
VER=4.6 ; PRIO=60
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-$VER $PRIO --slave /usr/bin/g++ g++ /usr/bin/g++-$VER
VER=6 ; PRIO=50
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-$VER $PRIO --slave /usr/bin/g++ g++ /usr/bin/g++-$VER
VER=4.8 ; PRIO=40
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-$VER $PRIO --slave /usr/bin/g++ g++ /usr/bin/g++-$VER
How to use onSavedInstanceState example please
One major note that all new Android developers should know is that any information in Widgets (TextView, Buttons, etc.) will be persisted automatically by Android as long as you assign an ID to them. So that means most of the UI state is taken care of without issue. Only when you need to store other data does this become an issue.
From Android Docs:
The only work required by you is to
provide a unique ID (with the
android:id attribute) for each widget
you want to save its state. If a
widget does not have an ID, then it
cannot save its state
How to convert numpy arrays to standard TensorFlow format?
You can use tf.pack (tf.stack in TensorFlow 1.0.0) method for this purpose. Here is how to pack a random image of type numpy.ndarray
into a Tensor
:
import numpy as np
import tensorflow as tf
random_image = np.random.randint(0,256, (300,400,3))
random_image_tensor = tf.pack(random_image)
tf.InteractiveSession()
evaluated_tensor = random_image_tensor.eval()
UPDATE: to convert a Python object to a Tensor you can use tf.convert_to_tensor function.
How do I view events fired on an element in Chrome DevTools?
For jQuery (at least version 1.11.2) the following procedure worked for me.
- Right click on the element and open 'Chrome Developer Tools'
- Type
$._data(($0), 'events');
in the 'Console'
- Expand the attached objects and double click the
handler:
value.
- This shows the source code of the attached function, search for part of that using the 'Search' tab.
And it's time to stop re-inventing the wheel and start using vanilla JS events ... :)
Failed to load resource: net::ERR_INSECURE_RESPONSE
Sometimes Google Chrome throws this error, even if it should not.
I experienced it when Chrome had a new version, and it needed to be restarted.
After restarting the same page worked without any errors.
The error in the console was:
net::ERR_INSECURE_RESPONSE
Remove duplicated rows using dplyr
For completeness’ sake, the following also works:
df %>% group_by(x) %>% filter (! duplicated(y))
However, I prefer the solution using distinct
, and I suspect it’s faster, too.
Get max and min value from array in JavaScript
Why not store it as an array of prices instead of object?
prices = []
$(allProducts).each(function () {
var price = parseFloat($(this).data('price'));
prices.push(price);
});
prices.sort(function(a, b) { return a - b }); //this is the magic line which sort the array
That way you can just
prices[0]; // cheapest
prices[prices.length - 1]; // most expensive
Note that you can do shift()
and pop()
to get min and max price respectively, but it will take off the price from the array.
Even better alternative is to use Sergei solution below, by using Math.max
and min
respectively.
EDIT:
I realized that this would be wrong if you have something like [11.5, 3.1, 3.5, 3.7]
as 11.5
is treated as a string, and would come before the 3.x
in dictionary order, you need to pass in custom sort function to make sure they are indeed treated as float:
prices.sort(function(a, b) { return a - b });
Running multiple async tasks and waiting for them all to complete
There should be a more succinct solution than the accepted answer. It shouldn't take three steps to run multiple tasks simultaneously and get their results.
- Create tasks
- await Task.WhenAll(tasks)
- Get task results (e.g., task1.Result)
Here's a method that cuts this down to two steps:
public async Task<Tuple<T1, T2>> WhenAllGeneric<T1, T2>(Task<T1> task1, Task<T2> task2)
{
await Task.WhenAll(task1, task2);
return Tuple.Create(task1.Result, task2.Result);
}
You can use it like this:
var taskResults = await Task.WhenAll(DoWorkAsync(), DoMoreWorkAsync());
var DoWorkResult = taskResults.Result.Item1;
var DoMoreWorkResult = taskResults.Result.Item2;
This removes the need for the temporary task variables. The problem with using this is that while it works for two tasks, you'd need to update it for three tasks, or any other number of tasks. Also it doesn't work well if one of the tasks doesn't return anything. Really, the .Net library should provide something that can do this
Declare global variables in Visual Studio 2010 and VB.NET
A global variable could be accessible in all your forms in your project if you use the keyword public shared
if it is in a class. It will also work if you use the keyword "public" if it is under a Module, but it is not the best practice for many reasons.
(... Yes, I somewhat repeating what "Cody Gray" and "RBarryYoung" said.)
One of the problems is when you have two threads that call the same global variable at the same time. You will have some surprises. You might have unexpected reactions if you don't know their limitations. Take a look at the post Global Variables in Visual Basic .NET and download the sample project!
Jquery checking success of ajax post
If you need a failure function, you can't use the $.get or $.post functions; you will need to call the $.ajax function directly. You pass an options object that can have "success" and "error" callbacks.
Instead of this:
$.post("/post/url.php", parameters, successFunction);
you would use this:
$.ajax({
url: "/post/url.php",
type: "POST",
data: parameters,
success: successFunction,
error: errorFunction
});
There are lots of other options available too. The documentation lists all the options available.
Float right and position absolute doesn't work together
Perhaps you should divide your content like such using floats:
<div style="overflow: auto;">
<div style="float: left; width: 600px;">
Here is my content!
</div>
<div style="float: right; width: 300px;">
Here is my sidebar!
</div>
</div>
Notice the overflow: auto;
, this is to ensure that you have some height to your container. Floating things takes them out of the DOM, to ensure that your elements below don't overlap your wandering floats, set a container div
to have an overflow: auto
(or overflow: hidden
) to ensure that floats are accounted for when drawing your height. Check out more information on floats and how to use them here.
Android How to adjust layout in Full Screen Mode when softkeyboard is visible
Today not working adjustResize on full screen issue is actual for android sdk.
From answers i found:
the solution - but solution has this showing on picture issue :
Than i found the solution and remove the one unnecessary action:
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
So, see my fixed solution code on Kotlin:
class AndroidBug5497Workaround constructor(val activity: Activity) {
private val content = activity.findViewById<View>(android.R.id.content) as FrameLayout
private val mChildOfContent = content.getChildAt(0)
private var usableHeightPrevious: Int = 0
private val contentContainer = activity.findViewById(android.R.id.content) as ViewGroup
private val rootView = contentContainer.getChildAt(0)
private val rootViewLayout = rootView.layoutParams as FrameLayout.LayoutParams
private val listener = {
possiblyResizeChildOfContent()
}
fun addListener() {
mChildOfContent.apply {
viewTreeObserver.addOnGlobalLayoutListener(listener)
}
}
fun removeListener() {
mChildOfContent.apply {
viewTreeObserver.removeOnGlobalLayoutListener(listener)
}
}
private fun possiblyResizeChildOfContent() {
val contentAreaOfWindowBounds = Rect()
mChildOfContent.getWindowVisibleDisplayFrame(contentAreaOfWindowBounds)
val usableHeightNow = contentAreaOfWindowBounds.height()
if (usableHeightNow != usableHeightPrevious) {
rootViewLayout.height = usableHeightNow
rootView.layout(contentAreaOfWindowBounds.left,
contentAreaOfWindowBounds.top, contentAreaOfWindowBounds.right, contentAreaOfWindowBounds.bottom);
mChildOfContent.requestLayout()
usableHeightPrevious = usableHeightNow
}
}
}
My bug fixing implement code:
class LeaveDetailActivity : BaseActivity(){
private val keyBoardBugWorkaround by lazy {
AndroidBug5497Workaround(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
override fun onResume() {
keyBoardBugWorkaround.addListener()
super.onResume()
}
override fun onPause() {
keyBoardBugWorkaround.removeListener()
super.onPause()
}
}
ConcurrentModificationException for ArrayList
Like the other answers say, you can't remove an item from a collection you're iterating over. You can get around this by explicitly using an Iterator
and removing the item there.
Iterator<Item> iter = list.iterator();
while(iter.hasNext()) {
Item blah = iter.next();
if(...) {
iter.remove(); // Removes the 'current' item
}
}
How can I find the number of elements in an array?
I personally think that sizeof(a) / sizeof(*a) looks cleaner.
I also prefer to define it as a macro:
#define NUM(a) (sizeof(a) / sizeof(*a))
Then you can use it in for-loops, thusly:
for (i = 0; i < NUM(a); i++)
Declaring an unsigned int in Java
It seems that you can handle the signing problem by doing a "logical AND" on the values before you use them:
Example (Value of byte[]
header[0]
is 0x86
):
System.out.println("Integer "+(int)header[0]+" = "+((int)header[0]&0xff));
Result:
Integer -122 = 134
C# Test if user has write access to a folder
For example for all users (Builtin\Users), this method works fine - enjoy.
public static bool HasFolderWritePermission(string destDir)
{
if(string.IsNullOrEmpty(destDir) || !Directory.Exists(destDir)) return false;
try
{
DirectorySecurity security = Directory.GetAccessControl(destDir);
SecurityIdentifier users = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
foreach(AuthorizationRule rule in security.GetAccessRules(true, true, typeof(SecurityIdentifier)))
{
if(rule.IdentityReference == users)
{
FileSystemAccessRule rights = ((FileSystemAccessRule)rule);
if(rights.AccessControlType == AccessControlType.Allow)
{
if(rights.FileSystemRights == (rights.FileSystemRights | FileSystemRights.Modify)) return true;
}
}
}
return false;
}
catch
{
return false;
}
}
HTML 'td' width and height
Following width worked well in HTML5: -
<table >
<tr>
<th style="min-width:120px">Month</th>
<th style="min-width:60px">Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</table>
Please note that
- TD tag is without CSS style.
MSVCP120d.dll missing
From the comments, the problem was caused by using dlls that were built with Visual Studio 2013 in a project compiled with Visual Studio 2012. The reason for this was a third party library named the folders containing the dlls vc11, vc12. One has to be careful with any system that uses the compiler version (less than 4 digits) since this does not match the version of Visual Studio (except for Visual Studio 2010).
- vc8 = Visual Studio 2005
- vc9 = Visual Studio 2008
- vc10 = Visual Studio 2010
- vc11 = Visual Studio 2012
- vc12 = Visual Studio 2013
- vc14 = Visual Studio 2015
- vc15 = Visual Studio 2017
- vc16 = Visual Studio 2019
The Microsoft C++ runtime dlls use a 2 or 3 digit code also based on the compiler version not the version of Visual Studio.
- MSVCP80.DLL is from Visual Studio 2005
- MSVCP90.DLL is from Visual Studio 2008
- MSVCP100.DLL is from Visual Studio 2010
- MSVCP110.DLL is from Visual Studio 2012
- MSVCP120.DLL is from Visual Studio 2013
- MSVCP140.DLL is from Visual Studio 2015, 2017 and 2019
There is binary compatibility between Visual Studio 2015, 2017 and 2019.
Why does cURL return error "(23) Failed writing body"?
For me, it was permission issue. Docker run is called with a user profile but root is the user inside the container. The solution was to make curl write to /tmp since that has write permission for all users , not just root.
I used the -o option.
-o /tmp/file_to_download
Generating random numbers in Objective-C
Use the arc4random_uniform(upper_bound)
function to generate a random number within a range. The following will generate a number between 0 and 73 inclusive.
arc4random_uniform(74)
arc4random_uniform(upper_bound)
avoids modulo bias as described in the man page:
arc4random_uniform() will return a uniformly distributed random number less than upper_bound. arc4random_uniform() is recommended over constructions like ``arc4random() % upper_bound'' as it avoids "modulo bias" when the upper bound is not a power of two.
How do I use FileSystemObject in VBA?
In excel 2013 the object creation string is:
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
instead of the code in the answer above:
Dim fs,fname
Set fs=Server.CreateObject("Scripting.FileSystemObject")
Splitting comma separated string in a PL/SQL stored proc
Here is a good solution:
FUNCTION comma_to_table(iv_raw IN VARCHAR2) RETURN dbms_utility.lname_array IS
ltab_lname dbms_utility.lname_array;
ln_len BINARY_INTEGER;
BEGIN
dbms_utility.comma_to_table(list => iv_raw
,tablen => ln_len
,tab => ltab_lname);
FOR i IN 1 .. ln_len LOOP
dbms_output.put_line('element ' || i || ' is ' || ltab_lname(i));
END LOOP;
RETURN ltab_lname;
END;
Source: CSV - comma separated values - and PL/SQL (link no longer valid)
Android Studio Could not initialize class org.codehaus.groovy.runtime.InvokerHelper
I also had the same problem and and it looks like this problem is due to the gradle version in the project directory
- This is the version of my jdk:
openjdk version "15-ea" 2020-09-15
OpenJDK Runtime Environment (build 15-ea+32-Ubuntu-220.04)
OpenJDK 64-Bit Server VM (build 15-ea+32-Ubuntu-220.04, mixed mode, sharing)
- Please check gradle whether it is installed. This is the version of my gradle:
------------------------------------------------------------
Gradle 6.8
------------------------------------------------------------
Build time: 2021-01-08 16:38:46 UTC
Revision: b7e82460c5373e194fb478a998c4fcfe7da53a7e
Kotlin: 1.4.20
Groovy: 2.5.12
Ant: Apache Ant(TM) version 1.10.9 compiled on September 27 2020
JVM: 15-ea (Private Build 15-ea+32-Ubuntu-220.04)
OS: Linux 5.4.0-65-generic amd64
Then open the gradle-wrapper.properties file in your project folder, in the folder: project name/android/gradle/wrapper/gradle-wrapper.properties
Change the gradle version. Here I changed the gradle version to 6.5
The video version can be seen here: https://www.youtube.com/watch?v=mcclcscUpV0
How to detect iPhone 5 (widescreen devices)?
I've taken the liberty to put the macro by Macmade into a C function, and name it properly because it detects widescreen availability and NOT necessarily the iPhone 5.
The macro also doesn't detect running on an iPhone 5 in case where the project doesn't include the [email protected]. Without the new Default image, the iPhone 5 will report a regular 480x320 screen size (in points). So the check isn't just for widescreen availability but for widescreen mode being enabled as well.
BOOL isWidescreenEnabled()
{
return (BOOL)(fabs((double)[UIScreen mainScreen].bounds.size.height -
(double)568) < DBL_EPSILON);
}
How to convert data.frame column from Factor to numeric
As an alternative to $dollarsign
notation, use a within
block:
breast <- within(breast, {
class <- as.numeric(as.character(class))
})
Note that you want to convert your vector to a character before converting it to a numeric. Simply calling as.numeric(class)
will not the ids corresponding to each factor level (1, 2) rather than the levels themselves.
How can I send mail from an iPhone application
Below code is used in my application to send email with an attachment here the attachments is an image .You can send any type of file only thing is to keep in mind is that you had to specify the correct 'mimeType'
add this to your .h file
#import <MessageUI/MFMailComposeViewController.h>
Add MessageUI.framework to your project file
NSArray *paths = SSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:@"myGreenCard.png"];
MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:@"Green card application"];
[controller setMessageBody:@"Hi , <br/> This is my new latest designed green card." isHTML:YES];
[controller addAttachmentData:[NSData dataWithContentsOfFile:getImagePath] mimeType:@"png" fileName:@"My Green Card"];
if (controller)
[self presentModalViewController:controller animated:YES];
[controller release];
Delegate method is as shown below
-(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error;
{
if (result == MFMailComposeResultSent) {
NSLog(@"It's away!");
}
[self dismissModalViewControllerAnimated:YES];
}
javascript get x and y coordinates on mouse click
simple solution is this:
game.js:
document.addEventListener('click', printMousePos, true);
function printMousePos(e){
cursorX = e.pageX;
cursorY= e.pageY;
$( "#test" ).text( "pageX: " + cursorX +",pageY: " + cursorY );
}
How to strip a specific word from a string?
You can also use a regexp with re.sub
:
article_title_str = re.sub(r'(\s?-?\|?\s?Times of India|\s?-?\|?\s?the Times of India|\s?-?\|?\s+?Gadgets No'',
article_title_str, flags=re.IGNORECASE)
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 :)
How to check if String is null
You can check with null or Number.
First, add a reference to Microsoft.VisualBasic
in your application.
Then, use the following code:
bool b = Microsoft.VisualBasic.Information.IsNumeric("null");
bool c = Microsoft.VisualBasic.Information.IsNumeric("abc");
In the above, b
and c
should both be false
.
how can get index & count in vuejs
Using Vue 1.x, use the special variable $index
like so:
<li v-for="catalog in catalogs">this index : {{$index + 1}}</li>
alternatively, you can specify an alias as a first argument for v-for
directive like so:
<li v-for="(itemObjKey, catalog) in catalogs">
this index : {{itemObjKey + 1}}
</li>
See : Vue 1.x guide
Using Vue 2.x, v-for
provides a second optional argument referencing the index of the current item, you can add 1 to it in your mustache template as seen before:
<li v-for="(catalog, itemObjKey) in catalogs">
this index : {{itemObjKey + 1}}
</li>
See: Vue 2.x guide
Eliminating the parentheses in the v-for
syntax also works fine hence:
<li v-for="catalog, itemObjKey in catalogs">
this index : {{itemObjKey + 1}}
</li>
Hope that helps.
Open Excel file for reading with VBA without display
Even though you've got your answer, for those that find this question, it is also possible to open an Excel spreadsheet as a JET data store. Borrowing the connection string from a project I've used it on, it will look kinda like this:
strExcelConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & objFile.Path & ";Extended Properties=""Excel 8.0;HDR=Yes"""
strSQL = "SELECT * FROM [RegistrationList$] ORDER BY DateToRegister DESC"
Note that "RegistrationList" is the name of the tab in the workbook. There are a few tutorials floating around on the web with the particulars of what you can and can't do accessing a sheet this way.
Just thought I'd add. :)
Why can't Python parse this JSON data?
There are two types in this parsing.
- Parsing data from a file from a system path
- Parsing JSON from remote URL.
From a file, you can use the following
import json
json = json.loads(open('/path/to/file.json').read())
value = json['key']
print json['value']
This arcticle explains the full parsing and getting values using two scenarios.Parsing JSON using Python
Summing radio input values
Your javascript is executed before the HTML is generated, so it doesn't "see" the ungenerated INPUT elements. For jQuery, you would either stick the Javascript at the end of the HTML or wrap it like this:
<script type="text/javascript"> $(function() { //jQuery trick to say after all the HTML is parsed. $("input[type=radio]").click(function() { var total = 0; $("input[type=radio]:checked").each(function() { total += parseFloat($(this).val()); }); $("#totalSum").val(total); }); }); </script>
EDIT: This code works for me
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <strong>Choose a base package:</strong> <input id="item_0" type="radio" name="pkg" value="1942" />Base Package 1 - $1942 <input id="item_1" type="radio" name="pkg" value="2313" />Base Package 2 - $2313 <input id="item_2" type="radio" name="pkg" value="2829" />Base Package 3 - $2829 <strong>Choose an add on:</strong> <input id="item_10" type="radio" name="ext" value="0" />No add-on - +$0 <input id="item_12" type="radio" name="ext" value="2146" />Add-on 1 - (+$2146) <input id="item_13" type="radio" name="ext" value="2455" />Add-on 2 - (+$2455) <input id="item_14" type="radio" name="ext" value="2764" />Add-on 3 - (+$2764) <input id="item_15" type="radio" name="ext" value="3073" />Add-on 4 - (+$3073) <input id="item_16" type="radio" name="ext" value="3382" />Add-on 5 - (+$3382) <input id="item_17" type="radio" name="ext" value="3691" />Add-on 6 - (+$3691) <strong>Your total is:</strong> <input id="totalSum" type="text" name="totalSum" readonly="readonly" size="5" value="" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"> $("input[type=radio]").click(function() { var total = 0; $("input[type=radio]:checked").each(function() { total += parseFloat($(this).val()); }); $("#totalSum").val(total); }); </script> </body> </html>
PHP random string generator
This code will help:
This function will return random string with length between $maxLength
and $minLength
.
NOTE: Function random_bytes
works since PHP 7.
If you need specific length, so $maxLength
and $minLength
must be same.
function getRandomString($maxLength = 20, $minLength = 10)
{
$minLength = $maxLength < $minLength ? $maxLength : $minLength;
$halfMin = ceil($minLength / 2);
$halfMax = ceil($maxLength / 2);
$bytes = random_bytes(rand($halfMin, $halfMax));
$randomString = bin2hex($bytes);
$randomString = strlen($randomString) > $maxLength ? substr($randomString, 0, -1) : $randomString;
return $randomString;
}
Determine the line of code that causes a segmentation fault?
There are a number of tools available which help debugging segmentation faults and I would like to add my favorite tool to the list: Address Sanitizers (often abbreviated ASAN).
Modern¹ compilers come with the handy -fsanitize=address
flag, adding some compile time and run time overhead which does more error checking.
According to the documentation these checks include catching segmentation faults by default. The advantage here is that you get a stack trace similar to gdb's output, but without running the program inside a debugger. An example:
int main() {
volatile int *ptr = (int*)0;
*ptr = 0;
}
$ gcc -g -fsanitize=address main.c
$ ./a.out
AddressSanitizer:DEADLYSIGNAL
=================================================================
==4848==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000000 (pc 0x5654348db1a0 bp 0x7ffc05e39240 sp 0x7ffc05e39230 T0)
==4848==The signal is caused by a WRITE memory access.
==4848==Hint: address points to the zero page.
#0 0x5654348db19f in main /tmp/tmp.s3gwjqb8zT/main.c:3
#1 0x7f0e5a052b6a in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x26b6a)
#2 0x5654348db099 in _start (/tmp/tmp.s3gwjqb8zT/a.out+0x1099)
AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: SEGV /tmp/tmp.s3gwjqb8zT/main.c:3 in main
==4848==ABORTING
The output is slightly more complicated than what gdb would output but there are upsides:
There is no need to reproduce the problem to receive a stack trace. Simply enabling the flag during development is enough.
ASANs catch a lot more than just segmentation faults. Many out of bounds accesses will be caught even if that memory area was accessible to the process.
¹ That is Clang 3.1+ and GCC 4.8+.
Compiling an application for use in highly radioactive environments
This answer assumes you are concerned with having a system that works correctly, over and above having a system that is minimum cost or fast; most people playing with radioactive things value correctness / safety over speed / cost
Several people have suggested hardware changes you can make (fine - there's lots of good stuff here in answers already and I don't intend repeating all of it), and others have suggested redundancy (great in principle), but I don't think anyone has suggested how that redundancy might work in practice. How do you fail over? How do you know when something has 'gone wrong'? Many technologies work on the basis everything will work, and failure is thus a tricky thing to deal with. However, some distributed computing technologies designed for scale expect failure (after all with enough scale, failure of one node of many is inevitable with any MTBF for a single node); you can harness this for your environment.
Here are some ideas:
Ensure that your entire hardware is replicated n
times (where n
is greater than 2, and preferably odd), and that each hardware element can communicate with each other hardware element. Ethernet is one obvious way to do that, but there are many other far simpler routes that would give better protection (e.g. CAN). Minimise common components (even power supplies). This may mean sampling ADC inputs in multiple places for instance.
Ensure your application state is in a single place, e.g. in a finite state machine. This can be entirely RAM based, though does not preclude stable storage. It will thus be stored in several place.
Adopt a quorum protocol for changes of state. See RAFT for example. As you are working in C++, there are well known libraries for this. Changes to the FSM would only get made when a majority of nodes agree. Use a known good library for the protocol stack and the quorum protocol rather than rolling one yourself, or all your good work on redundancy will be wasted when the quorum protocol hangs up.
Ensure you checksum (e.g. CRC/SHA) your FSM, and store the CRC/SHA in the FSM itself (as well as transmitting in the message, and checksumming the messages themselves). Get the nodes to check their FSM regularly against these checksum, checksum incoming messages, and check their checksum matches the checksum of the quorum.
Build as many other internal checks into your system as possible, making nodes that detect their own failure reboot (this is better than carrying on half working provided you have enough nodes). Attempt to let them cleanly remove themselves from the quorum during rebooting in case they don't come up again. On reboot have them checksum the software image (and anything else they load) and do a full RAM test before reintroducing themselves to the quorum.
Use hardware to support you, but do so carefully. You can get ECC RAM, for instance, and regularly read/write through it to correct ECC errors (and panic if the error is uncorrectable). However (from memory) static RAM is far more tolerant of ionizing radiation than DRAM is in the first place, so it may be better to use static DRAM instead. See the first point under 'things I would not do' as well.
Let's say you have an 1% chance of failure of any given node within one day, and let's pretend you can make failures entirely independent. With 5 nodes, you'll need three to fail within one day, which is a .00001% chance. With more, well, you get the idea.
Things I would not do:
Underestimate the value of not having the problem to start off with. Unless weight is a concern, a large block of metal around your device is going to be a far cheaper and more reliable solution than a team of programmers can come up with. Ditto optical coupling of inputs of EMI is an issue, etc. Whatever, attempt when sourcing your components to source those rated best against ionizing radiation.
Roll your own algorithms. People have done this stuff before. Use their work. Fault tolerance and distributed algorithms are hard. Use other people's work where possible.
Use complicated compiler settings in the naive hope you detect more failures. If you are lucky, you may detect more failures. More likely, you will use a code-path within the compiler which has been less tested, particularly if you rolled it yourself.
Use techniques which are untested in your environment. Most people writing high availability software have to simulate failure modes to check their HA works correctly, and miss many failure modes as a result. You are in the 'fortunate' position of having frequent failures on demand. So test each technique, and ensure its application actual improves MTBF by an amount that exceeds the complexity to introduce it (with complexity comes bugs). Especially apply this to my advice re quorum algorithms etc.
Docker and securing passwords
Definitely it is a concern. Dockerfiles are commonly checked in to repositories and shared with other people. An alternative is to provide any credentials (usernames, passwords, tokens, anything sensitive) as environment variables at runtime. This is possible via the -e
argument (for individual vars on the CLI) or --env-file
argument (for multiple variables in a file) to docker run
. Read this for using environmental with docker-compose.
Using --env-file
is definitely a safer option since this protects against the secrets showing up in ps
or in logs if one uses set -x
.
However, env vars are not particularly secure either. They are visible via docker inspect
, and hence they are available to any user that can run docker
commands. (Of course, any user that has access to docker
on the host also has root anyway.)
My preferred pattern is to use a wrapper script as the ENTRYPOINT
or CMD
. The wrapper script can first import secrets from an outside location in to the container at run time, then execute the application, providing the secrets. The exact mechanics of this vary based on your run time environment. In AWS, you can use a combination of IAM roles, the Key Management Service, and S3 to store encrypted secrets in an S3 bucket. Something like HashiCorp Vault or credstash is another option.
AFAIK there is no optimal pattern for using sensitive data as part of the build process. In fact, I have an SO question on this topic. You can use docker-squash to remove layers from an image. But there's no native functionality in Docker for this purpose.
You may find shykes comments on config in containers useful.
HTTP POST with Json on Body - Flutter/Dart
This works!
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
Future<http.Response> postRequest () async {
var url ='https://pae.ipportalegre.pt/testes2/wsjson/api/app/ws-authenticate';
Map data = {
'apikey': '12345678901234567890'
}
//encode Map to JSON
var body = json.encode(data);
var response = await http.post(url,
headers: {"Content-Type": "application/json"},
body: body
);
print("${response.statusCode}");
print("${response.body}");
return response;
}
Printing reverse of any String without using any predefined function?
package com.ofs;
public class ReverseWordsInString{
public static void main(String[] args) {
String str = "welcome to the new world and how are you feeling ?";
// Get the Java runtime
Runtime runtime = Runtime.getRuntime();
// Run the garbage collector
runtime.gc();
// Calculate the used memory
long firstUsageMemory = runtime.totalMemory() - runtime.freeMemory();
System.out.println("Used memory in bytes: " + firstUsageMemory);
System.out.println(str);
str = new StringBuffer(str).reverse().toString();
int count = 0;
int preValue = 0;
int lastspaceIndexVal = str.lastIndexOf(" ");
int strLen = str.length();
for (int i = 0; i < strLen - 1; i++) {
if (Character.isWhitespace(str.charAt(i))) {
if (i - preValue == 1 && count == 0) {
str = str.substring(0, preValue) + str.charAt(i - 1)
+ str.substring(i, strLen);
preValue = i;
count++;
} else if (i - preValue == 2 && count == 0) {
str = str.substring(0, preValue) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.substring(i, strLen);
preValue = i;
count++;
} else if (i - preValue == 3 && count == 0) {
str = str.substring(0, preValue) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.charAt(i - 3)
+ str.substring(i, strLen);
preValue = i;
count++;
} else if (i - preValue == 4 && count == 0) {
str = str.substring(0, preValue) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.charAt(i - 3)
+ str.charAt(i - 4) + str.substring(i, strLen);
preValue = i;
count++;
} else if (i - preValue == 5 && count == 0) {
str = str.substring(0, preValue) + str.charAt(i - 1)
+ str.substring(i - 2, i - 1) + str.charAt(i - 3)
+ str.charAt(i - 3) + str.charAt(i - 5)
+ str.substring(i, strLen);
preValue = i;
count++;
} else if (i - preValue == 6 && count == 0) {
str = str.substring(0, preValue) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.charAt(i - 3)
+ str.charAt(i - 4) + str.charAt(i - 5)
+ str.charAt(i - 6) + str.substring(i, strLen);
preValue = i;
count++;
} else if (i - preValue == 7 && count == 0) {
str = str.substring(0, preValue) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.charAt(i - 3)
+ str.charAt(i - 4) + str.charAt(i - 5)
+ str.charAt(i - 6) + str.charAt(i - 7)
+ str.substring(i, strLen);
preValue = i;
count++;
} else if (i - preValue == 8 && count == 0) {
str = str.substring(0, preValue) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.charAt(i - 3)
+ str.charAt(i - 4) + str.charAt(i - 5)
+ str.charAt(i - 6) + str.charAt(i - 7)
+ str.charAt(i - 8) + str.substring(i, strLen);
preValue = i;
count++;
} else if (i - preValue == 2 && count != 0) {
str = str.substring(0, preValue) + str.charAt(i - 1)
+ str.substring(i, strLen);
preValue = i;
} else if (i - preValue == 3 && count != 0) {
str = str.substring(0, preValue + 1) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.substring(i, strLen);
preValue = i;
} else if (i - preValue == 4 && count != 0) {
str = str.substring(0, preValue + 1) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.charAt(i - 3)
+ str.substring(i, strLen);
preValue = i;
} else if (i - preValue == 5 && count != 0) {
str = str.substring(0, preValue + 1) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.charAt(i - 3)
+ str.charAt(i - 4) + str.substring(i, strLen);
preValue = i;
count++;
} else if (i - preValue == 6 && count != 0) {
str = str.substring(0, preValue + 1) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.charAt(i - 3)
+ str.charAt(i - 4) + str.charAt(i - 5)
+ str.substring(i, strLen);
preValue = i;
count++;
} else if (i - preValue == 7 && count != 0) {
str = str.substring(0, preValue + 1) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.charAt(i - 3)
+ str.charAt(i - 4) + str.charAt(i - 5)
+ str.charAt(i - 6) + str.substring(i, strLen);
preValue = i;
count++;
} else if (i - preValue == 8 && count != 0) {
str = str.substring(0, preValue + 1) + str.charAt(i - 1)
+ str.charAt(i - 2) + str.charAt(i - 3)
+ str.charAt(i - 4) + str.charAt(i - 5)
+ str.charAt(i - 6) + str.charAt(i - 7)
+ str.substring(i, strLen);
preValue = i;
count++;
}
if (lastspaceIndexVal == preValue) {
if (strLen - lastspaceIndexVal == 2 && count != 0) {
str = str.substring(0, preValue + 1)
+ str.charAt(strLen - 1);
preValue = i;
} else if (strLen - lastspaceIndexVal == 3 && count != 0) {
str = str.substring(0, preValue + 1)
+ str.charAt(strLen - 1)
+ str.charAt(strLen - 2);
preValue = i;
} else if (strLen - lastspaceIndexVal == 4 && count != 0) {
str = str.substring(0, preValue + 1)
+ str.charAt(strLen - 1)
+ str.charAt(strLen - 2)
+ str.charAt(strLen - 3);
preValue = i;
count++;
} else if (strLen - lastspaceIndexVal == 5 && count != 0) {
str = str.substring(0, preValue + 1)
+ str.charAt(strLen - 1)
+ str.charAt(strLen - 2)
+ str.charAt(strLen - 3)
+ str.charAt(strLen - 4);
preValue = i;
} else if (strLen - lastspaceIndexVal == 6 && count != 0) {
str = str.substring(0, preValue + 1)
+ str.charAt(strLen - 1)
+ str.charAt(strLen - 2)
+ str.charAt(strLen - 3)
+ str.charAt(strLen - 4)
+ str.charAt(strLen - 5);
preValue = i;
count++;
} else if (strLen - lastspaceIndexVal == 7 && count != 0) {
str = str.substring(0, preValue + 1)
+ str.charAt(strLen - 1)
+ str.charAt(strLen - 2)
+ str.charAt(strLen - 3)
+ str.charAt(strLen - 4)
+ str.charAt(strLen - 5)
+ str.charAt(strLen - 6);
preValue = i;
} else if (strLen - lastspaceIndexVal == 8 && count != 0) {
str = str.substring(0, preValue + 1)
+ str.charAt(strLen - 1)
+ str.charAt(strLen - 2)
+ str.charAt(strLen - 3)
+ str.charAt(strLen - 4)
+ str.charAt(strLen - 5)
+ str.charAt(strLen - 6)
+ str.charAt(strLen - 7);
preValue = i;
}
}
}
}
runtime.gc();
// Calculate the used memory
long SecondaryUsageMemory = runtime.totalMemory()
- runtime.freeMemory();
System.out.println("Used memory in bytes: " + SecondaryUsageMemory);
System.out.println(str);
}
}
Convert Char to String in C
To answer the question without reading too much else into it i would
char str[2] = "\0"; /* gives {\0, \0} */
str[0] = fgetc(fp);
You could use the second line in a loop with what ever other string operations you want to keep using char's as strings.
Do you use source control for your database items?
Yes, always. You should be able to recreate your production database structure with a useful set of sample data whenever needed. If you don't, over time minor changes to keep things running get forgotten then one day you get bitten, big time. Its insurance that you might not think you need but the day you do it it worth the price 10 times over!
getActivity() returns null in Fragment function
The other answers that suggest keeping a reference to the activity in onAttach are just suggesting a bandaid to the real problem. When getActivity returns null it means that the Fragment is not attached to the Activity. Most commonly this happens when the Activity has gone away due to rotation or the Activity being finished but the Fragment still has some kind of callback listener registered. When the listener gets called if you need to do something with the Activity but the Activity is gone there isn't much you can do. In your code you should just check getActivity() != null
and if it's not there then don't do anything. If you keep a reference to the Activity that is gone you are preventing the Activity from being garbage collected. Any UI things you might try to do won't be seen by the user. I can imagine some situations where in the callback listener you want to have a Context for something non-UI related, in those cases it probably makes more sense to get the Application context. Note that the only reason that the onAttach
trick isn't a big memory leak is because normally after the callback listener executes it won't be needed anymore and can be garbage collected along with the Fragment, all its View's and the Activity context. If you setRetainInstance(true)
there is a bigger chance of a memory leak because the Activity field will also be retained but after rotation that could be the previous Activity not the current one.
Android: Test Push Notification online (Google Cloud Messaging)
POSTMAN : A google chrome extension
Use postman to send message instead of server. Postman settings are as follows :
Request Type: POST
URL: https://android.googleapis.com/gcm/send
Header
Authorization : key=your key //Google API KEY
Content-Type : application/json
JSON (raw) :
{
"registration_ids":["yours"],
"data": {
"Hello" : "World"
}
}
on success you will get
Response :
{
"multicast_id": 6506103988515583000,
"success": 1,
"failure": 0,
"canonical_ids": 0,
"results": [
{
"message_id": "0:1432811719975865%54f79db3f9fd7ecd"
}
]
}
C++ compiling on Windows and Linux: ifdef switch
I know it is not answer but added if someone looking same in Qt
In Qt
https://wiki.qt.io/Get-OS-name-in-Qt
QString Get::osName()
{
#if defined(Q_OS_ANDROID)
return QLatin1String("android");
#elif defined(Q_OS_BLACKBERRY)
return QLatin1String("blackberry");
#elif defined(Q_OS_IOS)
return QLatin1String("ios");
#elif defined(Q_OS_MAC)
return QLatin1String("osx");
#elif defined(Q_OS_WINCE)
return QLatin1String("wince");
#elif defined(Q_OS_WIN)
return QLatin1String("windows");
#elif defined(Q_OS_LINUX)
return QLatin1String("linux");
#elif defined(Q_OS_UNIX)
return QLatin1String("unix");
#else
return QLatin1String("unknown");
#endif
}
PHP - Insert date into mysql
How to debug SQL queries when you stuck
Print you query and run it directly in mysql or phpMyAdmin
$date = "2012-08-06";
$query= "INSERT INTO data_table (title, date_of_event)
VALUES('". $_POST['post_title'] ."',
'". $date ."')";
echo $query;
mysql_query($query) or die(mysql_error());
that way you can make sure that the problem is not in your PHP-script, but in your SQL-query
How to submit questions on SQ-queries
Make sure that you provided enough closure
- Table schema
- Query
- Error message is any
How do I filter query objects by date range in Django?
You can get around the "impedance mismatch" caused by the lack of precision in the DateTimeField/date
object comparison -- that can occur if using range -- by using a datetime.timedelta to add a day to last date in the range. This works like:
start = date(2012, 12, 11)
end = date(2012, 12, 18)
new_end = end + datetime.timedelta(days=1)
ExampleModel.objects.filter(some_datetime_field__range=[start, new_end])
As discussed previously, without doing something like this, records are ignored on the last day.
Edited to avoid the use of datetime.combine
-- seems more logical to stick with date instances when comparing against a DateTimeField
, instead of messing about with throwaway (and confusing) datetime
objects. See further explanation in comments below.
How can I test a PDF document if it is PDF/A compliant?
If you download the latest version of Adobe Acrobat Reader, it will tell you if your pdf is PDF/A compliant. Just open the PDF file and a big blue marking should appear.
OpenOffice supports PDF/A.
For some reason "PDF/A-1" is called
"SelectPdfVersion"
internally in OpenOffice.
Just add 1 to that value and your output should be PDF/A.
The different values can be
0 = PDFXNONE
1 = PDFX1A2001
2 = PDFX32002
3 = PDFA1A
4 = PDFA1B
You set
FilterData
to be a
HashMap('SelectPdfVersion',1) //1 for PDFX1A2001
Using a different font with twitter bootstrap
The easiest way I've seen is to use Google Fonts.
Go to Google Fonts and choose a font, then Google will give you a link to put in your HTML.
Then add this to your custom.css:
h1, h2, h3, h4, h5, h6 {
font-family: 'Your Font' !important;
}
p, div {
font-family: 'Your Font' !important;
}
or
body {
font-family: 'Your Font' !important;
}
Removing NA observations with dplyr::filter()
From @Ben Bolker:
[T]his has nothing specifically to do with dplyr::filter()
From @Marat Talipov:
[A]ny comparison with NA, including NA==NA, will return NA
From a related answer by @farnsy:
The == operator does not treat NA's as you would expect it to.
Think of NA as meaning "I don't know what's there". The correct answer
to 3 > NA is obviously NA because we don't know if the missing value
is larger than 3 or not. Well, it's the same for NA == NA. They are
both missing values but the true values could be quite different, so
the correct answer is "I don't know."
R doesn't know what you are doing in your analysis, so instead of
potentially introducing bugs that would later end up being published
an embarrassing you, it doesn't allow comparison operators to think NA
is a value.
EnterKey to press button in VBA Userform
Further to @Penn's comment, and in case the link breaks, you can also achieve this by setting the Default
property of the button to True
(you can set this in the properties window, open by hitting F4)
That way whenever Return is hit, VBA knows to activate the button's click event. Similarly setting the Cancel
property of a button to True
would cause that button's click event to run whenever ESC key is hit (useful for gracefully exiting the Userform)
Source: Olivier Jacot-Descombes's answer accessible here https://stackoverflow.com/a/22793040/6609896
relative path in BAT script
Use this in your batch file:
%~dp0\bin\Iris.exe
%~dp0
resolves to the full path of the folder in which the batch script resides.
How to detect running app using ADB command
No need to use grep. ps
in Android can filter by COMM
value (last 15 characters of the package name in case of java app)
Let's say we want to check if com.android.phone
is running:
adb shell ps m.android.phone
USER PID PPID VSIZE RSS WCHAN PC NAME
radio 1389 277 515960 33964 ffffffff 4024c270 S com.android.phone
Filtering by COMM
value option has been removed from ps
in Android 7.0. To check for a running process by name in Android 7.0 you can use pidof
command:
adb shell pidof com.android.phone
It returns the PID if such process was found or an empty string otherwise.
Unable to compile simple Java 10 / Java 11 project with Maven
UPDATE
The answer is now obsolete. See this answer.
maven-compiler-plugin
depends on the old version of ASM which does not support Java 10 (and Java 11) yet. However, it is possible to explicitly specify the right version of ASM:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<release>10</release>
</configuration>
<dependencies>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>6.2</version> <!-- Use newer version of ASM -->
</dependency>
</dependencies>
</plugin>
You can find the latest at https://search.maven.org/search?q=g:org.ow2.asm%20AND%20a:asm&core=gav
How do you store Java objects in HttpSession?
Add it to the session, not to the request.
HttpSession session = request.getSession();
session.setAttribute("object", object);
Also, don't use scriptlets in the JSP. Use EL instead; to access object
all you need is ${object}
.
A primary feature of JSP technology version 2.0 is its support for an expression language (EL). An expression language makes it possible to easily access application data stored in JavaBeans components. For example, the JSP expression language allows a page author to access a bean using simple syntax such as ${name}
for a simple variable or ${name.foo.bar}
for a nested property.
Split text file into smaller multiple text file using command line
Here's an example in C# (cause that's what I was searching for). I needed to split a 23 GB csv-file with around 175 million lines to be able to look at the files. I split it into files of one million rows each. This code did it in about 5 minutes on my machine:
var list = new List<string>();
var fileSuffix = 0;
using (var file = File.OpenRead(@"D:\Temp\file.csv"))
using (var reader = new StreamReader(file))
{
while (!reader.EndOfStream)
{
list.Add(reader.ReadLine());
if (list.Count >= 1000000)
{
File.WriteAllLines(@"D:\Temp\split" + (++fileSuffix) + ".csv", list);
list = new List<string>();
}
}
}
File.WriteAllLines(@"D:\Temp\split" + (++fileSuffix) + ".csv", list);
How do I get the latest version of my code?
I suspect that what's happened may be that you've deleted the files that you modified (because you didn't care about those changes) and now git is taking the deletion to be a change.
Here is an approach that moves your changes out of your working copy and into the "stash" (retrievable should it actually turn out that you ever need them again), so you can then pull the latest changes down from the upstream.
git stash
git pull
If you ever want to retrieve your files (potential conflicts with upstream changes and all), run a git stash apply
to stick those changes on top of your code. That way, you have an "undo" approach.
Vue.js data-bind style backgroundImage not working
Another solution:
<template>
<div :style="cssProps"></div>
</template>
<script>
export default {
data() {
return {
cssProps: {
backgroundImage: `url(${require('@/assets/path/to/your/img.jpg')})`
}
}
}
}
</script>
What makes this solution more convenient?
Firstly, it's cleaner. And then, if you're using Vue CLI (I assume you do), you can load it with webpack.
Note: don't forget that require()
is always relative to the current file's path.
How to change the text color of first select option
I really wanted this (placeholders should look the same for text boxes as select boxes!) and straight CSS wasn't working in Chrome. Here is what I did:
First make sure your select tag has a .has-prompt
class.
Then initialize this class somewhere in document.ready
.
# Adds a class to select boxes that have prompt currently selected.
# Allows for placeholder-like styling.
# Looks for has-prompt class on select tag.
Mess.Views.SelectPromptStyler = Backbone.View.extend
el: 'body'
initialize: ->
@$('select.has-prompt').trigger('change')
events:
'change select.has-prompt': 'changed'
changed: (e) ->
select = @$(e.currentTarget)
if select.find('option').first().is(':selected')
select.addClass('prompt-selected')
else
select.removeClass('prompt-selected')
Then in CSS:
select.prompt-selected {
color: $placeholder-color;
}
How to change font in ipython notebook
I would also suggest that you explore the options offered by the jupyter themer. For more modest interface changes you may be satisfied with running the syntax:
jupyter-themer [-c COLOR, --color COLOR]
[-l LAYOUT, --layout LAYOUT]
[-t TYPOGRAPHY, --typography TYPOGRAPHY]
where the options offered by themer would provide you with a less onerous way of making some changes in to the look of Jupyter Notebook. Naturally, you may still to prefer edit the .css
files if the changes you want to apply are elaborate.
How to add many functions in ONE ng-click?
Try this:
- Make a collection of functions
- Make a function that loops through and executes all the functions in the collection.
- Add the function to the html
array = [
function() {},
function() {},
function() {}
]
function loop() {
array.forEach(item) {
item()
}
}
ng - click = "loop()"
php function mail() isn't working
I think you are not configured properly,
if you are using XAMPP then you can easily send mail from localhost.
for example you can configure C:\xampp\php\php.ini
and c:\xampp\sendmail\sendmail.ini
for gmail to send mail.
in C:\xampp\php\php.ini
find extension=php_openssl.dll
and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.
in php.ini file find [mail function]
and change
SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"
(use the above send mail path only and it will work)
Now Open C:\xampp\sendmail\sendmail.ini
. Replace all the existing code in sendmail.ini with following code
[sendmail]
smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=my-gmail-password
[email protected]
Now you have done!! create php file with mail function and send mail from localhost.
Update
First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()
).
You can set the following settings in your PHP.ini:
ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");
getting " (1) no such column: _id10 " error
I think you missed a equal sign at:
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);
Change to:
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null);
H.264 file size for 1 hr of HD video
I'm a friend of keeping the original files, so that you can still use the archived original ones and do new encodes from these fresh ones when the old transcodes are out of date.
eg. migrating them from previously transocded mpeg2-hd to mpeg4-hd (and perhaps from mpeg4-hd to its successor in sometime). but all of these should be done from the original.
any compression step will followed by a loss of quality.
it will need some time to redo this again, but in my opinion it's worth the effort.
so, if you want to keep the originals, you can use the running time in seconds of you tapes times the maximum datarate of hdv (constants 27mbit/s I think) to get your needed storage capacity
How to start MySQL with --skip-grant-tables?
if you are running on Apple MacBook OSX
then:
- Stop your MySQL server (if it is already running).
- Find your MySQL configuration file,
my.cnf
. (For me it was placed @
/Applications/XAMPP/xamppfiles/etc
. You can just search if you
can't find it).
- Open
my.cnf
file in any text editor.
- Add
"skip-grant-tables"
(without quotes) at the end of [mysqld]
section and save the file.
- Now start your MySQL server. It'll start with
skip-grant-tables
option.
Do what you want now!!
PS: Please remove skip-grant-tables
from my.cnf
file once you are done with whatsoever you want to do ELSE MySQL server will always run without access grants.
Does calling clone() on an array also clone its contents?
1D array of primitives does copy elements when it is cloned. This tempts us to clone 2D array(Array of Arrays).
Remember that 2D array clone doesn't work due to shallow copy implementation of clone()
.
public static void main(String[] args) {
int row1[] = {0,1,2,3};
int row2[] = row1.clone();
row2[0] = 10;
System.out.println(row1[0] == row2[0]); // prints false
int table1[][]={{0,1,2,3},{11,12,13,14}};
int table2[][] = table1.clone();
table2[0][0] = 100;
System.out.println(table1[0][0] == table2[0][0]); //prints true
}
Floating elements within a div, floats outside of div. Why?
You can easily do with first you can make the div flex and apply justify content right or left and your problem is solved.
_x000D_
_x000D_
<div style="display: flex;padding-bottom: 8px;justify-content: flex-end;">_x000D_
<button style="font-weight: bold;outline: none;background-color: #2764ff;border-radius: 3px;margin-left: 12px;border: none;padding: 3px 6px;color: white;text-align: center;font-family: 'Open Sans', sans-serif;text-decoration: none;margin-right: 14px;">Sense</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_
PHP equivalent of .NET/Java's toString()
If you're converting anything other than simple types like integers or booleans, you'd need to write your own function/method for the type that you're trying to convert, otherwise PHP will just print the type (such as array, GoogleSniffer, or Bidet).
Clicking a button within a form causes page refresh
If you have a look at the W3C specification, it would seem like the obvious thing to try is to mark your button elements with type='button'
when you don't want them to submit.
The thing to note in particular is where it says
A button element with no type attribute specified represents the same thing as a button element with its type attribute set to "submit"
SQL Server - boolean literal?
This isn't mentioned in any of the other answers. If you want a value that orms (should) hydrate as boolean you can use
CONVERT(bit, 0) -- false
CONVERT(bit, 1) -- true
This gives you a bit which is not a boolean. You cannot use that value in an if statement for example:
IF CONVERT(bit, 0)
BEGIN
print 'Yay'
END
woudl not parse. You would still need to write
IF CONVERT(bit, 0) = 0
So its not terribly useful.
R plot: size and resolution
If you'd like to use base graphics, you may have a look at this. An extract:
You can correct this with the res= argument to png, which specifies the number of pixels per inch. The smaller this number, the larger the plot area in inches, and the smaller the text relative to the graph itself.
Group a list of objects by an attribute
Function<Student, List<Object>> compositKey = std ->
Arrays.asList(std.stud_location());
studentList.stream().collect(Collectors.groupingBy(compositKey, Collectors.toList()));
If you want to add multiple objects for group by you can simply add the object in compositKey
method separating by a comma:
Function<Student, List<Object>> compositKey = std ->
Arrays.asList(std.stud_location(),std.stud_name());
studentList.stream().collect(Collectors.groupingBy(compositKey, Collectors.toList()));
How can I remove Nan from list Python/NumPy
import numpy as np
mylist = [3, 4, 5, np.nan]
l = [x for x in mylist if ~np.isnan(x)]
This should remove all NaN. Of course, I assume that it is not a string here but actual NaN (np.nan
).
How to use variables in SQL statement in Python?
cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))
Note that the parameters are passed as a tuple.
The database API does proper escaping and quoting of variables. Be careful not to use the string formatting operator (%
), because
- it does not do any escaping or quoting.
- it is prone to Uncontrolled string format attacks e.g. SQL injection.
How do I uninstall nodejs installed from pkg (Mac OS X)?
This is the full list of commands I used (Many thanks to the posters above):
sudo rm -rf /usr/local/lib/node /usr/local/lib/node_modules /var/db/receipts/org.nodejs.*
sudo rm -rf /usr/local/include/node /Users/$USER/.npm
sudo rm /usr/local/bin/node
sudo rm /usr/local/share/man/man1/node.1
brew install node
How to validate domain credentials?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security;
using System.DirectoryServices.AccountManagement;
public struct Credentials
{
public string Username;
public string Password;
}
public class Domain_Authentication
{
public Credentials Credentials;
public string Domain;
public Domain_Authentication(string Username, string Password, string SDomain)
{
Credentials.Username = Username;
Credentials.Password = Password;
Domain = SDomain;
}
public bool IsValid()
{
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, Domain))
{
// validate the credentials
return pc.ValidateCredentials(Credentials.Username, Credentials.Password);
}
}
}
What are intent-filters in Android?
intent filter is expression which present in manifest in your app that specify the type of intents that the component is to receive.
If component does not have any intent filter it can receive explicit intent.
If component with filter then receive both implicit and explicit intent
How to get the sizes of the tables of a MySQL database?
You can use this query to show the size of a table (although you need to substitute the variables first):
SELECT
table_name AS `Table`,
round(((data_length + index_length) / 1024 / 1024), 2) `Size in MB`
FROM information_schema.TABLES
WHERE table_schema = "$DB_NAME"
AND table_name = "$TABLE_NAME";
or this query to list the size of every table in every database, largest first:
SELECT
table_schema as `Database`,
table_name AS `Table`,
round(((data_length + index_length) / 1024 / 1024), 2) `Size in MB`
FROM information_schema.TABLES
ORDER BY (data_length + index_length) DESC;
adding comment in .properties files
According to the documentation of the PropertyFile
task, you can append the generated properties to an existing file. You could have a properties file with just the comment line, and have the Ant task append the generated properties.
How to get a variable value if variable name is stored as string?
X=foo
Y=X
eval "Z=\$$Y"
sets Z to "foo"
Take care using eval
since this may allow accidential excution of code through values in ${Y}
. This may cause harm through code injection.
For example
Y="\`touch /tmp/eval-is-evil\`"
would create /tmp/eval-is-evil
. This could also be some rm -rf /
, of course.
tsc is not recognized as internal or external command
tsc is not recognized as internal or external command
As mentioned in another answer this is because tsc is not present in path.
1. Install as global package
To make TypeScript compiler available to all directories for this user, run the below command:
npm install -g typescript
You will see something similar to
C:\Users\username\AppData\Roaming\npm\tsserver -> C:\Users\username\AppData\Roaming\npm\node_modules\typescript\bin\tsserver
C:\Users\username\AppData\Roaming\npm\tsc -> C:\Users\username\AppData\Roaming\npm\node_modules\typescript\bin\tsc
+ [email protected]
added 1 package from 1 contributor in 4.769s
2. Set the environment variable
Add the npm installation folder to your "user variables" AND
"environment variables".
In windows you can add environment variable PATH with value
C:\Users\username\AppData\Roaming\npm\
i.e. wherever the npm installation folder is present.
Note: If multiple Paths are present separate them with a ;(semicolon)
If the below command gives the version then you have successfully installed
tsc --version
How to convert java.sql.timestamp to LocalDate (java8) java.time?
The accepted answer is not ideal, so I decided to add my 2 cents
timeStamp.toLocalDateTime().toLocalDate();
is a bad solution in general, I'm not even sure why they added this method to the JDK as it makes things really confusing by doing an implicit conversion using the system timezone. Usually when using only java8 date classes the programmer is forced to specify a timezone which is a good thing.
The good solution is
timestamp.toInstant().atZone(zoneId).toLocalDate()
Where zoneId is the timezone you want to use which is typically either ZoneId.systemDefault() if you want to use your system timezone or some hardcoded timezone like ZoneOffset.UTC
The general approach should be
- Break free to the new java8 date classes using a class that is directly related, e.g. in our case java.time.Instant is directly related to java.sql.Timestamp, i.e. no timezone conversions are needed between them.
- Use the well-designed methods in this java8 class to do the right thing. In our case atZone(zoneId) made it explicit that we are doing a conversion and using a particular timezone for it.
vertical-align image in div
Old question but nowadays CSS3 makes vertical alignment really simple!
Just add to the <div>
this css:
display:flex;
align-items:center;
justify-content:center;
JSFiddle demo
Live Example:
_x000D_
_x000D_
.img_thumb {_x000D_
float: left;_x000D_
height: 120px;_x000D_
margin-bottom: 5px;_x000D_
margin-left: 9px;_x000D_
position: relative;_x000D_
width: 147px;_x000D_
background-color: rgba(0, 0, 0, 0.5);_x000D_
border-radius: 3px;_x000D_
display:flex;_x000D_
align-items:center;_x000D_
justify-content:center;_x000D_
}
_x000D_
<div class="img_thumb">_x000D_
<a class="images_class" href="http://i.imgur.com/2FMLuSn.jpg" rel="images">_x000D_
<img src="http://i.imgur.com/2FMLuSn.jpg" title="img_title" alt="img_alt" />_x000D_
</a>_x000D_
</div>
_x000D_
_x000D_
_x000D_
Force re-download of release dependency using Maven
Go to build path... delete existing maven library u added... click add library ... click maven managed dependencies... then click maven project settings... check resolve maven dependencies check box..it'll download all maven dependencies
Getting the screen resolution using PHP
I don't think you can detect the screen size purely with PHP but you can detect the user-agent..
<?php
if ( stristr($ua, "Mobile" )) {
$DEVICE_TYPE="MOBILE";
}
if (isset($DEVICE_TYPE) and $DEVICE_TYPE=="MOBILE") {
echo '<link rel="stylesheet" href="/css/mobile.css" />'
}
?>
Here's a link to a more detailed script: PHP Mobile Detect
How to auto-size an iFrame?
In IE 5.5+, you can use the contentWindow property:
iframe.height = iframe.contentWindow.document.scrollHeight;
In Netscape 6 (assuming firefox as well), contentDocument property:
iframe.height = iframe.contentDocument.scrollHeight
How to send 500 Internal Server Error error from a PHP script
You can just put:
header("HTTP/1.0 500 Internal Server Error");
inside your conditions like:
if (that happened) {
header("HTTP/1.0 500 Internal Server Error");
}
As for the database query, you can just do that like this:
$result = mysql_query("..query string..") or header("HTTP/1.0 500 Internal Server Error");
You should remember that you have to put this code before any html tag (or output).
Java 8 Lambda function that throws exception?
There are a lot of great responses already posted here. Just attempting to solve the problem with a different perspective. Its just my 2 cents, please correct me if I am wrong somewhere.
Throws clause in FunctionalInterface is not a good idea
I think this is probably not a good idea to enforce throws IOException because of following reasons
This looks to me like an anti-pattern to Stream/Lambda. The whole idea is that the caller will decide what code to provide and how to handle the exception. In many scenarios, the IOException might not be applicable for the client. For example, if the client is getting value from cache/memory instead of performing actual I/O.
Also, the exceptions handling in streams becomes really hideous. For example, here is my code will look like if I use your API
acceptMyMethod(s -> {
try {
Integer i = doSomeOperation(s);
return i;
} catch (IOException e) {
// try catch block because of throws clause
// in functional method, even though doSomeOperation
// might not be throwing any exception at all.
e.printStackTrace();
}
return null;
});
Ugly isn't it? Moreover, as I mentioned in my first point, that the doSomeOperation method may or may not be throwing IOException (depending on the implementation of the client/caller), but because of the throws clause in your FunctionalInterface method, I always have to write the try-catch.
What do I do if I really know this API throws IOException
Then probably we are confusing FunctionalInterface with typical Interfaces. If you know this API will throw IOException, then most probably you also know some default/abstract behavior as well. I think you should define an interface and deploy your library (with default/abstract implementation) as follows
public interface MyAmazingAPI {
Integer myMethod(String s) throws IOException;
}
But, the try-catch problem still exists for the client. If I use your API in stream, I still need to handle IOException in hideous try-catch block.
Provide a default stream-friendly API as follows
public interface MyAmazingAPI {
Integer myMethod(String s) throws IOException;
default Optional<Integer> myMethod(String s, Consumer<? super Exception> exceptionConsumer) {
try {
return Optional.ofNullable(this.myMethod(s));
} catch (Exception e) {
if (exceptionConsumer != null) {
exceptionConsumer.accept(e);
} else {
e.printStackTrace();
}
}
return Optional.empty();
}
}
The default method takes the consumer object as argument, which will be responsible to handle the exception. Now, from client's point of view, the code will look like this
strStream.map(str -> amazingAPIs.myMethod(str, Exception::printStackTrace))
.filter(Optional::isPresent)
.map(Optional::get).collect(toList());
Nice right? Of course, logger or other handling logic could be used instead of Exception::printStackTrace.
You can also expose a method similar to https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html#exceptionally-java.util.function.Function- . Meaning that you can expose another method, which will contain the exception from previous method call. The disadvantage is that you are now making your APIs stateful, which means that you need to handle thread-safety and which will be eventually become a performance hit. Just an option to consider though.
How to send value attribute from radio button in PHP
Check whether you have put name="your_radio" where you have inserted radio tag
if you have done this then check your php code. Use isset()
e.g.
if(isset($_POST['submit']))
{
/*other variables*/
$radio_value = $_POST["your_radio"];
}
If you have done this as well then we need to look through your codes
How to launch PowerShell (not a script) from the command line
If you go to C:\Windows\system32\Windowspowershell\v1.0
(and C:\Windows\syswow64\Windowspowershell\v1.0
on x64 machines) in Windows Explorer and double-click powershell.exe
you will see that it opens PowerShell with a black background. The PowerShell console shows up as blue when opened from the start menu because the console properties for shortcuts to powershell.exe
can be set independently from the default properties.
To set the default options, font, colors and layout, open a PowerShell console, type Alt-Space, and select the Defaults menu option.
Running start powershell
from cmd.exe should start a new console with your default settings.
How to change Screen buffer size in Windows Command Prompt from batch script
I was just searching for an answer to this exact question, come to find out the command itself adjusts the buffer!
mode con:cols=140 lines=70
The lines=70 part actually adjusts the Height in the 'Screen Buffer Size' setting, NOT the Height in the 'Window Size' setting.
Easily proven by running the command with a setting for 'lines=2500' (or whatever buffer you want) and then check the 'Properties' of the window, you'll see that indeed the buffer is now set to 2500.
My batch script ends up looking like this:
@echo off
cmd "mode con:cols=140 lines=2500"
How to set a ripple effect on textview or imageview on Android?
In the case of the well voted solution posted by @Bikesh M Annur (here) doesn't work to you, try using:
<TextView
...
android:background="?android:attr/selectableItemBackgroundBorderless"
android:clickable="true" />
<ImageView
...
android:background="?android:attr/selectableItemBackgroundBorderless"
android:clickable="true" />
Also, when using android:clickable="true"
add android:focusable="true"
because:
"A widget that is declared to be clickable but not declared to be focusable is not accessible via the keyboard."
delete_all vs destroy_all?
You are right. If you want to delete the User and all associated objects -> destroy_all
However, if you just want to delete the User without suppressing all associated objects -> delete_all
According to this post : Rails :dependent => :destroy VS :dependent => :delete_all
destroy
/ destroy_all
: The associated objects are destroyed alongside this object by calling their destroy method
delete
/ delete_all
: All associated objects are destroyed immediately without calling their :destroy method
Javascript seconds to minutes and seconds
For people dropping in hoping for a quick simple and thus short solution to format seconds into M:SS
:
function fmtMSS(s){return(s-(s%=60))/60+(9<s?':':':0')+s}
done..
The function accepts either a Number
(preferred) or a String
(2 conversion 'penalties' which you can halve by prepending +
in the function call's argument for s
as in: fmtMSS(+strSeconds)
), representing positive integer seconds s
as argument.
Examples:
fmtMSS( 0 ); // 0:00
fmtMSS( '8'); // 0:08
fmtMSS( 9 ); // 0:09
fmtMSS( '10'); // 0:10
fmtMSS( 59 ); // 0:59
fmtMSS( +'60'); // 1:00
fmtMSS( 69 ); // 1:09
fmtMSS( 3599 ); // 59:59
fmtMSS('3600'); // 60:00
fmtMSS('3661'); // 61:01
fmtMSS( 7425 ); // 123:45
Breakdown:
function fmtMSS(s){ // accepts seconds as Number or String. Returns m:ss
return( s - // take value s and subtract (will try to convert String to Number)
( s %= 60 ) // the new value of s, now holding the remainder of s divided by 60
// (will also try to convert String to Number)
) / 60 + ( // and divide the resulting Number by 60
// (can never result in a fractional value = no need for rounding)
// to which we concatenate a String (converts the Number to String)
// who's reference is chosen by the conditional operator:
9 < s // if seconds is larger than 9
? ':' // then we don't need to prepend a zero
: ':0' // else we do need to prepend a zero
) + s ; // and we add Number s to the string (converting it to String as well)
}
Note: Negative range could be added by prepending (0>s?(s=-s,'-'):'')+
to the return expression (actually, (0>s?(s=-s,'-'):0)+
would work as well).
Bootstrap select dropdown list placeholder
If you are initializing the select field through javascript, the following can be added to replace the default placeholder text
noneSelectedText: 'Insert Placeholder text'
example: if you have:
<select class='picker'></select>
in your javascript, you initialize the selectpicker like this
$('.picker').selectpicker({noneSelectedText: 'Insert Placeholder text'});
Using GCC to produce readable assembly?
You can use gdb for this like objdump.
This excerpt is taken from http://sources.redhat.com/gdb/current/onlinedocs/gdb_9.html#SEC64
Here is an example showing mixed source+assembly for Intel x86:
(gdb) disas /m main
Dump of assembler code for function main:
5 {
0x08048330 : push %ebp
0x08048331 : mov %esp,%ebp
0x08048333 : sub $0x8,%esp
0x08048336 : and $0xfffffff0,%esp
0x08048339 : sub $0x10,%esp
6 printf ("Hello.\n");
0x0804833c : movl $0x8048440,(%esp)
0x08048343 : call 0x8048284
7 return 0;
8 }
0x08048348 : mov $0x0,%eax
0x0804834d : leave
0x0804834e : ret
End of assembler dump.
Can you use if/else conditions in CSS?
CSS has a feature: Conditional Rules. This feature of CSS is applied based on a specific condition. Conditional Rules are:
- @supports
- @media
- @document
Syntax:
@supports ("condition") {
/* your css style */
}
Example code snippet:
_x000D_
_x000D_
<!DOCTYPE html>
<html>
<head>
<title>Supports Rule</title>
<style>
@supports (display: block) {
section h1 {
background-color: pink;
color: white;
}
section h2 {
background-color: pink;
color: black;
}
}
</style>
</head>
<body>
<section>
<h1>Stackoverflow</h1>
<h2>Stackoverflow</h2>
</section>
</body>
</html>
_x000D_
_x000D_
_x000D_
How to post object and List using postman
I also had a similar question, sharing the below example if it helps.
My Controller:
@RequestMapping(value = {"/batchDeleteIndex"}, method = RequestMethod.POST)
@ResponseBody
public BaseResponse batchDeleteIndex(@RequestBody List<String> datasetQnames)
Postman:
Set the Body type to raw and add header Content-Type: application/json
["aaa","bbb","ccc"]
Imported a csv-dataset to R but the values becomes factors
When importing csv data files the import command should reflect both the data seperation between each column (;) and the float-number seperator for your numeric values (for numerical variable = 2,5 this would be ",").
The command for importing a csv, therefore, has to be a bit more comprehensive with more commands:
stuckey <- read.csv2("C:/kalle/R/stuckey.csv", header=TRUE, sep=";", dec=",")
This should import all variables as either integers or numeric.
Insert all values of a table into another table in SQL
There is an easier way where you don't have to type any code (Ideal for Testing or One-time updates):
Step 1
- Right click on table in the explorer and select "Edit top 100 rows";
Step 2
- Then you can select the rows that you want (Ctrl + Click or Ctrl + A), and Right click and Copy
(Note: If you want to add a "where" condition, then Right Click on Grid -> Pane -> SQL
Now you can edit Query and add WHERE condition, then Right Click again -> Execute SQL, your required rows will be available to select on bottom)
Step 3
- Follow Step 1 for the target table.
Step 4
- Now go to the end of the grid and the last row will have an asterix (*) in first column (This row is to add new entry). Click on that to select that entire row and then PASTE (Ctrl + V). The cell might have a Red Asterix (indicating that it is not saved)
Step 5
- Click on any other row to trigger the insert statement (the Red Asterix will disappear)
Note - 1: If the columns are not in the correct order as in Target table, you can always follow Step 2, and Select the Columns in the same order as in the Target table
Note - 2 - If you have Identity columns then execute SET IDENTITY_INSERT sometableWithIdentity ON
and then follow above steps, and in the end execute SET IDENTITY_INSERT sometableWithIdentity OFF
Simple 3x3 matrix inverse code (C++)
I went ahead and wrote it in python since I think it's a lot more readable than in c++ for a problem like this. The function order is in order of operations for solving this by hand via this video. Just import this and call "print_invert" on your matrix.
def print_invert (matrix):
i_matrix = invert_matrix (matrix)
for line in i_matrix:
print (line)
return
def invert_matrix (matrix):
determinant = str (determinant_of_3x3 (matrix))
cofactor = make_cofactor (matrix)
trans_matrix = transpose_cofactor (cofactor)
trans_matrix[:] = [[str (element) +'/'+ determinant for element in row] for row in trans_matrix]
return trans_matrix
def determinant_of_3x3 (matrix):
multiplication = 1
neg_multiplication = 1
total = 0
for start_column in range (3):
for row in range (3):
multiplication *= matrix[row][(start_column+row)%3]
neg_multiplication *= matrix[row][(start_column-row)%3]
total += multiplication - neg_multiplication
multiplication = neg_multiplication = 1
if total == 0:
total = 1
return total
def make_cofactor (matrix):
cofactor = [[0,0,0],[0,0,0],[0,0,0]]
matrix_2x2 = [[0,0],[0,0]]
# For each element in matrix...
for row in range (3):
for column in range (3):
# ...make the 2x2 matrix in this inner loop
matrix_2x2 = make_2x2_from_spot_in_3x3 (row, column, matrix)
cofactor[row][column] = determinant_of_2x2 (matrix_2x2)
return flip_signs (cofactor)
def make_2x2_from_spot_in_3x3 (row, column, matrix):
c_count = 0
r_count = 0
matrix_2x2 = [[0,0],[0,0]]
# ...make the 2x2 matrix in this inner loop
for inner_row in range (3):
for inner_column in range (3):
if row is not inner_row and inner_column is not column:
matrix_2x2[r_count % 2][c_count % 2] = matrix[inner_row][inner_column]
c_count += 1
if row is not inner_row:
r_count += 1
return matrix_2x2
def determinant_of_2x2 (matrix):
total = matrix[0][0] * matrix [1][1]
return total - (matrix [1][0] * matrix [0][1])
def flip_signs (cofactor):
sign_pos = True
# For each element in matrix...
for row in range (3):
for column in range (3):
if sign_pos:
sign_pos = False
else:
cofactor[row][column] *= -1
sign_pos = True
return cofactor
def transpose_cofactor (cofactor):
new_cofactor = [[0,0,0],[0,0,0],[0,0,0]]
for row in range (3):
for column in range (3):
new_cofactor[column][row] = cofactor[row][column]
return new_cofactor
Can you delete data from influxdb?
Because InfluxDB is a bit painful about deletes, we use a schema that has a boolean field called "ForUse", which looks like this when posting via the line protocol (v0.9):
your_measurement,your_tag=foo ForUse=TRUE,value=123.5 1262304000000000000
You can overwrite the same measurement, tag key, and time with whatever field keys you send, so we do "deletes" by setting "ForUse" to false, and letting retention policy keep the database size under control.
Since the overwrite happens seamlessly, you can retroactively add the schema too. Noice.
Getting a Request.Headers value
The following code should allow you to check for the existance of the header you're after in Request.Headers
:
if (Request.Headers.AllKeys.Contains("XYZComponent"))
{
// Can now check if the value is true:
var value = Convert.ToBoolean(Request.Headers["XYZComponent"]);
}
Is header('Content-Type:text/plain'); necessary at all?
no its not like that,here is Example for the support of my answer ---->the clear difference is visible ,when you go for HTTP Compression,which allows you to compress the data while travelling from Server to Client and the Type of this data automatically becomes as "gzip" which Tells browser that bowser got a zipped data and it has to upzip it,this is a example where Type really matters at Bowser.
HTML Form Redirect After Submit
Try this Javascript (jquery) code. Its an ajax request to an external URL. Use the callback function to fire any code:
<script type="text/javascript">
$(function() {
$('form').submit(function(){
$.post('http://example.com/upload', function() {
window.location = 'http://google.com';
});
return false;
});
});
</script>
Using BeautifulSoup to search HTML for string
text='Python'
searches for elements that have the exact text you provided:
import re
from BeautifulSoup import BeautifulSoup
html = """<p>exact text</p>
<p>almost exact text</p>"""
soup = BeautifulSoup(html)
print soup(text='exact text')
print soup(text=re.compile('exact text'))
Output
[u'exact text']
[u'exact text', u'almost exact text']
"To see if the string 'Python' is located on the page http://python.org":
import urllib2
html = urllib2.urlopen('http://python.org').read()
print 'Python' in html # -> True
If you need to find a position of substring within a string you could do html.find('Python')
.
File.separator vs FileSystem.getSeparator() vs System.getProperty("file.separator")?
If your code doesn't cross filesystem boundaries, i.e. you're just working with one filesystem, then use java.io.File.separator
.
This will, as explained, get you the default separator for your FS. As Bringer128 explained, System.getProperty("file.separator")
can be overriden via command line options and isn't as type safe as java.io.File.separator
.
The last one, java.nio.file.FileSystems.getDefault().getSeparator();
was introduced in Java 7, so you might as well ignore it for now if you want your code to be portable across older Java versions.
So, every one of these options is almost the same as others, but not quite. Choose one that suits your needs.
django MultiValueDictKeyError error, how do I deal with it
First check if the request object have the 'is_private' key parameter.
Most of the case's this MultiValueDictKeyError occurred for missing
key in the dictionary-like request object. Because dictionary is an
unordered key, value pair “associative memories” or “associative
arrays”
In another word. request.GET or request.POST is a dictionary-like
object containing all request parameters. This is specific to Django.
The method get() returns a value for the given key if key is in the
dictionary. If key is not available then returns default value None.
You can handle this error by putting :
is_private = request.POST.get('is_private', False);
Passing arguments to angularjs filters
You can simply do like this
In Template
<span ng-cloak>{{amount |firstFiler:'firstArgument':'secondArgument' }}</span>
In filter
angular.module("app")
.filter("firstFiler",function(){
console.log("filter loads");
return function(items, firstArgument,secondArgument){
console.log("item is ",items); // it is value upon which you have to filter
console.log("firstArgument is ",firstArgument);
console.log("secondArgument ",secondArgument);
return "hello";
}
});
What do the different readystates in XMLHttpRequest mean, and how can I use them?
Original definitive documentation
0
, 1
and 2
only track how many of the necessary methods to make a request you've called so far.
3
tells you that the server's response has started to come in. But when you're using the XMLHttpRequest
object from a web page there's almost nothing(*) you can do with that information, since you don't have access to the extended properties that allow you to read the partial data.
readyState 4
is the only one that holds any meaning.
(*: about the only conceivable use I can think of for checking for readyState 3
is that it signals some form of life at the server end, so you could possibly increase the amount of time you wait for a full response when you receive it.)
Ruby on Rails - Import Data from a CSV file
The smarter_csv
gem was specifically created for this use-case: to read data from CSV file and quickly create database entries.
require 'smarter_csv'
options = {}
SmarterCSV.process('input_file.csv', options) do |chunk|
chunk.each do |data_hash|
Moulding.create!( data_hash )
end
end
You can use the option chunk_size
to read N csv-rows at a time, and then use Resque in the inner loop to generate jobs which will create the new records, rather than creating them right away - this way you can spread the load of generating entries to multiple workers.
See also:
https://github.com/tilo/smarter_csv
Getting Excel to refresh data on sheet from within VBA
You might also try
Application.CalculateFull
or
Application.CalculateFullRebuild
if you don't mind rebuilding all open workbooks, rather than just the active worksheet. (CalculateFullRebuild
rebuilds dependencies as well.)
keytool error bash: keytool: command not found
Ensure jre is installed.
cd /path/to/jre/bin/folder
As keytool file is present in the bin folder of jre, give path till bin as in the command above.
Then you can do:
keytool -genkey -alias aliaskeyname -keyalg RSA -keystore C:\mykeystore
The additional option -keystore will help you to specify the path where you want the generated self signed certificate.
How to overlay density plots in R?
That's how I do it in base (it's actually mentionned in the first answer comments but I'll show the full code here, including legend as I can not comment yet...)
First you need to get the info on the max values for the y axis from the density plots. So you need to actually compute the densities separately first
dta_A <- density(VarA, na.rm = TRUE)
dta_B <- density(VarB, na.rm = TRUE)
Then plot them according to the first answer and define min and max values for the y axis that you just got. (I set the min value to 0)
plot(dta_A, col = "blue", main = "2 densities on one plot"),
ylim = c(0, max(dta_A$y,dta_B$y)))
lines(dta_B, col = "red")
Then add a legend to the top right corner
legend("topright", c("VarA","VarB"), lty = c(1,1), col = c("blue","red"))
Matplotlib different size subplots
Probably the simplest way is using subplot2grid
, described in Customizing Location of Subplot Using GridSpec.
ax = plt.subplot2grid((2, 2), (0, 0))
is equal to
import matplotlib.gridspec as gridspec
gs = gridspec.GridSpec(2, 2)
ax = plt.subplot(gs[0, 0])
so bmu's example becomes:
import numpy as np
import matplotlib.pyplot as plt
# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)
# plot it
fig = plt.figure(figsize=(8, 6))
ax0 = plt.subplot2grid((1, 3), (0, 0), colspan=2)
ax0.plot(x, y)
ax1 = plt.subplot2grid((1, 3), (0, 2))
ax1.plot(y, x)
plt.tight_layout()
plt.savefig('grid_figure.pdf')
HTML form readonly SELECT tag/input
You can re-enable the select object on submit.
EDIT: i.e., normally disabling the select tag (with the disabled attribute) and then re-enabling it automatically just before submiting the form:
Example with jQuery:
To disable it:
$('#yourSelect').prop('disabled', true);
To re-enable it before submission so that GET / POST data is included:
$('#yourForm').on('submit', function() {
$('#yourSelect').prop('disabled', false);
});
In addition, you could re-enable every disabled input or select:
$('#yourForm').on('submit', function() {
$('input, select').prop('disabled', false);
});
WITH (NOLOCK) vs SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
They are the same thing. If you use the set transaction isolation level
statement, it will apply to all the tables in the connection, so if you only want a nolock
on one or two tables use that; otherwise use the other.
Both will give you dirty reads. If you are okay with that, then use them. If you can't have dirty reads, then consider snapshot
or serializable
hints instead.
.Net picking wrong referenced assembly version
This isn't a clear answer as to why, but we had this problem, here's our circumstances and what solved it:
Dev 1:
Solution contains Project A referencing a NuGet Package, and an MVC project referencing Project A. Enabled NuGet Package Restore, then updated the NuGet package. Got a runtime error complaining the NuGet lib can't be found - but the error is it looking for the older, non-updated version. Solution (and this is ridiculous): Set a breakpoint on the first line of code in the MVC project that calls Project A. Step in with F11. Solved - never had a problem again.
Dev 2:
Same solution and projects, but the magic set breakpoint and step in solution doesn't work. Looked everywhere for version redirects or other bad references to this Nuget package, removed package and reinstalled it, wiped bin, obj, Asp.Net Temp, nothing solved it. Finally, renamed Project A, ran the MVC project - fixed. Renamed it back to its original name, it stayed fixed.
I don't have any explanation for why that worked, but it did get us out of a serious lurch.
Call to undefined function oci_connect()
Things to Make sure
- Whenever you connecting Oracle Database , try to use 32 Bit oracle client libraries, Since XAMP PHP is compiled with 32 Bit(Though you have 64 Bit windows Machine)
Download Oracle Client from Download From here
Paste it in C:\instantclient_12_1
- Then Set the path to above in System Environment Variable
- Then Go to C:\xampp\php\php.ini and uncomment extension=php_oci8_12c.dll
- Then Restart the XAMP and it should work without any Issue.
Rails: How do I create a default value for attributes in Rails activerecord's model?
For column types Rails supports out of the box - like the string in this question - the best approach is to set the column default in the database itself as Daniel Kristensen indicates. Rails will introspect on the DB and initialize the object accordingly. Plus, that makes your DB safe from somebody adding a row outside of your Rails app and forgetting to initialize that column.
For column types Rails doesn't support out of the box - e.g. ENUM columns - Rails won't be able to introspect the column default. For these cases you do not want to use after_initialize (it is called every time an object is loaded from the DB as well as every time an object is created using .new), before_create (because it occurs after validation), or before_save (because it occurs upon update too, which is usually not what you want).
Rather, you want to set the attribute in a before_validation on: create, like so:
before_validation :set_status_because_rails_cannot, on: :create
def set_status_because_rails_cannot
self.status ||= 'P'
end
How do I keep two side-by-side divs the same height?
You can use Jquery's Equal Heights Plugin to accomplish, this plugins makes all the div of exact same height as other. If one of them grows and other will also grow.
Here a sample of implementation
Usage: $(object).equalHeights([minHeight], [maxHeight]);
Example 1: $(".cols").equalHeights();
Sets all columns to the same height.
Example 2: $(".cols").equalHeights(400);
Sets all cols to at least 400px tall.
Example 3: $(".cols").equalHeights(100,300);
Cols are at least 100 but no more than 300 pixels tall. Elements with too much content will gain a scrollbar.
Here is the link
http://www.cssnewbie.com/equalheights-jquery-plugin/