Let the problem be: finding the Kth largest element in an unsorted array.
Divide the array into n/5 groups where each group consisting of 5 elements.
Now a1,a2,a3....a(n/5) represent the medians of each group.
x = Median of the elements a1,a2,.....a(n/5).
Now if k<n/2 then we can remove the largets, 2nd largest and 3rd largest element of the groups whose median is greater than the x. We can now call the function again with 7n/10 elements and finding the kth largest value.
else if k>n/2 then we can remove the smallest ,2nd smallest and 3rd smallest element of the group whose median is smaller than the x. We can now call the function of again with 7n/10 elements and finding the (k-3n/10)th largest value.
Time Complexity Analysis: T(n) time complexity to find the kth largest in an array of size n.
T(n) = T(n/5) + T(7n/10) + O(n)
if you solve this you will find out that T(n) is actually O(n)
n/5 + 7n/10 = 9n/10 < n
Here is my simple but efficient algorithm (in C++) for calculating running median from a stream of integers:
#include<algorithm>
#include<fstream>
#include<vector>
#include<list>
using namespace std;
void runningMedian(std::ifstream& ifs, std::ofstream& ofs, const unsigned bufSize) {
if (bufSize < 1)
throw exception("Wrong buffer size.");
bool evenSize = bufSize % 2 == 0 ? true : false;
list<int> q;
vector<int> nums;
int n;
unsigned count = 0;
while (ifs.good()) {
ifs >> n;
q.push_back(n);
auto ub = std::upper_bound(nums.begin(), nums.end(), n);
nums.insert(ub, n);
count++;
if (nums.size() >= bufSize) {
auto it = std::find(nums.begin(), nums.end(), q.front());
nums.erase(it);
q.pop_front();
if (evenSize)
ofs << count << ": " << (static_cast<double>(nums[nums.size() / 2 - 1] +
static_cast<double>(nums[nums.size() / 2]))) / 2.0 << '\n';
else
ofs << count << ": " << static_cast<double>(nums[nums.size() / 2]);
}
}
}
The bufferSize
specifies the size of the numbers sequence, on which the running median must be calculated. When reading numbers from the input stream ifs
the vector of the size bufferSize
is maintained in sorted order. The median is calculated by taking the middle of the sorted vector, if bufferSize
is odd, or the sum of the two middle elements divided by 2, when bufferSize
is even. Additinally, I maintain a list of last bufferSize
elements read from input. When a new element is added, I put it in the right place in sorted vector and remove from the vector the element added bufferSize
steps before (the value of the element retained in the front of the list). In the same time I remove the old element from the list: every new element is placed on the back of the list, every old element is removed from the front. After reaching the bufferSize
, both the list and the vector stop to grow, and every insertion of a new element is compensated be deletion of an old element, placed in the list bufferSize
steps before. Note, I do not care, whether I remove from the vector exactly the element, placed bufferSize
steps before, or just an element that has the same value. For the value of median it does not matter.
All calculated median values are output in the output stream.
I have created a heap wrapper that inverts the values to create a max-heap, as well as a wrapper class for a min-heap to make the library more OOP-like. Here is the gist. There are three classes; Heap (abstract class), HeapMin, and HeapMax.
Methods:
isempty() -> bool; obvious
getroot() -> int; returns min/max
push() -> None; equivalent to heapq.heappush
pop() -> int; equivalent to heapq.heappop
view_min()/view_max() -> int; alias for getroot()
pushpop() -> int; equivalent to heapq.pushpop
Neevek's solution works better than Joel's on devices running 3.2 and above. There is a bug in Android that will cause java.lang.IllegalArgumentException: pointerIndex out of range if a gesture detector is used inside a scollview. To duplicate the issue, implement a custom scollview as Joel suggested and put a view pager inside. If you drag (don't lift you figure) to one direction (left/right) and then to the opposite, you will see the crash. Also in Joel's solution, if you drag the view pager by moving your finger diagonally, once your finger leave the view pager's content view area, the pager will spring back to its previous position. All these issues are more to do with Android's internal design or lack of it than Joel's implementation, which itself is a piece of smart and concise code.
After further investigating on PSExec tool, I think I got the answer. I need to add -i option to tell PSExec to launch process on remote in interactive mode:
PSExec \\RPC001 -i -u myID -p myPWD PowerShell C:\script\StartPS.ps1 par1 par2
Without -i, powershell.exe is running on the remote in waiting mode. Interesting point is that if I run a simple bat (without PS in bat), it works fine. Maybe this is something special for PS case? Welcome comments and explanations.
I would use JPA's constructor expression feature. See also following answer:
JPQL Constructor Expression - org.hibernate.hql.ast.QuerySyntaxException:Table is not mapped
Following the example in the question, it would be something like this.
SELECT DISTINCT new com.mypackage.MyNameType(c.name) from Customer c
This doesn't seem to be a problem on a Core 2 Duo running Windows XP and JRE 1.5.0_06.
In a test with three threads I don't see System.nanoTime() going backwards. The processors are both busy, and threads go to sleep occasionally to provoke moving threads around.
[EDIT] I would guess that it only happens on physically separate processors, i.e. that the counters are synchronized for multiple cores on the same die.
Hibernate can create a table, hibernate sequence and tables used for many-to-many mapping on your behalf but you have to explicitly configure it by calling setProperty("hibernate.hbm2ddl.auto", "create") of the Configuration object. By Default, it just validates the schema with DB and fails if anything not already exists by giving error "ORA-00942: table or view does not exist".
If you do above configuration then order of performed actions will be:- a) Drop all tables and sequence and do not give an error if they are not already present. b) create all table and sequence c) alter tables with constraints d) insert data into it.
Below code will help you:
public class DeckListAdapter extends BaseAdapter{
private LayoutInflater mInflater;
ArrayList<String> teams=new ArrayList<String>();
ArrayList<Integer> teamcolor=new ArrayList<Integer>();
public DeckListAdapter(Context context) {
// Cache the LayoutInflate to avoid asking for a new one each time.
mInflater = LayoutInflater.from(context);
teams.add("Upload");
teams.add("Download");
teams.add("Device Browser");
teams.add("FTP Browser");
teams.add("Options");
teamcolor.add(Color.WHITE);
teamcolor.add(Color.LTGRAY);
teamcolor.add(Color.WHITE);
teamcolor.add(Color.LTGRAY);
teamcolor.add(Color.WHITE);
}
public int getCount() {
return teams.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.decklist, null);
holder = new ViewHolder();
holder.icon = (ImageView) convertView.findViewById(R.id.deckarrow);
holder.text = (TextView) convertView.findViewById(R.id.textname);
.......here you can use holder.text.setonclicklistner(new View.onclick.
for each textview
System.out.println(holder.text.getText().toString());
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(teams.get(position));
if(position<teamcolor.size())
holder.text.setBackgroundColor(teamcolor.get(position));
holder.icon.setImageResource(R.drawable.arraocha);
return convertView;
}
class ViewHolder {
ImageView icon;
TextView text;
}
}
Hope this helps.
var query = source.GroupBy(x => new { x.Column1, x.Column2 });
Another slight enhancement on CMS's answer. To easily allow for separate delays, you can use the following:
function makeDelay(ms) {
var timer = 0;
return function(callback){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
};
If you want to reuse the same delay, just do
var delay = makeDelay(250);
$(selector1).on('keyup', function() {delay(someCallback);});
$(selector2).on('keyup', function() {delay(someCallback);});
If you want separate delays, you can do
$(selector1).on('keyup', function() {makeDelay(250)(someCallback);});
$(selector2).on('keyup', function() {makeDelay(250)(someCallback);});
Here is complete console working application code. Please install RestSharp package.
using RestSharp;
using System;
namespace RESTSharpClient
{
class Program
{
static void Main(string[] args)
{
string url = "https://abc.example.com/";
string jsonString = "{" +
"\"auth\": {" +
"\"type\" : \"basic\"," +
"\"password\": \"@P&p@y_10364\"," +
"\"username\": \"prop_apiuser\"" +
"}," +
"\"requestId\" : 15," +
"\"method\": {" +
"\"name\": \"getProperties\"," +
"\"params\": {" +
"\"showAllStatus\" : \"0\"" +
"}" +
"}" +
"}";
IRestClient client = new RestClient(url);
IRestRequest request = new RestRequest("api/properties", Method.POST, DataFormat.Json);
request.AddHeader("Content-Type", "application/json; CHARSET=UTF-8");
request.AddJsonBody(jsonString);
var response = client.Execute(request);
Console.WriteLine(response.Content);
//TODO: do what you want to do with response.
}
}
}
Another possible reason is indirect reference. If a code references to a struct that not included in current c file, the compiler will complain.
a->b->c //error if b not included in current c file
DirectoryInfo d = new DirectoryInfo(@"D:\Test");//Assuming Test is your Folder
FileInfo[] Files = d.GetFiles("*.txt"); //Getting Text files
string str = "";
foreach(FileInfo file in Files )
{
str = str + ", " + file.Name;
}
Hope this will help...
You may need to run the cron job as a user with permissions to execute the PHP script. Try executing the cron job as root, using the command runuser
(man runuser
). Or create a system crontable and run the PHP script as an authorized user, as @Philip described.
I provide a detailed answer how to use cron in this stackoverflow post.
How to write a cron that will run a script every day at midnight?
you can try this out if you want to pass more than one type of arguments, first add them all to an array of type Object and pass that object to RunWorkerAsync() here is an example :
some_Method(){
List<string> excludeList = new List<string>(); // list of strings
string newPath ="some path"; // normal string
Object[] args = {newPath,excludeList };
backgroundAnalyzer.RunWorkerAsync(args);
}
Now in the doWork method of background worker
backgroundAnalyzer_DoWork(object sender, DoWorkEventArgs e)
{
backgroundAnalyzer.ReportProgress(50);
Object[] arg = e.Argument as Object[];
string path= (string)arg[0];
List<string> lst = (List<string>) arg[1];
.......
// do something......
//.....
}
I was getting the same the error inside a shared function, but it was only happening for some calls to this shared function. I eventually realized that one of classes calling the shared function wasn't wrapping it inside of a Unit of Work. Once I updated this classes functions with a Unit of Work everything worked as expected.
So just posting this for any future visitors who run into this same error, but for whom the accepted answer doesn't apply.
Here is an ES6 one liner which preserves the location hash and does not pollute browser history by using replaceState
:
(l=>{window.history.replaceState({},'',l.pathname+l.hash)})(location)
Be careful with permissions, it is problably you don't have some of them. You can see it in settings -> apps -> name of the application -> permissions -> active if not.
Because %
is only defined for integer types. That's the modulus operator.
5.6.2 of the standard:
The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]
As Oli pointed out, you can use fmod()
. Don't forget to include math.h
.
This question is kind of old, but wanted to share something which worked for me. Hope it will be useful for people who are searching for some information accessing properties in an external location.
This is what has worked for me.
Property file contents:
PROVIDER_URL=t3://localhost:8003,localhost:8004
applicationContext.xml
file contents: (Spring 3.2.3)
Note: ${user.home}
is a system property from OS.
<context:property-placeholder system-properties-mode="OVERRIDE" location="file:${user.home}/myapp/latest/bin/my-env.properties"/>
<bean id="appsclusterJndiTemplate" class="org.springframework.jndi.JndiTemplate">
<property name="environment">
<props>
<prop key="java.naming.factory.initial">weblogic.jndi.WLInitialContextFactory</prop>
<prop key="java.naming.provider.url">${PROVIDER_URL}</prop>
</props>
</property>
</bean>
${PROVIDER_URL}
got replaced with the value in the properties the file
Below is the link that suggests how to design Splash screen. To avoid white/black background we need to define a theme with splash background and set that theme to splash in manifest file.
https://android.jlelse.eu/right-way-to-create-splash-screen-on-android-e7f1709ba154
splash_background.xml inside res/drawable folder
<?xml version=”1.0" encoding=”utf-8"?>
<layer-list xmlns:android=”http://schemas.android.com/apk/res/android">
<item android:drawable=”@color/colorPrimary” />
<item>
<bitmap
android:gravity=”center”
android:src=”@mipmap/ic_launcher” />
</item>
</layer-list>
Add below styles
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<!-- Splash Screen theme. -->
<style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
<item name="android:windowBackground">@drawable/splash_background</item>
</style>
In Manifest set theme as shown below
<activity
android:name=".SplashActivity"
android:theme="@style/SplashTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Jquery Select Box Validation.You can Alert Message via alert or Put message in Div as per your requirements.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="message"></div>_x000D_
<form method="post">_x000D_
<select name="year" id="year">_x000D_
<option value="0">Year</option>_x000D_
<option value="1">1919</option>_x000D_
<option value="2">1920</option>_x000D_
<option value="3">1921</option>_x000D_
<option value="4">1922</option>_x000D_
</select>_x000D_
<button id="clickme">Click</button>_x000D_
</form>_x000D_
<script>_x000D_
$("#clickme").click(function(){_x000D_
_x000D_
if( $("#year option:selected").val()=='0'){_x000D_
_x000D_
alert("Please select one option at least");_x000D_
_x000D_
$("#message").html("Select At least one option");_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
});_x000D_
_x000D_
</script>
_x000D_
Not sure if this solution works for you or not but just want to heads you up on compiler and build tools version compatibility issues.
This could be because of Java and Gradle version mismatch.
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip
Gradle 4.4 is compatible with only Java 7 and 8. So, point your global variable JAVA_HOME to Java 7 or 8.
In mac, add below line to your ~/.bash_profile
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_191.jdk/Contents/Home
You can have multiple java versions. Just change the JAVA_HOME path based on need. You can do it easily, check this
in case you would like to print all file contents:
find . -type f -exec cat {} +
Try using the code after you active the sheet:
Dim J as integer
J = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row
If you use Cells.SpecialCells(xlCellTypeLastCell).Row
only, the problem will be that the xlCellTypeLastCell
information will not be updated unless one do a "Save file" action. But use UsedRange
will always update the information in realtime.
show user
to get connected user
select instance_name from v$instance
to get instance or set in sqlplus
set sqlprompt "_USER'@'_CONNECT_IDENTIFIER> "
Unless there's a way to retrieve the old index of the elements after they've been shuffled, I'd do it one of two ways:
A) Make another list multi_shuffler = [0, 1, 2, ... , file.size()] and shuffle it. Loop over it to get the order for your shuffled file/image lists.
ArrayList newFileList = new ArrayList(); ArrayList newImgList = new ArrayList(); for ( i=0; i
or B) Make a StringWrapper class to hold the file/image names and combine the two lists you've already got into one: ArrayList combinedList;
There's a working JSFiddle with a small example here, that demonstrates exactly what you are looking for (unless I've misunderstood your request): http://jsfiddle.net/9N7Z2/188/
There are a few issues with that method of loading javascript dynamically. When it comes to the very basal frameworks, like jQuery, you actually probably want to load them statically, because otherwise, you would have to write a whole JavaScript loading framework...
You could use some of the existing JavaScript loaders, or write your own by watching for window.jQuery
to get defined.
// Immediately-invoked function expression
(function() {
// Load the script
var script = document.createElement("SCRIPT");
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
script.type = 'text/javascript';
script.onload = function() {
var $ = window.jQuery;
// Use $ here...
};
document.getElementsByTagName("head")[0].appendChild(script);
})();
Just remember that if you need to support really old browsers, like IE8, load
event handlers do not execute. In that case, you would need to poll for the existance of window.jQuery
using repeated window.setTimeout
. There is a working JSFiddle with that method here: http://jsfiddle.net/9N7Z2/3/
There are lots of people who have already done what you need to do. Check out some of the existing JavaScript Loader frameworks, like:
Do you mean like this?
<!-- ... --->
<td>
this text should be left justified
and this text should be right justified?
</td>
<!-- ... --->
If yes
<!-- ... --->
<td>
<p style="text-align: left;">this text should be left justified</p>
<p style="text-align: right;">and this text should be right justified?</p>
</td>
<!-- ... --->
If you have android, you can install free app on phone (Wifi file Transfer) and enable ssl, port and other options for access and send data in both directions just start application and write in pc browser phone ip and port. enjoy!
I had this issue when I was trying to make my Docker container smaller. It was because I'd installed Python 2.7 with:
apt-get install -y --no-install-recommends python
And I should not have included the --no-install-recommends
flag:
apt-get install -y python
First convert it to a string:
var mynumber = 123;
alert((""+mynumber).length);
Adding an empty string to it will implicitly cause mynumber
to turn into a string.
You can use curlrequest to easily set what time of request you want to do... you can even set headers in the options to "fake" a browser call.
Select * from people p, address a where p.id = a.person_id and a.zip='97229';
Or you must TRY using JOIN
which is a more efficient and better way to do this as Gordon Linoff in the comments below also says that you need to learn this.
SELECT p.*, a.street, a.city FROM persons AS p
JOIN address AS a ON p.id = a.person_id
WHERE a.zip = '97299';
Here p.*
means it will show all the columns of PERSONS table.
Just use:
do
{
//enter code here
} while ( !condition );
So what this does is, it moves your 'check for condition' part to the end, since the while
is at the end. So it only checks the condition after running the code, just like how you want it
you can create a List[] and initialize them by for loop. it compiles without errors:
List<e>[] l;
for(int i = 0; i < l.length; i++){
l[i] = new ArrayList<e>();
}
it works with arrayList[] l as well.
DateTime
is not standard nullable type. If you want assign null to DateTime
type of variable, you have to use DateTime?
type which supports null value.
If you only want test your variable to be set (e.g. variable holds other than default value), you can use keyword "default" like in following code:
if (dateTimeVariable == default(DateTime))
{
//do work for dateTimeVariable == null situation
}
Just for completeness, you can get a list of kernels with jupyter kernelspec list
, but I ran into a case where one of the kernels did not show up in this list. You can find all kernel names by opening a Jupyter notebook and selecting Kernel -> Change kernel
. If you do not see everything in this list when you run jupyter kernelspec list
, try looking in common Jupyter folders:
ls ~/.local/share/jupyter/kernels # usually where local kernels go
ls /usr/local/share/jupyter/kernels # usually where system-wide kernels go
ls /usr/share/jupyter/kernels # also where system-wide kernels can go
Also, you can delete a kernel with jupyter kernelspec remove
or jupyter kernelspec uninstall
. The latter is an alias for remove
. From the in-line help text for the command:
uninstall
Alias for remove
remove
Remove one or more Jupyter kernelspecs by name.
I'm using this solution and works in IE8 or greater.
if (typeof Element.prototype.addEventListener === 'undefined') {
Element.prototype.addEventListener = function (e, callback) {
e = 'on' + e;
return this.attachEvent(e, callback);
};
}
And then:
<button class="click-me">Say Hello</button>
<script>
document.querySelectorAll('.click-me')[0].addEventListener('click', function () {
console.log('Hello');
});
</script>
This will work both IE8 and Chrome, Firefox, etc.
You can change the eclipse tomcat server configuration. Open the server view, double click on you server to open server configuration. Then click to activate "Publish module contents to separate XML files". Finally, restart your server, the message must disappear.
If you want to avoid the verbosity of if(){} else if{}
, you may consider switching this single file to kotlin and use the switch-like when expression in combination with is
operator.
In any case Kotlin and java files can co-exist in a project.
when (this) { //switch-like statement in kotlin supporting class-pattern-matching and smart casts via `is` operator.
is A -> doA()
is B -> doB()
is C -> doC()
}
The answers above check if a filesystem contains a path that is a file or directory. But it doesn't identify if a given path alone is a file or directory.
The answer is to identify directory-based paths using "/." like --> "/c/dos/run/." <-- trailing period.
Like a path of a directory or file that has not been written yet. Or a path from a different computer. Or a path where both a file and directory of the same name exists.
// /tmp/
// |- dozen.path
// |- dozen.path/.
// |- eggs.txt
//
// "/tmp/dozen.path" !== "/tmp/dozen.path/"
//
// Very few fs allow this. But still. Don't trust the filesystem alone!
// Converts the non-standard "path-ends-in-slash" to the standard "path-is-identified-by current "." or previous ".." directory symbol.
function tryGetPath(pathItem) {
const isPosix = pathItem.includes("/");
if ((isPosix && pathItem.endsWith("/")) ||
(!isPosix && pathItem.endsWith("\\"))) {
pathItem = pathItem + ".";
}
return pathItem;
}
// If a path ends with a current directory identifier, it is a path! /c/dos/run/. and c:\dos\run\.
function isDirectory(pathItem) {
const isPosix = pathItem.includes("/");
if (pathItem === "." || pathItem ==- "..") {
pathItem = (isPosix ? "./" : ".\\") + pathItem;
}
return (isPosix ? pathItem.endsWith("/.") || pathItem.endsWith("/..") : pathItem.endsWith("\\.") || pathItem.endsWith("\\.."));
}
// If a path is not a directory, and it isn't empty, it must be a file
function isFile(pathItem) {
if (pathItem === "") {
return false;
}
return !isDirectory(pathItem);
}
Node version: v11.10.0 - Feb 2019
Last thought: Why even hit the filesystem?
Try the following, in order:
Smaller buffer size. Writing ~2 MiB at a time might be a good start. On my last laptop, ~512 KiB was the sweet spot, but I haven't tested on my SSD yet.
Note: I've noticed that very large buffers tend to decrease performance. I've noticed speed losses with using 16-MiB buffers instead of 512-KiB buffers before.
Use _open
(or _topen
if you want to be Windows-correct) to open the file, then use _write
. This will probably avoid a lot of buffering, but it's not certain to.
Using Windows-specific functions like CreateFile
and WriteFile
. That will avoid any buffering in the standard library.
Start your IDE with administrative privilege( Windows: right click and run as admin), so that it has read write access to tomact folder for deployment. It worked for me.
Hope This useful...
form:
<form action="check.php" method="post" enctype="multipart/form-data">
<label>Upload An Image</label>
<input type="file" name="file_upload" />
<input type="submit" name="upload"/>
</form>
check.php:
<?php
if(isset($_POST['upload'])){
$maxsize=2097152;
$format=array('image/jpeg');
if($_FILES['file_upload']['size']>=$maxsize){
$error_1='File Size too large';
echo '<script>alert("'.$error_1.'")</script>';
}
elseif($_FILES['file_upload']['size']==0){
$error_2='Invalid File';
echo '<script>alert("'.$error_2.'")</script>';
}
elseif(!in_array($_FILES['file_upload']['type'],$format)){
$error_3='Format Not Supported.Only .jpeg files are accepted';
echo '<script>alert("'.$error_3.'")</script>';
}
else{
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["file_upload"]["name"]);
if(move_uploaded_file($_FILES["file_upload"]["tmp_name"], $target_file)){
echo "The file ". basename($_FILES["file_upload"]["name"]). " has been uploaded.";
}
else{
echo "sorry";
}
}
}
?>
I think the issue is with binding:
constructor(props){
super(props);
this.goBack = this.goBack.bind(this); // i think you are missing this
}
goBack(){
this.props.history.goBack();
}
.....
<button onClick={this.goBack}>Go Back</button>
As I have assumed before you posted the code:
constructor(props) {
super(props);
this.handleNext = this.handleNext.bind(this);
this.handleBack = this.handleBack.bind(this); // you are missing this line
}
this kind of solution causes many problems like this. for consistency and SEO considerations redirect on the main domain is the best solution.
do it redirection at the server level
How To Redirect www to Non-www with Nginx
or any other level like route 53 if are using
Your first one was basically right. This, FYI, is bad. It does an equality check between a DOM node and a string:
if (document.getElementById('customx') == ""){
DOM nodes are actually their own type of JavaScript object. Thus this comparison would never work at all since it's doing an equality comparison on two distinctly different data types.
Yet another try - Using event lambda expressions
As form initializes a single event handler can be assigned to all controls of type RadioButton in a group box, and use .tabIndex or .tag property to identify what option is checked when it changes.
This way you can subscribe to any of the events of each radio button in one go
int priceOption = 0;
foreach (RadioButton rbtn in grp_PriceOpt.Controls.OfType<RadioButton>())
{
rbtn.CheckedChanged += (o, e) =>
{
var button = (RadioButton)o;
if (button.Checked)
{
priceOption = button.TabIndex;
}
};
}
As events are assigned to radio buttons only, no type checking of sender is implemented.
Also notice as we loop all buttons this could be a perfect moment to assign data properties, change text etc.
People have been doing a good job explaining why NOT to use, so I will tell you a couple situations where you should use it:
(The following comments apply to Hotspot running on Linux with the CMS collector, where I feel confident saying that System.gc()
does in fact always invoke a full garbage collection).
After the initial work of starting up your application, you may be a terrible state of memory usage. Half your tenured generation could be full of garbage, meaning that you are that much closer to your first CMS. In applications where that matters, it is not a bad idea to call System.gc() to "reset" your heap to the starting state of live data.
Along the same lines as #1, if you monitor your heap usage closely, you want to have an accurate reading of what your baseline memory usage is. If the first 2 minutes of your application's uptime is all initialization, your data is going to be messed up unless you force (ahem... "suggest") the full gc up front.
You may have an application that is designed to never promote anything to the tenured generation while it is running. But maybe you need to initialize some data up-front that is not-so-huge as to automatically get moved to the tenured generation. Unless you call System.gc() after everything is set up, your data could sit in the new generation until the time comes for it to get promoted. All of a sudden your super-duper low-latency, low-GC application gets hit with a HUGE (relatively speaking, of course) latency penalty for promoting those objects during normal operations.
It is sometimes useful to have a System.gc call available in a production application for verifying the existence of a memory leak. If you know that the set of live data at time X should exist in a certain ratio to the set of live data at time Y, then it could be useful to call System.gc() a time X and time Y and compare memory usage.
Just go to follow link domain.com/wp-admin/about.php
Go to File > Preferences > Settings
(or press Ctrl+,) then click the leftmost icon in the top right corner, "Open Settings (JSON)"
In the JSON settings window, add this (within the curly braces {}
):
"terminal.integrated.shell.windows": "C:\\WINDOWS\\System32\\bash.exe"`
(Here you can put any other custom settings you want as well)
Checkout that path to make sure your bash.exe file is there otherwise find out where it is and point to that path instead.
Now if you open a new terminal window in VS Code, it should open with bash instead of PowerShell.
execute below
Python manage.py makemigrations
It will show missing package.
Install missing package and again run below command to make sure if nothing is missed.
Python manage.py makemigrations
It will resolve your issue.
There are few ways to read input string from your console/keyboard. The following sample code shows how to read a string from the console/keyboard by using Java.
public class ConsoleReadingDemo {
public static void main(String[] args) {
// ====
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter user name : ");
String username = null;
try {
username = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("You entered : " + username);
// ===== In Java 5, Java.util,Scanner is used for this purpose.
Scanner in = new Scanner(System.in);
System.out.print("Please enter user name : ");
username = in.nextLine();
System.out.println("You entered : " + username);
// ====== Java 6
Console console = System.console();
username = console.readLine("Please enter user name : ");
System.out.println("You entered : " + username);
}
}
The last part of code used java.io.Console
class. you can not get Console instance from System.console()
when running the demo code through Eclipse. Because eclipse runs your application as a background process and not as a top-level process with a system console.
The following code snippet enables/disables a button depending on whether at least one checkbox on the page has been checked.
$('input[type=checkbox]').change(function () {
$('#test > tbody tr').each(function () {
if ($('input[type=checkbox]').is(':checked')) {
$('#btnexcellSelect').removeAttr('disabled');
} else {
$('#btnexcellSelect').attr('disabled', 'disabled');
}
if ($(this).is(':checked')){
console.log( $(this).attr('id'));
}else{
console.log($(this).attr('id'));
}
});
});
Here is demo in JSFiddle.
The new version 2.4 of Apache HTTP Server has a module called mod_proxy_wstunnel which is a websocket proxy.
http://httpd.apache.org/docs/2.4/mod/mod_proxy_wstunnel.html
As stated in 1.7.12 Release Notes, you may use
$ git rebase -i --root
By default, gcc selects the language based on the file extension, but you can force gcc to select a different language backend with the -x option thus:
gcc -x c++
More options are detailed in the gcc man page under "Options controlling the kind of output". See e.g. http://linux.die.net/man/1/gcc (search on the page for the text -x language
).
This facility is very useful in cases where gcc can't guess the language using a file extension, for example if you're generating code and feeding it to gcc via stdin.
Well in order to understand how static and dynamic binding actually works? or how they are identified by compiler and JVM?
Let's take below example where Mammal
is a parent class which has a method speak()
and Human
class extends Mammal
, overrides the speak()
method and then again overloads it with speak(String language)
.
public class OverridingInternalExample {
private static class Mammal {
public void speak() { System.out.println("ohlllalalalalalaoaoaoa"); }
}
private static class Human extends Mammal {
@Override
public void speak() { System.out.println("Hello"); }
// Valid overload of speak
public void speak(String language) {
if (language.equals("Hindi")) System.out.println("Namaste");
else System.out.println("Hello");
}
@Override
public String toString() { return "Human Class"; }
}
// Code below contains the output and bytecode of the method calls
public static void main(String[] args) {
Mammal anyMammal = new Mammal();
anyMammal.speak(); // Output - ohlllalalalalalaoaoaoa
// 10: invokevirtual #4 // Method org/programming/mitra/exercises/OverridingInternalExample$Mammal.speak:()V
Mammal humanMammal = new Human();
humanMammal.speak(); // Output - Hello
// 23: invokevirtual #4 // Method org/programming/mitra/exercises/OverridingInternalExample$Mammal.speak:()V
Human human = new Human();
human.speak(); // Output - Hello
// 36: invokevirtual #7 // Method org/programming/mitra/exercises/OverridingInternalExample$Human.speak:()V
human.speak("Hindi"); // Output - Namaste
// 42: invokevirtual #9 // Method org/programming/mitra/exercises/OverridingInternalExample$Human.speak:(Ljava/lang/String;)V
}
}
When we compile the above code and try to look at the bytecode using javap -verbose OverridingInternalExample
, we can see that compiler generates a constant table where it assigns integer codes to every method call and byte code for the program which I have extracted and included in the program itself (see the comments below every method call)
By looking at above code we can see that the bytecodes of humanMammal.speak()
, human.speak()
and human.speak("Hindi")
are totally different (invokevirtual #4
, invokevirtual #7
, invokevirtual #9
) because the compiler is able to differentiate between them based on the argument list and class reference. Because all of this get resolved at compile time statically that is why Method Overloading is known as Static Polymorphism or Static Binding.
But bytecode for anyMammal.speak()
and humanMammal.speak()
is same (invokevirtual #4
) because according to compiler both methods are called on Mammal
reference.
So now the question comes if both method calls have same bytecode then how does JVM know which method to call?
Well, the answer is hidden in the bytecode itself and it is invokevirtual
instruction set. JVM uses the invokevirtual
instruction to invoke Java equivalent of the C++ virtual methods. In C++ if we want to override one method in another class we need to declare it as virtual, But in Java, all methods are virtual by default because we can override every method in the child class (except private, final and static methods).
In Java, every reference variable holds two hidden pointers
So all object references indirectly hold a reference to a table which holds all the method references of that object. Java has borrowed this concept from C++ and this table is known as virtual table (vtable).
A vtable is an array like structure which holds virtual method names and their references on array indices. JVM creates only one vtable per class when it loads the class into memory.
So whenever JVM encounter with a invokevirtual
instruction set, it checks the vtable of that class for the method reference and invokes the specific method which in our case is the method from a object not the reference.
Because all of this get resolved at runtime only and at runtime JVM gets to know which method to invoke, that is why Method Overriding is known as Dynamic Polymorphism or simply Polymorphism or Dynamic Binding.
You can read it more details on my article How Does JVM Handle Method Overloading and Overriding Internally.
You can look at the javadoc of the Pattern class: http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html
You need to escape any char listed there if you want the regular char and not the special meaning.
As a maybe simpler solution, you can put the template between \Q and \E - everything between them is considered as escaped.
I converted @syockit's answer as well as the step-down approach into a reusable Angular service for anyone who's interested: https://gist.github.com/fisch0920/37bac5e741eaec60e983
I included both solutions because they both have their own pros / cons. The lanczos convolution approach is higher quality at the cost of being slower, whereas the step-wise downscaling approach produces reasonably antialiased results and is significantly faster.
Example usage:
angular.module('demo').controller('ExampleCtrl', function (imageService) {
// EXAMPLE USAGE
// NOTE: it's bad practice to access the DOM inside a controller,
// but this is just to show the example usage.
// resize by lanczos-sinc filter
imageService.resize($('#myimg')[0], 256, 256)
.then(function (resizedImage) {
// do something with resized image
})
// resize by stepping down image size in increments of 2x
imageService.resizeStep($('#myimg')[0], 256, 256)
.then(function (resizedImage) {
// do something with resized image
})
})
The length function will do it. See http://www.techonthenet.com/oracle/functions/length.php
I've had same problem, and this is how I fixed it:
Just throw this in your web.config:
<system.webServer>
<modules>
<remove name="WebDAVModule" />
</modules>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Expose-Headers " value="WWW-Authenticate"/>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, PATCH, DELETE" />
<add name="Access-Control-Allow-Headers" value="accept, authorization, Content-Type" />
<remove name="X-Powered-By" />
</customHeaders>
</httpProtocol>
<handlers>
<remove name="WebDAV" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
you can print it as string:
printf("%s\n", foo);
Jeigen https://github.com/hughperkins/jeigen
A quick test, by multiplying two dense matrices, ie:
import static jeigen.MatrixUtil.*;
int K = 100;
int N = 100000;
DenseMatrix A = rand(N, K);
DenseMatrix B = rand(K, N);
Timer timer = new Timer();
DenseMatrix C = B.mmul(A);
timer.printTimeCheckMilliseconds();
Results:
Jama: 4090 ms
Jblas: 1594 ms
Ojalgo: 2381 ms (using two threads)
Jeigen: 2514 ms
The UDF approach is my preference compared to brittle substr
values.
#!/usr/bin/env python3
import sqlite3
from dateutil import parser
from pprint import pprint
def date_parse(s):
''' Converts a string to a date '''
try:
t = parser.parse(s, parser.parserinfo(dayfirst=True))
return t.strftime('%Y-%m-%d')
except:
return None
def dict_factory(cursor, row):
''' Helper for dict row results '''
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
def main():
''' Demonstrate UDF '''
with sqlite3.connect(":memory:") as conn:
conn.row_factory = dict_factory
setup(conn)
##################################################
# This is the code that matters. The rest is setup noise.
conn.create_function("date_parse", 1, date_parse)
cur = conn.cursor()
cur.execute(''' select "date", date_parse("date") as parsed from _test order by 2; ''')
pprint(cur.fetchall())
##################################################
def setup(conn):
''' Setup some values to parse '''
cur = conn.cursor()
# Make a table
sql = '''
create table _test (
"id" integer primary key,
"date" text
);
'''
cur.execute(sql)
# Fill the table
dates = [
'2/1/03', '03/2/04', '4/03/05', '05/04/06',
'6/5/2007', '07/6/2008', '8/07/2009', '09/08/2010',
'2-1-03', '03-2-04', '4-03-05', '05-04-06',
'6-5-2007', '07-6-2008', '8-07-2009', '09-08-2010',
'31/12/20', '31-12-2020',
'BOMB!',
]
params = [(x,) for x in dates]
cur.executemany(''' insert into _test ("date") values(?); ''', params)
if __name__ == "__main__":
main()
This will give you these results:
[{'date': 'BOMB!', 'parsed': None},
{'date': '2/1/03', 'parsed': '2003-01-02'},
{'date': '2-1-03', 'parsed': '2003-01-02'},
{'date': '03/2/04', 'parsed': '2004-02-03'},
{'date': '03-2-04', 'parsed': '2004-02-03'},
{'date': '4/03/05', 'parsed': '2005-03-04'},
{'date': '4-03-05', 'parsed': '2005-03-04'},
{'date': '05/04/06', 'parsed': '2006-04-05'},
{'date': '05-04-06', 'parsed': '2006-04-05'},
{'date': '6/5/2007', 'parsed': '2007-05-06'},
{'date': '6-5-2007', 'parsed': '2007-05-06'},
{'date': '07/6/2008', 'parsed': '2008-06-07'},
{'date': '07-6-2008', 'parsed': '2008-06-07'},
{'date': '8/07/2009', 'parsed': '2009-07-08'},
{'date': '8-07-2009', 'parsed': '2009-07-08'},
{'date': '09/08/2010', 'parsed': '2010-08-09'},
{'date': '09-08-2010', 'parsed': '2010-08-09'},
{'date': '31/12/20', 'parsed': '2020-12-31'},
{'date': '31-12-2020', 'parsed': '2020-12-31'}]
The SQLite equivalent of anything this robust is a tangled weave of substr
and instr
calls that you should avoid.
I think you have to allocate a new array and put the values into the new array. For example:
int[] array1and2 = new int[array1.length + array2.length];
int currentPosition = 0;
for( int i = 0; i < array1.length; i++) {
array1and2[currentPosition] = array1[i];
currentPosition++;
}
for( int j = 0; j < array2.length; j++) {
array1and2[currentPosition] = array2[j];
currentPosition++;
}
As far as I can tell just looking at it, this code should work.
If you change your html code a bit - remove the ids
<ul id='myid'>
<li>First</li>
<li>Second</li>
<li>Third</li>
<li>Fourth</li>
<li>Fifth</li>
</ul>
Then the jquery code you want is...
$("#myid li").click(function() {
alert($(this).prevAll().length+1);
});?
You don't need to place any ids, just keep on adding li items.
Take a look at demo
Useful links
My solution below is for cases when default maven repositories are not accessible (e.g. due to firewalls).
In case the default repository is not accessible appropriate local <pluginRepository>
has to be specified in the settings.xml. If it's the same as your local artifact repository it still needs to be added to the <pluginRepositories>
section for plugin jars to be found. Regular <repositories>
section is not used to fetch plugin jars.
In my case, however, the issue was caused by the fact that there were multiple plugin repositories defined in that section.
The first repository in the list did not contain the required maven-filtering jar.
I had to change the order of <pluginRepository>
definitions to ensure the first one contains maven-filtering.
Changing of repository definitions typically requires to clean ~/.m2/repository and start fresh.
First your code is not compiled. Line Long b = 1113;
is wrong. You have to say
Long b = 1113L;
Second when I fixed this compilation problem the code printed "not equals".
You can't declare an extern
local method inside of a method, or any other method with an attribute. Move your DLL import into the class:
using System.Runtime.InteropServices;
public class WindowHandling
{
[DllImport("User32.dll")]
public static extern int SetForegroundWindow(IntPtr point);
public void ActivateTargetApplication(string processName, List<string> barcodesList)
{
Process p = Process.Start("notepad++.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");
IntPtr processFoundWindow = p.MainWindowHandle;
}
}
string col1Value = rdr["ColumnOneName"].ToString();
or
string col1Value = rdr[0].ToString();
These are object
s, so you need to either cast them or .ToString()
.
Works for me. How log all php errors to a log fiie?
Just add following line to /etc/php.ini to log errors to specified file – /var/log/php-scripts.log
vi /etc/php.ini
Modify error_log directive
error_log = /var/log/php-scripts.log
Make sure display_errors set to Off (no errors to end users)
display_errors = Off
Save and close the file. Restart web server:
/etc/init.d/httpd restart
How do I log errors to syslog or Windows Server Event Log?
Modify error_log as follows :
error_log = syslog
How see logs?
Login using ssh or download a log file /var/log/php-scripts.log using sftp:
$ sudo tail -f /var/log/php-scripts.log
Try loading your javascript after.
Try this:
<h2>Hello World!</h2>
<p id="myParagraph">This is an example website</p>
<form>
<input type="text" id="myTextfield" placeholder="Type your name" />
<input type="submit" id="myButton" value="Go" />
</form>
<script src="js/script.js" type="text/javascript"></script>
As mentioned in the comments height:100% relies on the height of the parent container being explicitly defined. One way to achieve what you want is to use absolute/relative positioning, and specifying the left/right/top/bottom properties to "stretch" the content out to fill the available space. I have implemented what I gather you want to achieve in jsfiddle. Try resizing the Result window and you will see the content resizes automatically.
The limitation of this approach in your case is that you have to specify an explicit margin-top on the parent container to offset its contents down to make room for the header content. You can make it dynamic if you throw in javascript though.
In addition to Gilson PJ answer:
new webpack.optimize.CommonsChunkPlugin('common.js'),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin(),
new webpack.optimize.AggressiveMergingPlugin()
with
"scripts": {
"build": "NODE_ENV=production webpack -p --config ./webpack.production.config.js"
},
cause that the it tries to uglify your code twice. See https://webpack.github.io/docs/cli.html#production-shortcut-p for more information.
You can fix this by removing the UglifyJsPlugin from plugins-array or add the OccurrenceOrderPlugin and remove the "-p"-flag. so one possible solution would be
new webpack.optimize.CommonsChunkPlugin('common.js'),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin(),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.AggressiveMergingPlugin()
and
"scripts": {
"build": "NODE_ENV=production webpack --config ./webpack.production.config.js"
},
do it the simpler way,
direc=$(basename `pwd`)
Or use the shell
$ direc=${PWD##*/}
.then(() => new Promise((resolve) => setTimeout(resolve, 15000)))
UPDATE:
when I need sleep in async function I throw in
await new Promise(resolve => setTimeout(resolve, 1000))
You just need to wrap object in ()
var arr = [{_x000D_
id: 1,_x000D_
name: 'bill'_x000D_
}, {_x000D_
id: 2,_x000D_
name: 'ted'_x000D_
}]_x000D_
_x000D_
var result = arr.map(person => ({ value: person.id, text: person.name }));_x000D_
console.log(result)
_x000D_
Just to add to Alex Poole's answer, here is how you do the date and time:
TO_DATE('31/DEC/2017 12:59:59', 'dd/mm/yyyy hh24:mi:ss')
I tried other answers on this question, and there are mistakes with the different browser APIs, particularly Fullscreen
vs FullScreen
. Here is my code that works with the major browsers (as of Q1 2019) and should continue to work as they standardize.
function fullScreenTgl() {
let doc=document,elm=doc.documentElement;
if (elm.requestFullscreen ) { (!doc.fullscreenElement ? elm.requestFullscreen() : doc.exitFullscreen() ) }
else if (elm.mozRequestFullScreen ) { (!doc.mozFullScreen ? elm.mozRequestFullScreen() : doc.mozCancelFullScreen() ) }
else if (elm.msRequestFullscreen ) { (!doc.msFullscreenElement ? elm.msRequestFullscreen() : doc.msExitFullscreen() ) }
else if (elm.webkitRequestFullscreen) { (!doc.webkitIsFullscreen ? elm.webkitRequestFullscreen() : doc.webkitCancelFullscreen()) }
else { console.log("Fullscreen support not detected."); }
}
Fundamentally you hadn't declare location which is what nginx uses to bind URL with resources.
server {
listen 80;
server_name localhost;
access_log logs/localhost.access.log main;
location / {
root /var/www/board/public;
index index.html index.htm index.php;
}
}
Use -regex
:
From the man page:
-regex pattern
File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named './fubar3', you can use the
regular expression '.*bar.' or '.*b.*3', but not 'b.*r3'.
Also, I don't believe find
supports regex extensions such as \d
. You need to use [0-9]
.
find . -regex '.*test\.log\.[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]\.zip'
Go to the chosen directory and execute:
$ du -d 1 -h
where:
-d 1 is the depth of the directories
-h is the human-readable option
You'll see like that:
0 ./proc
8.5M ./run
0 ./sys
56M ./etc
12G ./root
33G ./var
23M ./tmp
3.2G ./usr
154M ./boot
26G ./home
0 ./media
0 ./mnt
421M ./opt
0 ./srv
2.6G ./backups
80G .
C# does not support this. Hejlsberg has described the reasons for not implementing the feature in an interview with Bruce Eckel:
And it's not clear that the added complexity is worth the small yield that you get. If something you want to do is not directly supported in the constraint system, you can do it with a factory pattern. You could have a
Matrix<T>
, for example, and in thatMatrix
you would like to define a dot product method. That of course that means you ultimately need to understand how to multiply twoT
s, but you can't say that as a constraint, at least not ifT
isint
,double
, orfloat
. But what you could do is have yourMatrix
take as an argument aCalculator<T>
, and inCalculator<T>
, have a method calledmultiply
. You go implement that and you pass it to theMatrix
.
However, this leads to fairly convoluted code, where the user has to supply their own Calculator<T>
implementation, for each T
that they want to use. As long as it doesn’t have to be extensible, i.e. if you just want to support a fixed number of types, such as int
and double
, you can get away with a relatively simple interface:
var mat = new Matrix<int>(w, h);
(Minimal implementation in a GitHub Gist.)
However, as soon as you want the user to be able to supply their own, custom types, you need to open up this implementation so that the user can supply their own Calculator
instances. For instance, to instantiate a matrix that uses a custom decimal floating point implementation, DFP
, you’d have to write this code:
var mat = new Matrix<DFP>(DfpCalculator.Instance, w, h);
… and implement all the members for DfpCalculator : ICalculator<DFP>
.
An alternative, which unfortunately shares the same limitations, is to work with policy classes, as discussed in Sergey Shandar’s answer.
Your looking for the onSelect event in the datepicker object:
$('.selector').datepicker({
onSelect: function(dateText, inst) { ... }
});
You can get desired result with help of Regular Expressions.
SELECT fiberbox from fiberbox where fiberbox REGEXP '[1740|1938|1940]';
We can test the above query please click SQL fiddle
SELECT fiberbox from fiberbox where fiberbox REGEXP '[174019381940]';
We can test the above query please click SQL fiddle
Actually it's java limitation caping it at 2^30-4 being 1073741820. Not 2^31-1. Dunno why but i tested it manually on jdk. 2^30-3 still throwing vm except
Edit: fixed -1 to -4, checked on windows jvm
I just triggered the tests on a pull request to be re-run by clicking 'update branch' here:
String onevalue;
if(request.getParameterMap().containsKey("one")!=false)
{
onevalue=request.getParameter("one").toString();
}
We can simply write the array data to the filesystem but this will raise one error in which ',' will be appended to the end of the file. To handle this below code can be used:
var fs = require('fs');
var file = fs.createWriteStream('hello.txt');
file.on('error', function(err) { Console.log(err) });
data.forEach(value => file.write(`${value}\r\n`));
file.end();
\r\n
is used for the new Line.
\n
won't help. Please refer this
You can make method which return the datatable of given sql query:
public DataTable GetDataTable()
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["BarManConnectionString"].ConnectionString);
conn.Open();
string query = "SELECT * FROM [EventOne] ";
SqlCommand cmd = new SqlCommand(query, conn);
DataTable t1 = new DataTable();
using (SqlDataAdapter a = new SqlDataAdapter(cmd))
{
a.Fill(t1);
}
return t1;
}
and now can be used like this:
table = GetDataTable();
I'd do this one of two ways. Since you're setting your start and end dates in your t-sql code, i wouldn't ask for parameters in the stored proc
Option 1
Create Procedure [Test] AS
DECLARE @StartDate varchar(10)
DECLARE @EndDate varchar(10)
Set @StartDate = '201620' --Define start YearWeek
Set @EndDate = (SELECT CAST(DATEPART(YEAR,getdate()) AS varchar(4)) + CAST(DATEPART(WEEK,getdate())-1 AS varchar(2)))
SELECT
*
FROM
(SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)
Option 2
Create Procedure [Test] @StartDate varchar(10),@EndDate varchar(10) AS
SELECT
*
FROM
(SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)
Then run exec test '2016-01-01','2016-01-25'
One more time, building off of @RalphyZ
This one doesn't break the exposed API.
from argparse import ArgumentParser, SUPPRESS
# Disable default help
parser = ArgumentParser(add_help=False)
required = parser.add_argument_group('required arguments')
optional = parser.add_argument_group('optional arguments')
# Add back help
optional.add_argument(
'-h',
'--help',
action='help',
default=SUPPRESS,
help='show this help message and exit'
)
required.add_argument('--required_arg', required=True)
optional.add_argument('--optional_arg')
Which will show the same as above and should survive future versions:
usage: main.py [-h] [--required_arg REQUIRED_ARG]
[--optional_arg OPTIONAL_ARG]
required arguments:
--required_arg REQUIRED_ARG
optional arguments:
-h, --help show this help message and exit
--optional_arg OPTIONAL_ARG
//auth required or redirect
app.use('/account', function(req, res, next) {
console.log(req.path);
if ( !req.session.user ) {
res.redirect('/login?ref='+req.path);
} else {
next();
}
});
req.path is / when it should be /account ??
The reason for this is that Express subtracts the path your handler function is mounted on, which is '/account'
in this case.
Why do they do this?
Because it makes it easier to reuse the handler function. You can make a handler function that does different things for req.path === '/'
and req.path === '/goodbye'
for example:
function sendGreeting(req, res, next) {
res.send(req.path == '/goodbye' ? 'Farewell!' : 'Hello there!')
}
Then you can mount it to multiple endpoints:
app.use('/world', sendGreeting)
app.use('/aliens', sendGreeting)
Giving:
/world ==> Hello there!
/world/goodbye ==> Farewell!
/aliens ==> Hello there!
/aliens/goodbye ==> Farewell!
The two main differences are:
ArgumentCaptor
can capture more than once.To illustrate the latter, say you have:
final ArgumentCaptor<Foo> captor = ArgumentCaptor.forClass(Foo.class);
verify(x, times(4)).someMethod(captor.capture()); // for instance
Then the captor will be able to give you access to all 4 arguments, which you can then perform assertions on separately.
This or any number of arguments in fact, since a VerificationMode
is not limited to a fixed number of invocations; in any event, the captor will give you access to all of them, if you wish.
This also has the benefit that such tests are (imho) much easier to write than having to implement your own ArgumentMatcher
s -- particularly if you combine mockito with assertj.
Oh, and please consider using TestNG instead of JUnit.
A modern solution using flexbox:
.container {_x000D_
display: flex;_x000D_
}_x000D_
.container > div {_x000D_
border: 1px solid black;_x000D_
height: 10px;_x000D_
}_x000D_
_x000D_
.left {_x000D_
width: 100px;_x000D_
}_x000D_
_x000D_
.right {_x000D_
width: 100%;_x000D_
background-color:#ddd;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="left"></div>_x000D_
<div class="right"></div>_x000D_
</div>
_x000D_
You can use the update()
method as well
d = {"a": 2}
d.update{"b": 4}
print(d) # {"a": 2, "b": 4}
PHP does not support overloading for now. Hope this will be implemented in the other versions like other programming languages.
Checkout this library, This will allow you to use PHP Overloading in terms of closures. https://github.com/Sahil-Gulati/Overloading
Editing the config.ini
file with
osgi.instance.area.default=\D:\\Projects\\Eclipse Workspace\\
worked for me.
I don't know why, but for some reason, the "/bin/bash" version didn't work for me. Instead, the simpler version worked, following the example given here at Oracle Docs.
String[] args = new String[] {"ping", "www.google.com"};
Process proc = new ProcessBuilder(args).start();
This is my JavaScript implementation of Algorithm P (Polar method for normal deviates) from Section 3.4.1 of Donald Knuth's book The Art of Computer Programming:
function normal_random(mean,stddev)
{
var V1
var V2
var S
do{
var U1 = Math.random() // return uniform distributed in [0,1[
var U2 = Math.random()
V1 = 2*U1-1
V2 = 2*U2-1
S = V1*V1+V2*V2
}while(S >= 1)
if(S===0) return 0
return mean+stddev*(V1*Math.sqrt(-2*Math.log(S)/S))
}
```yaml
{
"this-json": "looks awesome..."
}
If you want to have keys a different colour to the parameters, set your language as yaml
@Ankanna's answer gave me the idea of going through github's supported language list and yaml
was my best find.
When you read in git tag
man page:
One important aspect of git is it is distributed, and being distributed largely means there is no inherent "upstream" or "downstream" in the system.
, that simply means there is no absolute upstream repo or downstream repo.
Those notions are always relative between two repos and depends on the way data flows:
If "yourRepo" has declared "otherRepo" as a remote one, then:
Note the "from" and "for": you are not just "downstream", you are "downstream from/for", hence the relative aspect.
The DVCS (Distributed Version Control System) twist is: you have no idea what downstream actually is, beside your own repo relative to the remote repos you have declared.
Basically:
In term of "flow of data", your repo is at the bottom ("downstream") of a flow coming from upstream repos ("pull from") and going back to (the same or other) upstream repos ("push to").
You can see an illustration in the git-rebase
man page with the paragraph "RECOVERING FROM UPSTREAM REBASE":
It means you are pulling from an "upstream" repo where a rebase took place, and you (the "downstream" repo) is stuck with the consequence (lots of duplicate commits, because the branch rebased upstream recreated the commits of the same branch you have locally).
That is bad because for one "upstream" repo, there can be many downstream repos (i.e. repos pulling from the upstream one, with the rebased branch), all of them having potentially to deal with the duplicate commits.
Again, with the "flow of data" analogy, in a DVCS, one bad command "upstream" can have a "ripple effect" downstream.
Note: this is not limited to data.
It also applies to parameters, as git commands (like the "porcelain" ones) often call internally other git commands (the "plumbing" ones). See rev-parse
man page:
Many git porcelainish commands take mixture of flags (i.e. parameters that begin with a dash '
-
') and parameters meant for the underlyinggit rev-list
command they use internally and flags and parameters for the other commands they use downstream ofgit rev-list
. This command is used to distinguish between them.
When you insert the pair (10, 17)
and then (10, 20)
, there is technically no collision involved. You are just replacing the old value with the new value for a given key 10
(since in both cases, 10 is equal to 10 and also the hash code for 10 is always 10).
Collision happens when multiple keys hash to the same bucket. In that case, you need to make sure that you can distinguish between those keys. Chaining collision resolution is one of those techniques which is used for this.
As an example, let's suppose that two strings "abra ka dabra"
and "wave my wand"
yield hash codes 100
and 200
respectively. Assuming the total array size is 10, both of them end up in the same bucket (100 % 10
and 200 % 10
). Chaining ensures that whenever you do map.get( "abra ka dabra" );
, you end up with the correct value associated with the key. In the case of hash map in Java, this is done by using the equals
method.
If I understand well, you want to Join ScheduleRequest
with User
and apply the in
clause to the userName
property of the entity User
.
I'd need to work a bit on this schema. But you can try with this trick, that is much more readable than the code you posted, and avoids the Join
part (because it handles the Join
logic outside the Criteria Query).
List<String> myList = new ArrayList<String> ();
for (User u : usersList) {
myList.add(u.getUsername());
}
Expression<String> exp = scheduleRequest.get("createdBy");
Predicate predicate = exp.in(myList);
criteria.where(predicate);
In order to write more type-safe code you could also use Metamodel by replacing this line:
Expression<String> exp = scheduleRequest.get("createdBy");
with this:
Expression<String> exp = scheduleRequest.get(ScheduleRequest_.createdBy);
If it works, then you may try to add the Join
logic into the Criteria Query
. But right now I can't test it, so I prefer to see if somebody else wants to try.
Not a perfect answer though may be code snippets might help.
public <T> List<T> findListWhereInCondition(Class<T> clazz,
String conditionColumnName, Serializable... conditionColumnValues) {
QueryBuilder<T> queryBuilder = new QueryBuilder<T>(clazz);
addWhereInClause(queryBuilder, conditionColumnName,
conditionColumnValues);
queryBuilder.select();
return queryBuilder.getResultList();
}
private <T> void addWhereInClause(QueryBuilder<T> queryBuilder,
String conditionColumnName, Serializable... conditionColumnValues) {
Path<Object> path = queryBuilder.root.get(conditionColumnName);
In<Object> in = queryBuilder.criteriaBuilder.in(path);
for (Serializable conditionColumnValue : conditionColumnValues) {
in.value(conditionColumnValue);
}
queryBuilder.criteriaQuery.where(in);
}
Here's what I cooked up. It's pretty simple, but it works:
function eventFire(el, etype){
if (el.fireEvent) {
el.fireEvent('on' + etype);
} else {
var evObj = document.createEvent('Events');
evObj.initEvent(etype, true, false);
el.dispatchEvent(evObj);
}
}
Usage:
eventFire(document.getElementById('mytest1'), 'click');
Just install the latest version from nondefault repository:
$ sudo add-apt-repository ppa:ubuntu-toolchain-r/test
$ sudo apt-get update
$ sudo apt-get install libstdc++6-4.7-dev
I can't really say why you get the "No grammar constraints..." warning, but I can provoke it in Eclipse by completely removing the DOCTYPE declaration. When I put the declaration back and validate again, I get this error message:
The content of element type "template" must match "(description+,variation?,variation-field?,allow-multiple-variation?,class-pattern?,getter-setter?,allowed-file-extensions?,template-body+).
And that is correct, I believe (the "number-required-classes" element is not allowed).
Swift 4
To get the label of the selected row:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! TableViewCell
print(cell.textLabel?.text)
}
To get the label of the deselected row:
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! TableViewCell
print(cell.textLabel?.text)
}
From Ansible 2.5
when: variable1 is search("value")
You want to convert it to an object first and then access normally making sure to cast it.
JObject obj = JObject.Parse(json);
string name = (string) obj["Name"];
As DotNetMensch said but you DO NOT need to add another site in IIS as this can also cause further problems and make things more complicated because you then have a website within a website so the file paths, masterpage paths and web.config paths may need changing. You just need to edit teh bindings of the existing site and add the new subdomain there.
So:
Add sub-domain to DNS records. My host (RackSpace) uses a web portal to do this so you just log in and go to Network->Domains(DNS)->Actions->Create Zone, and enter your subdomain as mysubdomain.domain.com etc, leave the other settings as default
Go to your domain in IIS, right-click->Edit Bindings->Add, and add your new subdomain leaving everything else the same e.g. mysubdomain.domain.com
You may need to wait 5-10 mins for the DNS records to update but that's all you need.
Try this:
(add-hook 'text-mode-hook
(function
(lambda ()
(setq tab-width 4)
(define-key text-mode-map "\C-i" 'self-insert-command)
)))
That will make TAB always insert a literal TAB character with tab stops every 4 characters (but only in Text mode). If that's not what you're asking for, please describe the behavior you'd like to see.
Real problem is when you need draw some tile/sprites intersecting/spanning two or more other tiles.
After 2 (hard) months of personal analisys of problem I finally found and implemented a "correct render drawing" for my new cocos2d-js game. Solution consists in mapping, for each tile (susceptible), which sprites are "front, back, top and behind". Once doing that you can draw them following a "recursive logic".
Avro is a row-based storage format for Hadoop.
Parquet is a column-based storage format for Hadoop.
If your use case typically scans or retrieves all of the fields in a row in each query, Avro is usually the best choice.
If your dataset has many columns, and your use case typically involves working with a subset of those columns rather than entire records, Parquet is optimized for that kind of work.
I prefer to do the cast, but not manually. My favorite is using g_new
and g_new0
macros from glib. If glib is not used, I would add similar macros. Those macros reduce code duplication without compromising type safety. If you get the type wrong, you would get an implicit cast between non-void pointers, which would cause a warning (error in C++). If you forget to include the header that defines g_new
and g_new0
, you would get an error. g_new
and g_new0
both take the same arguments, unlike malloc
that takes fewer arguments than calloc
. Just add 0
to get zero-initialized memory. The code can be compiled with a C++ compiler without changes.
As per String literals:
String literals can be enclosed within single quotes (i.e.
'...'
) or double quotes (i.e."..."
). They can also be enclosed in matching groups of three single or double quotes (these are generally referred to as triple-quoted strings).The backslash character (i.e.
\
) is used to escape characters which otherwise will have a special meaning, such as newline, backslash itself, or the quote character. String literals may optionally be prefixed with a letterr
orR
. Such strings are called raw strings and use different rules for backslash escape sequences.In triple-quoted strings, unescaped newlines and quotes are allowed, except that the three unescaped quotes in a row terminate the string.
Unless an
r
orR
prefix is present, escape sequences in strings are interpreted according to rules similar to those used by Standard C.
So ideally you need to replace the line:
data = open("C:\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener")
To any one of the following characters:
Using raw prefix and single quotes (i.e. '...'
):
data = open(r'C:\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener')
Using double quotes (i.e. "..."
) and escaping backslash character (i.e. \
):
data = open("C:\\Users\\miche\\Documents\\school\\jaar2\\MIK\\2.6\\vektis_agb_zorgverlener")
Using double quotes (i.e. "..."
) and forwardslash character (i.e. /
):
data = open("C:/Users/miche/Documents/school/jaar2/MIK/2.6/vektis_agb_zorgverlener")
This helped me as I wanted to use only xmlHttpRequest
and post an object as form data:
function sendData(data) {
var XHR = new XMLHttpRequest();
var FD = new FormData();
// Push our data into our FormData object
for(name in data) {
FD.append(name, data[name]);
}
// Set up our request
XHR.open('POST', 'https://example.com/cors.php');
// Send our FormData object; HTTP headers are set automatically
XHR.send(FD);
}
https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript
A slightly nicer way of measuring execution time, is to use the rbenchmark package. This package (easily) allows you to specify how many times to replicate your test and would the relative benchmark should be.
See also a related question at stats.stackexchange
To achieve this you would do something like:
n=L[0][0]
m=len(A)
for i in range(m):
for j in range(m):
if L[i][j]==n:
//do some processing
else:
break;
i've found one solution:
$("#someElement")[0].className.match("test")
but somehow i believe that there's a better way!
This is the best way to implement Onclicklistener for many buttons in a row implement View.onclicklistener.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
This is a button in the MainActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt_submit = (Button) findViewById(R.id.submit);
bt_submit.setOnClickListener(this);
}
This is an override method
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.submit:
//action
break;
case R.id.secondbutton:
//action
break;
}
}
Go to this link ... https://github.com/bsodmike/android-avd-profiles-2016/blob/master/Samsung%20Galaxy%20Tab%20A%2010.1%20(2016).xml
Save as xml file in your computer. Go on Android Studio => Tools => AVD Manager => + Create Virtual Device => Import Hardware Profiles ... choose the saved file and the device will be available on the tablet's section.
Happy Android developments guys!!!
You could deploy a custom BeanPostProcessor in your application context to do it. Or if you don't mind implementing a Spring interface in your bean, you could use the InitializingBean interface or the "init-method" directive (same link).
In iOS 10 beta 4.The right code in HTML5 is
<video src="file.mp4" webkit-playsinline="true" playsinline="true">
webkit-playsinline
is for iOS < 10, and playsinline
is for iOS >= 10
See details via https://webkit.org/blog/6784/new-video-policies-for-ios/
We had a similar challenge to solve yesterday, and we solved it using a Google Apps Script!
The solution takes 5 mins to implement and I've documented with step-by-step instructions: https://github.com/nelsonic/html-form-send-email-via-google-script-without-server
Deploy the sample script as a Google Spreadsheet APP Script: google-script-just-email.js
remember to set the
TO_ADDRESS
in the script to where ever you want the emails to be sent.
and copy the APP URL so you can use it in the next step when you publish the script.
action
to the App URLUsing the sample html
file:
index.html
create a basic form.
remember to paste your APP URL into the form
action
in the HTML form.
Open the HTML Form in your Browser, Input some data & submit it!
Submit the form. You should see a confirmation that it was sent:
Open the inbox for the email address you set (above)
Everything about this is customisable, you can easily style/theme the form with your favourite CSS Library and Store the submitted data in a Google Spreadsheet for quick analysis.
The complete instructions are available on GitHub:
https://github.com/nelsonic/html-form-send-email-via-google-script-without-server
Pretty strange, it should work out of the box as the ".modal-backdrop" class is defined top-level in the css.
<div class="modal-backdrop"></div>
Made a small demo: http://jsfiddle.net/PfBnq/
I had this error too, but in my case the cause was using an outdated version of npm, v1.4.28.
Updating to npm v3 followed by
rm -rf node_modules
npm -i
worked for me. npm issue 2697 has details of the "maximally flat" folder structure included in npm v3 (released 2015-06-25).
What kind of object are you using for databinding? Typically I use Collection<T>, List<T>, or Queue<T> (depending on circumstances). These are relatively easy to sort using a custom delegate. See MSDN documentation on the Comparison(T) delegate.
EugeneXa mentioned it in a comment, but it deserves to be an answer:
var template = $("#modal_template").html().trim();
This trims the offending whitespace from the beginning of the string. I used it with Mustache, like so:
var markup = Mustache.render(template, data);
$(markup).appendTo(container);
The best bitmap encoder is the one you do not write yourself. The file format is a lot more involved, than one might expect. This is evidenced by the fact, that all proposed answers do not create a monochrome (1bpp) bitmap, but rather write out 24bpp files, that happen to only use 2 colors.
The following is a Windows-only solution, using the Windows Imaging Component. It doesn't rely on any external/3rd party libraries, other than what ships with Windows.
Like every C++ program, we need to include several header files. And link to Windowscodecs.lib while we're at it:
#include <Windows.h>
#include <comdef.h>
#include <comip.h>
#include <comutil.h>
#include <wincodec.h>
#include <vector>
#pragma comment(lib, "Windowscodecs.lib")
Next up, we declare our container (a vector, of vectors! Of bool
!), and a few smart pointers for convenience:
using _com_util::CheckError;
using container = std::vector<std::vector<bool>>;
_COM_SMARTPTR_TYPEDEF(IWICImagingFactory, __uuidof(IWICImagingFactory));
_COM_SMARTPTR_TYPEDEF(IWICBitmapEncoder, __uuidof(IWICBitmapEncoder));
_COM_SMARTPTR_TYPEDEF(IWICBitmapFrameEncode, __uuidof(IWICBitmapFrameEncode));
_COM_SMARTPTR_TYPEDEF(IWICStream, __uuidof(IWICStream));
_COM_SMARTPTR_TYPEDEF(IWICPalette, __uuidof(IWICPalette));
With that all settled, we can jump right into the implementation. There's a bit of setup required to get a factory, an encoder, a frame, and get everything prepared:
void write_bitmap(wchar_t const* pathname, container const& data)
{
// Create factory
IWICImagingFactoryPtr sp_factory { nullptr };
CheckError(sp_factory.CreateInstance(CLSID_WICImagingFactory, nullptr,
CLSCTX_INPROC_SERVER));
// Create encoder
IWICBitmapEncoderPtr sp_encoder { nullptr };
CheckError(sp_factory->CreateEncoder(GUID_ContainerFormatBmp, nullptr, &sp_encoder));
// Create stream
IWICStreamPtr sp_stream { nullptr };
CheckError(sp_factory->CreateStream(&sp_stream));
CheckError(sp_stream->InitializeFromFilename(pathname, GENERIC_WRITE));
// Initialize encoder with stream
CheckError(sp_encoder->Initialize(sp_stream, WICBitmapEncoderNoCache));
// Create new frame
IWICBitmapFrameEncodePtr sp_frame { nullptr };
IPropertyBag2Ptr sp_properties { nullptr };
CheckError(sp_encoder->CreateNewFrame(&sp_frame, &sp_properties));
// Initialize frame with default properties
CheckError(sp_frame->Initialize(sp_properties));
// Set pixel format
// SetPixelFormat() requires a pointer to non-const
auto pf { GUID_WICPixelFormat1bppIndexed };
CheckError(sp_frame->SetPixelFormat(&pf));
if (!::IsEqualGUID(pf, GUID_WICPixelFormat1bppIndexed))
{
// Report unsupported pixel format
CheckError(WINCODEC_ERR_UNSUPPORTEDPIXELFORMAT);
}
// Set size derived from data argument
auto const width { static_cast<UINT>(data.size()) };
auto const height { static_cast<UINT>(data[0].size()) };
CheckError(sp_frame->SetSize(width, height));
// Set palette on frame. This is required since we use an indexed pixel format.
// Only GIF files support global palettes, so make sure to set it on the frame
// rather than the encoder.
IWICPalettePtr sp_palette { nullptr };
CheckError(sp_factory->CreatePalette(&sp_palette));
CheckError(sp_palette->InitializePredefined(WICBitmapPaletteTypeFixedBW, FALSE));
CheckError(sp_frame->SetPalette(sp_palette));
At that point everything is set up, and we have a frame to dump our data into. For 1bpp files, every byte stores the information of 8 pixels. The left-most pixel is stored in the MSB, with pixels following all the way down to the right-most pixel stored in the LSB.
The code isn't entirely important; you'll be replacing that with whatever suits your needs, when you replace the data layout of your input anyway:
// Write data to frame
auto const stride { (width * 1 + 7) / 8 };
auto const size { height * stride };
std::vector<unsigned char> buffer(size, 127u);
// Convert data to match required layout. Each byte stores 8 pixels, with the
// MSB being the leftmost, the LSB the right-most.
for (size_t x { 0 }; x < data.size(); ++x)
{
for (size_t y { 0 }; y < data[x].size(); ++y)
{
auto shift { x % 8 };
auto mask { 0x80 >> shift };
auto bit { mask * data[x][y] };
auto& value { buffer[y * stride + x / 8] };
value &= ~mask;
value |= bit;
}
}
CheckError(sp_frame->WritePixels(height, stride,
static_cast<UINT>(buffer.size()), buffer.data()));
What's left is to commit the changes to the frame and the encoder, which will ultimately write the image file to disk:
// Commit frame
CheckError(sp_frame->Commit());
// Commit image
CheckError(sp_encoder->Commit());
}
This is a test program, writing out an image to a file passed as the first command-line argument:
#include <iostream>
int wmain(int argc, wchar_t* argv[])
try
{
if (argc != 2)
{
return -1;
}
CheckError(::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED));
// Create 64x64 matrix
container data(64, std::vector<bool>(64, false));
// Fill with arrow pointing towards the upper left
for (size_t i { 0 }; i < data.size(); ++i)
{
data[0][i] = true;
data[i][0] = true;
data[i][i] = true;
}
::write_bitmap(argv[1], data);
::CoUninitialize();
}
catch (_com_error const& e)
{
std::wcout << L"Error!\n" << L" Message: " << e.ErrorMessage() << std::endl;
}
It produces the following image (true 1bpp, 574 bytes in size):
This error of Cannot find the declaration of element 'beans' but for a whole different reason
It turs out my internet connection was not very reliable, so i decided to check first for this url
http://www.springframework.org/schema/context/spring-context-4.0.xsd
Once I saw that the xsd was open succesfully I clean the Eclipse(IDE) project and the error was gone
If you try this steps and still get the error then check the Spring version so that it matches as mentioned by another answer
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-**[MAYOR.MINOR]**.xsd">
Replace [MAYOR.MINOR] on the last line with whatever major.minor Spring version that you are using
For Spring 4.0 http://www.springframework.org/schema/context/spring-context-4.0.xsd
For Sprint 3.1 http://www.springframework.org/schema/beans spring-beans-3.1.xsd
All the contexts are available here http://www.springframework.org/schema/context/
Right click table in Object Explorer, Select top 1000 rows
It'll list all columns and not *. Then remove the unwanted column(s). Should be much faster than typing it yourself.
Then when you feel this is a bit too much work, get Red Gate's SQL Prompt, and type ssf from tbl, go to the * and click tab again.
Your server's response allows the request to include three specific non-simple headers:
Access-Control-Allow-Headers:origin, x-requested-with, content-type
but your request has a header not allowed by the server's response:
Access-Control-Request-Headers:access-control-allow-origin, content-type
All non-simple headers sent in a CORS request must be explicitly allowed by the Access-Control-Allow-Headers
response header. The unnecessary Access-Control-Allow-Origin
header sent in your request is not allowed by the server's CORS response. This is exactly what the "...not allowed by Access-Control-Allow-Headers
" error message was trying to tell you.
There is no reason for the request to have this header: it does nothing, because Access-Control-Allow-Origin
is a response header, not a request header.
Solution: Remove the setRequestHeader
call that adds a Access-Control-Allow-Origin
header to your request.
If your object is not polymorphic (and a stack implementation likely isn't), then as per other answers here, what you want is the copy constructor. Please note that there are differences between copy construction and assignment in C++; if you want both behaviors (and the default versions don't fit your needs), you'll have to implement both functions.
If your object is polymorphic, then slicing can be an issue and you might need to jump through some extra hoops to do proper copying. Sometimes people use as virtual method called clone() as a helper for polymorphic copying.
Finally, note that getting copying and assignment right, if you need to replace the default versions, is actually quite difficult. It is usually better to set up your objects (via RAII) in such a way that the default versions of copy/assign do what you want them to do. I highly recommend you look at Meyer's Effective C++, especially at items 10,11,12.
"The $.browser property is deprecated in jQuery 1.3, and its functionality may be moved to a team-supported plugin in a future release of jQuery."
You can use this extensions
public static class JsonExtensions
{
public static T ToObject<T>(this string jsonText)
{
return JsonConvert.DeserializeObject<T>(jsonText);
}
public static string ToJson<T>(this T obj)
{
return JsonConvert.SerializeObject(obj);
}
}
Here is an example that sorts by the header. This table is dynamic and changes with the JSON size.
I was able to build a dynamic table off of some other people's examples and documentation. http://jsfiddle.net/lastlink/v7pszemn/1/
<tr>
<th class="{{header}}" ng-repeat="(header, value) in items[0]" ng-click="changeSorting(header)">
{{header}}
<i ng-class="selectedCls2(header)"></i>
</tr>
<tbody>
<tr ng-repeat="row in pagedItems[currentPage] | orderBy:sort.sortingOrder:sort.reverse">
<td ng-repeat="cell in row">
{{cell}}
</td>
</tr>
Although the columns are out of order, on my .NET project they are in order.
Strings are "immutable" for good reason: It really saves a lot of headaches, more often than you'd think. It also allows python to be very smart about optimizing their use. If you want to process your string in increments, you can pull out part of it with split()
or separate it into two parts using indices:
a = "abc"
a, result = a[:-1], a[-1]
This shows that you're splitting your string in two. If you'll be examining every byte of the string, you can iterate over it (in reverse, if you wish):
for result in reversed(a):
...
I should add this seems a little contrived: Your string is more likely to have some separator, and then you'll use split
:
ans = "foo,blah,etc."
for a in ans.split(","):
...
I managed to do this from my Activity where i'm setting my Rv and not from the adapter
If someone need to do something similar here's the code
In this case the color changes on a logClick
@Override
public void onLongClick(View view, int position) {
Toast.makeText(UltimasConsultasActivity.this, "Item agregado a la lista de mails",
Toast.LENGTH_SHORT).show();
sendMultipleMails.setVisibility(View.VISIBLE);
valueEmail.setVisibility(View.VISIBLE);
itemsSeleccionados.setVisibility(View.VISIBLE);
listaEmails.add(superListItems.get(position));
listaItems ="";
NameOfyourRecyclerInActivity.findViewHolderForAdapterPosition(position).NameOfYourViewInTheViewholder.setBackgroundColor((Color.parseColor("#336F0D")));
for(int itemsSelect = 0; itemsSelect <= listaEmails.size() -1; itemsSelect++){
listaItems += "*"+listaEmails.get(itemsSelect).getDescripcion() + "\n";
}
itemsSeleccionados.setText("Items Seleccionados : "+ "\n" + listaItems);
}
}));
Combination of two previous answers:
var selected = [];
$('#checkboxes input:checked').each(function() {
selected.push($(this).attr('name'));
});
What about a little trickery like NgModel does with NgForm? You have to register your parent as a provider, then load your parent in the constructor of the child.
That way, you don't have to put [sharedList]
on all your children.
// Parent.ts
export var parentProvider = {
provide: Parent,
useExisting: forwardRef(function () { return Parent; })
};
@Component({
moduleId: module.id,
selector: 'parent',
template: '<div><ng-content></ng-content></div>',
providers: [parentProvider]
})
export class Parent {
@Input()
public sharedList = [];
}
// Child.ts
@Component({
moduleId: module.id,
selector: 'child',
template: '<div>child</div>'
})
export class Child {
constructor(private parent: Parent) {
parent.sharedList.push('Me.');
}
}
Then your HTML
<parent [sharedList]="myArray">
<child></child>
<child></child>
</parent>
You can find more information on the subject in the Angular documentation: https://angular.io/guide/dependency-injection-in-action#find-a-parent-component-by-injection
A typical situation where you encounter strict aliasing problems is when overlaying a struct (like a device/network msg) onto a buffer of the word size of your system (like a pointer to uint32_t
s or uint16_t
s). When you overlay a struct onto such a buffer, or a buffer onto such a struct through pointer casting you can easily violate strict aliasing rules.
So in this kind of setup, if I want to send a message to something I'd have to have two incompatible pointers pointing to the same chunk of memory. I might then naively code something like this:
typedef struct Msg
{
unsigned int a;
unsigned int b;
} Msg;
void SendWord(uint32_t);
int main(void)
{
// Get a 32-bit buffer from the system
uint32_t* buff = malloc(sizeof(Msg));
// Alias that buffer through message
Msg* msg = (Msg*)(buff);
// Send a bunch of messages
for (int i = 0; i < 10; ++i)
{
msg->a = i;
msg->b = i+1;
SendWord(buff[0]);
SendWord(buff[1]);
}
}
The strict aliasing rule makes this setup illegal: dereferencing a pointer that aliases an object that is not of a compatible type or one of the other types allowed by C 2011 6.5 paragraph 71 is undefined behavior. Unfortunately, you can still code this way, maybe get some warnings, have it compile fine, only to have weird unexpected behavior when you run the code.
(GCC appears somewhat inconsistent in its ability to give aliasing warnings, sometimes giving us a friendly warning and sometimes not.)
To see why this behavior is undefined, we have to think about what the strict aliasing rule buys the compiler. Basically, with this rule, it doesn't have to think about inserting instructions to refresh the contents of buff
every run of the loop. Instead, when optimizing, with some annoyingly unenforced assumptions about aliasing, it can omit those instructions, load buff[0]
and buff[1]
into CPU registers once before the loop is run, and speed up the body of the loop. Before strict aliasing was introduced, the compiler had to live in a state of paranoia that the contents of buff
could change by any preceding memory stores. So to get an extra performance edge, and assuming most people don't type-pun pointers, the strict aliasing rule was introduced.
Keep in mind, if you think the example is contrived, this might even happen if you're passing a buffer to another function doing the sending for you, if instead you have.
void SendMessage(uint32_t* buff, size_t size32)
{
for (int i = 0; i < size32; ++i)
{
SendWord(buff[i]);
}
}
And rewrote our earlier loop to take advantage of this convenient function
for (int i = 0; i < 10; ++i)
{
msg->a = i;
msg->b = i+1;
SendMessage(buff, 2);
}
The compiler may or may not be able to or smart enough to try to inline SendMessage and it may or may not decide to load or not load buff again. If SendMessage
is part of another API that's compiled separately, it probably has instructions to load buff's contents. Then again, maybe you're in C++ and this is some templated header only implementation that the compiler thinks it can inline. Or maybe it's just something you wrote in your .c file for your own convenience. Anyway undefined behavior might still ensue. Even when we know some of what's happening under the hood, it's still a violation of the rule so no well defined behavior is guaranteed. So just by wrapping in a function that takes our word delimited buffer doesn't necessarily help.
So how do I get around this?
Use a union. Most compilers support this without complaining about strict aliasing. This is allowed in C99 and explicitly allowed in C11.
union {
Msg msg;
unsigned int asBuffer[sizeof(Msg)/sizeof(unsigned int)];
};
You can disable strict aliasing in your compiler (f[no-]strict-aliasing in gcc))
You can use char*
for aliasing instead of your system's word. The rules allow an exception for char*
(including signed char
and unsigned char
). It's always assumed that char*
aliases other types. However this won't work the other way: there's no assumption that your struct aliases a buffer of chars.
Beginner beware
This is only one potential minefield when overlaying two types onto each other. You should also learn about endianness, word alignment, and how to deal with alignment issues through packing structs correctly.
1 The types that C 2011 6.5 7 allows an lvalue to access are:
I use Visual Studio 2013 Professional.
You also place the cursor for choosing a property. Use menu Edit → Refactor → Encapsulate Field...
Other information:
Since C# 3.0 (November 19th 2007), we can use auto-implemented properties (this is merely syntactic sugar).
And
private int productID;
public int ProductID
{
get { return productID; }
set { productID = value; }
}
becomes
public int ProductID { get; set; }
To check if it has a particular method:
hasattr(object,"method")
Drop the hash - that's for identifying the id attribute.
For PHP, "it is always safe to precede a non-alphanumeric with "\" to specify that it stands for itself." - http://php.net/manual/en/regexp.reference.escape.php.
Except if it's a " or '. :/
To escape regex pattern variables (or partial variables) in PHP use preg_quote()
A simple way to store a list in Django is to just convert it into a JSON string, and then save that as Text in the model. You can then retrieve the list by converting the (JSON) string back into a python list. Here's how:
The "list" would be stored in your Django model like so:
class MyModel(models.Model):
myList = models.TextField(null=True) # JSON-serialized (text) version of your list
In your view/controller code:
Storing the list in the database:
import simplejson as json # this would be just 'import json' in Python 2.7 and later
...
...
myModel = MyModel()
listIWantToStore = [1,2,3,4,5,'hello']
myModel.myList = json.dumps(listIWantToStore)
myModel.save()
Retrieving the list from the database:
jsonDec = json.decoder.JSONDecoder()
myPythonList = jsonDec.decode(myModel.myList)
Conceptually, here's what's going on:
>>> myList = [1,2,3,4,5,'hello']
>>> import simplejson as json
>>> myJsonList = json.dumps(myList)
>>> myJsonList
'[1, 2, 3, 4, 5, "hello"]'
>>> myJsonList.__class__
<type 'str'>
>>> jsonDec = json.decoder.JSONDecoder()
>>> myPythonList = jsonDec.decode(myJsonList)
>>> myPythonList
[1, 2, 3, 4, 5, u'hello']
>>> myPythonList.__class__
<type 'list'>
private fun openOtherApp() {
val sendIntent = packageManager.getLaunchIntentForPackage("org.mab.dhyanaqrscanner")
startActivity(sendIntent)
finishAffinity()
}
Just pass parameter
like
body - The content(query) from the customer
subject - subject that defined in mail subject
username - nothing name anything
mail - mail (required)
public static bool SendMail(String body, String subject, string username, String mail)
{
bool isSendSuccess = false;
try
{
var fromEmailAddress = ConfigurationManager.AppSettings["FromEmailAddress"].ToString();
var fromEmailDisplayName = ConfigurationManager.AppSettings["FromEmailDisplayName"].ToString();
var fromEmailPassword = ConfigurationManager.AppSettings["FromEmailPassword"].ToString();
var smtpHost = ConfigurationManager.AppSettings["SMTPHost"].ToString();
var smtpPort = ConfigurationManager.AppSettings["SMTPPort"].ToString();
MailMessage message = new MailMessage(new MailAddress(fromEmailAddress, fromEmailDisplayName),
new MailAddress(mail, username));
message.Subject = subject;
message.IsBodyHtml = true;
message.Body = body;
var client = new SmtpClient();
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(fromEmailAddress, fromEmailPassword);
client.Host = smtpHost;
client.EnableSsl = false;
client.Port = !string.IsNullOrEmpty(smtpPort) ? Convert.ToInt32(smtpPort) : 0;
client.Send(message);
isSendSuccess = true;
}
catch (Exception ex)
{
throw (new Exception("Mail send failed to loginId " + mail + ", though registration done."+ex.ToString()+"\n"+ex.StackTrace));
}
return isSendSuccess;
}
if your using go daddy server this work . add this in web.config
<appSettings>
---other ---setting
<add key="FromEmailAddress" value="[email protected]" />
<add key="FromEmailDisplayName" value="anyname" />
<add key="FromEmailPassword" value="mypassword@" />
<add key="SMTPHost" value="relay-hosting.secureserver.net" />
<add key="SMTPPort" value="25" />
</appSettings>
if you are using localhost or vps server change this configuration to this
<appSettings>
---other ---setting
<add key="FromEmailAddress" value="[email protected]" />
<add key="FromEmailDisplayName" value="anyname" />
<add key="FromEmailPassword" value="mypassword@" />
<add key="SMTPHost" value="smtp.gmail.com" />
<add key="SMTPPort" value="587" />
</appSettings>
change the code
client.EnableSsl = true;
if your are using gmail please enable secure app. using this link https://myaccount.google.com/lesssecureapps?pli=1&rapt=AEjHL4Pd6h3XxE663Flvd-FfeRXxW_eNrIsGTBlZklgkAHZEeuHvheCQuZ1-djB9uIWaB-2EV7hyLCU0dWKA7D0JzYKe4ZRkuA
If the long string to multiple lines confuses you. Then you may install mz-tools addin which is a freeware and has the utility which splits the line for you.
If your string looks like below
SqlQueryString = "Insert into Employee values(" & txtEmployeeNo.Value & "','" & txtContractStartDate.Value & "','" & txtSeatNo.Value & "','" & txtFloor.Value & "','" & txtLeaves.Value & "')"
Simply select the string > right click on VBA IDE > Select MZ-tools > Split Lines
I have created a realtively small (4.89 KB) javascript library for this exact functionality.
Found on my GitHub here: https://github.com/thelevicole/youtube-to-html5-loader/
It's as simple as:
<video data-yt2html5="https://www.youtube.com/watch?v=ScMzIvxBSi4"></video>
<script src="https://cdn.jsdelivr.net/gh/thelevicole/[email protected]/dist/YouTubeToHtml5.js"></script>
<script>new YouTubeToHtml5();</script>
Working example here: https://jsfiddle.net/thelevicole/5g6dbpx3/1/
What the library does is extract the video ID from the data attribute and makes a request to the https://www.youtube.com/get_video_info?video_id=
. It decodes the response which includes streaming information we can use to add a source to the <video>
tag.
Everybody says "Each id value must be used only once within a document", but what we do to get the elements we need when we have a stupid page that has more than one element with same id. If we use JQuery '#duplicatedId' selector we get the first element only. To achieve selecting the other elements you can do something like this
$("[id=duplicatedId]")
You will get a collection with all elements with id=duplicatedId
var countries = new Array();
countries[0] = 'ga';
countries[1] = 'cd';
after that you can do like:
var new_countries = countries.join(',')
after:
$.ajax({
type: "POST",
url: "Concessions.aspx/GetConcessions",
data: new_countries,
...
This thing work as JSON string format.
a.insert(a.end(), b.begin(), b.end());
or
a.insert(std::end(a), std::begin(b), std::end(b));
The second variant is a more generically applicable solution, as b
could also be an array. However, it requires C++11. If you want to work with user-defined types, use ADL:
using std::begin, std::end;
a.insert(end(a), begin(b), end(b));
This warning can appear with various functions that are related to file and directory access. It warns about a configuration issue.
When it appears, it means that access has been forbidden to some files.
The warning itself does not break anything, but most often a script does not properly work if file-access is prevented.
The fix is normally to change the PHP configuration, the related setting is called open_basedir
.
Sometimes the wrong file or directory names are used, the fix is then to use the right ones.
Related Questions:
It sometimes happens when you try to Insert/Update
an entity while the foreign key
that you are trying to Insert/Update
actually does not exist. So, be sure that the foreign key
exists and try again.
A reproducible example:
the_plot <- function()
{
x <- seq(0, 1, length.out = 100)
y <- pbeta(x, 1, 10)
plot(
x,
y,
xlab = "False Positive Rate",
ylab = "Average true positive rate",
type = "l"
)
}
James's suggestion of using pointsize
, in combination with the various cex
parameters, can produce reasonable results.
png(
"test.png",
width = 3.25,
height = 3.25,
units = "in",
res = 1200,
pointsize = 4
)
par(
mar = c(5, 5, 2, 2),
xaxs = "i",
yaxs = "i",
cex.axis = 2,
cex.lab = 2
)
the_plot()
dev.off()
Of course the better solution is to abandon this fiddling with base graphics and use a system that will handle the resolution scaling for you. For example,
library(ggplot2)
ggplot_alternative <- function()
{
the_data <- data.frame(
x <- seq(0, 1, length.out = 100),
y = pbeta(x, 1, 10)
)
ggplot(the_data, aes(x, y)) +
geom_line() +
xlab("False Positive Rate") +
ylab("Average true positive rate") +
coord_cartesian(0:1, 0:1)
}
ggsave(
"ggtest.png",
ggplot_alternative(),
width = 3.25,
height = 3.25,
dpi = 1200
)
Here's a nice easy way I found:
h <- hist(g, breaks = 10, density = 10,
col = "lightgray", xlab = "Accuracy", main = "Overall")
xfit <- seq(min(g), max(g), length = 40)
yfit <- dnorm(xfit, mean = mean(g), sd = sd(g))
yfit <- yfit * diff(h$mids[1:2]) * length(g)
lines(xfit, yfit, col = "black", lwd = 2)
Enumerable.First
returns the element instead of an index. In both cases you will get an exception if no matching element appears in the list (your original code will throw an IndexOutOfBoundsException
when you try to get the item at index -1, but First
will throw an InvalidOperationException
).
MyList.First(item => string.Equals("foo", item.name)).value
{{ }}
tells the template to print the value, this won't work in expressions like you're trying to do. Instead, use the {% set %}
template tag and then assign the value the same way you would in normal python code.
{% set testing = 'it worked' %}
{% set another = testing %}
{{ another }}
Result:
it worked
It just means that any graph which we are creating as a part of our code will appear in the same notebook and not in separate window which would happen if we have not used this magic statement.
Although @airdrumz solutions works, you will get lots of errors about you doing it wrong by accessing ID directly, this is not good for future compatibility.
But it lead me to inspect the object and create this OOP approach:
function myplug_get_prod_attrs() {
// Enqueue scripts happens very early, global $product has not been created yet, neither has the post/loop
global $product;
$wc_attr_objs = $product->get_attributes();
$prod_attrs = [];
foreach ($wc_attr_objs as $wc_attr => $wc_term_objs) {
$prod_attrs[$wc_attr] = [];
$wc_terms = $wc_term_objs->get_terms();
foreach ($wc_terms as $wc_term) {
array_push($prod_attrs[$wc_attr], $wc_term->slug);
}
}
return $prod_attrs;
}
Bonus, if you are performing the above early before the global $product item is created (e.g. during enqueue scripts), you can make it yourself with:
$product = wc_get_product(get_queried_object_id());
I just give other option for this question - you need to use '.dt' in your code:
import pandas as pd_x000D_
_x000D_
df.index = pd.to_datetime(df.index)_x000D_
_x000D_
#for get year_x000D_
df.index.dt.year_x000D_
_x000D_
#for get month_x000D_
df.index.dt.month_x000D_
_x000D_
#for get day_x000D_
df.index.dt.day_x000D_
_x000D_
#for get hour_x000D_
df.index.dt.hour_x000D_
_x000D_
#for get minute_x000D_
df.index.dt.minute
_x000D_
I know it's an old thread, but I still think it's worth to answer it.
select (
SELECT COLUMN FROM MY_TABLE WHERE ....
) into v_column
from dual;
Example of use:
declare v_column VARCHAR2(100);
begin
select (SELECT TABLE_NAME FROM ALL_TABLES WHERE TABLE_NAME = 'DOES NOT EXIST')
into v_column
from dual;
DBMS_OUTPUT.PUT_LINE('v_column=' || v_column);
end;
The easiest way to convert an ISO-8859-1 string to UTF-8 string.
private static String convertIsoToUTF8(String example) throws UnsupportedEncodingException {
return new String(example.getBytes("ISO-8859-1"), "utf-8");
}
If we want to convert an UTF-8 string to ISO-8859-1 string.
private static String convertUTF8ToISO(String example) throws UnsupportedEncodingException {
return new String(example.getBytes("utf-8"), "ISO-8859-1");
}
Moreover, a method that converts an ISO-8859-1 string to UTF-8 string without using the constructor of class String.
public static String convertISO_to_UTF8_personal(String strISO_8859_1) {
String res = "";
int i = 0;
for (i = 0; i < strISO_8859_1.length() - 1; i++) {
char ch = strISO_8859_1.charAt(i);
char chNext = strISO_8859_1.charAt(i + 1);
if (ch <= 127) {
res += ch;
} else if (ch == 194 && chNext >= 128 && chNext <= 191) {
res += chNext;
} else if(ch == 195 && chNext >= 128 && chNext <= 191){
int resNum = chNext + 64;
res += (char) resNum;
} else if(ch == 194){
res += (char) 173;
} else if(ch == 195){
res += (char) 224;
}
}
char ch = strISO_8859_1.charAt(i);
if (ch <= 127 ){
res += ch;
}
return res;
}
}
That method is based on enconding utf-8 to iso-8859-1 of this website. Encoding utf-8 to iso-8859-1
I have to disagree with Dale... The strong element is actually the wrong element to use, implying something about the meaning, use, or emphasis of the content while you are simply intending to provide style to the element.
Ideally you would be able to accomplish this with a pseudo-class and your stylesheet, but as that is not possible you should make your markup semantically correct and use <span class="first-word">
.
If you have nested objects and arrays, best way to populate FormData object is using recursion.
function createFormData(formData, data, key) {
if ( ( typeof data === 'object' && data !== null ) || Array.isArray(data) ) {
for ( let i in data ) {
if ( ( typeof data[i] === 'object' && data[i] !== null ) || Array.isArray(data[i]) ) {
createFormData(formData, data[i], key + '[' + i + ']');
} else {
formData.append(key + '[' + i + ']', data[i]);
}
}
} else {
formData.append(key, data);
}
}
In Java, ==
always just compares two references (for non-primitives, that is) - i.e. it tests whether the two operands refer to the same object.
However, the equals
method can be overridden - so two distinct objects can still be equal.
For example:
String x = "hello";
String y = new String(new char[] { 'h', 'e', 'l', 'l', 'o' });
System.out.println(x == y); // false
System.out.println(x.equals(y)); // true
Additionally, it's worth being aware that any two equal string constants (primarily string literals, but also combinations of string constants via concatenation) will end up referring to the same string. For example:
String x = "hello";
String y = "he" + "llo";
System.out.println(x == y); // true!
Here x
and y
are references to the same string, because y
is a compile-time constant equal to "hello"
.
<select class="dropdownmenu" name="drop-down">
<option class="dropdownmenu_list1" value="select-option">Choose ...</option>
<option class="dropdownmenu_list2" value="Topic 1">Option 1</option>
<option class="dropdownmenu_list3" value="Topic 2">Option 2</option>
</select>
This works best in Firefox. Too bad that Chrome and Safari do not support this rather easy CSS styling.
This code is very easy to upload file by php. In this code I am performing uploading task in same page that mean our html and php both code resides in the same file. This code generates new name of image name.
first of all see the html code
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" name="banner_image" >
<input type="submit" value="submit">
</form>
now see the php code
<?php
$image_name=$_FILES['banner_image']['name'];
$temp = explode(".", $image_name);
$newfilename = round(microtime(true)) . '.' . end($temp);
$imagepath="uploads/".$newfilename;
move_uploaded_file($_FILES["banner_image"]["tmp_name"],$imagepath);
?>
We can download a specified branch by using following magical command:
git clone -b < branch name > <remote_repo url>
You have to use image
.listStyle {
list-style: none;
background: url(bullet.jpg) no-repeat left center;
padding-left: 40px;
}
If we think of getting name of items from any specific category then we can do that by specifying the class name of that category using css selector:
import requests ; from bs4 import BeautifulSoup
soup = BeautifulSoup(requests.get('https://www.flipkart.com/').text, "lxml")
for link in soup.select('div._2kSfQ4'):
print(link.text)
This is the partial search results:
Puma, USPA, Adidas & moreUp to 70% OffMen's Shoes
Shirts, T-Shirts...Under ?599For Men
Nike, UCB, Adidas & moreUnder ?999Men's Sandals, Slippers
Philips & moreStarting ?99LED Bulbs & Emergency Lights
You should probably set the property dt.Columns["columnName"].ReadOnly = false;
before.
I didn't want a reference to EF in my application project (or to manually copy anything) so I added this to my EF project's Post-build events:
cp $(TargetDir)EntityFramework.SqlServer.dll $(SolutionDir){your-main-bin-folder}
Default user for MySQL is "root", and server "localhost".
#multiplying each element in the list and adding it into an empty list
original = [1, 2, 3]
results = []
for num in original:
results.append(num*2)# multiply each iterative number by 2 and add it to the empty list.
print(results)
If I want tranfer only the response variable y instead of a linear model with x specified, eg I wanna transfer/normalize a list of data, I can take 1 for x, then the object becomes a linear model:
library(MASS)
y = rf(500,30,30)
hist(y,breaks = 12)
result = boxcox(y~1, lambda = seq(-5,5,0.5))
mylambda = result$x[which.max(result$y)]
mylambda
y2 = (y^mylambda-1)/mylambda
hist(y2)
JSON is "JavaScript Object Notation". JavaScript specifies its keys must be strings or symbols.
The following quotation from MDN Docs uses the terms "key/property" to refer to what I more often hear termed as "key/value".
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Objects
In JavaScript, objects can be seen as a collection of properties. With the object literal syntax, a limited set of properties are initialized; then properties can be added and removed. Property values can be values of any type, including other objects, which enables building complex data structures. Properties are identified using key values. A key value is either a String or a Symbol value.
There is another way to pass multiple ranges to a function, which I think feels much cleaner for the user. When you call your function in the spreadsheet you wrap each set of ranges in brackets, for example: calculateIt( (A1,A3), (B6,B9) )
The above call assumes your two Sessions are in A1 and A3, and your two Customers are in B6 and B9.
To make this work, your function needs to loop through each of the Areas
in the input ranges. For example:
Function calculateIt(Sessions As Range, Customers As Range) As Single
' check we passed the same number of areas
If (Sessions.Areas.Count <> Customers.Areas.Count) Then
calculateIt = CVErr(xlErrNA)
Exit Function
End If
Dim mySession, myCustomers As Range
' run through each area and calculate
For a = 1 To Sessions.Areas.Count
Set mySession = Sessions.Areas(a)
Set myCustomers = Customers.Areas(a)
' calculate them...
Next a
End Function
The nice thing is, if you have both your inputs as a contiguous range, you can call this function just as you would a normal one, e.g. calculateIt(A1:A3, B6:B9)
.
Hope that helps :)
For those who still stumble upon this like I did, it's worth checking to make sure the attempted GRANT
does not already exist:
SHOW GRANTS FOR username;
In my case, the error was not actually because there was a permission error, but because the GRANT
already existed.
You can face this wrong in specific database which is created after SSMS update. Open SSMS and select your databases and open your required database then click Security--> Users--> and right click on Users and click again on 'New User' and add 'NT AUTHORITY\Authenticated Users' and save you work and go to your Form on Web/Desktop whatever do you. Enjoy....
There are multiple hardware revisions of Nexus 5. So, the accepted answer doesn't work for all devices (it didn't work for me).
Open Device Manager, right click and Properties. Now go to the "Details" tab And now select the property "Hardware Ids". Note down the PID and VID.
Download the Google driver
Update the android_winusb.inf with above VID and PID
%CompositeAdbInterface% = USB_Install, USB\VID_18D1&**PID_4EE1**
Now in Device Manager, find Nexus 5, and update the driver software, and browse to the location where you downloaded.
The driver should be installed, and you should be see the device in ADB.
In my case I added the following 4 lines to $middlewareGroups (in app/Http/Kernel.php):
'api' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
'throttle:60,1',
'bindings',
],
IMPORTANT: The 4 new lines must be added BEFORE 'throttle' and 'bindings'!
Otherwise a "CSRF token not match" error will rise. I've struggled in this for several hours just to find the order is important.
This allowed me to access session in my API. I also added VerifyCsrfToken as when cookies/sessions are involved, CSRF needs to be taken care of.
It's used in Kotlin
appCompatActivity?.getSupportFragmentManager()?.popBackStack()
I know it's been a while on this question, but I was just looking for the same answer and found this seems to be the simplest solution:
select * from sales where datediff(dd, salesDate, '20101111') = 0
I actually use it more to find things within the last day or two, so my version looks like this:
select * from sales where datediff(dd, salesDate, getdate()) = 0
And by changing the 0 for today to a 1 I get yesterday's transactions, 2 is the day before that, and so on. And if you want everything for the last week, just change the equals to a less-than-or-equal-to:
select * from sales where datediff(dd, salesDate, getdate()) <= 7
Simply mutiply the bottom of the division by 1.0 (or as many decimal places as you want)
PRINT @set1
PRINT @set2
SET @weight= @set1 / @set2 *1.00000;
PRINT @weight
Use the inspect
module:
from inspect import getmembers, isfunction
from somemodule import foo
print(getmembers(foo, isfunction))
Also see the pydoc
module, the help()
function in the interactive interpreter and the pydoc
command-line tool which generates the documentation you are after. You can just give them the class you wish to see the documentation of. They can also generate, for instance, HTML output and write it to disk.
This works in my case for getting table name and column name in the corresponding table for indexed fields.
SELECT TABLE_NAME , COLUMN_NAME, COMMENT
FROM information_schema.statistics
WHERE table_schema = 'database_name';
onblur
is the opposite of onfocus
.
First create an object of class2 in class1 and then use that object to call any function of class2 for example write this in class1
class2 obj= new class2();
obj.thefunctioname(args);
What are the steps for that? where is AppCompat located?
Download the support library here:
http://developer.android.com/tools/support-library/setup.html
If you are using Eclipse:
Go to the tabs at the top and select ( Windows -> Android SDK Manager ). Under the 'extras' section, check 'Android Support Library' and check it for installation.
After that, the AppCompat library can be found at:
android-sdk/extras/android/support/v7/appcompat
You need to reference this AppCompat library in your Android project.
Import the library into Eclipse.
You first create the filter with fspecial and then convolve the image with the filter using imfilter (which works on multidimensional images as in the example).
You specify sigma
and hsize
in fspecial
.
%%# Read an image
I = imread('peppers.png');
%# Create the gaussian filter with hsize = [5 5] and sigma = 2
G = fspecial('gaussian',[5 5],2);
%# Filter it
Ig = imfilter(I,G,'same');
%# Display
imshow(Ig)
Just like any other collection. With the addition of the List<T>.ForEach
method.
foreach (var item in myMoney)
Console.WriteLine("amount is {0}, and type is {1}", item.amount, item.type);
for (int i = 0; i < myMoney.Count; i++)
Console.WriteLine("amount is {0}, and type is {1}", myMoney[i].amount, myMoney[i].type);
myMoney.ForEach(item => Console.WriteLine("amount is {0}, and type is {1}", item.amount, item.type));
You could simply have: var result = (str == "true")
.
Sometimes you need to reset ADB. To do that, in Eclipse, go:
Window>> Show View >> Android (Might be found in the "Other" option)>>Devices
in the device Tab, click the down arrow, and choose reset adb.