Unable to make the session state request to the session state server
I've found that some developers will for some reason define the server's private IP outside of IIS in an unexpected location, like a nonstandard config file (i.e. not web.config) or a text file. This can cause internal operation to fail even when the service is started, ports aren't being blocked, reg keys are correct, etc.
Kaseya, in particular, places a file called serveripinternal.txt in the root IIS directory of the VSA server. I've seen the text of your error when somebody running their own Kaseya instance changed the server's internal IP. The server will be reachable, IIS will respond, and the login page will come up - but login will fail with the cited message.
Cannot import the keyfile 'blah.pfx' - error 'The keyfile may be password protected'
I reselected the Key(pfx) file in the "Choose a Strong Name Key File" drop-down box, Then provided password in the "ENTER PASSWORD" Popup Window. Saved my project and did rebuild.build succeeded.
- Open Project Properties.
- Click on the Signing section.
- Where it says ‘Choose a strong name key file:’, reselect the current value from the drop-down box:
- Visual Studio will now prompt you for the password. Enter it.
Save your project and do a rebuild.
If get error message:”An attempt was made to reference a token that does not exist” just ignore it and Continue the below steps
Click the ‘Change Password” button:
Enter the original password in all three boxes and click OK. If you’d like to change your password (or if your old password doesn’t meet complexity requirements), you can do so now.
Save your project and do a rebuild.
More Info..
PageSpeed Insights 99/100 because of Google Analytics - How can I cache GA?
In the Google docs, they've identified a pagespeed
filter that will load the script asynchronously:
ModPagespeedEnableFilters make_google_analytics_async
You can find the documentation here: https://developers.google.com/speed/pagespeed/module/filter-make-google-analytics-async
One thing to highlight is that the filter is considered high risk. From the docs:
The make_google_analytics_async filter is experimental and has not had extensive real-world testing. One case where a rewrite would cause errors is if the filter misses calls to Google Analytics methods that return values. If such methods are found, the rewrite is skipped. However, the disqualifying methods will be missed if they come before the load, are in attributes such as "onclick", or if they are in external resources. Those cases are expected to be rare.
A table name as a variable
You can't use a table name for a variable. You'd have to do this instead:
DECLARE @sqlCommand varchar(1000)
SET @sqlCommand = 'SELECT * from yourtable'
EXEC (@sqlCommand)
XMLHttpRequest Origin null is not allowed Access-Control-Allow-Origin for file:/// to file:/// (Serverless)
use the 'web server for chrome app'. (you actually have it on your pc, wether you know or not. just search it in cortana!). open it and click 'choose file' choose the folder with your file in it. do not actually select your file. select your files folder then click on the link(s) under the 'choose folder' button.
if it doesnt take you to the file, then add the name of the file to the urs. like this:
https://127.0.0.1:8887/fileName.txt
link to web server for chrome: click me
Raise an error manually in T-SQL to jump to BEGIN CATCH block
SQL has an error raising mechanism
RAISERROR ( { msg_id | msg_str | @local_variable }
{ ,severity ,state }
[ ,argument [ ,...n ] ] )
[ WITH option [ ,...n ] ]
Just look up Raiserror in the Books Online. But.. you have to generate an error of the appropriate severity, an error at severity 0 thru 10 do not cause you to jump to the catch block.
Jersey client: How to add a list as query parameter
@GET
does support List of Strings
Setup:
Java : 1.7
Jersey version : 1.9
Resource
@Path("/v1/test")
Subresource:
// receive List of Strings
@GET
@Path("/receiveListOfStrings")
public Response receiveListOfStrings(@QueryParam("list") final List<String> list){
log.info("receieved list of size="+list.size());
return Response.ok().build();
}
Jersey testcase
@Test
public void testReceiveListOfStrings() throws Exception {
WebResource webResource = resource();
ClientResponse responseMsg = webResource.path("/v1/test/receiveListOfStrings")
.queryParam("list", "one")
.queryParam("list", "two")
.queryParam("list", "three")
.get(ClientResponse.class);
Assert.assertEquals(200, responseMsg.getStatus());
}
Can not get a simple bootstrap modal to work
I finally found this solution from "Sven" and solved the problem. what I did was I included "bootstrap.min.js" with:
<script src="bootstrap.min.js"/>
instead of:
<script src="bootstrap.min.js"></script>
and it fixed the problem which looked really odd. can anyone explain why?
No value accessor for form control
For UnitTest angular 2 with angular material you have to add MatSelectModule module in imports section.
import { MatSelectModule } from '@angular/material';
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ CreateUserComponent ],
imports : [ReactiveFormsModule,
MatSelectModule,
MatAutocompleteModule,......
],
providers: [.........]
})
.compileComponents();
}));
How do you change video src using jQuery?
This is working on Flowplayer 6.0.2.
<script>
flowplayer().load({
sources: [
{ type: "video/mp4", src: variable }
]
});
</script>
where variable is a javascript/jquery variable value,
The video tag should be something this
<div class="flowplayer">
<video>
<source type="video/mp4" src="" class="videomp4">
</video>
</div>
Hope it helps anyone.
How to iterate through a list of dictionaries in Jinja template?
Just a side note for similar problem (If we don't want to loop through):
How to lookup a dictionary using a variable key within Jinja template?
Here is an example:
{% set key = target_db.Schema.upper()+"__"+target_db.TableName.upper() %}
{{ dict_containing_df.get(key).to_html() | safe }}
It might be obvious. But we don't need curly braces within curly braces. Straight python syntax works. (I am posting because I was confusing to me...)
Alternatively, you can simply do
{{dict[target_db.Schema.upper()+"__"+target_db.TableName.upper()]).to_html() | safe }}
But it will spit an error when no key is found. So better to use get
in Jinja.
How to get current date in 'YYYY-MM-DD' format in ASP.NET?
Might be worthwhile using the CultureInfo to apply DateTime formatting throughout the website. Insteado f running around formatting whever you have to.
CultureInfo.CurrentUICulture.DateTimeFormat.SetAllDateTimePatterns( ...
or
CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd";
Code should go somewhere in your Global.asax file
protected void Application_Start(){ ...
Check Postgres access for a user
You could query the table_privileges
table in the information schema:
SELECT table_catalog, table_schema, table_name, privilege_type
FROM information_schema.table_privileges
WHERE grantee = 'MY_USER'
What MySQL data type should be used for Latitude/Longitude with 8 decimal places?
Using migrate ruby on rails
class CreateNeighborhoods < ActiveRecord::Migration[5.0]
def change
create_table :neighborhoods do |t|
t.string :name
t.decimal :latitude, precision: 15, scale: 13
t.decimal :longitude, precision: 15, scale: 13
t.references :country, foreign_key: true
t.references :state, foreign_key: true
t.references :city, foreign_key: true
t.timestamps
end
end
end
mysql error 2005 - Unknown MySQL server host 'localhost'(11001)
The case is like :
mysql connects will localhost when network is not up.
mysql cannot connect when network is up.
You can try the following steps to diagnose and resolve the issue (my guess is that some other service is blocking port on which mysql is hosted):
- Disconnect the network.
- Stop mysql service (if windows, try from services.msc window)
- Connect to network.
- Try to start the mysql and see if it starts correctly.
- Check for system logs anyways to be sure that there is no error in starting mysql service.
- If all goes well try connecting.
- If fails, try to do a telnet localhost 3306 and see what output it shows.
- Try changing the port on which mysql is hosted, default 3306, you can change to some other port which is ununsed.
This should ideally resolve the issue you are facing.
plot data from CSV file with matplotlib
According to the docs numpy.loadtxt
is
a fast reader for simply formatted files. The genfromtxt function provides more sophisticated handling of, e.g., lines with missing values.
so there are only a few options to handle more complicated files.
As mentioned numpy.genfromtxt
has more options. So as an example you could use
import numpy as np
data = np.genfromtxt('e:\dir1\datafile.csv', delimiter=',', skip_header=10,
skip_footer=10, names=['x', 'y', 'z'])
to read the data and assign names to the columns (or read a header line from the file with names=True
) and than plot it with
ax1.plot(data['x'], data['y'], color='r', label='the data')
I think numpy is quite well documented now. You can easily inspect the docstrings from within ipython
or by using an IDE like spider
if you prefer to read them rendered as HTML.
Express.js req.body undefined
Building on @kevin-xue said, the content type needs to be declared. In my instance, this was only occurring with IE9 because the XDomainRequest doesn't set a content-type, so bodyparser and expressjs were ignoring the body of the request.
I got around this by setting the content-type explicitly before passing the request through to body parser, like so:
app.use(function(req, res, next) {
// IE9 doesn't set headers for cross-domain ajax requests
if(typeof(req.headers['content-type']) === 'undefined'){
req.headers['content-type'] = "application/json; charset=UTF-8";
}
next();
})
.use(bodyParser.json());
How to Automatically Start a Download in PHP?
Here is an example of sending back a pdf.
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
header('Content-Transfer-Encoding: binary');
readfile($filename);
@Swish I didn't find application/force-download content type to do anything different (tested in IE and Firefox). Is there a reason for not sending back the actual MIME type?
Also in the PHP manual Hayley Watson posted:
If you wish to force a file to be downloaded and saved, instead of being rendered, remember that there is no such MIME type as "application/force-download". The correct type to use in this situation is "application/octet-stream", and using anything else is merely relying on the fact that clients are supposed to ignore unrecognised MIME types and use "application/octet-stream" instead (reference: Sections 4.1.4 and 4.5.1 of RFC 2046).
Also according IANA there is no registered application/force-download type.
Android Room - simple select query - Cannot access database on the main thread
Database access on main thread locking the UI is the error, like Dale said.
--EDIT 2--
Since many people may come across this answer...
The best option nowadays, generally speaking, is Kotlin Coroutines. Room now supports it directly (currently in beta).
https://kotlinlang.org/docs/reference/coroutines-overview.html
https://developer.android.com/jetpack/androidx/releases/room#2.1.0-beta01
--EDIT 1--
For people wondering... You have other options.
I recommend taking a look into the new ViewModel and LiveData components. LiveData works great with Room.
https://developer.android.com/topic/libraries/architecture/livedata.html
Another option is the RxJava/RxAndroid. More powerful but more complex than LiveData.
https://github.com/ReactiveX/RxJava
--Original answer--
Create a static nested class (to prevent memory leak) in your Activity extending AsyncTask.
private static class AgentAsyncTask extends AsyncTask<Void, Void, Integer> {
//Prevent leak
private WeakReference<Activity> weakActivity;
private String email;
private String phone;
private String license;
public AgentAsyncTask(Activity activity, String email, String phone, String license) {
weakActivity = new WeakReference<>(activity);
this.email = email;
this.phone = phone;
this.license = license;
}
@Override
protected Integer doInBackground(Void... params) {
AgentDao agentDao = MyApp.DatabaseSetup.getDatabase().agentDao();
return agentDao.agentsCount(email, phone, license);
}
@Override
protected void onPostExecute(Integer agentsCount) {
Activity activity = weakActivity.get();
if(activity == null) {
return;
}
if (agentsCount > 0) {
//2: If it already exists then prompt user
Toast.makeText(activity, "Agent already exists!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(activity, "Agent does not exist! Hurray :)", Toast.LENGTH_LONG).show();
activity.onBackPressed();
}
}
}
Or you can create a final class on its own file.
Then execute it in the signUpAction(View view) method:
new AgentAsyncTask(this, email, phone, license).execute();
In some cases you might also want to hold a reference to the AgentAsyncTask in your activity so you can cancel it when the Activity is destroyed. But you would have to interrupt any transactions yourself.
Also, your question about the Google's test example...
They state in that web page:
The recommended approach for testing your database implementation is
writing a JUnit test that runs on an Android device. Because these
tests don't require creating an activity, they should be faster to
execute than your UI tests.
No Activity, no UI.
How to unzip gz file using Python
import gzip
import shutil
with gzip.open('file.txt.gz', 'rb') as f_in:
with open('file.txt', 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
How to create new folder?
Have you tried os.mkdir?
You might also try this little code snippet:
mypath = ...
if not os.path.isdir(mypath):
os.makedirs(mypath)
makedirs creates multiple levels of directories, if needed.
Side-by-side plots with ggplot2
In my experience gridExtra:grid.arrange works perfectly, if you are trying to generate plots in a loop.
Short Code Snippet:
gridExtra::grid.arrange(plot1, plot2, ncol = 2)
** Updating this comment to show how to use grid.arrange()
within a for loop to generate plots for different factors of a categorical variable.
for (bin_i in levels(athlete_clean$BMI_cat)) {
plot_BMI <- athlete_clean %>% filter(BMI_cat == bin_i) %>% group_by(BMI_cat,Team) %>% summarize(count_BMI_team = n()) %>%
mutate(percentage_cbmiT = round(count_BMI_team/sum(count_BMI_team) * 100,2)) %>%
arrange(-count_BMI_team) %>% top_n(10,count_BMI_team) %>%
ggplot(aes(x = reorder(Team,count_BMI_team), y = count_BMI_team, fill = Team)) +
geom_bar(stat = "identity") +
theme_bw() +
# facet_wrap(~Medal) +
labs(title = paste("Top 10 Participating Teams with \n",bin_i," BMI",sep=""), y = "Number of Athletes",
x = paste("Teams - ",bin_i," BMI Category", sep="")) +
geom_text(aes(label = paste(percentage_cbmiT,"%",sep = "")),
size = 3, check_overlap = T, position = position_stack(vjust = 0.7) ) +
theme(axis.text.x = element_text(angle = 00, vjust = 0.5), plot.title = element_text(hjust = 0.5), legend.position = "none") +
coord_flip()
plot_BMI_Medal <- athlete_clean %>%
filter(!is.na(Medal), BMI_cat == bin_i) %>%
group_by(BMI_cat,Team) %>%
summarize(count_BMI_team = n()) %>%
mutate(percentage_cbmiT = round(count_BMI_team/sum(count_BMI_team) * 100,2)) %>%
arrange(-count_BMI_team) %>% top_n(10,count_BMI_team) %>%
ggplot(aes(x = reorder(Team,count_BMI_team), y = count_BMI_team, fill = Team)) +
geom_bar(stat = "identity") +
theme_bw() +
# facet_wrap(~Medal) +
labs(title = paste("Top 10 Winning Teams with \n",bin_i," BMI",sep=""), y = "Number of Athletes",
x = paste("Teams - ",bin_i," BMI Category", sep="")) +
geom_text(aes(label = paste(percentage_cbmiT,"%",sep = "")),
size = 3, check_overlap = T, position = position_stack(vjust = 0.7) ) +
theme(axis.text.x = element_text(angle = 00, vjust = 0.5), plot.title = element_text(hjust = 0.5), legend.position = "none") +
coord_flip()
gridExtra::grid.arrange(plot_BMI, plot_BMI_Medal, ncol = 2)
}
One of the Sample Plots from the above for loop is included below.
The above loop will produce multiple plots for all levels of BMI category.
Sample Image
If you wish to see a more comprehensive use of grid.arrange()
within for
loops, check out https://rpubs.com/Mayank7j_2020/olympic_data_2000_2016
How to save data file into .RData?
Alternatively, when you want to save individual R objects, I recommend using saveRDS
.
You can save R objects using saveRDS
, then load them into R with a new variable name using readRDS
.
Example:
# Save the city object
saveRDS(city, "city.rds")
# ...
# Load the city object as city
city <- readRDS("city.rds")
# Or with a different name
city2 <- readRDS("city.rds")
But when you want to save many/all your objects in your workspace, use Manetheran's answer.
Impersonate tag in Web.Config
You had the identity
node as a child of authentication
node. That was the issue. As in the example above, authentication
and identity
nodes must be children of the system.web
node
MySQL Error: #1142 - SELECT command denied to user
This error also arises for a syntax error occurred due to aliasing tablename.
For instance, when executed below query,
select * from a.table1, b.table2 where a.table1= b.table2
below error occurs:
MySQL Error: #1142. Response form the database. SELECT command denied to user "username@ip" for table "table1"
Solution : Syntax to alias tablename should be used proper, syntax solution for above instance >select * from table1 a, table2 b where a.table1= b.table2
ASP.net Repeater get current index, pointer, or counter
Add a label control to your Repeater's ItemTemplate. Handle OnItemCreated event.
ASPX
<asp:Repeater ID="rptr" runat="server" OnItemCreated="RepeaterItemCreated">
<ItemTemplate>
<div id="width:50%;height:30px;background:#0f0a0f;">
<asp:Label ID="lblSr" runat="server"
style="width:30%;float:left;text-align:right;text-indent:-2px;" />
<span
style="width:65%;float:right;text-align:left;text-indent:-2px;" >
<%# Eval("Item") %>
</span>
</div>
</ItemTemplate>
</asp:Repeater>
Code Behind:
protected void RepeaterItemCreated(object sender, RepeaterItemEventArgs e)
{
Label l = e.Item.FindControl("lblSr") as Label;
if (l != null)
l.Text = e.Item.ItemIndex + 1+"";
}
Code not running in IE 11, works fine in Chrome
While the post of Oka is working great, it might be a bit outdated. I figured out that lodash can tackle it with one single function. If you have lodash installed, it might save you a few lines.
Just try:
import { startsWith } from lodash;
.
.
.
if (startsWith(yourVariable, 'REP')) {
return yourVariable;
return yourVariable;
}
}
Only get hash value using md5sum (without filename)
One way:
set -- $(md5sum $file)
md5=$1
Another way:
md5=$(md5sum $file | while read sum file; do echo $sum; done)
Another way:
md5=$(set -- $(md5sum $file); echo $1)
(Do not try that with back-ticks unless you're very brave and very good with backslashes.)
The advantage of these solutions over other solutions is that they only invoke md5sum
and the shell, rather than other programs such as awk
or sed
. Whether that actually matters is then a separate question; you'd probably be hard pressed to notice the difference.
Pass data from Activity to Service using an Intent
If you bind your service, you will get the Extra in onBind(Intent intent)
.
Activity:
Intent intent = new Intent(this, LocationService.class);
intent.putExtra("tour_name", mTourName);
bindService(intent, mServiceConnection, BIND_AUTO_CREATE);
Service:
@Override
public IBinder onBind(Intent intent) {
mTourName = intent.getStringExtra("tour_name");
return mBinder;
}
Xcode 5 and iOS 7: Architecture and Valid architectures
Set the architecture in build setting to Standard architectures(armv7,armv7s)
iPhone 5S is powered by A7 64bit processor. From apple docs
Xcode can build your app with both 32-bit and 64-bit binaries included. This combined binary requires a minimum deployment target of iOS 7 or later.
Note: A future version of Xcode will let you create a single app that supports the 32-bit runtime on iOS 6 and later, and that supports the 64-bit runtime on iOS 7.
From the documentation what i understood is
- Xcode can create both 64bit 32bit binaries for a single app but the
deployment target should be iOS7. They are saying in future it will
be iOS 6.0
- 32 bit binary will work fine in iPhone 5S(64 bit processor).
Update (Xcode 5.0.1)
In Xcode 5.0.1 they added the support to create 64 bit binary for iOS 5.1.1 onwards.
Xcode 5.0.1 can build your app with both 32-bit and 64-bit binaries included. This combined binary requires a minimum deployment target of iOS 5.1.1 or later. The 64-bit binary runs only on 64-bit devices running iOS 7.0.3 and later.
Update (Xcode 5.1)
Xcode 5.1 made significant change in the architecture section. This answer will be a followup for you.
Check this
how to find seconds since 1970 in java
The answer you want, "1317427200", is achieved if your reference months are January and October. If so, the dates you are looking for are 1970-JAN-01 and 2011-OCT-01, correct?
Then the problem are these numbers you are using for your months.
See, if you check the Calendar API documentation or even the constants provided in there ("Calendar.JANUARY", "Calendar.FEBRUARY" and so on), you'll discover that months start at 0 (being January).
So checking your code, you are passing february and november, which would result in "1317510000".
Best regards.
Add padding to HTML text input field
you can solve this, taking the input
tag inside a div
,
then put the padding property on div
tag. This work's for me...
Like this:
<div class="paded">
<input type="text" />
</div>
and css:
.paded{
padding-right: 20px;
}
CakePHP 3.0 installation: intl extension missing from system
In my case I was not actually trying to run cakephp locally, I was just trying to get it to auto update locally using composer (because I am playing with writing plugins that you install with composer). Since I don't actually even run it locally I could simply ignore requirements by adding the --ignore-platform-reqs flag.
php composer.phar update --ignore-platform-reqs
Javascript seconds to minutes and seconds
To add leading zeros, I would just do:
var minutes = "0" + Math.floor(time / 60);
var seconds = "0" + (time - minutes * 60);
return minutes.substr(-2) + ":" + seconds.substr(-2);
Nice and short
How to convert int to float in C?
Integer division truncates, so (50/100)
results in 0. You can cast to float
(better double
) or multiply with 100.0
(for double
precision, 100.0f
for float
precision) first,
double percentage;
// ...
percentage = 100.0*number/total;
// percentage = (double)number/total * 100;
or
float percentage;
// ...
percentage = (float)number/total * 100;
// percentage = 100.0f*number/total;
Since floating point arithmetic is not associative, the results of 100.0*number/total
and (double)number/total * 100
may be slightly different (the same holds for float
), but it's extremely unlikely to influence the first two places after the decimal point, so it probably doesn't matter which way you choose.
How do I format a number with commas in T-SQL?
Tried the money trick above, and this works great for numerical values with two or less significant digits. I created my own function to format numbers with decimals:
CREATE FUNCTION [dbo].[fn_FormatWithCommas]
(
-- Add the parameters for the function here
@value varchar(50)
)
RETURNS varchar(50)
AS
BEGIN
-- Declare the return variable here
DECLARE @WholeNumber varchar(50) = NULL, @Decimal varchar(10) = '', @CharIndex int = charindex('.', @value)
IF (@CharIndex > 0)
SELECT @WholeNumber = SUBSTRING(@value, 1, @CharIndex-1), @Decimal = SUBSTRING(@value, @CharIndex, LEN(@value))
ELSE
SET @WholeNumber = @value
IF(LEN(@WholeNumber) > 3)
SET @WholeNumber = dbo.fn_FormatWithCommas(SUBSTRING(@WholeNumber, 1, LEN(@WholeNumber)-3)) + ',' + RIGHT(@WholeNumber, 3)
-- Return the result of the function
RETURN @WholeNumber + @Decimal
END
Drop Down Menu/Text Field in one
Inspired by the js fiddle by @ajdeguzman (made my day), here is my node/React derivative:
<div style={{position:"relative",width:"200px",height:"25px",border:0,
padding:0,margin:0}}>
<select style={{position:"absolute",top:"0px",left:"0px",
width:"200px",height:"25px",lineHeight:"20px",
margin:0,padding:0}} onChange={this.onMenuSelect}>
<option></option>
<option value="starttime">Filter by Start Time</option>
<option value="user" >Filter by User</option>
<option value="buildid" >Filter by Build Id</option>
<option value="invoker" >Filter by Invoker</option>
</select>
<input name="displayValue" id="displayValue"
style={{position:"absolute",top:"2px",left:"3px",width:"180px",
height:"21px",border:"1px solid #A9A9A9"}}
onfocus={this.select} type="text" onChange={this.onIdFilterChange}
onMouseDown={this.onMouseDown} onMouseUp={this.onMouseUp}
placeholder="Filter by Build ID"/>
</div>
Looks like this:
How do I add a .click() event to an image?
You can't bind an event to the element before it exists, so you should do it in the onload
event:
<html>
<head>
<script type="text/javascript">
window.onload = function() {
document.getElementById('foo').addEventListener('click', function (e) {
var img = document.createElement('img');
img.setAttribute('src', 'http://blog.stackoverflow.com/wp-content/uploads/stackoverflow-logo-300.png');
e.target.appendChild(img);
});
};
</script>
</head>
<body>
<img id="foo" src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />
</body>
</html>
Read input from a JOptionPane.showInputDialog box
Your problem is that, if the user clicks cancel, operationType
is null and thus throws a NullPointerException. I would suggest that you move
if (operationType.equalsIgnoreCase("Q"))
to the beginning of the group of if statements, and then change it to
if(operationType==null||operationType.equalsIgnoreCase("Q")).
This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.
Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.
Check if record exists from controller in Rails
When you call Business.where(:user_id => current_user.id)
you will get an array. This Array may have no objects or one or many objects in it, but it won't be null. Thus the check == nil will never be true.
You can try the following:
if Business.where(:user_id => current_user.id).count == 0
So you check the number of elements in the array and compare them to zero.
or you can try:
if Business.find_by_user_id(current_user.id).nil?
this will return one or nil.
How to preserve aspect ratio when scaling image using one (CSS) dimension in IE6?
I'm glad that worked out, so I guess you had to explicitly set 'auto' on IE6 in order for it to mimic other browsers!
I actually recently found another technique for scaling images, again designed for backgrounds. This technique has some interesting features:
- The image aspect ratio is preserved
- The image's original size is maintained (that is, it can never shrink only grow)
The markup relies on a wrapper element:
<div id="wrap"><img src="test.png" /></div>
Given the above markup you then use these rules:
#wrap {
height: 100px;
width: 100px;
}
#wrap img {
min-height: 100%;
min-width: 100%;
}
If you then control the size of wrapper you get the interesting scale effects that I list above.
To be explicit, consider the following base state: A container that is 100x100 and an image that is 10x10. The result is a scaled image of 100x100.
- Starting at the base state, the
container resized to 20x100, the
image stays resized at 100x100.
- Starting at the base state, the
image is changed to 10x20, the image
resizes to 100x200.
So, in other words, the image is always at least as big as the container, but will scale beyond it to maintain it's aspect ratio.
This probably isn't useful for your site, and it doesn't work in IE6. But, it is useful to get a scaled background for your view port or container.
How to remove all the occurrences of a char in c++ string
Basically, replace
replaces a character with another and ''
is not a character. What you're looking for is erase
.
See this question which answers the same problem. In your case:
#include <algorithm>
str.erase(std::remove(str.begin(), str.end(), 'a'), str.end());
Or use boost
if that's an option for you, like:
#include <boost/algorithm/string.hpp>
boost::erase_all(str, "a");
All of this is well-documented on reference websites. But if you didn't know of these functions, you could easily do this kind of things by hand:
std::string output;
output.reserve(str.size()); // optional, avoids buffer reallocations in the loop
for(size_t i = 0; i < str.size(); ++i)
if(str[i] != 'a') output += str[i];
How to Use slideDown (or show) function on a table row?
http://jsfiddle.net/PvwfK/136/
<table cellspacing='0' cellpadding='0' class='table01' id='form_table' style='width:100%;'>
<tr>
<td style='cursor:pointer; width:20%; text-align:left;' id='header'>
<label style='cursor:pointer;'> <b id='header01'>? Customer Details</b>
</label>
</td>
</tr>
<tr>
<td style='widtd:20%; text-align:left;'>
<div id='content' class='content01'>
<table cellspacing='0' cellpadding='0' id='form_table'>
<tr>
<td>A/C ID</td>
<td>:</td>
<td>3000/A01</td>
</tr>
<tr>
<td>A/C ID</td>
<td>:</td>
<td>3000/A01</td>
</tr>
<tr>
<td>A/C ID</td>
<td>:</td>
<td>3000/A01</td>
</tr>
</table>
</div>
</td>
</tr>
$(function () {
$(".table01 td").on("click", function () {
var $rows = $('.content01');
if ($(".content01:first").is(":hidden")) {
$("#header01").text("? Customer Details");
$(".content01:first").slideDown();
} else {
$("#header01").text("? Customer Details");
$(".content01:first").slideUp();
}
});
});
ActionBarActivity: cannot be resolved to a type
UPDATE:
Since the version 22.1.0, the class ActionBarActivity is deprecated, so instead use AppCompatActivity.
For more details see here
Using ActionBarActivity:
In Eclipse:
1 - Make sure library project(appcompat_v7) is open & is proper referenced (added as library) in your application project.
2 - Delete android-support-v4.jar from your project's libs folder(if jar is present).
3 - Appcompat_v7 must have android-support-v4.jar & android-support-v7-appcompat.jar inside it's libs folder.
(If jars are not present copy them from /sdk/extras/android/support/v7/appcompat/libs folder of your installed
android sdk location)
4- Check whether ActionBarActivity is properly imported.
import android.support.v7.app.ActionBarActivity;
In Android Studio
Just add compile dependencies to app's build.gradle
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.1.1'
}
nano error: Error opening terminal: xterm-256color
edit your .bash_profile
file
vim .bash_profile
commnet
#export TERM=xterm-256color
add this
export TERMINFO=/usr/share/terminfo
export TERM=xterm-basic
to your .bash_profile
finally
run:
source .bash_profile
Unable to find the wrapper "https" - did you forget to enable it when you configured PHP?
Your Apache is probably not compiled with SSL support. Use cURL instead of file_get_contents anyway. Try this code, if it fails then I am right.
function curl_get_contents($url)
{
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
$data = curl_exec($curl);
curl_close($curl);
return $data;
}
"NoClassDefFoundError: Could not initialize class" error
I had this:
class Util {
static boolean isNeverAsync = System.getenv().get("asyncc_exclude_redundancy").equals("yes");
}
you can probably see the problem, the env var might return null instead of string.
So just to test my theory, I changed it to:
class Util {
static boolean isNeverAsync = false;
}
and the problem went away. Too bad that Java can't give you the exact stack trace of the error though, kinda weird.
Pad with leading zeros
The concept of leading zero is meaningless for an int, which is what you have. It is only meaningful, when printed out or otherwise rendered as a string.
Console.WriteLine("{0:0000000}", FileRecordCount);
Forgot to end the double quotes!
Converting JSON data to Java object
Bewaaaaare of Gson! It's very cool, very great, but the second you want to do anything other than simple objects, you could easily need to start building your own serializers (which isn't that hard).
Also, if you have an array of Objects, and you deserialize some json into that array of Objects, the true types are LOST! The full objects won't even be copied! Use XStream.. Which, if using the jsondriver and setting the proper settings, will encode ugly types into the actual json, so that you don't loose anything. A small price to pay (ugly json) for true serialization.
Note that Jackson fixes these issues, and is faster than GSON.
Why does integer division in C# return an integer and not a float?
Since you don't use any suffix, the literals 13
and 4
are interpreted as integer:
Manual:
If the literal has no suffix, it has the first of these types in which its value can be represented: int
, uint
, long
, ulong
.
Thus, since you declare 13
as integer, integer division will be performed:
Manual:
For an operation of the form x / y, binary operator overload resolution is applied to select a specific operator implementation. The operands are converted to the parameter types of the selected operator, and the type of the result is the return type of the operator.
The predefined division operators are listed below. The operators all compute the quotient of x and y.
Integer division:
int operator /(int x, int y);
uint operator /(uint x, uint y);
long operator /(long x, long y);
ulong operator /(ulong x, ulong y);
And so rounding down occurs:
The division rounds the result towards zero, and the absolute value of the result is the largest possible integer that is less than the absolute value of the quotient of the two operands. The result is zero or positive when the two operands have the same sign and zero or negative when the two operands have opposite signs.
If you do the following:
int x = 13f / 4f;
You'll receive a compiler error, since a floating-point division (the /
operator of 13f
) results in a float, which cannot be cast to int implicitly.
If you want the division to be a floating-point division, you'll have to make the result a float:
float x = 13 / 4;
Notice that you'll still divide integers, which will implicitly be cast to float: the result will be 3.0
. To explicitly declare the operands as float, using the f
suffix (13f
, 4f
).
Finding whether a point lies inside a rectangle or not
In continuation matts answer. we need to use
https://math.stackexchange.com/questions/190111/how-to-check-if-a-point-is-inside-a-rectangle/190373#190373
solution to make it work
Below does not work
0 <= dot(AB,AM) <= dot(AB,AB) && 0 <= dot(BC,BM) <= dot(BC,BC)
Below works
0 <= dot(AB,AM) <= dot(AB,AB) && 0 <= dot(AM,AC) <= dot(AC,AC)
you check by pasting below in javascript console
//Javascript solution for same
var screenWidth = 320;
var screenHeight = 568;
var appHeaderWidth = 320;
var AppHeaderHeight = 65;
var regionWidth = 200;
var regionHeight = 200;
this.topLeftBoundary = {
A: {x: 0, y: AppHeaderHeight},
B: {x: regionWidth, y: AppHeaderHeight},
C: {x: 0, y: regionHeight + AppHeaderHeight},
D: {x: regionWidth, y: regionHeight + AppHeaderHeight}
}
this.topRightBoundary = {
A: {x: screenWidth, y: AppHeaderHeight},
B: {x: screenWidth - regionWidth, y: AppHeaderHeight},
C: {x: screenWidth, y: regionHeight + AppHeaderHeight},
D: {x: screenWidth - regionWidth, y: regionHeight + AppHeaderHeight}
}
this.bottomRightBoundary = {
A: {x: screenWidth, y: screenHeight},
B: {x: screenWidth - regionWidth, y: screenHeight},
C: {x: screenWidth, y: screenHeight - regionHeight},
D: {x: screenWidth - regionWidth, y: screenHeight - regionHeight}
}
this.bottomLeftBoundary = {
A: {x: 0, y: screenHeight},
B: {x: regionWidth, y: screenHeight},
C: {x: 0, y: screenHeight - regionHeight},
D: {x: regionWidth, y: screenHeight - regionHeight}
}
console.log(this.topLeftBoundary);
console.log(this.topRightBoundary);
console.log(this.bottomRightBoundary);
console.log(this.bottomLeftBoundary);
checkIfTapFallsInBoundary = function (region, point) {
console.log("region " + JSON.stringify(region));
console.log("point" + JSON.stringify(point));
var r = region;
var m = point;
function vector(p1, p2) {
return {
x: (p2.x - p1.x),
y: (p2.y - p1.y)
};
}
function dot(u, v) {
console.log("DOT " + (u.x * v.x + u.y * v.y));
return u.x * v.x + u.y * v.y;
}
function pointInRectangle(m, r) {
var AB = vector(r.A, r.B);
var AM = vector(r.A, m);
var AC = vector(r.A, r.C);
var BC = vector(r.B, r.C);
var BM = vector(r.B, m);
console.log("AB " + JSON.stringify(AB));
console.log("AM " + JSON.stringify(AM));
console.log("AM " + JSON.stringify(AC));
console.log("BC " + JSON.stringify(BC));
console.log("BM " + JSON.stringify(BM));
var dotABAM = dot(AB, AM);
var dotABAB = dot(AB, AB);
var dotBCBM = dot(BC, BM);
var dotBCBC = dot(BC, BC);
var dotAMAC = dot(AM, AC);
var dotACAC = dot(AC, AC);
console.log("ABAM " + JSON.stringify(dotABAM));
console.log("ABAB " + JSON.stringify(dotABAB));
console.log("BCBM " + JSON.stringify(dotBCBM));
console.log("BCBC " + JSON.stringify(dotBCBC));
console.log("AMAC " + JSON.stringify(dotAMAC));
console.log("ACAC" + JSON.stringify(dotACAC));
var check = ((0 <= dotABAM && dotABAM <= dotABAB) && (0 <= dotBCBM && dotBCBM <= dotBCBC));
console.log(" first check" + check);
var check = ((0 <= dotABAM && dotABAM <= dotABAB) && (0 <= dotAMAC && dotAMAC <= dotACAC));
console.log("second check" + check);
return check;
}
return pointInRectangle(m, r);
}
//var point = {x: 136, y: 342};
checkIfTapFallsInBoundary(topLeftBoundary, {x: 136, y: 342});
checkIfTapFallsInBoundary(topRightBoundary, {x: 136, y: 274});
checkIfTapFallsInBoundary(bottomRightBoundary, {x: 141, y: 475});
checkIfTapFallsInBoundary(bottomRightBoundary, {x: 131, y: 272});
checkIfTapFallsInBoundary(bottomLeftBoundary, {x: 131, y: 272});
LDAP Authentication using Java
This is my LDAP Java login test application supporting LDAP:// and LDAPS:// self-signed test certificate. Code is taken from few SO posts, simplified implementation and removed legacy sun.java.* imports.
Usage
I have run this in Windows7 and Linux machines against WinAD directory service. Application prints username and member groups.
$ java -cp classes test.LoginLDAP url=ldap://1.2.3.4:389 [email protected]
password=mypwd
$ java -cp classes test.LoginLDAP url=ldaps://1.2.3.4:636 [email protected]
password=mypwd
Test application supports temporary self-signed test certificates for ldaps:// protocol, this DummySSLFactory accepts any server cert so man-in-the-middle is possible. Real life installation should import server certificate to a local JKS keystore file and not using dummy factory.
Application uses enduser's username+password for initial context and ldap queries, it works for WinAD but don't know if can be used for all ldap server implementations. You could create context with internal username+pwd then run queries to see if given enduser is found.
LoginLDAP.java
package test;
import java.util.*;
import javax.naming.*;
import javax.naming.directory.*;
public class LoginLDAP {
public static void main(String[] args) throws Exception {
Map<String,String> params = createParams(args);
String url = params.get("url"); // ldap://1.2.3.4:389 or ldaps://1.2.3.4:636
String principalName = params.get("username"); // [email protected]
String domainName = params.get("domain"); // mydomain.com or empty
if (domainName==null || "".equals(domainName)) {
int delim = principalName.indexOf('@');
domainName = principalName.substring(delim+1);
}
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
props.put(Context.PROVIDER_URL, url);
props.put(Context.SECURITY_PRINCIPAL, principalName);
props.put(Context.SECURITY_CREDENTIALS, params.get("password")); // secretpwd
if (url.toUpperCase().startsWith("LDAPS://")) {
props.put(Context.SECURITY_PROTOCOL, "ssl");
props.put(Context.SECURITY_AUTHENTICATION, "simple");
props.put("java.naming.ldap.factory.socket", "test.DummySSLSocketFactory");
}
InitialDirContext context = new InitialDirContext(props);
try {
SearchControls ctrls = new SearchControls();
ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> results = context.search(toDC(domainName),"(& (userPrincipalName="+principalName+")(objectClass=user))", ctrls);
if(!results.hasMore())
throw new AuthenticationException("Principal name not found");
SearchResult result = results.next();
System.out.println("distinguisedName: " + result.getNameInNamespace() ); // CN=Firstname Lastname,OU=Mycity,DC=mydomain,DC=com
Attribute memberOf = result.getAttributes().get("memberOf");
if(memberOf!=null) {
for(int idx=0; idx<memberOf.size(); idx++) {
System.out.println("memberOf: " + memberOf.get(idx).toString() ); // CN=Mygroup,CN=Users,DC=mydomain,DC=com
//Attribute att = context.getAttributes(memberOf.get(idx).toString(), new String[]{"CN"}).get("CN");
//System.out.println( att.get().toString() ); // CN part of groupname
}
}
} finally {
try { context.close(); } catch(Exception ex) { }
}
}
/**
* Create "DC=sub,DC=mydomain,DC=com" string
* @param domainName sub.mydomain.com
* @return
*/
private static String toDC(String domainName) {
StringBuilder buf = new StringBuilder();
for (String token : domainName.split("\\.")) {
if(token.length()==0) continue;
if(buf.length()>0) buf.append(",");
buf.append("DC=").append(token);
}
return buf.toString();
}
private static Map<String,String> createParams(String[] args) {
Map<String,String> params = new HashMap<String,String>();
for(String str : args) {
int delim = str.indexOf('=');
if (delim>0) params.put(str.substring(0, delim).trim(), str.substring(delim+1).trim());
else if (delim==0) params.put("", str.substring(1).trim());
else params.put(str, null);
}
return params;
}
}
And SSL helper class.
package test;
import java.io.*;
import java.net.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.*;
import javax.net.ssl.*;
public class DummySSLSocketFactory extends SSLSocketFactory {
private SSLSocketFactory socketFactory;
public DummySSLSocketFactory() {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[]{ new DummyTrustManager()}, new SecureRandom());
socketFactory = ctx.getSocketFactory();
} catch ( Exception ex ){ throw new IllegalArgumentException(ex); }
}
public static SocketFactory getDefault() { return new DummySSLSocketFactory(); }
@Override public String[] getDefaultCipherSuites() { return socketFactory.getDefaultCipherSuites(); }
@Override public String[] getSupportedCipherSuites() { return socketFactory.getSupportedCipherSuites(); }
@Override public Socket createSocket(Socket socket, String string, int i, boolean bln) throws IOException {
return socketFactory.createSocket(socket, string, i, bln);
}
@Override public Socket createSocket(String string, int i) throws IOException, UnknownHostException {
return socketFactory.createSocket(string, i);
}
@Override public Socket createSocket(String string, int i, InetAddress ia, int i1) throws IOException, UnknownHostException {
return socketFactory.createSocket(string, i, ia, i1);
}
@Override public Socket createSocket(InetAddress ia, int i) throws IOException {
return socketFactory.createSocket(ia, i);
}
@Override public Socket createSocket(InetAddress ia, int i, InetAddress ia1, int i1) throws IOException {
return socketFactory.createSocket(ia, i, ia1, i1);
}
}
class DummyTrustManager implements X509TrustManager {
@Override public void checkClientTrusted(X509Certificate[] xcs, String str) {
// do nothing
}
@Override public void checkServerTrusted(X509Certificate[] xcs, String str) {
/*System.out.println("checkServerTrusted for authType: " + str); // RSA
for(int idx=0; idx<xcs.length; idx++) {
X509Certificate cert = xcs[idx];
System.out.println("X500Principal: " + cert.getSubjectX500Principal().getName());
}*/
}
@Override public X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0];
}
}
C# equivalent of C++ map<string,double>
Roughly:-
var accounts = new Dictionary<string, double>();
// Initialise to zero...
accounts["Fred"] = 0;
accounts["George"] = 0;
accounts["Fred"] = 0;
// Add cash.
accounts["Fred"] += 4.56;
accounts["George"] += 1.00;
accounts["Fred"] += 1.00;
Console.WriteLine("Fred owes me ${0}", accounts["Fred"]);
Recommended way to save uploaded files in a servlet application
Store it anywhere in an accessible location except of the IDE's project folder aka the server's deploy folder, for reasons mentioned in the answer to Uploaded image only available after refreshing the page:
Changes in the IDE's project folder does not immediately get reflected in the server's work folder. There's kind of a background job in the IDE which takes care that the server's work folder get synced with last updates (this is in IDE terms called "publishing"). This is the main cause of the problem you're seeing.
In real world code there are circumstances where storing uploaded files in the webapp's deploy folder will not work at all. Some servers do (either by default or by configuration) not expand the deployed WAR file into the local disk file system, but instead fully in the memory. You can't create new files in the memory without basically editing the deployed WAR file and redeploying it.
Even when the server expands the deployed WAR file into the local disk file system, all newly created files will get lost on a redeploy or even a simple restart, simply because those new files are not part of the original WAR file.
It really doesn't matter to me or anyone else where exactly on the local disk file system it will be saved, as long as you do not ever use getRealPath()
method. Using that method is in any case alarming.
The path to the storage location can in turn be definied in many ways. You have to do it all by yourself. Perhaps this is where your confusion is caused because you somehow expected that the server does that all automagically. Please note that @MultipartConfig(location)
does not specify the final upload destination, but the temporary storage location for the case file size exceeds memory storage threshold.
So, the path to the final storage location can be definied in either of the following ways:
Hardcoded:
File uploads = new File("/path/to/uploads");
Environment variable via SET UPLOAD_LOCATION=/path/to/uploads
:
File uploads = new File(System.getenv("UPLOAD_LOCATION"));
VM argument during server startup via -Dupload.location="/path/to/uploads"
:
File uploads = new File(System.getProperty("upload.location"));
*.properties
file entry as upload.location=/path/to/uploads
:
File uploads = new File(properties.getProperty("upload.location"));
web.xml
<context-param>
with name upload.location
and value /path/to/uploads
:
File uploads = new File(getServletContext().getInitParameter("upload.location"));
If any, use the server-provided location, e.g. in JBoss AS/WildFly:
File uploads = new File(System.getProperty("jboss.server.data.dir"), "uploads");
Either way, you can easily reference and save the file as follows:
File file = new File(uploads, "somefilename.ext");
try (InputStream input = part.getInputStream()) {
Files.copy(input, file.toPath());
}
Or, when you want to autogenerate an unique file name to prevent users from overwriting existing files with coincidentally the same name:
File file = File.createTempFile("somefilename-", ".ext", uploads);
try (InputStream input = part.getInputStream()) {
Files.copy(input, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
How to obtain part
in JSP/Servlet is answered in How to upload files to server using JSP/Servlet? and how to obtain part
in JSF is answered in How to upload file using JSF 2.2 <h:inputFile>? Where is the saved File?
Note: do not use Part#write()
as it interprets the path relative to the temporary storage location defined in @MultipartConfig(location)
.
See also:
Check if a string matches a regex in Bash script
A good way to test if a string is a correct date is to use the command date:
if date -d "${DATE}" >/dev/null 2>&1
then
# do what you need to do with your date
else
echo "${DATE} incorrect date" >&2
exit 1
fi
from comment: one can use formatting
if [ "2017-01-14" == $(date -d "2017-01-14" '+%Y-%m-%d') ]
LINQ extension methods - Any() vs. Where() vs. Exists()
foreach (var item in model.Where(x => !model2.Any(y => y.ID == x.ID)).ToList())
{
enter code here
}
same work you also can do with Contains
secondly Where
is give you new list of values.
thirdly using Exist
is not a good practice, you can achieve your target from Any
and contains
like
EmployeeDetail _E = Db.EmployeeDetails.where(x=>x.Id==1).FirstOrDefault();
Hope this will clear your confusion.
Python Web Crawlers and "getting" html source code
Use Python 2.7, is has more 3rd party libs at the moment. (Edit: see below).
I recommend you using the stdlib module urllib2
, it will allow you to comfortably get web resources.
Example:
import urllib2
response = urllib2.urlopen("http://google.de")
page_source = response.read()
For parsing the code, have a look at BeautifulSoup
.
BTW: what exactly do you want to do:
Just for background, I need to download a page and replace any img with ones I have
Edit: It's 2014 now, most of the important libraries have been ported, and you should definitely use Python 3 if you can. python-requests
is a very nice high-level library which is easier to use than urllib2
.
Access to the path is denied
In my case I had to add a .NET Authorization Rule for the web site in IIS.
I added a rule to allow anonymous users.
How to redirect a url in NGINX
First make sure you have installed Nginx with the HTTP rewrite module. To install this we need to have pcre-library
How to install pcre library
If the above mentioned are done or if you already have them, then just add the below code in your nginx server block
if ($host !~* ^www\.) {
rewrite ^(.*)$ http://www.$host$1 permanent;
}
To remove www from every request you can use
if ($host = 'www.your_domain.com' ) {
rewrite ^/(.*)$ http://your_domain.com/$1 permanent;
}
so your server block will look like
server {
listen 80;
server_name test.com;
if ($host !~* ^www\.) {
rewrite ^(.*)$ http://www.$host$1 permanent;
}
client_max_body_size 10M;
client_body_buffer_size 128k;
root /home/test/test/public;
passenger_enabled on;
rails_env production;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
Get Number of Rows returned by ResultSet in Java
You could count with sql and retrieve the answer from the resultset like so:
Statment stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet ct = stmt.executeQuery("SELECT COUNT(*) FROM [table_name]");
if(ct.next()){
td.setTotalNumRows(ct.getInt(1));
}
Here I'm counting everything but you can easily modify the SQL to count based on a criteria.
How to convert index of a pandas dataframe into a column?
If you want to use the reset_index
method and also preserve your existing index you should use:
df.reset_index().set_index('index', drop=False)
or to change it in place:
df.reset_index(inplace=True)
df.set_index('index', drop=False, inplace=True)
For example:
print(df)
gi ptt_loc
0 384444683 593
4 384444684 594
9 384444686 596
print(df.reset_index())
index gi ptt_loc
0 0 384444683 593
1 4 384444684 594
2 9 384444686 596
print(df.reset_index().set_index('index', drop=False))
index gi ptt_loc
index
0 0 384444683 593
4 4 384444684 594
9 9 384444686 596
And if you want to get rid of the index label you can do:
df2 = df.reset_index().set_index('index', drop=False)
df2.index.name = None
print(df2)
index gi ptt_loc
0 0 384444683 593
4 4 384444684 594
9 9 384444686 596
Datetime format Issue: String was not recognized as a valid DateTime
Below code worked for me:
string _stDate = Convert.ToDateTime(DateTime.Today.AddMonths(-12)).ToString("MM/dd/yyyy");
String format ="MM/dd/yyyy";
IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);
DateTime _Startdate = DateTime.ParseExact(_stDate, format, culture);
What causes javac to issue the "uses unchecked or unsafe operations" warning
This warning also could be raised due to
new HashMap() or new ArrayList() that is generic type has to be specific otherwise the compiler will generate warning.
Please make sure that if you code contains the following you have to change accordingly
new HashMap() => Map map = new HashMap()
new HashMap() => Map map = new HashMap<>()
new ArrayList() => List map = new ArrayList()
new ArrayList() => List map = new ArrayList<>()
C++ cast to derived class
First of all - prerequisite for downcast is that object you are casting is of the type you are casting to. Casting with dynamic_cast will check this condition in runtime (provided that casted object has some virtual functions) and throw bad_cast
or return NULL
pointer on failure. Compile-time casts will not check anything and will just lead tu undefined behaviour if this prerequisite does not hold.
Now analyzing your code:
DerivedType m_derivedType = m_baseType;
Here there is no casting. You are creating a new object of type DerivedType
and try to initialize it with value of m_baseType variable.
Next line is not much better:
DerivedType m_derivedType = (DerivedType)m_baseType;
Here you are creating a temporary of DerivedType
type initialized with m_baseType
value.
The last line
DerivedType * m_derivedType = (DerivedType*) & m_baseType;
should compile provided that BaseType
is a direct or indirect public base class of DerivedType
. It has two flaws anyway:
- You use deprecated C-style cast. The proper way for such casts is
static_cast<DerivedType *>(&m_baseType)
- The actual type of casted object is not of DerivedType (as it was defined as
BaseType m_baseType;
so any use of m_derivedType
pointer will result in undefined behaviour.
TypeError: 'type' object is not subscriptable when indexing in to a dictionary
Normally Python throws NameError
if the variable is not defined:
>>> d[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined
However, you've managed to stumble upon a name that already exists in Python.
Because dict
is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.
The type of dict
is a type
. All types are objects in Python. Thus you are actually trying to index into the type
object. This is why the error message says that the "'type' object is not subscriptable."
>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable
Note that you can blindly assign to the dict
name, but you really don't want to do that. It's just going to cause you problems later.
>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]
'a'
The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:
d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))
How to get first and last day of the current week in JavaScript
Be careful with the accepted answer, it does not set the time to 00:00:00 and 23:59:59, so you can have problems.
You can use a third party date library to deal with dates. For example:
var startOfWeek = moment().startOf('week').toDate();
var endOfWeek = moment().endOf('week').toDate();
EDIT: As of September 2020, using Moment is discouraged for new projects (blog post)
Another popular alternative is date-fns.
Returning multiple values from a C++ function
std::pair<int, int> divide(int dividend, int divisor)
{
// :
return std::make_pair(quotient, remainder);
}
std::pair<int, int> answer = divide(5,2);
// answer.first == quotient
// answer.second == remainder
std::pair is essentially your struct solution, but already defined for you, and ready to adapt to any two data types.
How to select bottom most rows?
Querying a simple subquery sorted descending, followed by sorting on the same column ascending does the trick.
SELECT * FROM
(SELECT TOP 200 * FROM [table] t2 ORDER BY t2.[column] DESC) t1
ORDER BY t1.[column]
How to run multiple sites on one apache instance
Yes with Virtual Host you can have as many parallel programs as you want:
Open
/etc/httpd/conf/httpd.conf
Listen 81
Listen 82
Listen 83
<VirtualHost *:81>
ServerAdmin [email protected]
DocumentRoot /var/www/site1/html
ServerName site1.com
ErrorLog logs/site1-error_log
CustomLog logs/site1-access_log common
ScriptAlias /cgi-bin/ "/var/www/site1/cgi-bin/"
</VirtualHost>
<VirtualHost *:82>
ServerAdmin [email protected]
DocumentRoot /var/www/site2/html
ServerName site2.com
ErrorLog logs/site2-error_log
CustomLog logs/site2-access_log common
ScriptAlias /cgi-bin/ "/var/www/site2/cgi-bin/"
</VirtualHost>
<VirtualHost *:83>
ServerAdmin [email protected]
DocumentRoot /var/www/site3/html
ServerName site3.com
ErrorLog logs/site3-error_log
CustomLog logs/site3-access_log common
ScriptAlias /cgi-bin/ "/var/www/site3/cgi-bin/"
</VirtualHost>
Restart apache
service httpd restart
You can now refer Site1 :
http://<ip-address>:81/
http://<ip-address>:81/cgi-bin/
Site2 :
http://<ip-address>:82/
http://<ip-address>:82/cgi-bin/
Site3 :
http://<ip-address>:83/
http://<ip-address>:83/cgi-bin/
If path is not hardcoded in any script then your websites should work seamlessly.
Spring mvc @PathVariable
Let us assume you hit a url as www.example.com/test/111 .
Now you have to retrieve value 111 (which is dynamic) to your controller method .At time you ll be using @PathVariable as follows :
@RequestMapping(value = " /test/{testvalue}", method=RequestMethod.GET)
public void test(@PathVariable String testvalue){
//you can use test value here
}
SO the variable value is retrieved from the url
Error when trying to access XAMPP from a network
This answer is for XAMPP on Ubuntu.
The manual for installation and download is on (site official)
http://www.apachefriends.org/it/xampp-linux.html
After to start XAMPP simply call this command:
sudo /opt/lampp/lampp start
You should now see something like this on your screen:
Starting XAMPP 1.8.1...
LAMPP: Starting Apache...
LAMPP: Starting MySQL...
LAMPP started.
If you have this
Starting XAMPP for Linux 1.8.1...
XAMPP: Another web server daemon is already running.
XAMPP: Another MySQL daemon is already running.
XAMPP: Starting ProFTPD...
XAMPP for Linux started
. The solution is
sudo /etc/init.d/apache2 stop
sudo /etc/init.d/mysql stop
And the restast with sudo //opt/lampp/lampp restart
You to fix most of the security weaknesses simply call the following command:
/opt/lampp/lampp security
After the change this file
sudo kate //opt/lampp/etc/extra/httpd-xampp.conf
Find and replace on
#
# New XAMPP security concept
#
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
Order deny,allow
Deny from all
Allow from ::1 127.0.0.0/8
Allow from all
#\
# fc00::/7 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 \
# fe80::/10 169.254.0.0/16
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>
Notepad++ Multi editing
In the position where you want to add text, do:
Shift
+ Alt
+ down arrow
and select the lines you want. Then type. The text you type is inserted on all of the lines you selected.
How to access parameters in a RESTful POST method
Your @POST
method should be accepting a JSON object instead of a string. Jersey uses JAXB to support marshaling and unmarshaling JSON objects (see the jersey docs for details). Create a class like:
@XmlRootElement
public class MyJaxBean {
@XmlElement public String param1;
@XmlElement public String param2;
}
Then your @POST
method would look like the following:
@POST @Consumes("application/json")
@Path("/create")
public void create(final MyJaxBean input) {
System.out.println("param1 = " + input.param1);
System.out.println("param2 = " + input.param2);
}
This method expects to receive JSON object as the body of the HTTP POST. JAX-RS passes the content body of the HTTP message as an unannotated parameter -- input
in this case. The actual message would look something like:
POST /create HTTP/1.1
Content-Type: application/json
Content-Length: 35
Host: www.example.com
{"param1":"hello","param2":"world"}
Using JSON in this way is quite common for obvious reasons. However, if you are generating or consuming it in something other than JavaScript, then you do have to be careful to properly escape the data. In JAX-RS, you would use a MessageBodyReader and MessageBodyWriter to implement this. I believe that Jersey already has implementations for the required types (e.g., Java primitives and JAXB wrapped classes) as well as for JSON. JAX-RS supports a number of other methods for passing data. These don't require the creation of a new class since the data is passed using simple argument passing.
HTML <FORM>
The parameters would be annotated using @FormParam:
@POST
@Path("/create")
public void create(@FormParam("param1") String param1,
@FormParam("param2") String param2) {
...
}
The browser will encode the form using "application/x-www-form-urlencoded". The JAX-RS runtime will take care of decoding the body and passing it to the method. Here's what you should see on the wire:
POST /create HTTP/1.1
Host: www.example.com
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 25
param1=hello¶m2=world
The content is URL encoded in this case.
If you do not know the names of the FormParam's you can do the following:
@POST @Consumes("application/x-www-form-urlencoded")
@Path("/create")
public void create(final MultivaluedMap<String, String> formParams) {
...
}
HTTP Headers
You can using the @HeaderParam annotation if you want to pass parameters via HTTP headers:
@POST
@Path("/create")
public void create(@HeaderParam("param1") String param1,
@HeaderParam("param2") String param2) {
...
}
Here's what the HTTP message would look like. Note that this POST does not have a body.
POST /create HTTP/1.1
Content-Length: 0
Host: www.example.com
param1: hello
param2: world
I wouldn't use this method for generalized parameter passing. It is really handy if you need to access the value of a particular HTTP header though.
HTTP Query Parameters
This method is primarily used with HTTP GETs but it is equally applicable to POSTs. It uses the @QueryParam annotation.
@POST
@Path("/create")
public void create(@QueryParam("param1") String param1,
@QueryParam("param2") String param2) {
...
}
Like the previous technique, passing parameters via the query string does not require a message body. Here's the HTTP message:
POST /create?param1=hello¶m2=world HTTP/1.1
Content-Length: 0
Host: www.example.com
You do have to be particularly careful to properly encode query parameters on the client side. Using query parameters can be problematic due to URL length restrictions enforced by some proxies as well as problems associated with encoding them.
HTTP Path Parameters
Path parameters are similar to query parameters except that they are embedded in the HTTP resource path. This method seems to be in favor today. There are impacts with respect to HTTP caching since the path is what really defines the HTTP resource. The code looks a little different than the others since the @Path annotation is modified and it uses @PathParam:
@POST
@Path("/create/{param1}/{param2}")
public void create(@PathParam("param1") String param1,
@PathParam("param2") String param2) {
...
}
The message is similar to the query parameter version except that the names of the parameters are not included anywhere in the message.
POST /create/hello/world HTTP/1.1
Content-Length: 0
Host: www.example.com
This method shares the same encoding woes that the query parameter version. Path segments are encoded differently so you do have to be careful there as well.
As you can see, there are pros and cons to each method. The choice is usually decided by your clients. If you are serving FORM
-based HTML pages, then use @FormParam
. If your clients are JavaScript+HTML5-based, then you will probably want to use JAXB-based serialization and JSON objects. The MessageBodyReader/Writer
implementations should take care of the necessary escaping for you so that is one fewer thing that can go wrong. If your client is Java based but does not have a good XML processor (e.g., Android), then I would probably use FORM
encoding since a content body is easier to generate and encode properly than URLs are. Hopefully this mini-wiki entry sheds some light on the various methods that JAX-RS supports.
Note: in the interest of full disclosure, I haven't actually used this feature of Jersey yet. We were tinkering with it since we have a number of JAXB+JAX-RS applications deployed and are moving into the mobile client space. JSON is a much better fit that XML on HTML5 or jQuery-based solutions.
How do I declare a global variable in VBA?
A good way to create Public/Global variables is to treat the Form like a class object and declare properties and use Public Property Get [variable] to access property/method. Also you might need to reference or pass a Reference to the instantiated Form module. You will get errors if you call methods to forms/reports that are closed.
Example: pass Me.Form.Module.Parent into sub/function not inside form.
Option Compare Database
Option Explicit
''***********************************''
' Name: Date: Created Date Author: Name
' Current Version: 1.0
' Called by:
''***********************************''
' Notes: Explain Who what when why...
' This code Example requires properties to be filled in
''***********************************''
' Global Variables
Public GlobalData As Variant
''***********************************''
' Private Variables
Private ObjectReference As Object
Private ExampleVariable As Variant
Private ExampleData As Variant
''***********************************''
' Public properties
Public Property Get ObjectVariable() As Object
Set ObjectVariable = ObjectReference
End Property
Public Property Get Variable1() As Variant
'Recommend using variants to avoid data errors
Variable1 = ExampleVariable
End property
''***********************************''
' Public Functions that return values
Public Function DataReturn (Input As Variant) As Variant
DataReturn = ExampleData + Input
End Function
''***********************************''
' Public Sub Routines
Public Sub GlobalMethod()
'call local Functions/Subs outside of form
Me.Form.Refresh
End Sub
''***********************************''
' Private Functions/Subs used not visible outside
''***********************************''
End Code
So in the other module you would be able to access:
Public Sub Method1(objForm as Object)
'read/write data value
objForm.GlobalData
'Get object reference (need to add Public Property Set to change reference object)
objForm.ObjectVariable
'read only (needs Public property Let to change value)
objForm.Variable1
'Gets result of function with input
objForm.DataReturn([Input])
'runs sub/function from outside of normal scope
objForm.GlobalMethod
End Sub
If you use Late Binding like I do always check for Null values and objects that are Nothing before attempting to do any processing.
Popup Message boxes
first you have to import:
import javax.swing.JOptionPane;
then you can call it using this:
JOptionPane.showMessageDialog(null,
"ALERT MESSAGE",
"TITLE",
JOptionPane.WARNING_MESSAGE);
the null puts it in the middle of the screen. put whatever in quotes under alert message. Title is obviously title and the last part will format it like an error message. if you want a regular message just replace it with PLAIN_MESSAGE
. it works pretty well in a lot of ways mostly for errors.
remote rejected master -> master (pre-receive hook declined)
I also faced the same issue The solution for this is
Delete the package-lock.json file on both the client and server
Make sure that you are using at least the LTS version of Node locally
Make sure your local Node version matches what is shown in the package.json file's engines property.
Run the git add . , git commit -m "fixing versions" and git push heroku master commands to force a rebuild.
Angular Directive refresh on parameter change
If You're under AngularJS 1.5.3 or newer, You should consider to move to components instead of directives.
Those works very similar to directives but with some very useful additional feautures, such as $onChanges(changesObj), one of the lifecycle hook, that will be called whenever one-way bindings are updated.
app.component('conversation ', {
bindings: {
type: '@',
typeId: '='
},
controller: function() {
this.$onChanges = function(changes) {
// check if your specific property has changed
// that because $onChanges is fired whenever each property is changed from you parent ctrl
if(!!changes.typeId){
refreshYourComponent();
}
};
},
templateUrl: 'conversation .html'
});
Here's the docs for deepen into components.
Double array initialization in Java
You can initialize an array by writing actual values it holds in curly braces on the right hand side like:
String[] strArr = { "one", "two", "three"};
int[] numArr = { 1, 2, 3};
In the same manner two-dimensional array or array-of-arrays holds an array as a value, so:
String strArrayOfArrays = { {"a", "b", "c"}, {"one", "two", "three"} };
Your example shows exactly that
double m[][] = {
{0*0,1*0,2*0,3*0},
{0*1,1*1,2*1,3*1},
{0*2,1*2,2*2,3*2},
{0*3,1*3,2*3,3*3}
};
But also the multiplication of number will also be performed and its the same as:
double m[][] = { {0, 0, 0, 0}, {0, 1, 2, 3}, {0, 2, 4, 6}, {0, 3, 6, 9} };
How to add a TextView to a LinearLayout dynamically in Android?
layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="@+id/layoutTest"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
</LinearLayout>
</RelativeLayout>
class file:
setContentView(R.layout.layout_dynamic);
layoutTest=(LinearLayout)findViewById(R.id.layoutTest);
TextView textView = new TextView(getApplicationContext());
textView.setText("testDynamic textView");
layoutTest.addView(textView);
Image Greyscale with CSS & re-color on mouse-over?
There are numerous methods of accomplishing this, which I'll detail with a few examples below.
Pure CSS (using only one colored image)
img.grayscale {
filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale"); /* Firefox 3.5+ */
filter: gray; /* IE6-9 */
-webkit-filter: grayscale(100%); /* Chrome 19+ & Safari 6+ */
}
img.grayscale:hover {
filter: none;
-webkit-filter: grayscale(0%);
}
_x000D_
_x000D_
img.grayscale {_x000D_
filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");_x000D_
/* Firefox 3.5+, IE10 */_x000D_
filter: gray;_x000D_
/* IE6-9 */_x000D_
-webkit-filter: grayscale(100%);_x000D_
/* Chrome 19+ & Safari 6+ */_x000D_
-webkit-transition: all .6s ease;_x000D_
/* Fade to color for Chrome and Safari */_x000D_
-webkit-backface-visibility: hidden;_x000D_
/* Fix for transition flickering */_x000D_
}_x000D_
_x000D_
img.grayscale:hover {_x000D_
filter: none;_x000D_
-webkit-filter: grayscale(0%);_x000D_
}_x000D_
_x000D_
svg {_x000D_
background: url(http://4.bp.blogspot.com/-IzPWLqY4gJ0/T01CPzNb1KI/AAAAAAAACgA/_8uyj68QhFE/s400/a2cf7051-5952-4b39-aca3-4481976cb242.jpg);_x000D_
}_x000D_
_x000D_
svg image {_x000D_
transition: all .6s ease;_x000D_
}_x000D_
_x000D_
svg image:hover {_x000D_
opacity: 0;_x000D_
}
_x000D_
<p>Firefox, Chrome, Safari, IE6-9</p>_x000D_
<img class="grayscale" src="http://4.bp.blogspot.com/-IzPWLqY4gJ0/T01CPzNb1KI/AAAAAAAACgA/_8uyj68QhFE/s1600/a2cf7051-5952-4b39-aca3-4481976cb242.jpg" width="400">_x000D_
<p>IE10 with inline SVG</p>_x000D_
<svg xmlns="http://www.w3.org/2000/svg" id="svgroot" viewBox="0 0 400 377" width="400" height="377">_x000D_
<defs>_x000D_
<filter id="filtersPicture">_x000D_
<feComposite result="inputTo_38" in="SourceGraphic" in2="SourceGraphic" operator="arithmetic" k1="0" k2="1" k3="0" k4="0" />_x000D_
<feColorMatrix id="filter_38" type="saturate" values="0" data-filterid="38" />_x000D_
</filter>_x000D_
</defs>_x000D_
<image filter="url("#filtersPicture")" x="0" y="0" width="400" height="377" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://4.bp.blogspot.com/-IzPWLqY4gJ0/T01CPzNb1KI/AAAAAAAACgA/_8uyj68QhFE/s1600/a2cf7051-5952-4b39-aca3-4481976cb242.jpg" />_x000D_
</svg>
_x000D_
_x000D_
_x000D_
You can find an article related to this technique here.
Pure CSS (using a grayscale and colored images)
This approach requires two copies of an image: one in grayscale and the other in full color. Using the CSS :hover
psuedoselector, you can update the background of your element to toggle between the two:
#yourimage {
background: url(../grayscale-image.png);
}
#yourImage:hover {
background: url(../color-image.png};
}
_x000D_
_x000D_
#google {_x000D_
background: url('http://www.google.com/logos/keystroke10-hp.png');_x000D_
height: 95px;_x000D_
width: 275px;_x000D_
display: block;_x000D_
/* Optional for a gradual animation effect */_x000D_
transition: 0.5s;_x000D_
}_x000D_
_x000D_
#google:hover {_x000D_
background: url('https://graphics217b.files.wordpress.com/2011/02/logo1w.png');_x000D_
}
_x000D_
<a id='google' href='http://www.google.com'></a>
_x000D_
_x000D_
_x000D_
This could also be accomplished by using a Javascript-based hover effect such as jQuery's hover()
function in the same manner.
Consider a Third-Party Library
The desaturate library is a common library that allows you to easily switch between a grayscale version and full-colored version of a given element or image.
/bin/sh: pushd: not found
pushd
is a bash
enhancement to the POSIX-specified Bourne Shell. pushd
cannot be easily implemented as a command, because the current working directory is a feature of a process that cannot be changed by child processes. (A hypothetical pushd
command might do the chdir(2)
call and then start a new shell, but ... it wouldn't be very usable.) pushd
is a shell builtin, just like cd
.
So, either change your script to start with #!/bin/bash
or store the current working directory in a variable, do your work, then change back. Depends if you want a shell script that works on very reduced systems (say, a Debian build server) or if you're fine always requiring bash
.
Viewing localhost website from mobile device
To view localhost website from mobile device you have to follow thoses steps :
- In your computer, you have to retrieve your IP address (Run > cmd > ipconfig)
- If your localhost use a specific port (like localhost:12345 ), you have to open the port on your computer (Control Panel > System and Security > Firewall > Advanced settings and add Inbound rule)
- Finally, you can access to your website from mobile device by navigate to : http://192.168.X.X:12345/
Hope it helps
How to install JQ on Mac by command-line?
The simplest way to install jq
and test that it works is through brew and then using the simplest filter that merely formats the JSON
Install
brew
is the easiest way to manage packages on a mac:
brew install jq
Need brew
? Run the following command:
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Failing that: instructions to install and use are on https://brew.sh/
Test
The .
filter takes its input and produces it unchanged as output. This is the identity operator. (quote the docs)
echo '{ "name":"John", "age":31, "city":"New York" }' | jq .
The result should appear like so in your terminal:
{
"name": "John",
"age": 31,
"city": "New York"
}
Efficient Algorithm for Bit Reversal (from MSB->LSB to LSB->MSB) in C
Anders Cedronius's answer provides a great solution for people that have an x86 CPU with AVX2 support. For x86 platforms without AVX support or non-x86 platforms, either of the following implementations should work well.
The first code is a variant of the classic binary partitioning method, coded to maximize the use of the shift-plus-logic idiom useful on various ARM processors. In addition, it uses on-the-fly mask generation which could be beneficial for RISC processors that otherwise require multiple instructions to load each 32-bit mask value. Compilers for x86 platforms should use constant propagation to compute all masks at compile time rather than run time.
/* Classic binary partitioning algorithm */
inline uint32_t brev_classic (uint32_t a)
{
uint32_t m;
a = (a >> 16) | (a << 16); // swap halfwords
m = 0x00ff00ff; a = ((a >> 8) & m) | ((a << 8) & ~m); // swap bytes
m = m^(m << 4); a = ((a >> 4) & m) | ((a << 4) & ~m); // swap nibbles
m = m^(m << 2); a = ((a >> 2) & m) | ((a << 2) & ~m);
m = m^(m << 1); a = ((a >> 1) & m) | ((a << 1) & ~m);
return a;
}
In volume 4A of "The Art of Computer Programming", D. Knuth shows clever ways of reversing bits that somewhat surprisingly require fewer operations than the classical binary partitioning algorithms. One such algorithm for 32-bit operands, that I cannot find in TAOCP, is shown in this document on the Hacker's Delight website.
/* Knuth's algorithm from http://www.hackersdelight.org/revisions.pdf. Retrieved 8/19/2015 */
inline uint32_t brev_knuth (uint32_t a)
{
uint32_t t;
a = (a << 15) | (a >> 17);
t = (a ^ (a >> 10)) & 0x003f801f;
a = (t + (t << 10)) ^ a;
t = (a ^ (a >> 4)) & 0x0e038421;
a = (t + (t << 4)) ^ a;
t = (a ^ (a >> 2)) & 0x22488842;
a = (t + (t << 2)) ^ a;
return a;
}
Using the Intel compiler C/C++ compiler 13.1.3.198, both of the above functions auto-vectorize nicely targetting XMM
registers. They could also be vectorized manually without a lot of effort.
On my IvyBridge Xeon E3 1270v2, using the auto-vectorized code, 100 million uint32_t
words were bit-reversed in 0.070 seconds using brev_classic()
, and 0.068 seconds using brev_knuth()
. I took care to ensure that my benchmark was not limited by system memory bandwidth.
What do we mean by Byte array?
I assume you know what a byte is. A byte array is simply an area of memory containing a group of contiguous (side by side) bytes, such that it makes sense to talk about them in order: the first byte, the second byte etc..
Just as bytes can encode different types and ranges of data (numbers from 0 to 255, numbers from -128 to 127, single characters using ASCII e.g. 'a' or '%', CPU op-codes), each byte in a byte array may be any of these things, or contribute to some multi-byte values such as numbers with larger range (e.g. 16-bit unsigned int from 0..65535), international character sets, textual strings ("hello"), or part/all of a compiled computer programs.
The crucial thing about a byte array is that it gives indexed (fast), precise, raw access to each 8-bit value being stored in that part of memory, and you can operate on those bytes to control every single bit. The bad thing is the computer just treats every entry as an independent 8-bit number - which may be what your program is dealing with, or you may prefer some powerful data-type such as a string that keeps track of its own length and grows as necessary, or a floating point number that lets you store say 3.14 without thinking about the bit-wise representation. As a data type, it is inefficient to insert or remove data near the start of a long array, as all the subsequent elements need to be shuffled to make or fill the gap created/required.
How to listen for a WebView finishing loading a URL?
You can trace the Progress Staus by the getProgress method in webview class.
Initialize the progress status
private int mProgressStatus = 0;
then the AsyncTask for loading like this:
private class Task_News_ArticleView extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(
your_class.this);
// can use UI thread here
protected void onPreExecute() {
this.dialog.setMessage("Loading...");
this.dialog.setCancelable(false);
this.dialog.show();
}
@Override
protected Void doInBackground(Void... params) {
try {
while (mProgressStatus < 100) {
mProgressStatus = webview.getProgress();
}
} catch (Exception e) {
}
return null;
}
protected void onPostExecute(Void result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
}
C# int to byte[]
The RFC is just trying to say that a signed integer is a normal 4-byte integer with bytes ordered in a big-endian way.
Now, you are most probably working on a little-endian machine and BitConverter.GetBytes()
will give you the byte[]
reversed. So you could try:
int intValue;
byte[] intBytes = BitConverter.GetBytes(intValue);
Array.Reverse(intBytes);
byte[] result = intBytes;
For the code to be most portable, however, you can do it like this:
int intValue;
byte[] intBytes = BitConverter.GetBytes(intValue);
if (BitConverter.IsLittleEndian)
Array.Reverse(intBytes);
byte[] result = intBytes;
Get name of current class?
EDIT: Yes, you can; but you have to cheat: The currently running class name is present on the call stack, and the traceback
module allows you to access the stack.
>>> import traceback
>>> def get_input(class_name):
... return class_name.encode('rot13')
...
>>> class foo(object):
... _name = traceback.extract_stack()[-1][2]
... input = get_input(_name)
...
>>>
>>> foo.input
'sbb'
However, I wouldn't do this; My original answer is still my own preference as a solution. Original answer:
probably the very simplest solution is to use a decorator, which is similar to Ned's answer involving metaclasses, but less powerful (decorators are capable of black magic, but metaclasses are capable of ancient, occult black magic)
>>> def get_input(class_name):
... return class_name.encode('rot13')
...
>>> def inputize(cls):
... cls.input = get_input(cls.__name__)
... return cls
...
>>> @inputize
... class foo(object):
... pass
...
>>> foo.input
'sbb'
>>>
How to add a title to a html select tag
<select>
<option selected disabled>Choose one</option>
<option value="sydney">Sydney</option>
<option value="melbourne">Melbourne</option>
<option value="cromwell">Cromwell</option>
<option value="queenstown">Queenstown</option>
</select>
Using selected
and disabled
will make "Choose one" be the default selected value, but also make it impossible for the user to actually select the item, like so:
What is JSON and why would I use it?
It's very simple. JSON stands for Java Script Object Notation. Think of it as an alternative to using XML for transferring data between software components.
For example, I recently wrote a bunch of web services that returned JSON, and some Javascript developers then wrote code which called the services and consumed the information returned in that format.
Best Way to View Generated Source of Webpage?
This is an old question, and here's an old answer that has once worked flawlessly for me for many years, but doesn't any more, at least not as of January 2016:
The "Generated Source" bookmarklet from SquareFree does exactly what you want -- and, unlike the otherwise fine "old gold" from @Johnny5, displays as source code (rather than being rendered normally by the browser, at least in the case of Google Chrome on Mac):
https://www.squarefree.com/bookmarklets/webdevel.html#generated_source
Unfortunately, it behaves just like the "old gold" from @Johnny5: it does not show up as source code any more. Sorry.
How to show hidden divs on mouseover?
There is a really simple way to do this in a CSS only way.
Apply an opacity to 0, therefore making it invisible, but it will still react to JavaScript events and CSS selectors.
In the hover selector, make it visible by changing the opacity value.
_x000D_
_x000D_
#mouse_over {_x000D_
opacity: 0;_x000D_
}_x000D_
_x000D_
#mouse_over:hover {_x000D_
opacity: 1;_x000D_
}
_x000D_
<div style='border: 5px solid black; width: 120px; font-family: sans-serif'>_x000D_
<div style='height: 20px; width: 120px; background-color: cyan;' id='mouse_over'>Now you see me</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
Convert an image (selected by path) to base64 string
Since most of us like oneliners:
Convert.ToBase64String(File.ReadAllBytes(imageFilepath));
If you need it as Base64 byte array:
Encoding.ASCII.GetBytes(Convert.ToBase64String(File.ReadAllBytes(imageFilepath)));
Best HTML5 markup for sidebar
Look at the following example, from the HTML5 specification about aside
.
It makes clear that what currently is recommended (October 2012) it is to group widgets inside aside
elements. Then, each widget is whatever best represents it, a nav
, a serie of blockquotes
, etc
The following extract shows how aside can be used for blogrolls and
other side content on a blog:
<body>
<header>
<h1>My wonderful blog</h1>
<p>My tagline</p>
</header>
<aside>
<!-- this aside contains two sections that are tangentially related
to the page, namely, links to other blogs, and links to blog posts
from this blog -->
<nav>
<h1>My blogroll</h1>
<ul>
<li><a href="http://blog.example.com/">Example Blog</a>
</ul>
</nav>
<nav>
<h1>Archives</h1>
<ol reversed>
<li><a href="/last-post">My last post</a>
<li><a href="/first-post">My first post</a>
</ol>
</nav>
</aside>
<aside>
<!-- this aside is tangentially related to the page also, it
contains twitter messages from the blog author -->
<h1>Twitter Feed</h1>
<blockquote cite="http://twitter.example.net/t31351234">
I'm on vacation, writing my blog.
</blockquote>
<blockquote cite="http://twitter.example.net/t31219752">
I'm going to go on vacation soon.
</blockquote>
</aside>
<article>
<!-- this is a blog post -->
<h1>My last post</h1>
<p>This is my last post.</p>
<footer>
<p><a href="/last-post" rel=bookmark>Permalink</a>
</footer>
</article>
<article>
<!-- this is also a blog post -->
<h1>My first post</h1>
<p>This is my first post.</p>
<aside>
<!-- this aside is about the blog post, since it's inside the
<article> element; it would be wrong, for instance, to put the
blogroll here, since the blogroll isn't really related to this post
specifically, only to the page as a whole -->
<h1>Posting</h1>
<p>While I'm thinking about it, I wanted to say something about
posting. Posting is fun!</p>
</aside>
<footer>
<p><a href="/first-post" rel=bookmark>Permalink</a>
</footer>
</article>
<footer>
<nav>
<a href="/archives">Archives</a> —
<a href="/about">About me</a> —
<a href="/copyright">Copyright</a>
</nav>
</footer>
</body>
How to get a user's time zone?
NSTimeZone *timeZone = [NSTimeZone localTimeZone];
NSString *tzName = [timeZone name];
The name will be something like "Australia/Sydney", or "Europe/Lisbon".
Since it sounds like you might only care about the continent, that might be all you need.
jQuery UI DatePicker to show year only
I had the same problem and, after a day of research, I came up with this solution: http://jsfiddle.net/konstantc/4jkef3a1/
_x000D_
_x000D_
// *** (month and year only) ***_x000D_
$(function() { _x000D_
$('#datepicker1').datepicker( {_x000D_
yearRange: "c-100:c",_x000D_
changeMonth: true,_x000D_
changeYear: true,_x000D_
showButtonPanel: true,_x000D_
closeText:'Select',_x000D_
currentText: 'This year',_x000D_
onClose: function(dateText, inst) {_x000D_
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();_x000D_
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();_x000D_
$(this).val($.datepicker.formatDate('MM yy (M y) (mm/y)', new Date(year, month, 1)));_x000D_
}_x000D_
}).focus(function () {_x000D_
$(".ui-datepicker-calendar").hide();_x000D_
$(".ui-datepicker-current").hide();_x000D_
$("#ui-datepicker-div").position({_x000D_
my: "left top",_x000D_
at: "left bottom",_x000D_
of: $(this)_x000D_
});_x000D_
}).attr("readonly", false);_x000D_
});_x000D_
// --------------------------------_x000D_
_x000D_
_x000D_
_x000D_
// *** (year only) ***_x000D_
$(function() { _x000D_
$('#datepicker2').datepicker( {_x000D_
yearRange: "c-100:c",_x000D_
changeMonth: false,_x000D_
changeYear: true,_x000D_
showButtonPanel: true,_x000D_
closeText:'Select',_x000D_
currentText: 'This year',_x000D_
onClose: function(dateText, inst) {_x000D_
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();_x000D_
$(this).val($.datepicker.formatDate('yy', new Date(year, 1, 1)));_x000D_
}_x000D_
}).focus(function () {_x000D_
$(".ui-datepicker-month").hide();_x000D_
$(".ui-datepicker-calendar").hide();_x000D_
$(".ui-datepicker-current").hide();_x000D_
$(".ui-datepicker-prev").hide();_x000D_
$(".ui-datepicker-next").hide();_x000D_
$("#ui-datepicker-div").position({_x000D_
my: "left top",_x000D_
at: "left bottom",_x000D_
of: $(this)_x000D_
});_x000D_
}).attr("readonly", false);_x000D_
});_x000D_
// --------------------------------_x000D_
_x000D_
_x000D_
_x000D_
// *** (year only, no controls) ***_x000D_
$(function() { _x000D_
$('#datepicker3').datepicker( {_x000D_
dateFormat: "yy",_x000D_
yearRange: "c-100:c",_x000D_
changeMonth: false,_x000D_
changeYear: true,_x000D_
showButtonPanel: false,_x000D_
closeText:'Select',_x000D_
currentText: 'This year',_x000D_
onClose: function(dateText, inst) {_x000D_
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();_x000D_
$(this).val($.datepicker.formatDate('yy', new Date(year, 1, 1)));_x000D_
},_x000D_
onChangeMonthYear : function () {_x000D_
$(this).datepicker( "hide" );_x000D_
}_x000D_
}).focus(function () {_x000D_
$(".ui-datepicker-month").hide();_x000D_
$(".ui-datepicker-calendar").hide();_x000D_
$(".ui-datepicker-current").hide();_x000D_
$(".ui-datepicker-prev").hide();_x000D_
$(".ui-datepicker-next").hide();_x000D_
$("#ui-datepicker-div").position({_x000D_
my: "left top",_x000D_
at: "left bottom",_x000D_
of: $(this)_x000D_
});_x000D_
}).attr("readonly", false);_x000D_
});_x000D_
// --------------------------------
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />_x000D_
_x000D_
<div class="container">_x000D_
_x000D_
<h2 class="font-weight-light text-lg-left mt-4 mb-0"><b>jQuery UI Datepicker</b> custom select</h2>_x000D_
_x000D_
<hr class="mt-2 mb-3">_x000D_
<div class="row text-lg-left">_x000D_
<div class="col-12">_x000D_
_x000D_
<form>_x000D_
_x000D_
<div class="form-label-group">_x000D_
<label for="datepicker1">(month and year only : <code>id="datepicker1"</code> )</label>_x000D_
<input type="text" class="form-control" id="datepicker1" _x000D_
placeholder="(month and year only)" />_x000D_
</div>_x000D_
_x000D_
<hr />_x000D_
_x000D_
<div class="form-label-group">_x000D_
<label for="datepicker2">(year only : <code>input id="datepicker2"</code> )</label>_x000D_
<input type="text" class="form-control" id="datepicker2" _x000D_
placeholder="(year only)" />_x000D_
</div>_x000D_
_x000D_
<hr />_x000D_
_x000D_
<div class="form-label-group">_x000D_
<label for="datepicker3">(year only, no controls : <code>input id="datepicker3"</code> )</label>_x000D_
<input type="text" class="form-control" id="datepicker3" _x000D_
placeholder="(year only, no controls)" />_x000D_
</div>_x000D_
_x000D_
</form>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_
I know this question is pretty old but I thought that my solution can be of use to others that encounter this problem. Hope it helps.
Java Try and Catch IOException Problem
The reason you are getting the the IOException is because you are not catching the IOException of your countLines method. You'll want to do something like this:
public static void main(String[] args) {
int lines = 0;
// TODO - Need to get the filename to populate sFileName. Could
// come from the command line arguments.
try {
lines = LineCounter.countLines(sFileName);
}
catch(IOException ex){
System.out.println (ex.toString());
System.out.println("Could not find file " + sFileName);
}
if(lines > 0) {
// Do rest of program.
}
}
Byte Array to Hex String
Using str.format
:
>>> array_alpha = [ 133, 53, 234, 241 ]
>>> print ''.join('{:02x}'.format(x) for x in array_alpha)
8535eaf1
or using format
>>> print ''.join(format(x, '02x') for x in array_alpha)
8535eaf1
Note: In the format statements, the 02
means it will pad with up to 2 leading 0
s if necessary. This is important since [0x1, 0x1, 0x1] i.e. (0x010101)
would be formatted to "111"
instead of "010101"
or using bytearray
with binascii.hexlify
:
>>> import binascii
>>> binascii.hexlify(bytearray(array_alpha))
'8535eaf1'
Here is a benchmark of above methods in Python 3.6.1:
from timeit import timeit
import binascii
number = 10000
def using_str_format() -> str:
return "".join("{:02x}".format(x) for x in test_obj)
def using_format() -> str:
return "".join(format(x, "02x") for x in test_obj)
def using_hexlify() -> str:
return binascii.hexlify(bytearray(test_obj)).decode('ascii')
def do_test():
print("Testing with {}-byte {}:".format(len(test_obj), test_obj.__class__.__name__))
if using_str_format() != using_format() != using_hexlify():
raise RuntimeError("Results are not the same")
print("Using str.format -> " + str(timeit(using_str_format, number=number)))
print("Using format -> " + str(timeit(using_format, number=number)))
print("Using binascii.hexlify -> " + str(timeit(using_hexlify, number=number)))
test_obj = bytes([i for i in range(255)])
do_test()
test_obj = bytearray([i for i in range(255)])
do_test()
Result:
Testing with 255-byte bytes:
Using str.format -> 1.459474583090427
Using format -> 1.5809937679100738
Using binascii.hexlify -> 0.014521426401399307
Testing with 255-byte bytearray:
Using str.format -> 1.443447684109402
Using format -> 1.5608712609513171
Using binascii.hexlify -> 0.014114164661833684
Methods using format
do provide additional formatting options, as example separating numbers with spaces " ".join
, commas ", ".join
, upper-case printing "{:02X}".format(x)
/format(x, "02X")
, etc., but at a cost of great performance impact.
javascript functions to show and hide divs
<script>
function show() {
if(document.getElementById('benefits').style.display=='none') {
document.getElementById('benefits').style.display='block';
}
return false;
}
function hide() {
if(document.getElementById('benefits').style.display=='block') {
document.getElementById('benefits').style.display='none';
}
return false;
}
</script>
<div id="opener"><a href="#1" name="1" onclick="return show();">click here</a></div>
<div id="benefits" style="display:none;">some input in here plus the close button
<div id="upbutton"><a onclick="return hide();">click here</a></div>
</div>
SSL cert "err_cert_authority_invalid" on mobile chrome only
I just spent the morning dealing with this. The problem wasn't that I had a certificate missing. It was that I had an extra.
I started out with my ssl.conf containing my server key and three files provided by my SSL certificate authority:
# Server Certificate:
SSLCertificateFile /etc/pki/tls/certs/myserver.cer
# Server Private Key:
SSLCertificateKeyFile /etc/pki/tls/private/myserver.key
# Server Certificate Chain:
SSLCertificateChainFile /etc/pki/tls/certs/AddTrustExternalCARoot.pem
# Certificate Authority (CA):
SSLCACertificateFile /etc/pki/tls/certs/InCommonServerCA.pem
It worked fine on desktops, but Chrome on Android gave me err_cert_authority_invalid
A lot of headaches, searching and poor documentation later, I figured out that it was the Server Certificate Chain:
SSLCertificateChainFile /etc/pki/tls/certs/AddTrustExternalCARoot.pem
That was creating a second certificate chain which was incomplete. I commented out that line, leaving me with
# Server Certificate:
SSLCertificateFile /etc/pki/tls/certs/myserver.cer
# Server Private Key:
SSLCertificateKeyFile /etc/pki/tls/private/myserver.key
# Certificate Authority (CA):
SSLCACertificateFile /etc/pki/tls/certs/InCommonServerCA.pem
and now it's working on Android again. This was on Linux running Apache 2.2.
What does $(function() {} ); do?
$(function() { ... });
is just jQuery short-hand for
$(document).ready(function() { ... });
What it's designed to do (amongst other things) is ensure that your function is called once all the DOM elements of the page are ready to be used.
However, I don't think that's the problem you're having - can you clarify what you mean by 'Somehow, some functions are cannot be called and I have to call those function inside' ?
Maybe post some code to show what's not working as expected ?
Edit: Re-reading your question, it could be that your function is running before the page has finished loaded, and therefore won't execute properly; putting it in $(function) would indeed fix that!
Convert array of integers to comma-separated string
You can have a pair of extension methods to make this task easier:
public static string ToDelimitedString<T>(this IEnumerable<T> lst, string separator = ", ")
{
return lst.ToDelimitedString(p => p, separator);
}
public static string ToDelimitedString<S, T>(this IEnumerable<S> lst, Func<S, T> selector,
string separator = ", ")
{
return string.Join(separator, lst.Select(selector));
}
So now just:
new int[] { 1, 2, 3, 4, 5 }.ToDelimitedString();
What's the best way to parse command line arguments?
Lightweight command line argument defaults
Although argparse
is great and is the right answer for fully documented command line switches and advanced features, you can use function argument defaults to handles straightforward positional arguments very simply.
import sys
def get_args(name='default', first='a', second=2):
return first, int(second)
first, second = get_args(*sys.argv)
print first, second
The 'name' argument captures the script name and is not used. Test output looks like this:
> ./test.py
a 2
> ./test.py A
A 2
> ./test.py A 20
A 20
For simple scripts where I just want some default values, I find this quite sufficient. You might also want to include some type coercion in the return values or command line values will all be strings.
How to load property file from classpath?
If you use the static method and load the properties file from the classpath folder so you can use the below code :
//load a properties file from class path, inside static method
Properties prop = new Properties();
prop.load(Classname.class.getClassLoader().getResourceAsStream("foo.properties"));
Eclipse says: “Workspace in use or cannot be created, chose a different one.” How do I unlock a workspace?
Choosing a "different one" is actually a pretty easy solution.
I had been running Eclipse as an administrator (sudo eclipse
from the command line) because the "workspace" folder was throwing the Workspace in use or cannot be created…
error (and running as administrator seemed to be the only solution that fixed it).
A coworker (working on this same issue with me) wanted to run Eclipse by clicking on an icon. So when he ran Eclipse, and the dialogue box came up with the choose your workspace, he just added a "2" to the end of "workspace".
This created a new folder: "workspace2". Eclipse ran fine with that; and I haven’t had any of the locking problems since.
How do I center an anchor element in CSS?
Two options, that have different uses:
HTML:
<a class="example" href="http://www.example.com">example</a>
CSS:
.example { text-align: center; }
Or:
.example { display:block; width:100px; margin:0 auto;}
What is the point of the diamond operator (<>) in Java 7?
The issue with
List<String> list = new LinkedList();
is that on the left hand side, you are using the generic type List<String>
where on the right side you are using the raw type LinkedList
. Raw types in Java effectively only exist for compatibility with pre-generics code and should never be used in new code unless
you absolutely have to.
Now, if Java had generics from the beginning and didn't have types, such as LinkedList
, that were originally created before it had generics, it probably could have made it so that the constructor for a generic type automatically infers its type parameters from the left-hand side of the assignment if possible. But it didn't, and it must treat raw types and generic types differently for backwards compatibility. That leaves them needing to make a slightly different, but equally convenient, way of declaring a new instance of a generic object without having to repeat its type parameters... the diamond operator.
As far as your original example of List<String> list = new LinkedList()
, the compiler generates a warning for that assignment because it must. Consider this:
List<String> strings = ... // some list that contains some strings
// Totally legal since you used the raw type and lost all type checking!
List<Integer> integers = new LinkedList(strings);
Generics exist to provide compile-time protection against doing the wrong thing. In the above example, using the raw type means you don't get this protection and will get an error at runtime. This is why you should not use raw types.
// Not legal since the right side is actually generic!
List<Integer> integers = new LinkedList<>(strings);
The diamond operator, however, allows the right hand side of the assignment to be defined as a true generic instance with the same type parameters as the left side... without having to type those parameters again. It allows you to keep the safety of generics with almost the same effort as using the raw type.
I think the key thing to understand is that raw types (with no <>
) cannot be treated the same as generic types. When you declare a raw type, you get none of the benefits and type checking of generics. You also have to keep in mind that generics are a general purpose part of the Java language... they don't just apply to the no-arg constructors of Collection
s!
How to do this in Laravel, subquery where in
You can use Eloquent in different queries and make things easier to understand and mantain:
$productCategory = ProductCategory::whereIn('category_id', ['223', '15'])
->select('product_id'); //don't need ->get() or ->first()
and then we put all together:
Products::whereIn('id', $productCategory)
->where('active', 1)
->select('id', 'name', 'img', 'safe_name', 'sku', 'productstatusid')
->get();//runs all queries at once
This will generate the same query that you wrote in your question.
Simulate string split function in Excel formula
A formula to return either the first word or all the other words.
=IF(ISERROR(FIND(" ",TRIM(A2),1)),TRIM(A2),MID(TRIM(A2),FIND(" ",TRIM(A2),1),LEN(A2)))
Examples and results
Text Description Results
Blank
Space
some Text no space some
some text Text with space text
some Text with leading space some
some Text with trailing space some
some text some text Text with multiple spaces text some text
Comments on Formula:
- The TRIM function is used to remove all leading and trailing spaces. Duplicate spacing within the text is also removed.
- The FIND function then finds the
first space
- If there is no space then the trimmed
text is returned
- Otherwise the MID function is
used to return any text after the
first space
Angular 2: How to access an HTTP response body?
I had the same issue too and this worked for me try:
this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10').
subscribe((res) => {
let resSTR = JSON.stringify(res);
let resJSON = JSON.parse(resStr);
console.log(resJSON._body);
})
Sending cookies with postman
I used postman chrome extension until it became deprecated. Chrome extension also less usable and powerful then native postman application. So, it became not very convenient to use chrome extension.
I have found next approach:
- copy any request in chrome/any other browser as CURL request (image
1)
- import to postman copied request (image 2)
- save imported request in postman's list
image 1
image 2
file_get_contents() how to fix error "Failed to open stream", "No such file"
The URL is missing the protocol information. PHP thinks it is a filesystem path and tries to access the file at the specified location. However, the location doesn't actually exist in your filesystem and an error is thrown.
You'll need to add http
or https
at the beginning of the URL you're trying to get the contents from:
$json = json_decode(file_get_contents('http://...'));
As for the following error:
Unable to find the wrapper - did you forget to enable it when you configured PHP?
Your Apache installation probably wasn't compiled with SSL support. You could manually try to install OpenSSL and use it, or use cURL. I personally prefer cURL over file_get_contents()
. Here's a function you can use:
function curl_get_contents($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
Usage:
$url = 'https://...';
$json = json_decode(curl_get_contents($url));
Prevent typing non-numeric in input type number
Based on Nrzonline's answer: I fixed the problem of the multiple "." at the end of the input by adding a
let lastCharacterEntered
outside of the input and then onKeyPress
e => {
var allowedChars = "0123456789.";
function contains(stringValue, charValue) {
return stringValue.indexOf(charValue) > -1;
}
var invalidKey =
(e.key.length === 1 && !contains(allowedChars, e.key)) ||
(e.key === "." && contains(e.target.value, "."));
console.log(e.target.value);
invalidKey && e.preventDefault();
if (!invalidKey) {
if (lastCharacterEntered === "." && e.key === ".") {
e.preventDefault();
} else {
lastCharacterEntered = e.key;
}
}
}
Uncaught TypeError: .indexOf is not a function
Convert timeofday to string to use indexOf
var timeofday = new Date().getHours() + (new Date().getMinutes()) / 60;
console.log(typeof(timeofday)) // for testing will log number
function timeD2C(time) { // Converts 11.5 (decimal) to 11:30 (colon)
var pos = time.indexOf('.');
var hrs = time.substr(1, pos - 1);
var min = (time.substr(pos, 2)) * 60;
if (hrs > 11) {
hrs = (hrs - 12) + ":" + min + " PM";
} else {
hrs += ":" + min + " AM";
}
return hrs;
}
// "" for typecasting to string
document.getElementById("oset").innerHTML = timeD2C(""+timeofday);
Test Here
Solution 2
use toString()
to convert to string
document.getElementById("oset").innerHTML = timeD2C(timeofday.toString());
jsfiddle with toString()
Accessing AppDelegate from framework?
If you're creating a framework the whole idea is to make it portable. Tying a framework to the app delegate defeats the purpose of building a framework. What is it you need the app delegate for?
Unable instantiate android.gms.maps.MapFragment
Please read carefully
If everything is woking same as google code then please check manifest file in my case i added geo key and map key that's why exception occurs,
Note - do not add two keys in manifest file remove map key
meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="@string/google_maps_key"/>
add this code.
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/auto_location"/>
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version"/>
Creating Dynamic button with click event in JavaScript
Firstly, you need to change this line:
element.setAttribute("onclick", alert("blabla"));
To something like this:
element.setAttribute("onclick", function() { alert("blabla"); });
Secondly, you may have browser compatibility issues when attaching events that way. You might need to use .attachEvent / .addEvent, depending on which browser. I haven't tried manually setting event handlers for a while, but I remember firefox and IE treating them differently.
Saving image from PHP URL
$data = file_get_contents('http://example.com/image.php');
$img = imagecreatefromstring($data);
imagepng($img, 'test.png');
How to check if a Unix .tar.gz file is a valid file without uncompressing?
A nice option is to use tar -tvvf <filePath>
which adds a line that reports the kind of file.
Example in a valid .tar file:
> tar -tvvf filename.tar
drwxr-xr-x 0 diegoreymendez staff 0 Jul 31 12:46 ./testfolder2/
-rw-r--r-- 0 diegoreymendez staff 82 Jul 31 12:46 ./testfolder2/._.DS_Store
-rw-r--r-- 0 diegoreymendez staff 6148 Jul 31 12:46 ./testfolder2/.DS_Store
drwxr-xr-x 0 diegoreymendez staff 0 Jul 31 12:42 ./testfolder2/testfolder/
-rw-r--r-- 0 diegoreymendez staff 82 Jul 31 12:42 ./testfolder2/testfolder/._.DS_Store
-rw-r--r-- 0 diegoreymendez staff 6148 Jul 31 12:42 ./testfolder2/testfolder/.DS_Store
-rw-r--r-- 0 diegoreymendez staff 325377 Jul 5 09:50 ./testfolder2/testfolder/Scala.pages
Archive Format: POSIX ustar format, Compression: none
Corrupted .tar file:
> tar -tvvf corrupted.tar
tar: Unrecognized archive format
Archive Format: (null), Compression: none
tar: Error exit delayed from previous errors.
HttpURLConnection timeout settings
HttpURLConnection
has a setConnectTimeout method.
Just set the timeout to 5000 milliseconds, and then catch java.net.SocketTimeoutException
Your code should look something like this:
try {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setRequestMethod("HEAD");
con.setConnectTimeout(5000); //set timeout to 5 seconds
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
} catch (java.net.SocketTimeoutException e) {
return false;
} catch (java.io.IOException e) {
return false;
}
How do you create a Swift Date object?
I often have a need to combine date values from one place with time values for another. I wrote a helper function to accomplish this.
let startDateTimeComponents = NSDateComponents()
startDateTimeComponents.year = NSCalendar.currentCalendar().components(NSCalendarUnit.Year, fromDate: date).year
startDateTimeComponents.month = NSCalendar.currentCalendar().components(NSCalendarUnit.Month, fromDate: date).month
startDateTimeComponents.day = NSCalendar.currentCalendar().components(NSCalendarUnit.Day, fromDate: date).day
startDateTimeComponents.hour = NSCalendar.currentCalendar().components(NSCalendarUnit.Hour, fromDate: time).hour
startDateTimeComponents.minute = NSCalendar.currentCalendar().components(NSCalendarUnit.Minute, fromDate: time).minute
let startDateCalendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
combinedDateTime = startDateCalendar!.dateFromComponents(startDateTimeComponents)!
How to resize an Image C#
If you're working with a BitmapSource
:
var resizedBitmap = new TransformedBitmap(
bitmapSource,
new ScaleTransform(scaleX, scaleY));
If you want finer control over quality, run this first:
RenderOptions.SetBitmapScalingMode(
bitmapSource,
BitmapScalingMode.HighQuality);
(Default is BitmapScalingMode.Linear
which is equivalent to BitmapScalingMode.LowQuality
.)
Can I store images in MySQL
Yes, you can store images in the database, but it's not advisable in my opinion, and it's not general practice.
A general practice is to store images in directories on the file system and store references to the images in the database. e.g. path to the image,the image name, etc.. Or alternatively, you may even store images on a content delivery network (CDN) or numerous hosts across some great expanse of physical territory, and store references to access those resources in the database.
Images can get quite large, greater than 1MB. And so storing images in a database can potentially put unnecessary load on your database and the network between your database and your web server if they're on different hosts.
I've worked at startups, mid-size companies and large technology companies with 400K+ employees. In my 13 years of professional experience, I've never seen anyone store images in a database. I say this to support the statement it is an uncommon practice.
strdup() - what does it do in C?
Exactly what it sounds like, assuming you're used to the abbreviated way in which C and UNIX assigns words, it duplicates strings :-)
Keeping in mind it's actually not part of the ISO C standard itself(a) (it's a POSIX thing), it's effectively doing the same as the following code:
char *strdup(const char *src) {
char *dst = malloc(strlen (src) + 1); // Space for length plus nul
if (dst == NULL) return NULL; // No memory
strcpy(dst, src); // Copy the characters
return dst; // Return the new string
}
In other words:
It tries to allocate enough memory to hold the old string (plus a '\0' character to mark the end of the string).
If the allocation failed, it sets errno
to ENOMEM
and returns NULL
immediately. Setting of errno
to ENOMEM
is something malloc
does in POSIX so we don't need to explicitly do it in our strdup
. If you're not POSIX compliant, ISO C doesn't actually mandate the existence of ENOMEM
so I haven't included that here(b).
Otherwise the allocation worked so we copy the old string to the new string(c) and return the new address (which the caller is responsible for freeing at some point).
Keep in mind that's the conceptual definition. Any library writer worth their salary may have provided heavily optimised code targeting the particular processor being used.
(a) However, functions starting with str
and a lower case letter are reserved by the standard for future directions. From C11 7.1.3 Reserved identifiers
:
Each header declares or defines all identifiers listed in its associated sub-clause, and *optionally declares or defines identifiers listed in its associated future library directions sub-clause.**
The future directions for string.h
can be found in C11 7.31.13 String handling <string.h>
:
Function names that begin with str
, mem
, or wcs
and a lowercase letter may be added to the declarations in the <string.h>
header.
So you should probably call it something else if you want to be safe.
(b) The change would basically be replacing if (d == NULL) return NULL;
with:
if (d == NULL) {
errno = ENOMEM;
return NULL;
}
(c) Note that I use strcpy
for that since that clearly shows the intent. In some implementations, it may be faster (since you already know the length) to use memcpy
, as they may allow for transferring the data in larger chunks, or in parallel. Or it may not :-) Optimisation mantra #1: "measure, don't guess".
In any case, should you decide to go that route, you would do something like:
char *strdup(const char *src) {
size_t len = strlen(src) + 1; // String plus '\0'
char *dst = malloc(len); // Allocate space
if (dst == NULL) return NULL; // No memory
memcpy (dst, src, len); // Copy the block
return dst; // Return the new string
}
Using different Web.config in development and production environment
This is one of the huge benefits of using the machine.config. At my last job, we had development, test and production environments. We could use the machine.config for things like connection strings (to the appropriate, dev/test/prod SQL machine).
This may not be a solution for you if you don't have access to the actual production machine (like, if you were using a hosting company on a shared host).
How to debug Apache mod_rewrite
One trick is to turn on the rewrite log. To turn it on, try this line in your apache main config or current virtual host file (not in .htaccess
):
LogLevel alert rewrite:trace6
Before Apache httpd 2.4 mod_rewrite, such a per-module logging configuration did not exist yet, instead you could use the following logging settings:
RewriteEngine On
RewriteLog "/var/log/apache2/rewrite.log"
RewriteLogLevel 3