Using onBackPressed() in Android Fragments
I didn't find any good answer about this problem, so this is my solution.
If you want to get backPress in each fragment do the following.
create interface OnBackPressedListener
public interface OnBackPressedListener {
void onBackPressed();
}
That each fragment that wants to be informed of backPress
implements this interface.
In parent activity , you can override onBackPressed()
@Override
public void onBackPressed() {
List<Fragment> fragmentList = getSupportFragmentManager().getFragments();
if (fragmentList != null) {
//TODO: Perform your logic to pass back press here
for(Fragment fragment : fragmentList){
if(fragment instanceof OnBackPressedListener){
((OnBackPressedListener)fragment).onBackPressed();
}
}
}
}
Add Items to ListView - Android
Try this one it will work
public class Third extends ListActivity {
private ArrayAdapter<String> adapter;
private List<String> liste;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };
liste = new ArrayList<String>();
Collections.addAll(liste, values);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, liste);
setListAdapter(adapter);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
liste.add("Nokia");
adapter.notifyDataSetChanged();
}
}
How do I start an activity from within a Fragment?
I done it, below code is working for me....
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.hello_world, container, false);
Button newPage = (Button)v.findViewById(R.id.click);
newPage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), HomeActivity.class);
startActivity(intent);
}
});
return v;
}
and Please make sure that your destination activity should be register in Manifest.xml file,
but in my case all tabs are not shown in HomeActivity, is any solution for that ?
Intent from Fragment to Activity
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame, new MySchedule()).commit();
MySchedule is the name of my java class.
How to move from one fragment to another fragment on click of an ImageView in Android?
When you are inside an activity and need to go to a fragment use below
getFragmentManager().beginTransaction().replace(R.id.*TO_BE_REPLACED_LAYOUT_ID*, new tasks()).commit();
But when you are inside a fragment and need to go to a fragment then just add a getActivity().
before, so it would become
getActivity().getFragmentManager().beginTransaction().replace(R.id.*TO_BE_REPLACED_LAYOUT_ID*, new tasks()).commit();
as simple as that.
The *TO_BE_REPLACED_LAYOUT_ID*
can be the entire page of activity or a part of it, just make sure to put an id to the layout to be replaced. It is general practice to put the replaceable layout in a FrameLayout
.
Cannot resolve method 'getSupportFragmentManager ( )' inside Fragment
If you're instantiating an android.support.v4.app.Fragment
class, the you have to call getActivity().getSupportFragmentManager()
to get rid of the cannot-resolve problem. However the official Android docs on Fragment by Google tends to over look this simple problem and they still document it without the getActivity()
prefix.
Receive result from DialogFragment
For anyone still reading this: setTargetFragment()
has been deprecated. It is now recommended to use the FragmentResultListener
API like this:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setFragmentResultListener("requestKey") { key, bundle ->
val result = bundle.getString("resultKey")
// Do something with the result...
}
...
// Somewhere show your dialog
MyDialogFragment.newInstance().show(parentFragmentManager, "tag")
}
Then in your MyDialogFragment
set the result:
button.setOnClickListener{
val result = "some string"
setFragmentResult("requestKey", bundleOf("resultKey" to result))
dismiss()
}
Handling back button in Android Navigation Component
If you use Navigation Component follow the codes below in your onCreateView() method (in this example I want just to close my app by this fragment)
OnBackPressedCallback backPressedCallback = new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
new AlertDialog.Builder(Objects.requireNonNull(getActivity()))
.setIcon(R.drawable.icon_01)
.setTitle(getResources().getString(R.string.close_app_title))
.setMessage(getResources().getString(R.string.close_app_message))
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
getActivity().finish();
}
})
.setNegativeButton(R.string.no, null)
.show();
}
};
requireActivity().getOnBackPressedDispatcher().addCallback(this, backPressedCallback);
FragmentActivity to Fragment
first of all;
a Fragment
must be inside a FragmentActivity
, that's the first rule,
a FragmentActivity
is quite similar to a standart Activity
that you already know, besides having some Fragment oriented methods
second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView
, where you inflate your layout, think of it as the setContentLayout
here is an example:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.fragment_layout, container, false); return mView; }
and continu your work based on that mView, so to find a View
by id, call mView.findViewById(..);
for the FragmentActivity
part:
the xml part "must" have a FrameLayout
in order to inflate a fragment in it
<FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" > </FrameLayout>
as for the inflation part
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();
begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site
Android - save/restore fragment state
Android fragment has some advantages and some disadvantages.
The most disadvantage of the fragment is that when you want to use a fragment you create it ones.
When you use it, onCreateView
of the fragment is called for each time. If you want to keep state of the components in the fragment you must save fragment state and yout must load its state in the next shown.
This make fragment view a bit slow and weird.
I have found a solution and I have used this solution: "Everything is great. Every body can try".
When first time onCreateView
is being run, create view as a global variable. When second time you call this fragment onCreateView
is called again you can return this global view. The fragment component state will be kept.
View view;
@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
setActionBar(null);
if (view != null) {
if ((ViewGroup)view.getParent() != null)
((ViewGroup)view.getParent()).removeView(view);
return view;
}
view = inflater.inflate(R.layout.mylayout, container, false);
}
How does "FOR" work in cmd batch file?
for /f
iterates per line input, so in your program will only output first path.
your program treats %PATH% as one-line input, and deliminate by ;
, put first result to %%g, then output %%g (first deliminated path).
how to convert JSONArray to List of Object using camel-jackson
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
String jsonText = readAll(inputofyourjsonstream);
JSONObject json = new JSONObject(jsonText);
JSONArray arr = json.getJSONArray("Compemployes");
Your arr would looks like: [
{
"id":1001,
"name":"jhon"
},
{
"id":1002,
"name":"jhon"
}
]
You can use:
arr.getJSONObject(index)
to get the objects inside of the array.
How to use string.substr() function?
Possible solution with string_view
void do_it_with_string_view( void )
{
std::string a { "12345" };
for ( std::string_view v { a }; v.size() - 1; v.remove_prefix( 1 ) )
std::cout << v.substr( 0, 2 ) << " ";
std::cout << std::endl;
}
Laravel 5 – Clear Cache in Shared Hosting Server
You can call an Artisan command outside the CLI.
Route::get('/clear-cache', function() {
$exitCode = Artisan::call('cache:clear');
// return what you want
});
You can check the official doc here
http://laravel.com/docs/5.0/artisan#calling-commands-outside-of-cli
Update
There is no way to delete the view cache. Neither php artisan cache:clear
does that.
If you really want to clear the view cache, I think you have to write your own artisan
command and call it as I said before, or entirely skip the artisan
path and clear the view cache in some class that you call from a controller or a route.
But, my real question is do you really need to clear the view cache? In a project I'm working on now, I have almost 100 cached views and they weight less then 1 Mb, while my vendor
directory is > 40 Mb. I don't think view cache is a real bottleneck in disk usage and never had a real need to clear it.
As for the application cache, it is stored in the storage/framework/cache
directory, but only if you configured the file
driver in config/cache.php
. You can choose many different drivers, such as Redis or Memcached, to improve performances over a file-based cache.
How do I POST a x-www-form-urlencoded request using Fetch?
You have to put together the x-www-form-urlencoded payload yourself, like this:
var details = {
'userName': '[email protected]',
'password': 'Password!',
'grant_type': 'password'
};
var formBody = [];
for (var property in details) {
var encodedKey = encodeURIComponent(property);
var encodedValue = encodeURIComponent(details[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
fetch('https://example.com/login', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
body: formBody
})
Note that if you were using fetch
in a (sufficiently modern) browser, instead of React Native, you could instead create a URLSearchParams
object and use that as the body, since the Fetch Standard states that if the body
is a URLSearchParams
object then it should be serialised as application/x-www-form-urlencoded
. However, you can't do this in React Native because React Native does not implement URLSearchParams
.
What is the apply function in Scala?
1 - Treat functions as objects.
2 - The apply method is similar to __call __ in Python, which allows you to use an instance of a given class as a function.
How do I get this javascript to run every second?
You can use setTimeout to run the function/command once or setInterval to run the function/command at specified intervals.
var a = setTimeout("alert('run just one time')",500);
var b = setInterval("alert('run each 3 seconds')",3000);
//To abort the interval you can use this:
clearInterval(b);
How do I convert 2018-04-10T04:00:00.000Z string to DateTime?
Update: Using DateTimeFormat
, introduced in java 8:
The idea is to define two formats: one for the input format, and one for the output format. Parse with the input formatter, then format with the output formatter.
Your input format looks quite standard, except the trailing Z
. Anyway, let's deal with this: "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
. The trailing 'Z'
is the interesting part. Usually there's time zone data here, like -0700
. So the pattern would be ...Z
, i.e. without apostrophes.
The output format is way more simple: "dd-MM-yyyy"
. Mind the small y
-s.
Here is the example code:
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyy", Locale.ENGLISH);
LocalDate date = LocalDate.parse("2018-04-10T04:00:00.000Z", inputFormatter);
String formattedDate = outputFormatter.format(date);
System.out.println(formattedDate); // prints 10-04-2018
Original answer - with old API SimpleDateFormat
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
SimpleDateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = inputFormat.parse("2018-04-10T04:00:00.000Z");
String formattedDate = outputFormat.format(date);
System.out.println(formattedDate); // prints 10-04-2018
Virtualhost For Wildcard Subdomain and Static Subdomain
<VirtualHost *:80>
DocumentRoot /var/www/app1
ServerName app1.example.com
</VirtualHost>
<VirtualHost *:80>
DocumentRoot /var/www/example
ServerName example.com
</VirtualHost>
<VirtualHost *:80>
DocumentRoot /var/www/wildcard
ServerName other.example.com
ServerAlias *.example.com
</VirtualHost>
Should work. The first entry will become the default if you don't get an explicit match. So if you had app.otherexample.com point to it, it would be caught be app1.example.com.
How To Convert A Number To an ASCII Character?
I was googling about how to convert an int to char, that got me here. But my question was to convert for example int of 6 to char of '6'.
For those who came here like me, this is how to do it:
int num = 6;
num.ToString().ToCharArray()[0];
PHP CURL & HTTPS
Another option like Gavin Palmer answer is to use the .pem
file but with a curl option
download the last updated .pem
file from https://curl.haxx.se/docs/caextract.html and save it somewhere on your server(outside the public folder)
set the option in your code instead of the php.ini
file.
In your code
curl_setopt($ch, CURLOPT_CAINFO, $_SERVER['DOCUMENT_ROOT'] . "/../cacert-2017-09-20.pem");
NOTE: setting the cainfo in the php.ini
like @Gavin Palmer did is better than setting it in your code like I did, because it will save a disk IO every time the function is called, I just make it like this in case you want to test the cainfo file on the fly instead of changing the php.ini
while testing your function.
indexOf and lastIndexOf in PHP?
This is the best way to do it, very simple.
$msg = "Hello this is a string";
$first_index_of_i = stripos($msg,'i');
$last_index_of_i = strripos($msg, 'i');
echo "First i : " . $first_index_of_i . PHP_EOL ."Last i : " . $last_index_of_i;
Listing only directories in UNIX
### If you need full path of dir and list selective dir with "name" of dir(or dir_prefix*):
find $(pwd) -maxdepth 1 -type d -name "SL*"
Align image in center and middle within div
for a long time, i also tried the solution to put the img at the center of the div, but for my case i just need this type of component on ajax loading progress so i simply tried the following solution, hope this helps for you!
<div id="loader" style="position: absolute;top: 0;right: 0;left: 0;bottom: 0;z-index: 1;background: rgba(255,255,255,0.5) url('your_image_url') no-repeat center;background-size: 135px;display: none;"></div>
UIButton title text color
In Swift:
Changing the label text color is quite different than changing it for a UIButton
. To change the text color for a UIButton
use this method:
self.headingButton.setTitleColor(UIColor(red: 107.0/255.0, green: 199.0/255.0, blue: 217.0/255.0), forState: UIControlState.Normal)
How to add minutes to current time in swift
You can use in swift 4 or 5
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd H:mm:ss"
let current_date_time = dateFormatter.string(from: date)
print("before add time-->",current_date_time)
//adding 5 miniuts
let addminutes = date.addingTimeInterval(5*60)
dateFormatter.dateFormat = "yyyy-MM-dd H:mm:ss"
let after_add_time = dateFormatter.string(from: addminutes)
print("after add time-->",after_add_time)
output:
before add time--> 2020-02-18 10:38:15
after add time--> 2020-02-18 10:43:15
Store JSON object in data attribute in HTML jQuery
Actually, your last example:
<div data-foobar='{"foo":"bar"}'></div>
seems to be working well (see http://jsfiddle.net/GlauberRocha/Q6kKU/).
The nice thing is that the string in the data- attribute is automatically converted to a JavaScript object. I don't see any drawback in this approach, on the contrary! One attribute is sufficient to store a whole set of data, ready to use in JavaScript through object properties.
(Note: for the data- attributes to be automatically given the type Object rather than String, you must be careful to write valid JSON, in particular to enclose the key names in double quotes).
Difference in months between two dates
My problem was solved with this solution:
static void Main(string[] args)
{
var date1 = new DateTime(2018, 12, 05);
var date2 = new DateTime(2019, 03, 01);
int CountNumberOfMonths() => (date2.Month - date1.Month) + 12 * (date2.Year - date1.Year);
var numberOfMonths = CountNumberOfMonths();
Console.WriteLine("Number of months between {0} and {1}: {2} months.", date1.ToString(), date2.ToString(), numberOfMonths.ToString());
Console.ReadKey();
//
// *** Console Output:
// Number of months between 05/12/2018 00:00:00 and 01/03/2019 00:00:00: 3 months.
//
}
Javascript button to insert a big black dot (•) into a html textarea
Just access the element and append it to the value.
<input
type="button"
onclick="document.getElementById('myTextArea').value += '•'"
value="Add •">
See a live demo.
For the sake of keeping things simple, I haven't written unobtrusive JS. For a production system you should.
Also it needs to be a UTF8 character.
Browsers generally submit forms using the encoding they received the page in. Serve your page as UTF-8 if you want UTF-8 data submitted back.
How to ALTER multiple columns at once in SQL Server
As lots of others have said, you will need to use multiple ALTER COLUMN
statements, one for each column you want to modify.
If you want to modify all or several of the columns in your table to the same datatype (such as expanding a VARCHAR field from 50 to 100 chars), you can generate all the statements automatically using the query below. This technique is also useful if you want to replace the same character in multiple fields (such as removing \t from all columns).
SELECT
TABLE_CATALOG
,TABLE_SCHEMA
,TABLE_NAME
,COLUMN_NAME
,'ALTER TABLE ['+TABLE_SCHEMA+'].['+TABLE_NAME+'] ALTER COLUMN ['+COLUMN_NAME+'] VARCHAR(300)' as 'code'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'your_table' AND TABLE_SCHEMA = 'your_schema'
This generates an ALTER TABLE
statement for each column for you.
Go doing a GET request and building the Querystring
Using NewRequest
just to create an URL is an overkill. Use the net/url
package:
package main
import (
"fmt"
"net/url"
)
func main() {
base, err := url.Parse("http://www.example.com")
if err != nil {
return
}
// Path params
base.Path += "this will get automatically encoded"
// Query params
params := url.Values{}
params.Add("q", "this will get encoded as well")
base.RawQuery = params.Encode()
fmt.Printf("Encoded URL is %q\n", base.String())
}
Playground: https://play.golang.org/p/YCTvdluws-r
How to increase font size in a plot in R?
For completeness, scaling text by 150% with cex = 1.5
, here is a full solution:
cex <- 1.5
par(cex.lab=cex, cex.axis=cex, cex.main=cex)
plot(...)
par(cex.lab=1, cex.axis=1, cex.main=1)
I recommend wrapping things like this to reduce boilerplate, e.g.:
plot_cex <- function(x, y, cex=1.5, ...) {
par(cex.lab=cex, cex.axis=cex, cex.main=cex)
plot(x, y, ...)
par(cex.lab=1, cex.axis=1, cex.main=1)
invisible(0)
}
which you can then use like this:
plot_cex(x=1:5, y=rnorm(5), cex=1.3)
The ...
are known as ellipses in R and are used to pass additional parameters on to functions. Hence, they are commonly used for plotting. So, the following works as expected:
plot_cex(x=1:5, y=rnorm(5), cex=1.5, ylim=c(-0.5,0.5))
Postgresql SELECT if string contains
SELECT id FROM TAG_TABLE WHERE 'aaaaaaaa' LIKE '%' || "tag_name" || '%';
tag_name
should be in quotation otherwise it will give error as tag_name doest not exist
How do you calculate log base 2 in Java for integers?
If you are thinking about using floating-point to help with integer arithmetics, you have to be careful.
I usually try to avoid FP calculations whenever possible.
Floating-point operations are not exact. You can never know for sure what will (int)(Math.log(65536)/Math.log(2))
evaluate to. For example, Math.ceil(Math.log(1<<29) / Math.log(2))
is 30 on my PC where mathematically it should be exactly 29. I didn't find a value for x where (int)(Math.log(x)/Math.log(2))
fails (just because there are only 32 "dangerous" values), but it does not mean that it will work the same way on any PC.
The usual trick here is using "epsilon" when rounding. Like (int)(Math.log(x)/Math.log(2)+1e-10)
should never fail. The choice of this "epsilon" is not a trivial task.
More demonstration, using a more general task - trying to implement int log(int x, int base)
:
The testing code:
static int pow(int base, int power) {
int result = 1;
for (int i = 0; i < power; i++)
result *= base;
return result;
}
private static void test(int base, int pow) {
int x = pow(base, pow);
if (pow != log(x, base))
System.out.println(String.format("error at %d^%d", base, pow));
if(pow!=0 && (pow-1) != log(x-1, base))
System.out.println(String.format("error at %d^%d-1", base, pow));
}
public static void main(String[] args) {
for (int base = 2; base < 500; base++) {
int maxPow = (int) (Math.log(Integer.MAX_VALUE) / Math.log(base));
for (int pow = 0; pow <= maxPow; pow++) {
test(base, pow);
}
}
}
If we use the most straight-forward implementation of logarithm,
static int log(int x, int base)
{
return (int) (Math.log(x) / Math.log(base));
}
this prints:
error at 3^5
error at 3^10
error at 3^13
error at 3^15
error at 3^17
error at 9^5
error at 10^3
error at 10^6
error at 10^9
error at 11^7
error at 12^7
...
To completely get rid of errors I had to add epsilon which is between 1e-11 and 1e-14.
Could you have told this before testing?
I definitely could not.
How to get selected value from Dropdown list in JavaScript
Hope it's working for you
function GetSelectedItem()
{
var index = document.getElementById(select1).selectedIndex;
alert("value =" + document.getElementById(select1).value); // show selected value
alert("text =" + document.getElementById(select1).options[index].text); // show selected text
}
set initial viewcontroller in appdelegate - swift
Here is a good way to approach it. This example places a navigation controller as the root view controller, and puts the view controller of your choice within it at the bottom of the navigation stack, ready for you to push whatever you need to from it.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
// mainStoryboard
let mainStoryboard = UIStoryboard(name: "MainStoryboard", bundle: nil)
// rootViewController
let rootViewController = mainStoryboard.instantiateViewControllerWithIdentifier("MainViewController") as? UIViewController
// navigationController
let navigationController = UINavigationController(rootViewController: rootViewController!)
navigationController.navigationBarHidden = true // or not, your choice.
// self.window
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.rootViewController = navigationController
self.window!.makeKeyAndVisible()
}
To make this example work you would set "MainViewController" as the Storyboard ID on your main view controller, and the storyboard's file name in this case would be "MainStoryboard.storyboard". I rename my storyboards this way because Main.storyboard to me is not a proper name, particularly if you ever go to subclass it.
Error importing Seaborn module in Python
Problem may not be associated with Seaborn but Utils package which may not be installed
sudo pip uninstall requests
and reinstalling, it no longer would work at all.
Luckily, dnf install python-requests fixed the whole thing...
Also check for utils package is installed or not
You can install package using
sudo pip install utils
Check this link Python ImportError: cannot import name utils
JQUERY: Uncaught Error: Syntax error, unrecognized expression
The "double quote" + 'single quote' combo is not needed
console.log( $('#'+d) ); // single quotes only
console.log( $("#"+d) ); // double quotes only
Your selector results like this, which is overkill with the quotes:
$('"#abc"') // -> it'll try to find <div id='"#abc"'>
// In css, this would be the equivalent:
"#abc"{ /* Wrong */ } // instead of:
#abc{ /* Right */ }
Application Installation Failed in Android Studio
Here's my solution (there's no need to deactivate instant run) Do all these steps in the stated order:
1- Gradle Build (root level)
gradle
2 - Gradle build + clean (app level)
gradle app
3 - Choose app on the top bar (left of Run 'app')
4 - Clean Project:
Navigate to Build > Clean Project
And it should work now! You shouldn't disable instant run if you follow these steps
How to delete mysql database through shell command
If you are tired of typing your password, create a (chmod 600) file ~/.my.cnf
, and put in it:
[client]
user = "you"
password = "your-password"
For the sake of conversation:
echo 'DROP DATABASE foo;' | mysql
Import Excel Spreadsheet Data to an EXISTING sql table?
Saudate, I ran across this looking for a different problem. You most definitely can use the Sql Server Import wizard to import data into a new table. Of course, you do not wish to leave that table in the database, so my suggesting is that you import into a new table, then script the data in query manager to insert into the existing table. You can add a line to drop the temp table created by the import wizard as the last step upon successful completion of the script.
I believe your original issue is in fact related to Sql Server 64 bit and is due to your having a 32 bit Excel and these drivers don't play well together. I did run into a very similar issue when first using 64 bit excel.
How to search for an element in an stl list?
No, not directly in the std::list
template itself. You can however use std::find
algorithm like that:
std::list<int> my_list;
//...
int some_value = 12;
std::list<int>::iterator iter = std::find (my_list.begin(), my_list.end(), some_value);
// now variable iter either represents valid iterator pointing to the found element,
// or it will be equal to my_list.end()
How to increase the timeout period of web service in asp.net?
1 - You can set a timeout in your application :
var client = new YourServiceReference.YourServiceClass();
client.Timeout = 60; // or -1 for infinite
It is in milliseconds.
2 - Also you can increase timeout value in httpruntime tag in web/app.config :
<configuration>
<system.web>
<httpRuntime executionTimeout="<<**seconds**>>" />
...
</system.web>
</configuration>
For ASP.NET applications, the Timeout property value should always be less than the executionTimeout attribute of the httpRuntime element in Machine.config. The default value of executionTimeout is 90 seconds. This property determines the time ASP.NET continues to process the request before it returns a timed out error. The value of executionTimeout should be the proxy Timeout, plus processing time for the page, plus buffer time for queues. -- Source
How can I iterate over files in a given directory?
I'm not quite happy with this implementation yet, I wanted to have a custom constructor that does DirectoryIndex._make(next(os.walk(input_path)))
such that you can just pass the path you want a file listing for. Edits welcome!
import collections
import os
DirectoryIndex = collections.namedtuple('DirectoryIndex', ['root', 'dirs', 'files'])
for file_name in DirectoryIndex(*next(os.walk('.'))).files:
file_path = os.path.join(path, file_name)
IF... OR IF... in a windows batch file
Even if this question is a little older:
If you want to use if cond1 or cond 2
- you should not use complicated loops or stuff like that.
Simple provide both ifs
after each other combined with goto
- that's an implicit or.
//thats an implicit IF cond1 OR cond2 OR cond3
if cond1 GOTO doit
if cond2 GOTO doit
if cond3 GOTO doit
//thats our else.
GOTO end
:doit
echo "doing it"
:end
Without goto but an "inplace" action, you might execute the action 3 times, if ALL conditions are matching.
fatal: This operation must be run in a work tree
You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree
option for single commands, or the GIT_WORK_TREE
environment variable. There is also the core.worktree
configuration option but it will not work in a bare repository (check the man page for what it does).
# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status
How do I protect Python code?
I have looked at software protection in general for my own projects and the general philosophy is that complete protection is impossible. The only thing that you can hope to achieve is to add protection to a level that would cost your customer more to bypass than it would to purchase another license.
With that said I was just checking google for python obsfucation and not turning up a lot of anything. In a .Net solution, obsfucation would be a first approach to your problem on a windows platform, but I am not sure if anyone has solutions on Linux that work with Mono.
The next thing would be to write your code in a compiled language, or if you really want to go all the way, then in assembler. A stripped out executable would be a lot harder to decompile than an interpreted language.
It all comes down to tradeoffs. On one end you have ease of software development in python, in which it is also very hard to hide secrets. On the other end you have software written in assembler which is much harder to write, but is much easier to hide secrets.
Your boss has to choose a point somewhere along that continuum that supports his requirements. And then he has to give you the tools and time so you can build what he wants. However my bet is that he will object to real development costs versus potential monetary losses.
Difference between core and processor
CPU is a central processing unit. Since 2002 we have only single core processor i.e. we will only perform a single task or a program at a time.
For having multiple programs run at a time we have to use the multiple processor for executing multi processes at a time so we required another motherboard for that and that is very expensive.
So, Intel introduced the concept of hyper threading i.e. it will convert the single CPU into two virtual CPUs i.e we have two cores for our task. Now the CPU is single, but it is only pretending (masqueraded) that it has a dual CPU and performs multiple tasks. But having real multiple cores will be better than that so people develop making multi-core processor i.e. multiple processors on a single box i.e. grabbing a multiple CPU on single big CPU. I.e. multiple cores.
Real escape string and PDO
PDO offers an alternative designed to replace mysql_escape_string() with the PDO::quote() method.
Here is an excerpt from the PHP website:
<?php
$conn = new PDO('sqlite:/home/lynn/music.sql3');
/* Simple string */
$string = 'Nice';
print "Unquoted string: $string\n";
print "Quoted string: " . $conn->quote($string) . "\n";
?>
The above code will output:
Unquoted string: Nice
Quoted string: 'Nice'
How to execute raw queries with Laravel 5.1?
I found the solution in this topic and I code this:
$cards = DB::select("SELECT
cards.id_card,
cards.hash_card,
cards.`table`,
users.name,
0 as total,
cards.card_status,
cards.created_at as last_update
FROM cards
LEFT JOIN users
ON users.id_user = cards.id_user
WHERE hash_card NOT IN ( SELECT orders.hash_card FROM orders )
UNION
SELECT
cards.id_card,
orders.hash_card,
cards.`table`,
users.name,
sum(orders.quantity*orders.product_price) as total,
cards.card_status,
max(orders.created_at) last_update
FROM menu.orders
LEFT JOIN cards
ON cards.hash_card = orders.hash_card
LEFT JOIN users
ON users.id_user = cards.id_user
GROUP BY hash_card
ORDER BY id_card ASC");
mvn clean install vs. deploy vs. release
mvn install
will put your packaged maven project into the local repository, for local application using your project as a dependency.
mvn release
will basically put your current code in a tag on your SCM, change your version in your projects.
mvn deploy
will put your packaged maven project into a remote repository for sharing with other developers.
Resources :
scale Image in an UIButton to AspectFit?
I had problems with the image not resizing proportionately so the way I fixed it was using edge insets.
fooButton.contentEdgeInsets = UIEdgeInsetsMake(10, 15, 10, 15);
How do I get the SQLSRV extension to work with PHP, since MSSQL is deprecated?
Quoting http://php.net/manual/en/intro.mssql.php:
The MSSQL extension is not available anymore on Windows with PHP 5.3 or later.
SQLSRV, an alternative driver for MS SQL is available from Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.
Once you downloaded that, follow the instructions at this page:
In a nutshell:
Put the driver file in your PHP extension directory.
Modify the php.ini file to include the driver. For example:
extension=php_sqlsrv_53_nts_vc9.dll
Restart the Web server.
See Also (copied from that page)
The PHP Manual for the SQLSRV extension is located at http://php.net/manual/en/sqlsrv.installation.php and offers the following for Installation:
The SQLSRV extension is enabled by adding appropriate DLL file to your PHP extension directory and the corresponding entry to the php.ini file. The SQLSRV download comes with several driver files. Which driver file you use will depend on 3 factors: the PHP version you are using, whether you are using thread-safe or non-thread-safe PHP, and whether your PHP installation was compiled with the VC6 or VC9 compiler. For example, if you are running PHP 5.3, you are using non-thread-safe PHP, and your PHP installation was compiled with the VC9 compiler, you should use the php_sqlsrv_53_nts_vc9.dll file. (You should use a non-thread-safe version compiled with the VC9 compiler if you are using IIS as your web server). If you are running PHP 5.2, you are using thread-safe PHP, and your PHP installation was compiled with the VC6 compiler, you should use the php_sqlsrv_52_ts_vc6.dll file.
The drivers can also be used with PDO.
Multiple actions were found that match the request in Web Api
Your route map is probably something like this:
routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });
But in order to have multiple actions with the same http method you need to provide webapi with more information via the route like so:
routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional });
Notice that the routeTemplate now includes an action. Lots more info here: http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api
Update:
Alright, now that I think I understand what you are after here is another take at this:
Perhaps you don't need the action url parameter and should describe the contents that you are after in another way. Since you are saying that the methods are returning data from the same entity then just let the parameters do the describing for you.
For example your two methods could be turned into:
public HttpResponseMessage Get()
{
return null;
}
public HttpResponseMessage Get(MyVm vm)
{
return null;
}
What kind of data are you passing in the MyVm object? If you are able to just pass variables through the URI, I would suggest going that route. Otherwise, you'll need to send the object in the body of the request and that isn't very HTTP of you when doing a GET (it works though, just use [FromBody] infront of MyVm).
Hopefully this illustrates that you can have multiple GET methods in a single controller without using the action name or even the [HttpGet] attribute.
How can a windows service programmatically restart itself?
Set the service to restart after failure (double click the service in the control panel and have a look around on those tabs - I forget the name of it). Then, anytime you want the service to restart, just call Environment.Exit(1)
(or any non-zero return) and the OS will restart it for you.
Convenient way to parse incoming multipart/form-data parameters in a Servlet
Not always there's a servlet before of an upload (I could use a filter for example).
Or could be that the same controller ( again a filter or also a servelt ) can serve many actions, so I think that rely on that servlet configuration to use the getPart method (only for Servlet API >= 3.0), I don't know, I don't like.
In general, I prefer independent solutions, able to live alone, and in this case http://commons.apache.org/proper/commons-fileupload/ is one of that.
List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : multiparts) {
if (!item.isFormField()) {
//your operations on file
} else {
String name = item.getFieldName();
String value = item.getString();
//you operations on paramters
}
}
Null & empty string comparison in Bash
fedorqui has a working solution but there is another way to do the same thing.
Chock if a variable is set
#!/bin/bash
amIEmpty='Hello'
# This will be true if the variable has a value
if [ $amIEmpty ]; then
echo 'No, I am not!';
fi
Or to verify that a variable is empty
#!/bin/bash
amIEmpty=''
# This will be true if the variable is empty
if [ ! $amIEmpty ]; then
echo 'Yes I am!';
fi
tldp.org has good documentation about if in bash:
http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html
Default session timeout for Apache Tomcat applications
Open $CATALINA_BASE/conf/web.xml
and find this
<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly -->
<!-- created sessions by modifying the value below. -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
all webapps implicitly inherit from this default web descriptor. You can override session-config as well as other settings defined there in your web.xml.
This is actually from my Tomcat 7 (Windows) but I think 5.5 conf is not very different
How to apply color in Markdown?
Seems that kramdown supports colors in some form.
Kramdown allows inline html:
This is <span style="color: red">written in red</span>.
Also it has another syntax for including css classes inline:
This is *red*{: style="color: red"}.
This page further explains how GitLab utilizes more compact way to apply css classes in Kramdown:
Applying blue
class to text:
This is a paragraph that for some reason we want blue.
{: .blue}
Applying blue
class to headings:
#### A blue heading
{: .blue}
Applying two classes:
A blue and bold paragraph.
{: .blue .bold}
Applying ids:
#### A blue heading
{: .blue #blue-h}
This produces:
<h4 class="blue" id="blue-h">A blue heading</h4>
There is a lot of other stuff explained at above link. You may need to check.
Also, as other answer said, Kramdown is also the default markdown renderer behind Jekyll. So if you are authoring anything on github pages, above functionality might be available out of the box.
CodeIgniter: How to get Controller, Action, URL information
Update
The answer was added was in 2015 and the following methods are deprecated now
$this->router->fetch_class(); in favour of $this->router->class;
$this->router->fetch_method(); in favour of $this->router->method;
Hi you should use the following approach
$this->router->fetch_class(); // class = controller
$this->router->fetch_method(); // action
for this purpose but for using this you need to extend your hook from the CI_Controller
and it works like a charm, you should not use uri segments
Append an object to a list in R in amortized constant time, O(1)?
In the other answers, only the list
approach results in O(1) appends, but it results in a deeply nested list structure, and not a plain single list. I have used the below datastructures, they supports O(1) (amortized) appends, and allow the result to be converted back to a plain list.
expandingList <- function(capacity = 10) {
buffer <- vector('list', capacity)
length <- 0
methods <- list()
methods$double.size <- function() {
buffer <<- c(buffer, vector('list', capacity))
capacity <<- capacity * 2
}
methods$add <- function(val) {
if(length == capacity) {
methods$double.size()
}
length <<- length + 1
buffer[[length]] <<- val
}
methods$as.list <- function() {
b <- buffer[0:length]
return(b)
}
methods
}
and
linkedList <- function() {
head <- list(0)
length <- 0
methods <- list()
methods$add <- function(val) {
length <<- length + 1
head <<- list(head, val)
}
methods$as.list <- function() {
b <- vector('list', length)
h <- head
for(i in length:1) {
b[[i]] <- head[[2]]
head <- head[[1]]
}
return(b)
}
methods
}
Use them as follows:
> l <- expandingList()
> l$add("hello")
> l$add("world")
> l$add(101)
> l$as.list()
[[1]]
[1] "hello"
[[2]]
[1] "world"
[[3]]
[1] 101
These solutions could be expanded into full objects that support al list-related operations by themselves, but that will remain as an exercise for the reader.
Another variant for a named list:
namedExpandingList <- function(capacity = 10) {
buffer <- vector('list', capacity)
names <- character(capacity)
length <- 0
methods <- list()
methods$double.size <- function() {
buffer <<- c(buffer, vector('list', capacity))
names <<- c(names, character(capacity))
capacity <<- capacity * 2
}
methods$add <- function(name, val) {
if(length == capacity) {
methods$double.size()
}
length <<- length + 1
buffer[[length]] <<- val
names[length] <<- name
}
methods$as.list <- function() {
b <- buffer[0:length]
names(b) <- names[0:length]
return(b)
}
methods
}
Benchmarks
Performance comparison using @phonetagger's code (which is based on @Cron Arconis' code). I have also added a better_env_as_container
and changed the env_as_container_
a bit. The original env_as_container_
was broken and doesn't actually store all the numbers.
library(microbenchmark)
lPtrAppend <- function(lstptr, lab, obj) {lstptr[[deparse(lab)]] <- obj}
### Store list inside new environment
envAppendList <- function(lstptr, obj) {lstptr$list[[length(lstptr$list)+1]] <- obj}
env2list <- function(env, len) {
l <- vector('list', len)
for (i in 1:len) {
l[[i]] <- env[[as.character(i)]]
}
l
}
envl2list <- function(env, len) {
l <- vector('list', len)
for (i in 1:len) {
l[[i]] <- env[[paste(as.character(i), 'L', sep='')]]
}
l
}
runBenchmark <- function(n) {
microbenchmark(times = 5,
env_with_list_ = {
listptr <- new.env(parent=globalenv())
listptr$list <- NULL
for(i in 1:n) {envAppendList(listptr, i)}
listptr$list
},
c_ = {
a <- list(0)
for(i in 1:n) {a = c(a, list(i))}
},
list_ = {
a <- list(0)
for(i in 1:n) {a <- list(a, list(i))}
},
by_index = {
a <- list(0)
for(i in 1:n) {a[length(a) + 1] <- i}
a
},
append_ = {
a <- list(0)
for(i in 1:n) {a <- append(a, i)}
a
},
env_as_container_ = {
listptr <- new.env(hash=TRUE, parent=globalenv())
for(i in 1:n) {lPtrAppend(listptr, i, i)}
envl2list(listptr, n)
},
better_env_as_container = {
env <- new.env(hash=TRUE, parent=globalenv())
for(i in 1:n) env[[as.character(i)]] <- i
env2list(env, n)
},
linkedList = {
a <- linkedList()
for(i in 1:n) { a$add(i) }
a$as.list()
},
inlineLinkedList = {
a <- list()
for(i in 1:n) { a <- list(a, i) }
b <- vector('list', n)
head <- a
for(i in n:1) {
b[[i]] <- head[[2]]
head <- head[[1]]
}
},
expandingList = {
a <- expandingList()
for(i in 1:n) { a$add(i) }
a$as.list()
},
inlineExpandingList = {
l <- vector('list', 10)
cap <- 10
len <- 0
for(i in 1:n) {
if(len == cap) {
l <- c(l, vector('list', cap))
cap <- cap*2
}
len <- len + 1
l[[len]] <- i
}
l[1:len]
}
)
}
# We need to repeatedly add an element to a list. With normal list concatenation
# or element setting this would lead to a large number of memory copies and a
# quadratic runtime. To prevent that, this function implements a bare bones
# expanding array, in which list appends are (amortized) constant time.
expandingList <- function(capacity = 10) {
buffer <- vector('list', capacity)
length <- 0
methods <- list()
methods$double.size <- function() {
buffer <<- c(buffer, vector('list', capacity))
capacity <<- capacity * 2
}
methods$add <- function(val) {
if(length == capacity) {
methods$double.size()
}
length <<- length + 1
buffer[[length]] <<- val
}
methods$as.list <- function() {
b <- buffer[0:length]
return(b)
}
methods
}
linkedList <- function() {
head <- list(0)
length <- 0
methods <- list()
methods$add <- function(val) {
length <<- length + 1
head <<- list(head, val)
}
methods$as.list <- function() {
b <- vector('list', length)
h <- head
for(i in length:1) {
b[[i]] <- head[[2]]
head <- head[[1]]
}
return(b)
}
methods
}
# We need to repeatedly add an element to a list. With normal list concatenation
# or element setting this would lead to a large number of memory copies and a
# quadratic runtime. To prevent that, this function implements a bare bones
# expanding array, in which list appends are (amortized) constant time.
namedExpandingList <- function(capacity = 10) {
buffer <- vector('list', capacity)
names <- character(capacity)
length <- 0
methods <- list()
methods$double.size <- function() {
buffer <<- c(buffer, vector('list', capacity))
names <<- c(names, character(capacity))
capacity <<- capacity * 2
}
methods$add <- function(name, val) {
if(length == capacity) {
methods$double.size()
}
length <<- length + 1
buffer[[length]] <<- val
names[length] <<- name
}
methods$as.list <- function() {
b <- buffer[0:length]
names(b) <- names[0:length]
return(b)
}
methods
}
result:
> runBenchmark(1000)
Unit: microseconds
expr min lq mean median uq max neval
env_with_list_ 3128.291 3161.675 4466.726 3361.837 3362.885 9318.943 5
c_ 3308.130 3465.830 6687.985 8578.913 8627.802 9459.252 5
list_ 329.508 343.615 389.724 370.504 449.494 455.499 5
by_index 3076.679 3256.588 5480.571 3395.919 8209.738 9463.931 5
append_ 4292.321 4562.184 7911.882 10156.957 10202.773 10345.177 5
env_as_container_ 24471.511 24795.849 25541.103 25486.362 26440.591 26511.200 5
better_env_as_container 7671.338 7986.597 8118.163 8153.726 8335.659 8443.493 5
linkedList 1700.754 1755.439 1829.442 1804.746 1898.752 1987.518 5
inlineLinkedList 1109.764 1115.352 1163.751 1115.631 1206.843 1271.166 5
expandingList 1422.440 1439.970 1486.288 1519.728 1524.268 1525.036 5
inlineExpandingList 942.916 973.366 1002.461 1012.197 1017.784 1066.044 5
> runBenchmark(10000)
Unit: milliseconds
expr min lq mean median uq max neval
env_with_list_ 357.760419 360.277117 433.810432 411.144799 479.090688 560.779139 5
c_ 685.477809 734.055635 761.689936 745.957553 778.330873 864.627811 5
list_ 3.257356 3.454166 3.505653 3.524216 3.551454 3.741071 5
by_index 445.977967 454.321797 515.453906 483.313516 560.374763 633.281485 5
append_ 610.777866 629.547539 681.145751 640.936898 760.570326 763.896124 5
env_as_container_ 281.025606 290.028380 303.885130 308.594676 314.972570 324.804419 5
better_env_as_container 83.944855 86.927458 90.098644 91.335853 92.459026 95.826030 5
linkedList 19.612576 24.032285 24.229808 25.461429 25.819151 26.223597 5
inlineLinkedList 11.126970 11.768524 12.216284 12.063529 12.392199 13.730200 5
expandingList 14.735483 15.854536 15.764204 16.073485 16.075789 16.081726 5
inlineExpandingList 10.618393 11.179351 13.275107 12.391780 14.747914 17.438096 5
> runBenchmark(20000)
Unit: milliseconds
expr min lq mean median uq max neval
env_with_list_ 1723.899913 1915.003237 1921.23955 1938.734718 1951.649113 2076.910767 5
c_ 2759.769353 2768.992334 2810.40023 2820.129738 2832.350269 2870.759474 5
list_ 6.112919 6.399964 6.63974 6.453252 6.910916 7.321647 5
by_index 2163.585192 2194.892470 2292.61011 2209.889015 2436.620081 2458.063801 5
append_ 2832.504964 2872.559609 2983.17666 2992.634568 3004.625953 3213.558197 5
env_as_container_ 573.386166 588.448990 602.48829 597.645221 610.048314 642.912752 5
better_env_as_container 154.180531 175.254307 180.26689 177.027204 188.642219 206.230191 5
linkedList 38.401105 47.514506 46.61419 47.525192 48.677209 50.952958 5
inlineLinkedList 25.172429 26.326681 32.33312 34.403442 34.469930 41.293126 5
expandingList 30.776072 30.970438 34.45491 31.752790 38.062728 40.712542 5
inlineExpandingList 21.309278 22.709159 24.64656 24.290694 25.764816 29.158849 5
I have added linkedList
and expandingList
and an inlined version of both. The inlinedLinkedList
is basically a copy of list_
, but it also converts the nested structure back into a plain list. Beyond that the difference between the inlined and non-inlined versions is due to the overhead of the function calls.
All variants of expandingList
and linkedList
show O(1) append performance, with the benchmark time scaling linearly with the number of items appended. linkedList
is slower than expandingList
, and the function call overhead is also visible. So if you really need all the speed you can get (and want to stick to R code), use an inlined version of expandingList
.
I've also had a look at the C implementation of R, and both approaches should be O(1) append for any size up until you run out of memory.
I have also changed env_as_container_
, the original version would store every item under index "i", overwriting the previously appended item. The better_env_as_container
I have added is very similar to env_as_container_
but without the deparse
stuff. Both exhibit O(1) performance, but they have an overhead that is quite a bit larger than the linked/expanding lists.
Memory overhead
In the C R implementation there is an overhead of 4 words and 2 ints per allocated object. The linkedList
approach allocates one list of length two per append, for a total of (4*8+4+4+2*8=) 56 bytes per appended item on 64-bit computers (excluding memory allocation overhead, so probably closer to 64 bytes). The expandingList
approach uses one word per appended item, plus a copy when doubling the vector length, so a total memory usage of up to 16 bytes per item. Since the memory is all in one or two objects the per-object overhead is insignificant. I haven't looked deeply into the env
memory usage, but I think it will be closer to linkedList
.
How to convert the system date format to dd/mm/yy in SQL Server 2008 R2?
SELECT CONVERT(varchar(11),getdate(),101) -- mm/dd/yyyy
SELECT CONVERT(varchar(11),getdate(),103) -- dd/mm/yyyy
Check this . I am assuming D30.SPGD30_TRACKED_ADJUSTMENT_X is of datetime datatype .
That is why i am using CAST()
function to make it as an character expression because CHARINDEX()
works on character expression.
Also I think there is no need of OR condition.
select case when CHARINDEX('-',cast(D30.SPGD30_TRACKED_ADJUSTMENT_X as varchar )) > 0
then 'Score Calculation - '+CONVERT(VARCHAR(11), D30.SPGD30_TRACKED_ADJUSTMENT_X, 103)
end
EDIT:
select case when CHARINDEX('-',D30.SPGD30_TRACKED_ADJUSTMENT_X) > 0
then 'Score Calculation - '+
CONVERT( VARCHAR(11), CAST(D30.SPGD30_TRACKED_ADJUSTMENT_X as DATETIME) , 103)
end
See this link for conversion to other date formats: https://www.w3schools.com/sql/func_sqlserver_convert.asp
jsonify a SQLAlchemy result set in Flask
If you are using flask-restful
you can use marshal:
from flask.ext.restful import Resource, fields, marshal
topic_fields = {
'title': fields.String,
'content': fields.String,
'uri': fields.Url('topic'),
'creator': fields.String,
'created': fields.DateTime(dt_format='rfc822')
}
class TopicListApi(Resource):
def get(self):
return {'topics': [marshal(topic, topic_fields) for topic in DbTopic.query.all()]}
You need to explicitly list what you are returning and what type it is, which I prefer anyway for an api. Serialization is easily taken care of (no need for jsonify
), dates are also not a problem. Note that the content for the uri
field is automatically generated based on the topic
endpoint and the id.
JavaScript string encryption and decryption?
How about CryptoJS?
It's a solid crypto library, with a lot of functionality. It implements hashers, HMAC, PBKDF2 and ciphers. In this case ciphers is what you need. Check out the quick-start quide on the project's homepage.
You could do something like with the AES:
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes.js"></script>
<script>
var encryptedAES = CryptoJS.AES.encrypt("Message", "My Secret Passphrase");
var decryptedBytes = CryptoJS.AES.decrypt(encryptedAES, "My Secret Passphrase");
var plaintext = decryptedBytes.toString(CryptoJS.enc.Utf8);
</script>
As for security, at the moment of my writing AES algorithm is thought to be unbroken
Edit :
Seems online URL is down & you can use the downloaded files for encryption from below given link & place the respective files in your root folder of the application.
https://code.google.com/archive/p/crypto-js/downloads
or used other CDN like https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/components/aes-min.js
How can I see function arguments in IPython Notebook Server 3?
Adding screen shots(examples) and some more context for the answer of @Thomas G.
if its not working please make sure if you have executed code properly. In this case make sure import pandas as pd
is ran properly before checking below shortcut.
Place the cursor in middle of parenthesis ()
before you use shortcut.
shift + tab
Display short document and few params
shift + tab + tab
Expands document with scroll bar
shift + tab + tab + tab
Provides document with a Tooltip: "will linger for 10secs while you type". which means it allows you write params and waits for 10secs.
shift + tab + tab + tab + tab
It opens a small window in bottom with option(top righ corner of small window) to open full documentation in new browser tab.
Using .Select and .Where in a single LINQ statement
Did you add the Select()
after the Where()
or before?
You should add it after, because of the concurrency logic:
1 Take the entire table
2 Filter it accordingly
3 Select only the ID's
4 Make them distinct.
If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.
Update: For clarity, this order of operators should work:
db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();
Probably want to add a .toList()
at the end but that's optional :)
Merging cells in Excel using Apache POI
i made a method that merge cells and put border.
protected void setMerge(Sheet sheet, int numRow, int untilRow, int numCol, int untilCol, boolean border) {
CellRangeAddress cellMerge = new CellRangeAddress(numRow, untilRow, numCol, untilCol);
sheet.addMergedRegion(cellMerge);
if (border) {
setBordersToMergedCells(sheet, cellMerge);
}
}
protected void setBordersToMergedCells(Sheet sheet, CellRangeAddress rangeAddress) {
RegionUtil.setBorderTop(BorderStyle.MEDIUM, rangeAddress, sheet);
RegionUtil.setBorderLeft(BorderStyle.MEDIUM, rangeAddress, sheet);
RegionUtil.setBorderRight(BorderStyle.MEDIUM, rangeAddress, sheet);
RegionUtil.setBorderBottom(BorderStyle.MEDIUM, rangeAddress, sheet);
}
How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception
The others are right about making the driver JAR available to your servlet container. My comment was meant to suggest that you verify from the command line whether the driver itself is intact.
Rather than an empty main()
, try something like this, adapted from the included documentation:
public class LoadDriver {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
}
}
On my platform, I'd do this:
$ ls mysql-connector-java-5.1.12-bin.jar
mysql-connector-java-5.1.12-bin.jar
$ javac LoadDriver.java
$ java -cp mysql-connector-java-5.1.12-bin.jar:. LoadDriver
On your platform, you need to use ;
as the path separator, as discussed here and here.
How to Find Item in Dictionary Collection?
Sometimes you still need to use FirstOrDefault if you have to do different tests.
If the Key component of your dictionnary is nullable, you can do this:
thisTag = _tags.FirstOrDefault(t => t.Key.SubString(1,1) == 'a');
if(thisTag.Key != null) { ... }
Using FirstOrDefault, the returned KeyValuePair's key and value will both be null if no match is found.
Can functions be passed as parameters?
You can pass function as parameter to a Go function. Here is an example of passing function as parameter to another Go function:
package main
import "fmt"
type fn func(int)
func myfn1(i int) {
fmt.Printf("\ni is %v", i)
}
func myfn2(i int) {
fmt.Printf("\ni is %v", i)
}
func test(f fn, val int) {
f(val)
}
func main() {
test(myfn1, 123)
test(myfn2, 321)
}
You can try this out at: https://play.golang.org/p/9mAOUWGp0k
How to get access to raw resources that I put in res folder?
getClass().getResourcesAsStream()
works fine on Android. Just make sure the file you are trying to open is correctly embedded in your APK (open the APK as ZIP).
Normally on Android you put such files in the assets
directory. So if you put the raw_resources.dat
in the assets
subdirectory of your project, it will end up in the assets
directory in the APK and you can use:
getClass().getResourcesAsStream("/assets/raw_resources.dat");
It is also possible to customize the build process so that the file doesn't land in the assets
directory in the APK.
Streaming via RTSP or RTP in HTML5
The spirit of the question, I think, was not truly answered. No, you cannot use a video tag to play rtsp streams as of now. The other answer regarding the link to Chromium guy's "never" is a bit misleading as the linked thread / answer is not directly referring to Chrome playing rtsp via the video tag. Read the entire linked thread, especially the comments at the very bottom and links to other threads.
The real answer is this: No, you cannot just put a video tag on an html 5 page and play rtsp. You need to use a Javascript library of some sort (unless you want to get into playing things with flash and silverlight players) to play streaming video. {IMHO} At the rate the html 5 video discussion and implementation is going, the various vendors of proprietary video standards are not interested in helping this move forward so don't count of the promised ease of use of the video tag unless the browser makers take it upon themselves to somehow solve the problem...again, not likely.{/IMHO}
Managing SSH keys within Jenkins for Git
It looks like the github.com
host which jenkins tries to connect to is not listed under the Jenkins user's $HOME/.ssh/known_hosts
. Jenkins runs on most distros as the user jenkins
and hence has its own .ssh
directory to store the list of public keys and known_hosts
.
The easiest solution I can think of to fix this problem is:
# Login as the jenkins user and specify shell explicity,
# since the default shell is /bin/false for most
# jenkins installations.
sudo su jenkins -s /bin/bash
cd SOME_TMP_DIR
# git clone YOUR_GITHUB_URL
# Allow adding the SSH host key to your known_hosts
# Exit from su
exit
Using Google maps API v3 how do I get LatLng with a given address?
There is a pretty good example on https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple
To shorten it up a little:
geocoder = new google.maps.Geocoder();
function codeAddress() {
//In this case it gets the address from an element on the page, but obviously you could just pass it to the method instead
var address = document.getElementById( 'address' ).value;
geocoder.geocode( { 'address' : address }, function( results, status ) {
if( status == google.maps.GeocoderStatus.OK ) {
//In this case it creates a marker, but you can get the lat and lng from the location.LatLng
map.setCenter( results[0].geometry.location );
var marker = new google.maps.Marker( {
map : map,
position: results[0].geometry.location
} );
} else {
alert( 'Geocode was not successful for the following reason: ' + status );
}
} );
}
Can I get image from canvas element and use it in img src tag?
Do this. Add this to the bottom of your doc just before you close the body tag.
<script>
function canvasToImg() {
var canvas = document.getElementById("yourCanvasID");
var ctx=canvas.getContext("2d");
//draw a red box
ctx.fillStyle="#FF0000";
ctx.fillRect(10,10,30,30);
var url = canvas.toDataURL();
var newImg = document.createElement("img"); // create img tag
newImg.src = url;
document.body.appendChild(newImg); // add to end of your document
}
canvasToImg(); //execute the function
</script>
Of course somewhere in your doc you need the canvas tag that it will grab.
<canvas id="yourCanvasID" />
Under what conditions is a JSESSIONID created?
Here is some information about one more source of the JSESSIONID
cookie:
I was just debugging some Java code that runs on a tomcat server. I was not calling request.getSession()
explicitly anywhere in my code but I noticed that a JSESSIONID
cookie was still being set.
I finally took a look at the generated Java code corresponding to a JSP in the work directory under Tomcat.
It appears that, whether you like it or not, if you invoke a JSP from a servlet, JSESSIONID
will get created!
Added: I just found that by adding the following JSP directive:
<%@ page session="false" %>
you can disable the setting of JSESSIONID
by a JSP.
Changing the maximum length of a varchar column?
ALTER TABLE TABLE_NAME MODIFY COLUMN_NAME VARCHAR(40);
Late to the question - but I am using Oracle SQL Developer and @anonymous's answer was the closest but kept receiving syntax errors until I edited the query to this.
Hope this helps someone
How to exit a 'git status' list in a terminal?
You can disable pager for commands that don't recognize --no-pager
flag.
git config --global pager.<command> false
I disable for log aliases and set specific quantity to return.
git config --global pager.log false
Maven error :Perhaps you are running on a JRE rather than a JDK?
Add this configurations in pom.xml
<project ...>
...
<build>
...
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<fork>true</fork>
<executable>C:\Program Files\Java\jdk1.7.0_79\bin\javac</executable>
</configuration>
</plugin>
</plugins>
</build>
...
</project>
Find text in string with C#
I have different approach on ReplaceTextBetween() function.
public static string ReplaceTextBetween(this string strSource, string strStart, string strEnd, string strReplace)
{
if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
var startIndex = strSource.IndexOf(strStart, 0) + strStart.Length;
var endIndex = strSource.IndexOf(strEnd, startIndex);
var strSourceLength = strSource.Length;
var strToReplace = strSource.Substring(startIndex, endIndex - startIndex);
var concatStart = startIndex + strToReplace.Length;
var beforeReplaceStr = strSource.Substring(0, startIndex);
var afterReplaceStr = strSource.Substring(concatStart, strSourceLength - endIndex);
return string.Concat(beforeReplaceStr, strReplace, afterReplaceStr);
}
return strSource;
}
Unit testing with mockito for constructors
I have used "Pattern 2 - the "factory helper pattern"
Pattern 2 - the factory helper pattern
One case where this pattern won't work is if MyClass is final. Most of the Mockito framework doesn't play particularly well with final classes; and this includes the use of spy(). Another case is where MyClass uses getClass() somewhere, and requires the resulting value to be MyClass. This won't work, because the class of a spy is actually a Mockito-generated subclass of the original class.
In either of these cases, you'll need the slightly more robust factory helper pattern, as follows.
public class MyClass{
static class FactoryHelper{
Foo makeFoo( A a, B b, C c ){
return new Foo( a, b, c );
}
}
//...
private FactoryHelper helper;
public MyClass( X x, Y y ){
this( x, y, new FactoryHelper());
}
MyClass( X x, Y, y, FactoryHelper helper ){
//...
this.helper = helper;
}
//...
Foo foo = helper.makeFoo( a, b, c );
}
So, you have a special constructor, just for testing, that has an additional argument. This is used from your test class, when creating the object that you're going to test. In your test class, you mock the FactoryHelper class, as well as the object that you want to create.
@Mock private MyClass.FactoryHelper mockFactoryHelper;
@Mock private Foo mockFoo;
private MyClass toTest;
and you can use it like this
toTest = new MyClass( x, y, mockFactoryHelper );
when( mockFactoryHelper.makeFoo(
any( A.class ), any( B.class ), any( C.class )))
.thenReturn( mockFoo );
Source: http://web.archive.org/web/20160322155004/http://code.google.com/p/mockito/wiki/MockingObjectCreation
Tool for sending multipart/form-data request
UPDATE: I have created a video on sending multipart/form-data requests to explain this better.
Actually, Postman can do this. Here is a screenshot
Newer version : Screenshot captured from postman chrome extension
Another version
Older version
Make sure you check the comment from @maxkoryukov
Be careful with explicit Content-Type header. Better - do not set it's
value, the Postman is smart enough to fill this header for you. BUT,
if you want to set the Content-Type: multipart/form-data - do not
forget about boundary field.
Truncate (not round) decimal places in SQL Server
Please try to use this code for converting 3 decimal values after a point into 2 decimal places:
declare @val decimal (8, 2)
select @val = 123.456
select @val = @val
select @val
The output is 123.46
What is the difference between i++ and ++i?
int i = 0;
Console.WriteLine(i++); // Prints 0. Then value of "i" becomes 1.
Console.WriteLine(--i); // Value of "i" becomes 0. Then prints 0.
Does this answer your question ?
Core Data: Quickest way to delete all instances of an entity
iOS 9.0 and Later :
NSBatchDeleteRequest
is used to delete records in core data. It works very fast and takes less time to delete all records from an entity. It requires NSFetchRequest
in argument. If you want to delete all records from an entity, you can use it and it works for me.
let manageObject:NSManagedObjectContext = appDelegateObject.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: “EnityName”)
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
let persistCor:NSPersistentStoreCoordinator = appDelegateObject.persistentObject
do {
try persistCor.executeRequest(deleteRequest, withContext: manageObject)
try manageObject.save()
} catch {
print(error?.localizedDescription)
}
Python: Total sum of a list of numbers with the for loop
I think what you mean is how to encapsulate that for general use, e.g. in a function:
def sum_list(l):
sum = 0
for x in l:
sum += x
return sum
Now you can apply this to any list. Examples:
l = [1, 2, 3, 4, 5]
sum_list(l)
l = list(map(int, input("Enter numbers separated by spaces: ").split()))
sum_list(l)
But note that sum
is already built in!
How to read a specific line using the specific line number from a file in Java?
you can use the skip() function to skip the lines from begining.
public static void readFile(String filePath, long lineNum) {
List<String> list = new ArrayList<>();
long totalLines, startLine = 0;
try (Stream<String> lines = Files.lines(Paths.get(filePath))) {
totalLines = Files.lines(Paths.get(filePath)).count();
startLine = totalLines - lineNum;
// Stream<String> line32 = lines.skip(((startLine)+1));
list = lines.skip(startLine).collect(Collectors.toList());
// lines.forEach(list::add);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
list.forEach(System.out::println);
}
Redirect on Ajax Jquery Call
JQuery is looking for a json type result, but because the redirect is processed automatically, it will receive the generated html source of your login.htm
page.
One idea is to let the the browser know that it should redirect by adding a redirect
variable to to the resulting object and checking for it in JQuery:
$(document).ready(function(){
jQuery.ajax({
type: "GET",
url: "populateData.htm",
dataType:"json",
data:"userId=SampleUser",
success:function(response){
if (response.redirect) {
window.location.href = response.redirect;
}
else {
// Process the expected results...
}
},
error: function(xhr, textStatus, errorThrown) {
alert('Error! Status = ' + xhr.status);
}
});
});
You could also add a Header Variable to your response and let your browser decide where to redirect. In Java, instead of redirecting, do response.setHeader("REQUIRES_AUTH", "1")
and in JQuery you do on success(!):
//....
success:function(response){
if (response.getResponseHeader('REQUIRES_AUTH') === '1'){
window.location.href = 'login.htm';
}
else {
// Process the expected results...
}
}
//....
Hope that helps.
My answer is heavily inspired by this thread which shouldn't left any questions in case you still have some problems.
A select query selecting a select statement
I was over-complicating myself. After taking a long break and coming back, the desired output could be accomplished by this simple query:
SELECT Sandwiches.[Sandwich Type], Sandwich.Bread, Count(Sandwiches.[SandwichID]) AS [Total Sandwiches]
FROM Sandwiches
GROUP BY Sandwiches.[Sandwiches Type], Sandwiches.Bread;
Thanks for answering, it helped my train of thought.
How to place div side by side
There are many ways to do what you're asking for:
- Using CSS
float
property:
_x000D_
_x000D_
<div style="width: 100%; overflow: hidden;">
<div style="width: 600px; float: left;"> Left </div>
<div style="margin-left: 620px;"> Right </div>
</div>
_x000D_
_x000D_
_x000D_
- Using CSS
display
property - which can be used to make div
s act like a table
:
_x000D_
_x000D_
<div style="width: 100%; display: table;">
<div style="display: table-row">
<div style="width: 600px; display: table-cell;"> Left </div>
<div style="display: table-cell;"> Right </div>
</div>
</div>
_x000D_
_x000D_
_x000D_
There are more methods, but those two are the most popular.
Insert an element at a specific index in a list and return the updated list
Most performance efficient approach
You may also insert the element using the slice indexing in the list. For example:
>>> a = [1, 2, 4]
>>> insert_at = 2 # Index at which you want to insert item
>>> b = a[:] # Created copy of list "a" as "b".
# Skip this step if you are ok with modifying the original list
>>> b[insert_at:insert_at] = [3] # Insert "3" within "b"
>>> b
[1, 2, 3, 4]
For inserting multiple elements together at a given index, all you need to do is to use a list
of multiple elements that you want to insert. For example:
>>> a = [1, 2, 4]
>>> insert_at = 2 # Index starting from which multiple elements will be inserted
# List of elements that you want to insert together at "index_at" (above) position
>>> insert_elements = [3, 5, 6]
>>> a[insert_at:insert_at] = insert_elements
>>> a # [3, 5, 6] are inserted together in `a` starting at index "2"
[1, 2, 3, 5, 6, 4]
To know more about slice indexing, you can refer: Understanding slice notation.
Note: In Python 3.x, difference of performance between slice indexing and list.index(...)
is significantly reduced and both are almost equivalent. However, in Python 2.x, this difference is quite noticeable. I have shared performance comparisons later in this answer.
Alternative using list comprehension (but very slow in terms of performance):
As an alternative, it can be achieved using list comprehension with enumerate
too. (But please don't do it this way. It is just for illustration):
>>> a = [1, 2, 4]
>>> insert_at = 2
>>> b = [y for i, x in enumerate(a) for y in ((3, x) if i == insert_at else (x, ))]
>>> b
[1, 2, 3, 4]
Performance comparison of all solutions
Here's the timeit
comparison of all the answers with list of 1000 elements on Python 3.9.1 and Python 2.7.16. Answers are listed in the order of performance for both the Python versions.
Python 3.9.1
My answer using sliced insertion - Fastest ( 2.25 µsec per loop)
python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b[500:500] = [3]"
100000 loops, best of 5: 2.25 µsec per loop
Rushy Panchal's answer with most votes using list.insert(...)
- Second (2.33 µsec per loop)
python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b.insert(500, 3)"
100000 loops, best of 5: 2.33 µsec per loop
ATOzTOA's accepted answer based on merge of sliced lists - Third (5.01 µsec per loop)
python3 -m timeit -s "a = list(range(1000))" "b = a[:500] + [3] + a[500:]"
50000 loops, best of 5: 5.01 µsec per loop
My answer with List Comprehension and enumerate
- Fourth (very slow with 135 µsec per loop)
python3 -m timeit -s "a = list(range(1000))" "[y for i, x in enumerate(a) for y in ((3, x) if i == 500 else (x, )) ]"
2000 loops, best of 5: 135 µsec per loop
Python 2.7.16
My answer using sliced insertion - Fastest (2.09 µsec per loop)
python -m timeit -s "a = list(range(1000))" "b = a[:]; b[500:500] = [3]"
100000 loops, best of 3: 2.09 µsec per loop
Rushy Panchal's answer with most votes using list.insert(...)
- Second (2.36 µsec per loop)
python -m timeit -s "a = list(range(1000))" "b = a[:]; b.insert(500, 3)"
100000 loops, best of 3: 2.36 µsec per loop
ATOzTOA's accepted answer based on merge of sliced lists - Third (4.44 µsec per loop)
python -m timeit -s "a = list(range(1000))" "b = a[:500] + [3] + a[500:]"
100000 loops, best of 3: 4.44 µsec per loop
My answer with List Comprehension and enumerate
- Fourth (very slow with 103 µsec per loop)
python -m timeit -s "a = list(range(1000))" "[y for i, x in enumerate(a) for y in ((3, x) if i == 500 else (x, )) ]"
10000 loops, best of 3: 103 µsec per loop
Rounding Bigdecimal values with 2 Decimal Places
I think that the RoundingMode
you are looking for is ROUND_HALF_EVEN
. From the javadoc:
Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor. Behaves as for ROUND_HALF_UP if the digit to the left of the discarded fraction is odd; behaves as for ROUND_HALF_DOWN if it's even. Note that this is the rounding mode that minimizes cumulative error when applied repeatedly over a sequence of calculations.
Here is a quick test case:
BigDecimal a = new BigDecimal("10.12345");
BigDecimal b = new BigDecimal("10.12556");
a = a.setScale(2, BigDecimal.ROUND_HALF_EVEN);
b = b.setScale(2, BigDecimal.ROUND_HALF_EVEN);
System.out.println(a);
System.out.println(b);
Correctly prints:
10.12
10.13
UPDATE:
setScale(int, int)
has not been recommended since Java 1.5, when enums were first introduced, and was finally deprecated in Java 9. You should now use setScale(int, RoundingMode)
e.g:
setScale(2, RoundingMode.HALF_EVEN)
AngularJS Dropdown required validation
You need to add a name
attribute to your dropdown list, then you need to add a required
attribute, and then you can reference the error using myForm.[input name].$error.required
:
HTML:
<form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
<input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
<select name="service_id" class="Sitedropdown" style="width: 220px;"
ng-model="ServiceID"
ng-options="service.ServiceID as service.ServiceName for service in services"
required>
<option value="">Select Service</option>
</select>
<span ng-show="myForm.service_id.$error.required">Select service</span>
</form>
Controller:
function Ctrl($scope) {
$scope.services = [
{ServiceID: 1, ServiceName: 'Service1'},
{ServiceID: 2, ServiceName: 'Service2'},
{ServiceID: 3, ServiceName: 'Service3'}
];
$scope.save = function(myForm) {
console.log('Selected Value: '+ myForm.service_id.$modelValue);
alert('Data Saved! without validate');
};
}
Here's a working plunker.
Making a WinForms TextBox behave like your browser's address bar
First of all, thanks for answers! 9 total answers. Thank you.
Bad news: all of the answers had some quirks or didn't work quite right (or at all). I've added a comment to each of your posts.
Good news: I've found a way to make it work. This solution is pretty straightforward and seems to work in all the scenarios (mousing down, selecting text, tabbing focus, etc.)
bool alreadyFocused;
...
textBox1.GotFocus += textBox1_GotFocus;
textBox1.MouseUp += textBox1_MouseUp;
textBox1.Leave += textBox1_Leave;
...
void textBox1_Leave(object sender, EventArgs e)
{
alreadyFocused = false;
}
void textBox1_GotFocus(object sender, EventArgs e)
{
// Select all text only if the mouse isn't down.
// This makes tabbing to the textbox give focus.
if (MouseButtons == MouseButtons.None)
{
this.textBox1.SelectAll();
alreadyFocused = true;
}
}
void textBox1_MouseUp(object sender, MouseEventArgs e)
{
// Web browsers like Google Chrome select the text on mouse up.
// They only do it if the textbox isn't already focused,
// and if the user hasn't selected all text.
if (!alreadyFocused && this.textBox1.SelectionLength == 0)
{
alreadyFocused = true;
this.textBox1.SelectAll();
}
}
As far as I can tell, this causes a textbox to behave exactly like a web browser's address bar.
Hopefully this helps the next guy who tries to solve this deceptively simple problem.
Thanks again, guys, for all your answers that helped lead me towards the correct path.
SVN commit command
Command-line SVN
You need to add your files to your working copy, before you commit your changes to the repository:
svn add <file|folder>
Afterwards:
svn commit
See here for detailed information about svn add
.
TortoiseSVN
It works with TortoiseSVN, because it adds the file to your working copy automatically (commit dialog):
If you want to include an unversioned file, just check that file to add it to the commit.
See: TortoiseSVN: Committing Your Changes To The Repository
Merge two (or more) lists into one, in C# .NET
I've already commented it but I still think is a valid option, just test if in your environment is better one solution or the other. In my particular case, using source.ForEach(p => dest.Add(p))
performs better than the classic AddRange
but I've not investigated why at the low level.
You can see an example code here: https://gist.github.com/mcliment/4690433
So the option would be:
var allProducts = new List<Product>(productCollection1.Count +
productCollection2.Count +
productCollection3.Count);
productCollection1.ForEach(p => allProducts.Add(p));
productCollection2.ForEach(p => allProducts.Add(p));
productCollection3.ForEach(p => allProducts.Add(p));
Test it to see if it works for you.
Disclaimer: I'm not advocating for this solution, I find Concat
the most clear one. I just stated -in my discussion with Jon- that in my machine this case performs better than AddRange
, but he says, with far more knowledge than I, that this does not make sense. There's the gist if you want to compare.
javax.persistence.PersistenceException: No Persistence provider for EntityManager named customerManager
my experience tells me that missing persistence.xml,will generate the same exception too.
i caught the same error msg today when i tried to run a jar package packed by ant.
when i used jar tvf to check the content of the jar file, i realized that "ant" forgot to pack the persistnece.xml for me.
after I manually repacked the jar file ,the error msg disappered.
so i believe maybe you should try simplely putting META-INF under src directory and placing your persistence.xml there.
Unable to find velocity template resources
VelocityEngine velocityEngin = new VelocityEngine();
velocityEngin.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
velocityEngin.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
velocityEngin.init();
Template template = velocityEngin.getTemplate("nameOfTheTemplateFile.vtl");
you could use the above code to set the properties for velocity template. You can then give the name of the tempalte file when initializing the Template and it will find if it exists in the classpath.
All the above classes come from package org.apache.velocity*
Best timing method in C?
gettimeofday() will probably do what you want.
If you're on Intel hardware, here's how to read the CPU real-time instruction counter. It will tell you the number of CPU cycles executed since the processor was booted. This is probably the finest-grained, lowest overhead counter you can get for performance measurement.
Note that this is the number of CPU cycles. On linux you can get the CPU speed from /proc/cpuinfo and divide to get the number of seconds. Converting this to a double is quite handy.
When I run this on my box, I get
11867927879484732
11867927879692217
it took this long to call printf: 207485
Here's the Intel developer's guide that gives tons of detail.
#include <stdio.h>
#include <stdint.h>
inline uint64_t rdtsc() {
uint32_t lo, hi;
__asm__ __volatile__ (
"xorl %%eax, %%eax\n"
"cpuid\n"
"rdtsc\n"
: "=a" (lo), "=d" (hi)
:
: "%ebx", "%ecx");
return (uint64_t)hi << 32 | lo;
}
main()
{
unsigned long long x;
unsigned long long y;
x = rdtsc();
printf("%lld\n",x);
y = rdtsc();
printf("%lld\n",y);
printf("it took this long to call printf: %lld\n",y-x);
}
Check if a file exists locally using JavaScript only
Your question is ambiguous, so there are multiple possible answers depending on what you're really trying to achieve.
If you're developping as I'm guessing a desktop application using Titanium, then you can use the FileSystem module's getFile to get the file object, then check if it exists using the exists method.
Here's an example taken from the Appcelerator website:
var homeDir = Titanium.Filesystem.getUserDirectory();
var mySampleFile = Titanium.Filesystem.getFile(homeDir, 'sample.txt');
if (mySampleFile.exists()) {
alert('A file called sample.txt already exists in your home directory.');
...
}
Check the getFile method reference documentation
And the exists method reference documentation
For those who thought that he was asking about an usual Web development situation, then thse are the two answers I'd have given:
1) you want to check if a server-side file exists.
In this case you can use an ajax request try and get the file and react upon the received answer. Although, be aware that you can only check for files that are exposed by your web server. A better approach would be to write a server-side script (e.g., php) that would do the check for you, given a filename and call that script via ajax. Also, be aware that you could very easily create a security hole in your application/server if you're not careful enough.
2) you want to check if a client-side file exists.
In this case, as pointed you by others, it is not allowed for security reasons (although IE allowed this in the past via ActiveX and the Scripting.FileSystemObject class) and it's fine like that (nobody wants you to be able to go through their files), so forget about this.
DateTime2 vs DateTime in SQL Server
Old Question... But I want to add something not already stated by anyone here... (Note: This is my own observation, so don't ask for any reference)
Datetime2 is faster when used in filter criteria.
TLDR:
In SQL 2016 I had a table with hundred thousand rows and a datetime column ENTRY_TIME because it was required to store the exact time up to seconds. While executing a complex query with many joins and a sub query, when I used where clause as:
WHERE ENTRY_TIME >= '2017-01-01 00:00:00' AND ENTRY_TIME < '2018-01-01 00:00:00'
The query was fine initially when there were hundreds of rows, but when number of rows increased, the query started to give this error:
Execution Timeout Expired. The timeout period elapsed prior
to completion of the operation or the server is not responding.
I removed the where clause, and unexpectedly, the query was run in 1 sec, although now ALL rows for all dates were fetched. I run the inner query with where clause, and it took 85 seconds, and without where clause it took 0.01 secs.
I came across many threads here for this issue as datetime filtering performance
I optimized query a bit. But the real speed I got was by changing the datetime column to datetime2.
Now the same query that timed out previously takes less than a second.
cheers
Drop-down menu that opens up/upward with pure css
Add bottom:100%
to your #menu:hover ul li:hover ul
rule
#menu:hover ul li:hover ul {
position: absolute;
margin-top: 1px;
font: 10px;
bottom: 100%; /* added this attribute */
}
Or better yet to prevent the submenus from having the same effect, just add this rule
#menu>ul>li:hover>ul {
bottom:100%;
}
source: http://jsfiddle.net/W5FWW/4/
And to get back the border you can add the following attribute
#menu>ul>li:hover>ul {
bottom:100%;
border-bottom: 1px solid transparent
}
Postgresql - change the size of a varchar column to lower length
I have found a very easy way to change the size i.e. the annotation @Size(min = 1, max = 50) which is part of "import javax.validation.constraints" i.e.
"import javax.validation.constraints.Size;"
@Size(min = 1, max = 50)
private String country;
when executing this is hibernate you get in pgAdmin III
CREATE TABLE address
(
.....
country character varying(50),
.....
)
Java, looping through result set
Result Set
are actually contains multiple rows of data, and use a cursor to point out current position. So in your case, rs4.getString(1)
only get you the data in first column of first row. In order to change to next row, you need to call next()
a quick example
while (rs.next()) {
String sid = rs.getString(1);
String lid = rs.getString(2);
// Do whatever you want to do with these 2 values
}
there are many useful method in ResultSet
, you should take a look :)
Add a user control to a wpf window
You probably need to add the namespace:
<Window x:Class="UserControlTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:UserControlTest"
Title="User Control Test" Height="300" Width="300">
<local:UserControl1 />
</Window>
Android and setting alpha for (image) view alpha
Maybe a helpful alternative for a plain-colored background:
Put a LinearLayout over the ImageView and use the LinearLayout as a opacity filter. In the following a small example with a black background:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF000000" >
<RelativeLayout
android:id="@+id/relativeLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/icon_stop_big" />
<LinearLayout
android:id="@+id/opacityFilter"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#CC000000"
android:orientation="vertical" >
</LinearLayout>
</RelativeLayout>
Vary the android:background attribute of the LinearLayout between #00000000 (fully transparent) and #FF000000 (fully opaque).
List of encodings that Node.js supports
If the above solution does not work for you it is may be possible to obtain the same result with the following pure nodejs code. The above did not work for me and resulted in a compilation exception when running 'npm install iconv' on OSX:
npm install iconv
npm WARN package.json [email protected] No README.md file found!
npm http GET https://registry.npmjs.org/iconv
npm http 200 https://registry.npmjs.org/iconv
npm http GET https://registry.npmjs.org/iconv/-/iconv-2.0.4.tgz
npm http 200 https://registry.npmjs.org/iconv/-/iconv-2.0.4.tgz
> [email protected] install /Users/markboyd/git/portal/app/node_modules/iconv
> node-gyp rebuild
gyp http GET http://nodejs.org/dist/v0.10.1/node-v0.10.1.tar.gz
gyp http 200 http://nodejs.org/dist/v0.10.1/node-v0.10.1.tar.gz
xcode-select: Error: No Xcode is selected. Use xcode-select -switch <path-to-xcode>, or see the xcode-select manpage (man xcode-select) for further information.
fs.readFileSync() returns a Buffer if no encoding is specified. And Buffer has a toString() method that will convert to UTF8 if no encoding is specified giving you the file's contents. See the nodejs documentation. This worked for me.
Excel formula to get ranking position
The way I've done this, which is a bit convoluted, is as follows:
- Sort rows by the points in descending order
- Create an additional column (D) starting at D2 with numbers 1,2,3,... total number of positions
- In the cell for the actual positions (D2) use the formula if(C2=C1), D2, C1). This checks if the points in this row are the same as the points in the previous row. If it is it gives you the position of the previous row, otherwise it uses the value from column D and thus handle people with equal positions.
- Copy this formula down the entire column
- Copy the positions column(C), then paste special >> values to overwrite the formula with positions
- Resort the rows to their original order
That's worked for me! If there's a better way I'd love to know it!
Get the Id of current table row with Jquery
Create a class in css name it .buttoncontact, add the class attribute to your buttons
function ClickedRow() {
$(document).on('click', '.buttoncontact', function () {
var row = $(this).parents('tr').attr('id');
var rowtext = $(this).closest('tr').text();
alert(row);
});
}
Practical uses for AtomicInteger
In Java 8 atomic classes have been extended with two interesting functions:
- int getAndUpdate(IntUnaryOperator updateFunction)
- int updateAndGet(IntUnaryOperator updateFunction)
Both are using the updateFunction to perform update of the atomic value. The difference is that the first one returns old value and the second one return the new value. The updateFunction may be implemented to do more complex "compare and set" operations than the standard one. For example it can check that atomic counter doesn't go below zero, normally it would require synchronization, and here the code is lock-free:
public class Counter {
private final AtomicInteger number;
public Counter(int number) {
this.number = new AtomicInteger(number);
}
/** @return true if still can decrease */
public boolean dec() {
// updateAndGet(fn) executed atomically:
return number.updateAndGet(n -> (n > 0) ? n - 1 : n) > 0;
}
}
The code is taken from Java Atomic Example.
How can I use iptables on centos 7?
I had the problem that rebooting wouldn't start iptables.
This fixed it:
yum install iptables-services
systemctl mask firewalld
systemctl enable iptables
systemctl enable ip6tables
systemctl stop firewalld
systemctl start iptables
systemctl start ip6tables
Convert a char to upper case using regular expressions (EditPad Pro)
I know this thread is about EditPad Pro, but I came here because I had the same need with a javascript regexp.
For the people who are here needing the same tip, you can use a function or lambda as the replace argument.
I use the function below to convert css names with -
to the javascript equivalent, for example, "border-top"
will be transformed into "borderTop"
:
s = s.replace(/\-[a-z]/g, x => x[1].toUpperCase());
Octave/Matlab: Adding new elements to a vector
x(end+1) = newElem
is a bit more robust.
x = [x newElem]
will only work if x
is a row-vector, if it is a column vector x = [x; newElem]
should be used. x(end+1) = newElem
, however, works for both row- and column-vectors.
In general though, growing vectors should be avoided. If you do this a lot, it might bring your code down to a crawl. Think about it: growing an array involves allocating new space, copying everything over, adding the new element, and cleaning up the old mess...Quite a waste of time if you knew the correct size beforehand :)
How do I check if an element is hidden in jQuery?
Often when checking if something is visible or not, you are going to go right ahead immediately and do something else with it. jQuery chaining makes this easy.
So if you have a selector and you want to perform some action on it only if is visible or hidden, you can use filter(":visible")
or filter(":hidden")
followed by chaining it with the action you want to take.
So instead of an if
statement, like this:
if ($('#btnUpdate').is(":visible"))
{
$('#btnUpdate').animate({ width: "toggle" }); // Hide button
}
Or more efficient, but even uglier:
var button = $('#btnUpdate');
if (button.is(":visible"))
{
button.animate({ width: "toggle" }); // Hide button
}
You can do it all in one line:
$('#btnUpdate').filter(":visible").animate({ width: "toggle" });
C# ASP.NET Send Email via TLS
TLS (Transport Level Security) is the slightly broader term that has replaced SSL (Secure Sockets Layer) in securing HTTP communications. So what you are being asked to do is enable SSL.
How to use paths in tsconfig.json?
This works for me:
yarn add --dev tsconfig-paths
ts-node -r tsconfig-paths/register <your-index-file>.ts
This loads all paths in tsconfig.json. A sample tsconfig.json:
{
"compilerOptions": {
{…}
"baseUrl": "./src",
"paths": {
"assets/*": [ "assets/*" ],
"styles/*": [ "styles/*" ]
}
},
}
Make sure you have both baseUrl and paths for this to work
And then you can import like :
import {AlarmIcon} from 'assets/icons'
Java program to get the current date without timestamp
I think this will work. Use Calendar to manipulate time fields (reset them to zero), then get the Date from the Calendar.
Calendar c = GregorianCalendar.getInstance();
c.clear( Calendar.HOUR_OF_DAY );
c.clear( Calendar.MINUTE );
c.clear( Calendar.SECOND );
c.clear( Calendar.MILLISECOND );
Date today = c.getTime();
Or do the opposite. Put the date you want to compare to in a calendar and compare calendar dates
Date compareToDate; // assume this is set before going in.
Calendar today = GregorianCalendar.getInstance();
Calendar compareTo = GregorianCalendar.getInstance();
compareTo.setTime( compareToDate );
if( today.get( Calendar.YEAR ) == compareTo.get( Calendar.YEAR ) &&
today.get( Calendar.DAY_OF_YEAR ) == compareTo.get( Calendar.DAY_OF_YEAR ) ) {
// They are the same day!
}
Sometimes adding a WCF Service Reference generates an empty reference.cs
In my case I had a solution with VB Web Forms project that referenced a C# UserControl. Both the VB project and the CS project had a Service Reference to the same service. The reference appeared under Service References in the VB project and under the Connected Services grouping in the CS (framework) project.
In order to update the service reference (ie, get the Reference.vb file to not be empty) in the VB web forms project, I needed to REMOVE THE CS PROJECT, then update the VB Service Reference, then add the CS project back into the solution.
How to loop through a dataset in powershell?
Here's a practical example (build a dataset from your current location):
$ds = new-object System.Data.DataSet
$ds.Tables.Add("tblTest")
[void]$ds.Tables["tblTest"].Columns.Add("Name",[string])
[void]$ds.Tables["tblTest"].Columns.Add("Path",[string])
dir | foreach {
$dr = $ds.Tables["tblTest"].NewRow()
$dr["Name"] = $_.name
$dr["Path"] = $_.fullname
$ds.Tables["tblTest"].Rows.Add($dr)
}
$ds.Tables["tblTest"]
$ds.Tables["tblTest"]
is an object that you can manipulate just like any other Powershell object:
$ds.Tables["tblTest"] | foreach {
write-host 'Name value is : $_.name
write-host 'Path value is : $_.path
}
Plot logarithmic axes with matplotlib in python
First of all, it's not very tidy to mix pylab
and pyplot
code. What's more, pyplot style is preferred over using pylab.
Here is a slightly cleaned up code, using only pyplot
functions:
from matplotlib import pyplot
a = [ pow(10,i) for i in range(10) ]
pyplot.subplot(2,1,1)
pyplot.plot(a, color='blue', lw=2)
pyplot.yscale('log')
pyplot.show()
The relevant function is pyplot.yscale()
. If you use the object-oriented version, replace it by the method Axes.set_yscale()
. Remember that you can also change the scale of X axis, using pyplot.xscale()
(or Axes.set_xscale()
).
Check my question What is the difference between ‘log’ and ‘symlog’? to see a few examples of the graph scales that matplotlib offers.
Node.js - get raw request body using Express
This is a variation on hexacyanide's answer above. This middleware also handles the 'data' event but does not wait for the data to be consumed before calling 'next'. This way both this middleware and bodyParser may coexist, consuming the stream in parallel.
app.use(function(req, res, next) {
req.rawBody = '';
req.setEncoding('utf8');
req.on('data', function(chunk) {
req.rawBody += chunk;
});
next();
});
app.use(express.bodyParser());
How can I expose more than 1 port with Docker?
if you use docker-compose.yml
file:
services:
varnish:
ports:
- 80
- 6081
You can also specify the host/network port as HOST/NETWORK_PORT:CONTAINER_PORT
varnish:
ports:
- 81:80
- 6081:6081
Remove Item in Dictionary based on Value
You can use the following as extension method
public static void RemoveByValue<T,T1>(this Dictionary<T,T1> src , T1 Value)
{
foreach (var item in src.Where(kvp => kvp.Value.Equals( Value)).ToList())
{
src.Remove(item.Key);
}
}
How to add Active Directory user group as login in SQL Server
You can use T-SQL:
use master
GO
CREATE LOGIN [NT AUTHORITY\LOCALSERVICE] FROM WINDOWS WITH
DEFAULT_DATABASE=yourDbName
GO
CREATE LOGIN [NT AUTHORITY\NETWORKSERVICE] FROM WINDOWS WITH
DEFAULT_DATABASE=yourDbName
I use this as a part of restore from production server to testing machine:
USE master
GO
ALTER DATABASE yourDbName SET OFFLINE WITH ROLLBACK IMMEDIATE
RESTORE DATABASE yourDbName FROM DISK = 'd:\DropBox\backup\myDB.bak'
ALTER DATABASE yourDbName SET ONLINE
GO
CREATE LOGIN [NT AUTHORITY\LOCALSERVICE] FROM WINDOWS WITH
DEFAULT_DATABASE=yourDbName
GO
CREATE LOGIN [NT AUTHORITY\NETWORKSERVICE] FROM WINDOWS WITH
DEFAULT_DATABASE=yourDbName
GO
You will need to use localized name of services in case of German or French Windows, see How to create a SQL Server login for a service account on a non-English Windows?
How do I parse JSON with Objective-C?
- I recommend and use TouchJSON for parsing JSON.
To answer your comment to Alex. Here's quick code that should allow you to get the fields like activity_details, last_name, etc. from the json dictionary that is returned:
NSDictionary *userinfo=[jsondic valueforKey:@"#data"];
NSDictionary *user;
NSInteger i = 0;
NSString *skey;
if(userinfo != nil){
for( i = 0; i < [userinfo count]; i++ ) {
if(i)
skey = [NSString stringWithFormat:@"%d",i];
else
skey = @"";
user = [userinfo objectForKey:skey];
NSLog(@"activity_details:%@",[user objectForKey:@"activity_details"]);
NSLog(@"last_name:%@",[user objectForKey:@"last_name"]);
NSLog(@"first_name:%@",[user objectForKey:@"first_name"]);
NSLog(@"photo_url:%@",[user objectForKey:@"photo_url"]);
}
}
After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName
This worked for me.
application.properties
, used jdbc-url instead of url:
datasource.apidb.jdbc-url=jdbc:mysql://localhost:3306/apidb?useSSL=false
datasource.apidb.username=root
datasource.apidb.password=123
datasource.apidb.driver-class-name=com.mysql.jdbc.Driver
Configuration class:
@Configuration
@EnableJpaRepositories(
entityManagerFactoryRef = "fooEntityManagerFactory",
basePackages = {"com.buddhi.multidatasource.foo.repository"}
)
public class FooDataSourceConfig {
@Bean(name = "fooDataSource")
@ConfigurationProperties(prefix = "datasource.foo")
public HikariDataSource dataSource() {
return DataSourceBuilder.create().type(HikariDataSource.class).build();
}
@Bean(name = "fooEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean fooEntityManagerFactory(
EntityManagerFactoryBuilder builder,
@Qualifier("fooDataSource") DataSource dataSource
) {
return builder
.dataSource(dataSource)
.packages("com.buddhi.multidatasource.foo.model")
.persistenceUnit("fooDb")
.build();
}
}
How do I find which program is using port 80 in Windows?
Start menu → Accessories → right click on "Command prompt". In the menu, click "Run as Administrator" (on Windows XP you can just run it as usual), run netstat -anb
, and then look through output for your program.
BTW, Skype by default tries to use ports 80 and 443 for incoming connections.
You can also run netstat -anb >%USERPROFILE%\ports.txt
followed by start %USERPROFILE%\ports.txt
to open the port and process list in a text editor, where you can search for the information you want.
You can also use PowerShell to parse netstat
output and present it in a better way (or process it any way you want):
$proc = @{};
Get-Process | ForEach-Object { $proc.Add($_.Id, $_) };
netstat -aon | Select-String "\s*([^\s]+)\s+([^\s]+):([^\s]+)\s+([^\s]+):([^\s]+)\s+([^\s]+)?\s+([^\s]+)" | ForEach-Object {
$g = $_.Matches[0].Groups;
New-Object PSObject |
Add-Member @{ Protocol = $g[1].Value } -PassThru |
Add-Member @{ LocalAddress = $g[2].Value } -PassThru |
Add-Member @{ LocalPort = [int]$g[3].Value } -PassThru |
Add-Member @{ RemoteAddress = $g[4].Value } -PassThru |
Add-Member @{ RemotePort = $g[5].Value } -PassThru |
Add-Member @{ State = $g[6].Value } -PassThru |
Add-Member @{ PID = [int]$g[7].Value } -PassThru |
Add-Member @{ Process = $proc[[int]$g[7].Value] } -PassThru;
#} | Format-Table Protocol,LocalAddress,LocalPort,RemoteAddress,RemotePort,State -GroupBy @{Name='Process';Expression={$p=$_.Process;@{$True=$p.ProcessName; $False=$p.MainModule.FileName}[$p.MainModule -eq $Null] + ' PID: ' + $p.Id}} -AutoSize
} | Sort-Object PID | Out-GridView
Also it does not require elevation to run.
How to generate different random numbers in a loop in C++?
The way the function rand()
works is that every time you call it, it generates a random number. In your code, you've called it once and stored it into the variable random_x
. To get your desired random numbers instead of storing it into a variable, just call the function like this:
for (int t=0;t<10;t++)
{
cout << "\nRandom X = " << rand() % 100;
}
Column name or number of supplied values does not match table definition
The problem is that you are trying to insert data into the database without using columns. Sql server gives you that error message.
error: insert into users values('1', '2','3')
- this works fine as long you only have 3 columns
if you have 4 columns but only want to insert into 3 of them
correct: insert into users (firstName,lastName,city) values ('Tom', 'Jones', 'Miami')
hope this helps
Is it possible to add dynamically named properties to JavaScript object?
Here's how I solved the problem.
var obj = {
};
var field = "someouter.someinner.someValue";
var value = 123;
function _addField( obj, field, value )
{
// split the field into tokens
var tokens = field.split( '.' );
// if there's more than one token, this field is an object
if( tokens.length > 1 )
{
var subObj = tokens[0];
// define the object
if( obj[ subObj ] !== undefined ) obj[ subObj ] = {};
// call addfield again on the embedded object
var firstDot = field.indexOf( '.' );
_addField( obj[ subObj ], field.substr( firstDot + 1 ), value );
}
else
{
// no embedded objects, just field assignment
obj[ field ] = value;
}
}
_addField( obj, field, value );
_addField(obj, 'simpleString', 'string');
console.log( JSON.stringify( obj, null, 2 ) );
Generates the following object:
{
"someouter": {
"someinner": {
"someValue": 123
}
},
"simpleString": "string"
}
PHP function to get the subdomain of a URL
I know I'm really late to the game, but here goes.
What I did was take the HTTP_HOST server variable ($_SERVER['HTTP_HOST']
) and the number of letters in the domain (so for example.com
it would be 11).
Then I used the substr
function to get the subdomain. I did
$numberOfLettersInSubdomain = strlen($_SERVER['HTTP_HOST'])-12
$subdomain = substr($_SERVER['HTTP_HOST'], $numberOfLettersInSubdomain);
I cut the substring off at 12 instead of 11 because substrings start on 1 for the second parameter. So now if you entered test.example.com, the value of $subdomain
would be test
.
This is better than using explode
because if the subdomain has a .
in it, this will not cut it off.
Converting an OpenCV Image to Black and White
For those doing video I cobbled the following based on @tsh :
import cv2 as cv
import numpy as np
def nothing(x):pass
cap = cv.VideoCapture(0)
cv.namedWindow('videoUI', cv.WINDOW_NORMAL)
cv.createTrackbar('T','videoUI',0,255,nothing)
while(True):
ret, frame = cap.read()
vid_gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
thresh = cv.getTrackbarPos('T','videoUI');
vid_bw = cv.threshold(vid_gray, thresh, 255, cv.THRESH_BINARY)[1]
cv.imshow('videoUI',cv.flip(vid_bw,1))
if cv.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv.destroyAllWindows()
Results in:
How to solve the system.data.sqlclient.sqlexception (0x80131904) error
You also need to change the DataSource
of the connection string. KELVIN-PC
is the name of your local machine and the sql server is running on the default instance.
If you are sure the the server is running as the default instance, you can always use .
in the DataSource, eg.
connectionString="Data Source=.;Initial Catalog=LMS;User ID=sa;Password=temperament"
otherwise, you need to specify the name of the instance of the server,
connectionString="Data Source=.\INSTANCENAME;Initial Catalog=LMS;User ID=sa;Password=temperament"
set the iframe height automatically
Solomon's answer about bootstrap inspired me to add the CSS the bootstrap solution uses, which works really well for me.
.iframe-embed {
position: absolute;
top: 0;
left: 0;
bottom: 0;
height: 100%;
width: 100%;
border: 0;
}
.iframe-embed-wrapper {
position: relative;
display: block;
height: 0;
padding: 0;
overflow: hidden;
}
.iframe-embed-responsive-16by9 {
padding-bottom: 56.25%;
}
<div class="iframe-embed-wrapper iframe-embed-responsive-16by9">
<iframe class="iframe-embed" src="vid.mp4"></iframe>
</div>
cannot call member function without object
You are right - you declared a new use defined type (Name_pairs) and you need variable of that type to use it.
The code should go like this:
Name_pairs np;
np.read_names()
Calling Python in PHP
You can run a python script via php, and outputs on browser.
Basically you have to call the python script this way:
$command = "python /path/to/python_script.py 2>&1";
$pid = popen( $command,"r");
while( !feof( $pid ) )
{
echo fread($pid, 256);
flush();
ob_flush();
usleep(100000);
}
pclose($pid);
Note: if you run any time.sleep() in you python code, it will not outputs the results on browser.
For full codes working, visit How to execute python script from php and show output on browser
Can I draw rectangle in XML?
Create rectangle.xml
using Shape Drawable Like this put in to your Drawable Folder...
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="@android:color/transparent"/>
<corners android:radius="12px"/>
<stroke android:width="2dip" android:color="#000000"/>
</shape>
put it in to an ImageView
<ImageView
android:id="@+id/rectimage"
android:layout_height="150dp"
android:layout_width="150dp"
android:src="@drawable/rectangle">
</ImageView>
Hope this will help you.
How do I import a CSV file in R?
You would use the read.csv
function; for example:
dat = read.csv("spam.csv", header = TRUE)
You can also reference this tutorial for more details.
Note: make sure the .csv
file to read is in your working directory (using getwd()
) or specify the right path to file. If you want, you can set the current directory using setwd
.
Android Studio and Gradle build error
If you are using the Gradle Wrapper (the recommended option in Android Studio), you enable stacktrace by running gradlew compileDebug --stacktrace
from the command line in the root folder of your project (where the gradlew
file is).
If you are not using the gradle wrapper, you use gradle compileDebug --stacktrace
instead (presumably).
You don't really need to run with --stacktrace
though, running gradlew compileDebug
by itself, from the command line, should tell you where the error is.
I based this information on this comment:
Android Studio new project can not run, throwing error
How to open Emacs inside Bash
In the spirit of providing functionality, go to your .profile
or .bashrc
file located at /home/usr/
and at the bottom add the line:
alias enw='emacs -nw'
Now each time you open a terminal session you just type, for example, enw
and you have the Emacs no-window option with three letters :).
Invalid postback or callback argument. Event validation is enabled using '<pages enableEventValidation="true"/>'
The following example shows how to test the value of the IsPostBack property when the page is loaded in order to determine whether the page is being rendered for the first time or is responding to a postback. If the page is being rendered for the first time, the code calls the Page.Validate method.
The page markup (not shown) contains RequiredFieldValidator controls that display asterisks if no entry is made for a required input field. Calling Page.Validate causes the asterisks to be displayed immediately when the page is rendered, instead of waiting until the user clicks the Submit button. After a postback, you do not have to call Page.Validate, because that method is called as part of the Page life cycle.
private void Page_Load()
{
if (!IsPostBack)
{
}
}